function Web3(provider) { this._requestManager = new RequestManager(provider); this.currentProvider = provider; this.eth = new Eth(this); this.db = new DB(this); this.shh = new Shh(this); this.net = new Net(this); this.personal = new Personal(this); this.bzz = new Swarm(this); this.settings = new Settings(); this.version = { api: version.version }; this.providers = { HttpProvider: HttpProvider, IpcProvider: IpcProvider }; this._extend = extend(this); this._extend({ properties: properties() }); }
n/a
address = function () { this._inputFormatter = f.formatInputInt; this._outputFormatter = f.formatOutputAddress; }
...
};
/**
* Transforms direct icap to address
*/
Web3.prototype.fromICAP = function (icap) {
var iban = new Iban(icap);
return iban.address();
};
var properties = function () {
return [
new Property({
name: 'version.node',
getter: 'web3_clientVersion'
...
allevents = function (requestManager, json, address) { this._requestManager = requestManager; this._json = json; this._address = address; }
n/a
batch = function (web3) { this.requestManager = web3._requestManager; this.requests = []; }
n/a
bool = function () { this._inputFormatter = f.formatInputBool; this._outputFormatter = f.formatOutputBool; }
n/a
bytes = function () { this._inputFormatter = f.formatInputBytes; this._outputFormatter = f.formatOutputBytes; }
n/a
contract = function (eth, abi) {
this.eth = eth;
this.abi = abi;
/**
* Should be called to create new contract on a blockchain
*
* @method new
* @param {Any} contract constructor param1 (optional)
* @param {Any} contract constructor param2 (optional)
* @param {Object} contract transaction object (required)
* @param {Function} callback
* @returns {Contract} returns contract instance
*/
this.new = function () {
/*jshint maxcomplexity: 7 */
var contract = new Contract(this.eth, this.abi);
// parse arguments
var options = {}; // required!
var callback;
var args = Array.prototype.slice.call(arguments);
if (utils.isFunction(args[args.length - 1])) {
callback = args.pop();
}
var last = args[args.length - 1];
if (utils.isObject(last) && !utils.isArray(last)) {
options = args.pop();
}
if (options.value > 0) {
var constructorAbi = abi.filter(function (json) {
return json.type === 'constructor' && json.inputs.length === args.length;
})[0] || {};
if (!constructorAbi.payable) {
throw new Error('Cannot send value to non-payable constructor');
}
}
var bytes = encodeConstructorParams(this.abi, args);
options.data += bytes;
if (callback) {
// wait for the contract address adn check if the code was deployed
this.eth.sendTransaction(options, function (err, hash) {
if (err) {
callback(err);
} else {
// add the transaction hash
contract.transactionHash = hash;
// call callback for the first time
callback(null, contract);
checkForContractAddress(contract, callback);
}
});
} else {
var hash = this.eth.sendTransaction(options);
// add the transaction hash
contract.transactionHash = hash;
checkForContractAddress(contract);
}
return contract;
};
this.new.getData = this.getData.bind(this);
}
...
"type": "uint256"
}
],
"name": "Approval",
"type": "event"
}
];
var myContract = new web3.eth.contract(jsoninterface);
...
dynamicbytes = function () { this._inputFormatter = f.formatInputDynamicBytes; this._outputFormatter = f.formatOutputDynamicBytes; }
n/a
function Eth(web3) { this._requestManager = web3._requestManager; var self = this; methods().forEach(function(method) { method.attachToObject(self); method.setRequestManager(self._requestManager); }); properties().forEach(function(p) { p.attachToObject(self); p.setRequestManager(self._requestManager); }); this.iban = Iban; this.sendIBANTransaction = transfer.bind(null, this); }
...
callback = arguments[arguments.length - 1];
if(arguments.length === 1)
options = null;
}
var o = this.encode(options);
var formatter = this.decode.bind(this);
return new Filter(this._requestManager, o, watches.eth(), formatter, callback);
};
AllSolidityEvents.prototype.attachToContract = function (contract) {
var execute = this.execute.bind(this);
contract.allEvents = execute;
};
...
event = function (requestManager, json, address) { this._requestManager = requestManager; this._params = json.inputs; this._name = utils.transformToFullName(json); this._address = address; this._anonymous = json.anonymous; }
n/a
filter = function (requestManager, options, methods, formatter, callback, filterCreationErrorCallback) { var self = this; var implementation = {}; methods.forEach(function (method) { method.setRequestManager(requestManager); method.attachToObject(implementation); }); this.requestManager = requestManager; this.options = getOptions(options); this.implementation = implementation; this.filterId = null; this.callbacks = []; this.getLogsCallbacks = []; this.pollFilters = []; this.formatter = formatter; this.implementation.newFilter(this.options, function(error, id){ if(error) { self.callbacks.forEach(function(cb){ cb(error); }); filterCreationErrorCallback(error); } else { self.filterId = id; // check if there are get pending callbacks as a consequence // of calling get() with filterId unassigned. self.getLogsCallbacks.forEach(function (cb){ self.get(cb); }); self.getLogsCallbacks = []; // get filter logs for the already existing watch calls self.callbacks.forEach(function(cb){ getLogsAtStart(self, cb); }); if(self.callbacks.length > 0) pollFilter(self); // start to watch immediately if(typeof callback === 'function') { return self.watch(callback); } } }); return this; }
...
*
* @method _requireType
* @param {String} type
* @returns {SolidityType}
* @throws {Error} throws if no matching type is found
*/
SolidityCoder.prototype._requireType = function (type) {
var solidityType = this._types.filter(function (t) {
return t.isType(type);
})[0];
if (!solidityType) {
throw Error('invalid solidity type!: ' + type);
}
...
function = function (eth, json, address) { this._eth = eth; this._inputTypes = json.inputs.map(function (i) { return i.type; }); this._outputTypes = json.outputs.map(function (i) { return i.type; }); this._constant = json.constant; this._payable = json.payable; this._name = utils.transformToFullName(json); this._address = address; }
n/a
iban = function (iban) { this._iban = iban; }
n/a
int = function () { this._inputFormatter = f.formatInputInt; this._outputFormatter = f.formatOutputInt; }
n/a
method = function (options) { this.name = options.name; this.call = options.call; this.params = options.params || 0; this.inputFormatter = options.inputFormatter; this.outputFormatter = options.outputFormatter; this.requestManager = null; }
n/a
param = function (value, offset) { this.value = value || ''; this.offset = offset; // offset in bytes }
n/a
property = function (options) { this.name = options.name; this.getter = options.getter; this.setter = options.setter; this.outputFormatter = options.outputFormatter; this.inputFormatter = options.inputFormatter; this.requestManager = null; }
n/a
providers.HttpProvider = function (host, timeout) { this.host = host || 'http://localhost:8545'; this.timeout = timeout || 0; }
...
```js
console.log(web3); // {eth: .., shh: ...} // it's here!
```
Set a provider (HttpProvider)
```js
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
```
There you go, now you can use it:
```js
var coinbase = web3.eth.coinbase;
var balance = web3.eth.getBalance(coinbase);
...
providers.IpcProvider = function (path, net) {
var _this = this;
this.responseCallbacks = {};
this.path = path;
this.connection = net.connect({path: this.path});
this.connection.on('error', function(e){
console.error('IPC Connection Error', e);
_this._timeout();
});
this.connection.on('end', function(){
_this._timeout();
});
// LISTEN FOR CONNECTION RESPONSES
this.connection.on('data', function(data) {
/*jshint maxcomplexity: 6 */
_this._parseResponse(data.toString()).forEach(function(result){
var id = null;
// get the id which matches the returned id
if(utils.isArray(result)) {
result.forEach(function(load){
if(_this.responseCallbacks[load.id])
id = load.id;
});
} else {
id = result.id;
}
// fire the callback
if(_this.responseCallbacks[id]) {
_this.responseCallbacks[id](null, result);
delete _this.responseCallbacks[id];
}
});
});
}
n/a
real = function () { this._inputFormatter = f.formatInputReal; this._outputFormatter = f.formatOutputReal; }
n/a
requestmanager = function (provider) { this.provider = provider; this.polls = {}; this.timeout = null; }
n/a
shh = function (web3) { this._requestManager = web3._requestManager; var self = this; methods().forEach(function(method) { method.attachToObject(self); method.setRequestManager(self._requestManager); }); }
...
methods().forEach(function(method) {
method.attachToObject(self);
method.setRequestManager(self._requestManager);
});
};
Shh.prototype.filter = function (fil, callback) {
return new Filter(this._requestManager, fil, watches.shh(), formatters.outputPostFormatter
, callback);
};
var methods = function () {
var post = new Method({
name: 'post',
call: 'shh_post',
...
string = function () { this._inputFormatter = f.formatInputString; this._outputFormatter = f.formatOutputString; }
n/a
syncing = function (requestManager, callback) { this.requestManager = requestManager; this.pollId = 'syncPoll_'+ count++; this.callbacks = []; this.addCallback(callback); this.lastSyncState = false; pollSyncing(this); return this; }
n/a
type = function (config) { this._inputFormatter = config.inputFormatter; this._outputFormatter = config.outputFormatter; }
n/a
uint = function () { this._inputFormatter = f.formatInputInt; this._outputFormatter = f.formatOutputUInt; }
n/a
ureal = function () { this._inputFormatter = f.formatInputReal; this._outputFormatter = f.formatOutputUReal; }
n/a
function BigNumber( n, b ) { var c, e, i, num, len, str, x = this; // Enable constructor usage without new. if ( !( x instanceof BigNumber ) ) { // 'BigNumber() constructor call without new: {n}' if (ERRORS) raise( 26, 'constructor call without new', n ); return new BigNumber( n, b ); } // 'new BigNumber() base not an integer: {b}' // 'new BigNumber() base out of range: {b}' if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) { // Duplicate. if ( n instanceof BigNumber ) { x.s = n.s; x.e = n.e; x.c = ( n = n.c ) ? n.slice() : n; id = 0; return; } if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) { x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1; // Fast path for integers. if ( n === ~~n ) { for ( e = 0, i = n; i >= 10; i /= 10, e++ ); x.e = e; x.c = [n]; id = 0; return; } str = n + ''; } else { if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num ); x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1; } } else { b = b | 0; str = n + ''; // Ensure return value is rounded to DECIMAL_PLACES as with other bases. // Allow exponential notation to be used with base 10 argument. if ( b == 10 ) { x = new BigNumber( n instanceof BigNumber ? n : str ); return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE ); } // Avoid potential interpretation of Infinity and NaN as base 44+ values. // Any number in exponential form will fail due to the [Ee][+-]. if ( ( num = typeof n == 'number' ) && n * 0 != 0 || !( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) + '(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) { return parseNumeric( x, str, num, b ); } if (num) { x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1; if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) { // 'new BigNumber() number type has more than 15 significant digits: {n}' raise( id, tooManyDigits, n ); } // Prevent later check for length on converted number. num = false; } else { x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1; } str = convertBase( str, 10, b, x.s ); } // Decimal point? if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' ); // Exponential form? if ( ( i = str.search( /e/i ) ) > 0 ) { // Determine exponent. if ( e < 0 ) e = i; e += +str.slice( i + 1 ); str = str.substring( 0, i ); } else if ( e < 0 ) { // Integer. e = str.length; } // Determine leading zeros. for ( i = 0; str.charCodeAt(i) === 48; i++ ); // Determine trailing zeros. for ( len = str.length; str.charCodeAt(--len) === 48; ); str = str.slice( i, len + 1 ); if (str) { len = str.length; // Disallow numbers with over 15 significant digits if number type. // 'new BigNumber() number type has more than 15 significant digits: {n}' if ( num && ERRORS && len > 15 ) raise( id, tooManyDigits, x.s * n ); e = e - i - 1; // Overflow? if ( e > MAX_EXP ) { // Infinity. x.c = x.e = null; // Underflow? } else if ( e < MIN_EXP ) { // Zero. x.c = [ x.e = 0 ]; } else { x.e = e; x.c = []; // Transform base // e is the base 10 exponent. // i is where to slice str to get the first element of the coefficient array. i = ( e + 1 ) % LOG_BASE; if ( e < 0 ) i += LOG_BASE; if ( i < len ) { ...
n/a
address = function () { this._inputFormatter = f.formatInputInt; this._outputFormatter = f.formatOutputAddress; }
...
};
/**
* Transforms direct icap to address
*/
Web3.prototype.fromICAP = function (icap) {
var iban = new Iban(icap);
return iban.address();
};
var properties = function () {
return [
new Property({
name: 'version.node',
getter: 'web3_clientVersion'
...
constructor = function () { this._inputFormatter = f.formatInputInt; this._outputFormatter = f.formatOutputAddress; }
n/a
isType = function (name) { return !!name.match(/address(\[([0-9]*)\])?/); }
...
* @method _requireType
* @param {String} type
* @returns {SolidityType}
* @throws {Error} throws if no matching type is found
*/
SolidityCoder.prototype._requireType = function (type) {
var solidityType = this._types.filter(function (t) {
return t.isType(type);
})[0];
if (!solidityType) {
throw Error('invalid solidity type!: ' + type);
}
return solidityType;
...
allevents = function (requestManager, json, address) { this._requestManager = requestManager; this._json = json; this._address = address; }
n/a
attachToContract = function (contract) { var execute = this.execute.bind(this); contract.allEvents = execute; }
...
*/
var addFunctionsToContract = function (contract) {
contract.abi.filter(function (json) {
return json.type === 'function';
}).map(function (json) {
return new SolidityFunction(contract._eth, json, contract.address);
}).forEach(function (f) {
f.attachToContract(contract);
});
};
/**
* Should be called to add events to contract object
*
* @method addEventsToContract
...
decode = function (data) { data.data = data.data || ''; data.topics = data.topics || []; var eventTopic = data.topics[0].slice(2); var match = this._json.filter(function (j) { return eventTopic === sha3(utils.transformToFullName(j)); })[0]; if (!match) { // cannot find matching event? console.warn('cannot find event for log'); return data; } var event = new SolidityEvent(this._requestManager, match, this._address); return event.decode(data); }
...
* @return {Array} array of plain params
*/
SolidityCoder.prototype.decodeParams = function (types, bytes) {
var solidityTypes = this.getSolidityTypes(types);
var offsets = this.getOffsets(types, solidityTypes);
return solidityTypes.map(function (solidityType, index) {
return solidityType.decode(bytes, offsets[index], types[index], index);
});
};
SolidityCoder.prototype.getOffsets = function (types, solidityTypes) {
var lengths = solidityTypes.map(function (solidityType, index) {
return solidityType.staticPartLength(types[index]);
});
...
encode = function (options) { options = options || {}; var result = {}; ['fromBlock', 'toBlock'].filter(function (f) { return options[f] !== undefined; }).forEach(function (f) { result[f] = formatters.inputBlockNumberFormatter(options[f]); }); result.address = this._address; return result; }
...
* @param {Array} params
* @return {String} encoded list of params
*/
SolidityCoder.prototype.encodeParams = function (types, params) {
var solidityTypes = this.getSolidityTypes(types);
var encodeds = solidityTypes.map(function (solidityType, index) {
return solidityType.encode(params[index], types[index]);
});
var dynamicOffset = solidityTypes.reduce(function (acc, solidityType, index) {
var staticPartLength = solidityType.staticPartLength(types[index]);
var roundedStaticPartLength = Math.floor((staticPartLength + 31) / 32) * 32;
return acc + (isDynamic(solidityTypes[index], types[index]) ?
...
execute = function (options, callback) { if (utils.isFunction(arguments[arguments.length - 1])) { callback = arguments[arguments.length - 1]; if(arguments.length === 1) options = null; } var o = this.encode(options); var formatter = this.decode.bind(this); return new Filter(this._requestManager, o, watches.eth(), formatter, callback); }
...
*
* @return {CipherParams} A cipher params object with the key, IV, and salt.
*
* @static
*
* @example
*
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password',
256/32, 128/32);
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
*/
execute: function (password, keySize, ivSize, salt) {
// Generate random salt
if (!salt) {
salt = WordArray.random(64/8);
}
...
batch = function (web3) { this.requestManager = web3._requestManager; this.requests = []; }
n/a
add = function (request) { this.requests.push(request); }
...
});
gulp.task('light', ['clean'], function () {
return browserify(browserifyOptions)
.require('./' + src + '.js', {expose: 'web3'})
.ignore('bignumber.js')
.require('./lib/utils/browser-bn.js', {expose: 'bignumber.js'}) // fake bignumber.js
.add('./' + src + '.js')
.bundle()
.pipe(exorcist(path.join( DEST, lightDst + '.js.map')))
.pipe(source(lightDst + '.js'))
.pipe(gulp.dest( DEST ))
.pipe(streamify(uglify()))
.pipe(rename(lightDst + '.min.js'))
.pipe(gulp.dest( DEST ));
...
execute = function () { var requests = this.requests; this.requestManager.sendBatch(requests, function (err, results) { results = results || []; requests.map(function (request, index) { return results[index] || {}; }).forEach(function (result, index) { if (requests[index].callback) { if (!Jsonrpc.isValidResponse(result)) { return requests[index].callback(errors.InvalidResponse(result)); } requests[index].callback(null, (requests[index].format ? requests[index].format(result.result) : result.result)); } }); }); }
...
*
* @return {CipherParams} A cipher params object with the key, IV, and salt.
*
* @static
*
* @example
*
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password',
256/32, 128/32);
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
*/
execute: function (password, keySize, ivSize, salt) {
// Generate random salt
if (!salt) {
salt = WordArray.random(64/8);
}
...
testAddress = function (bloom, address) { if (!utils.isBloom(bloom)) throw "invalid bloom"; if (!utils.isAddress(address)) throw "invalid address"; return testBytes(bloom, address); }
n/a
testTopic = function (bloom, topic) { if (!utils.isBloom(bloom)) throw "invalid bloom"; if (!utils.isTopic(topic)) throw "invalid topic"; return testBytes(bloom, topic); }
n/a
bool = function () { this._inputFormatter = f.formatInputBool; this._outputFormatter = f.formatOutputBool; }
n/a
constructor = function () { this._inputFormatter = f.formatInputBool; this._outputFormatter = f.formatOutputBool; }
n/a
isType = function (name) { return !!name.match(/^bool(\[([0-9]*)\])*$/); }
...
* @method _requireType
* @param {String} type
* @returns {SolidityType}
* @throws {Error} throws if no matching type is found
*/
SolidityCoder.prototype._requireType = function (type) {
var solidityType = this._types.filter(function (t) {
return t.isType(type);
})[0];
if (!solidityType) {
throw Error('invalid solidity type!: ' + type);
}
return solidityType;
...
XMLHttpRequest = function () {
"use strict";
/**
* Private variables
*/
var self = this;
var http = require("http");
var https = require("https");
// Holds http.js objects
var request;
var response;
// Request settings
var settings = {};
// Disable header blacklist.
// Not part of XHR specs.
var disableHeaderCheck = false;
// Set some default headers
var defaultHeaders = {
"User-Agent": "node-XMLHttpRequest",
"Accept": "*/*",
};
var headers = {};
var headersCase = {};
// These headers are not user setable.
// The following are allowed but banned in the spec:
// * user-agent
var forbiddenRequestHeaders = [
"accept-charset",
"accept-encoding",
"access-control-request-headers",
"access-control-request-method",
"connection",
"content-length",
"content-transfer-encoding",
"cookie",
"cookie2",
"date",
"expect",
"host",
"keep-alive",
"origin",
"referer",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"via"
];
// These request methods are not allowed
var forbiddenRequestMethods = [
"TRACE",
"TRACK",
"CONNECT"
];
// Send flag
var sendFlag = false;
// Error flag, used when errors occur or abort is called
var errorFlag = false;
// Event listeners
var listeners = {};
/**
* Constants
*/
this.UNSENT = 0;
this.OPENED = 1;
this.HEADERS_RECEIVED = 2;
this.LOADING = 3;
this.DONE = 4;
/**
* Public vars
*/
// Current state
this.readyState = this.UNSENT;
// default ready state change handler in case one is not set or is set late
this.onreadystatechange = null;
// Result & response
this.responseText = "";
this.responseXML = "";
this.status = null;
this.statusText = null;
// Whether cross-site Access-Control requests should be made using
// credentials such as cookies or authorization headers
this.withCredentials = false;
/**
* Private methods
*/
/**
* Check if the specified header is allowed.
*
* @param string header Header to validate
* @return boolean False if not allowed, otherwise true
*/
var isAllowedHttpHeader = function(header) {
return disableHeaderCheck || (header && forbiddenRequestHeaders.indexOf(header.toLowerCase()) === -1);
};
/**
* Check if the specified method is allowed.
*
* @param string method Request method to validate
* @return boolean False if not allowed, otherwise true
*/
var isAllowedHttpMethod = function(method) {
return (method && forbiddenRequestMethods.indexOf(method) === -1);
};
/**
* Public methods
*/
/**
* Open the connection. Currently supports local server requests.
*
* @param string method Connection method (eg GET, POST)
* @param string url URL for the connection.
* @param boolean async Asynchronous connection. Default is true.
* @param string user Username for basic authentication (optional)
* @param string password Password for basic authentication (optional)
*/
this.open = function(method, url, async, user, password) {
this.abort();
errorFlag = false;
// Check for valid request method
if (!isAllowedHttpMethod(method)) {
throw new Error("SecurityError: Request method not allowed");
}
settings = {
"method": method,
"url": url.toString(),
"async": (typeof async !== "boolean" ? true : async),
"user": user || null,
"password": password || null
};
setState(this.OPENED);
};
/**
* Disables or enables isAllowedHttpHeader() check the request. Enabled by default.
* This does not conform to the W3C spec.
*
* @param boolean state Enable or disable header checking.
*/
this.setDisableHeaderCheck = function(state) {
disableHeaderCheck = state;
};
/**
* Sets a header for the request or appends the value if one is already set.
*
* @param string header Header name
* @param string value Header value
*/
this.setRequestHeader = function(header, value) {
if (this.readyState !== this.OPENED ...
n/a
bytes = function () { this._inputFormatter = f.formatInputBytes; this._outputFormatter = f.formatOutputBytes; }
n/a
constructor = function () { this._inputFormatter = f.formatInputBytes; this._outputFormatter = f.formatOutputBytes; }
n/a
isType = function (name) { return !!name.match(/^bytes([0-9]{1,})(\[([0-9]*)\])*$/); }
...
* @method _requireType
* @param {String} type
* @returns {SolidityType}
* @throws {Error} throws if no matching type is found
*/
SolidityCoder.prototype._requireType = function (type) {
var solidityType = this._types.filter(function (t) {
return t.isType(type);
})[0];
if (!solidityType) {
throw Error('invalid solidity type!: ' + type);
}
return solidityType;
...
contract = function (eth, abi) {
this.eth = eth;
this.abi = abi;
/**
* Should be called to create new contract on a blockchain
*
* @method new
* @param {Any} contract constructor param1 (optional)
* @param {Any} contract constructor param2 (optional)
* @param {Object} contract transaction object (required)
* @param {Function} callback
* @returns {Contract} returns contract instance
*/
this.new = function () {
/*jshint maxcomplexity: 7 */
var contract = new Contract(this.eth, this.abi);
// parse arguments
var options = {}; // required!
var callback;
var args = Array.prototype.slice.call(arguments);
if (utils.isFunction(args[args.length - 1])) {
callback = args.pop();
}
var last = args[args.length - 1];
if (utils.isObject(last) && !utils.isArray(last)) {
options = args.pop();
}
if (options.value > 0) {
var constructorAbi = abi.filter(function (json) {
return json.type === 'constructor' && json.inputs.length === args.length;
})[0] || {};
if (!constructorAbi.payable) {
throw new Error('Cannot send value to non-payable constructor');
}
}
var bytes = encodeConstructorParams(this.abi, args);
options.data += bytes;
if (callback) {
// wait for the contract address adn check if the code was deployed
this.eth.sendTransaction(options, function (err, hash) {
if (err) {
callback(err);
} else {
// add the transaction hash
contract.transactionHash = hash;
// call callback for the first time
callback(null, contract);
checkForContractAddress(contract, callback);
}
});
} else {
var hash = this.eth.sendTransaction(options);
// add the transaction hash
contract.transactionHash = hash;
checkForContractAddress(contract);
}
return contract;
};
this.new.getData = this.getData.bind(this);
}
...
"type": "uint256"
}
],
"name": "Approval",
"type": "event"
}
];
var myContract = new web3.eth.contract(jsoninterface);
...
at = function (address, callback) { var contract = new Contract(this.eth, this.abi, address); // this functions are not part of prototype, // because we dont want to spoil the interface addFunctionsToContract(contract); addEventsToContract(contract); if (callback) { callback(null, contract); } return contract; }
...
};
Eth.prototype.filter = function (fil, callback) {
return new Filter(this._requestManager, fil, watches.eth(), formatters.outputLogFormatter, callback);
};
Eth.prototype.namereg = function () {
return this.contract(namereg.global.abi).at(namereg.global.address);
};
Eth.prototype.icapNamereg = function () {
return this.contract(namereg.icap.abi).at(namereg.icap.address);
};
Eth.prototype.isSyncing = function (callback) {
...
getData = function () { var options = {}; // required! var args = Array.prototype.slice.call(arguments); var last = args[args.length - 1]; if (utils.isObject(last) && !utils.isArray(last)) { options = args.pop(); } var bytes = encodeConstructorParams(this.abi, args); options.data += bytes; return options.data; }
n/a
dynamicbytes = function () { this._inputFormatter = f.formatInputDynamicBytes; this._outputFormatter = f.formatOutputDynamicBytes; }
n/a
constructor = function () { this._inputFormatter = f.formatInputDynamicBytes; this._outputFormatter = f.formatOutputDynamicBytes; }
n/a
isDynamicType = function () { return true; }
...
var SolidityTypeDynamicBytes = require('./dynamicbytes');
var SolidityTypeString = require('./string');
var SolidityTypeReal = require('./real');
var SolidityTypeUReal = require('./ureal');
var SolidityTypeBytes = require('./bytes');
var isDynamic = function (solidityType, type) {
return solidityType.isDynamicType(type) ||
solidityType.isDynamicArray(type);
};
/**
* SolidityCoder prototype should be used to encode/decode solidity params of any type
*/
var SolidityCoder = function (types) {
...
isType = function (name) { return !!name.match(/^bytes(\[([0-9]*)\])*$/); }
...
* @method _requireType
* @param {String} type
* @returns {SolidityType}
* @throws {Error} throws if no matching type is found
*/
SolidityCoder.prototype._requireType = function (type) {
var solidityType = this._types.filter(function (t) {
return t.isType(type);
})[0];
if (!solidityType) {
throw Error('invalid solidity type!: ' + type);
}
return solidityType;
...
ConnectionTimeout = function (ms){ return new Error('CONNECTION TIMEOUT: timeout of ' + ms + ' ms achived'); }
...
}
callback(error, result);
}
};
request.ontimeout = function() {
callback(errors.ConnectionTimeout(this.timeout));
};
try {
request.send(JSON.stringify(payload));
} catch(error) {
callback(errors.InvalidConnection(this.host));
}
...
InvalidConnection = function (host){ return new Error('CONNECTION ERROR: Couldn\'t connect to node '+ host +'.'); }
...
*/
HttpProvider.prototype.send = function (payload) {
var request = this.prepareRequest(false);
try {
request.send(JSON.stringify(payload));
} catch(error) {
throw errors.InvalidConnection(this.host);
}
var result = request.responseText;
try {
result = JSON.parse(result);
} catch(e) {
...
InvalidNumberOfParams = function () { return new Error('Invalid number of input parameters'); }
...
*
* @method validateArgs
* @param {Array} arguments
* @throws {Error} if it is not
*/
Method.prototype.validateArgs = function (args) {
if (args.length !== this.params) {
throw errors.InvalidNumberOfParams();
}
};
/**
* Should be called to format input args of method
*
* @method formatInput
...
InvalidProvider = function () { return new Error('Provider not set or invalid'); }
...
*
* @method send
* @param {Object} data
* @return {Object}
*/
RequestManager.prototype.send = function (data) {
if (!this.provider) {
console.error(errors.InvalidProvider());
return null;
}
var payload = Jsonrpc.toPayload(data.method, data.params);
var result = this.provider.send(payload);
if (!Jsonrpc.isValidResponse(result)) {
...
InvalidResponse = function (result){ var message = !!result && !!result.error && !!result.error.message ? result.error.message : 'Invalid JSON RPC response: ' + JSON.stringify(result); return new Error(message); }
...
results = results || [];
requests.map(function (request, index) {
return results[index] || {};
}).forEach(function (result, index) {
if (requests[index].callback) {
if (!Jsonrpc.isValidResponse(result)) {
return requests[index].callback(errors.InvalidResponse(result));
}
requests[index].callback(null, (requests[index].format ? requests[index].format(result.result) : result.result));
}
});
});
};
...
function Eth(web3) { this._requestManager = web3._requestManager; var self = this; methods().forEach(function(method) { method.attachToObject(self); method.setRequestManager(self._requestManager); }); properties().forEach(function(p) { p.attachToObject(self); p.setRequestManager(self._requestManager); }); this.iban = Iban; this.sendIBANTransaction = transfer.bind(null, this); }
...
callback = arguments[arguments.length - 1];
if(arguments.length === 1)
options = null;
}
var o = this.encode(options);
var formatter = this.decode.bind(this);
return new Filter(this._requestManager, o, watches.eth(), formatter, callback);
};
AllSolidityEvents.prototype.attachToContract = function (contract) {
var execute = this.execute.bind(this);
contract.allEvents = execute;
};
...
contract = function (abi) { var factory = new Contract(this, abi); return factory; }
...
"type": "uint256"
}
],
"name": "Approval",
"type": "event"
}
];
var myContract = new web3.eth.contract(jsoninterface);
...
filter = function (fil, callback) { return new Filter(this._requestManager, fil, watches.eth(), formatters.outputLogFormatter, callback); }
...
*
* @method _requireType
* @param {String} type
* @returns {SolidityType}
* @throws {Error} throws if no matching type is found
*/
SolidityCoder.prototype._requireType = function (type) {
var solidityType = this._types.filter(function (t) {
return t.isType(type);
})[0];
if (!solidityType) {
throw Error('invalid solidity type!: ' + type);
}
...
icapNamereg = function () { return this.contract(namereg.icap.abi).at(namereg.icap.address); }
...
}
if (iban.isDirect()) {
return transferToAddress(eth, from, iban.address(), value, callback);
}
if (!callback) {
var address = eth.icapNamereg().addr(iban.institution());
return deposit(eth, from, address, value, iban.client());
}
eth.icapNamereg().addr(iban.institution(), function (err, address) {
return deposit(eth, from, address, value, iban.client(), callback);
});
...
isSyncing = function (callback) { return new IsSyncing(this._requestManager, callback); }
n/a
namereg = function () { return this.contract(namereg.global.abi).at(namereg.global.address); }
n/a
event = function (requestManager, json, address) { this._requestManager = requestManager; this._params = json.inputs; this._name = utils.transformToFullName(json); this._address = address; this._anonymous = json.anonymous; }
n/a
attachToContract = function (contract) { var execute = this.execute.bind(this); var displayName = this.displayName(); if (!contract[displayName]) { contract[displayName] = execute; } contract[displayName][this.typeName()] = this.execute.bind(this, contract); }
...
*/
var addFunctionsToContract = function (contract) {
contract.abi.filter(function (json) {
return json.type === 'function';
}).map(function (json) {
return new SolidityFunction(contract._eth, json, contract.address);
}).forEach(function (f) {
f.attachToContract(contract);
});
};
/**
* Should be called to add events to contract object
*
* @method addEventsToContract
...
decode = function (data) { data.data = data.data || ''; data.topics = data.topics || []; var argTopics = this._anonymous ? data.topics : data.topics.slice(1); var indexedData = argTopics.map(function (topics) { return topics.slice(2); }).join(""); var indexedParams = coder.decodeParams(this.types(true), indexedData); var notIndexedData = data.data.slice(2); var notIndexedParams = coder.decodeParams(this.types(false), notIndexedData); var result = formatters.outputLogFormatter(data); result.event = this.displayName(); result.address = data.address; result.args = this._params.reduce(function (acc, current) { acc[current.name] = current.indexed ? indexedParams.shift() : notIndexedParams.shift(); return acc; }, {}); delete result.data; delete result.topics; return result; }
...
* @return {Array} array of plain params
*/
SolidityCoder.prototype.decodeParams = function (types, bytes) {
var solidityTypes = this.getSolidityTypes(types);
var offsets = this.getOffsets(types, solidityTypes);
return solidityTypes.map(function (solidityType, index) {
return solidityType.decode(bytes, offsets[index], types[index], index);
});
};
SolidityCoder.prototype.getOffsets = function (types, solidityTypes) {
var lengths = solidityTypes.map(function (solidityType, index) {
return solidityType.staticPartLength(types[index]);
});
...
displayName = function () { return utils.extractDisplayName(this._name); }
...
var indexedData = argTopics.map(function (topics) { return topics.slice(2); }).join("");
var indexedParams = coder.decodeParams(this.types(true), indexedData);
var notIndexedData = data.data.slice(2);
var notIndexedParams = coder.decodeParams(this.types(false), notIndexedData);
var result = formatters.outputLogFormatter(data);
result.event = this.displayName();
result.address = data.address;
result.args = this._params.reduce(function (acc, current) {
acc[current.name] = current.indexed ? indexedParams.shift() : notIndexedParams.shift();
return acc;
}, {});
...
encode = function (indexed, options) { indexed = indexed || {}; options = options || {}; var result = {}; ['fromBlock', 'toBlock'].filter(function (f) { return options[f] !== undefined; }).forEach(function (f) { result[f] = formatters.inputBlockNumberFormatter(options[f]); }); result.topics = []; result.address = this._address; if (!this._anonymous) { result.topics.push('0x' + this.signature()); } var indexedTopics = this._params.filter(function (i) { return i.indexed === true; }).map(function (i) { var value = indexed[i.name]; if (value === undefined || value === null) { return null; } if (utils.isArray(value)) { return value.map(function (v) { return '0x' + coder.encodeParam(i.type, v); }); } return '0x' + coder.encodeParam(i.type, value); }); result.topics = result.topics.concat(indexedTopics); return result; }
...
* @param {Array} params
* @return {String} encoded list of params
*/
SolidityCoder.prototype.encodeParams = function (types, params) {
var solidityTypes = this.getSolidityTypes(types);
var encodeds = solidityTypes.map(function (solidityType, index) {
return solidityType.encode(params[index], types[index]);
});
var dynamicOffset = solidityTypes.reduce(function (acc, solidityType, index) {
var staticPartLength = solidityType.staticPartLength(types[index]);
var roundedStaticPartLength = Math.floor((staticPartLength + 31) / 32) * 32;
return acc + (isDynamic(solidityTypes[index], types[index]) ?
...
execute = function (indexed, options, callback) { if (utils.isFunction(arguments[arguments.length - 1])) { callback = arguments[arguments.length - 1]; if(arguments.length === 2) options = null; if(arguments.length === 1) { options = null; indexed = {}; } } var o = this.encode(indexed, options); var formatter = this.decode.bind(this); return new Filter(this._requestManager, o, watches.eth(), formatter, callback); }
...
*
* @return {CipherParams} A cipher params object with the key, IV, and salt.
*
* @static
*
* @example
*
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password',
256/32, 128/32);
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
*/
execute: function (password, keySize, ivSize, salt) {
// Generate random salt
if (!salt) {
salt = WordArray.random(64/8);
}
...
signature = function () { return sha3(this._name); }
...
result[f] = formatters.inputBlockNumberFormatter(options[f]);
});
result.topics = [];
result.address = this._address;
if (!this._anonymous) {
result.topics.push('0x' + this.signature());
}
var indexedTopics = this._params.filter(function (i) {
return i.indexed === true;
}).map(function (i) {
var value = indexed[i.name];
if (value === undefined || value === null) {
...
typeName = function () { return utils.extractTypeName(this._name); }
...
*/
SolidityEvent.prototype.attachToContract = function (contract) {
var execute = this.execute.bind(this);
var displayName = this.displayName();
if (!contract[displayName]) {
contract[displayName] = execute;
}
contract[displayName][this.typeName()] = this.execute.bind(this, contract);
};
module.exports = SolidityEvent;
},{"../solidity/coder":7,"../utils/sha3":19,"../utils/utils":20,"./filter":29,"./formatters
":30,"./methods/watches":43}],28:[function(require,module,exports){
var formatters = require('./formatters');
...
types = function (indexed) { return this._params.filter(function (i) { return i.indexed === indexed; }).map(function (i) { return i.type; }); }
...
SolidityEvent.prototype.decode = function (data) {
data.data = data.data || '';
data.topics = data.topics || [];
var argTopics = this._anonymous ? data.topics : data.topics.slice(1);
var indexedData = argTopics.map(function (topics) { return topics.slice(2); }).join("");
var indexedParams = coder.decodeParams(this.types(true), indexedData);
var notIndexedData = data.data.slice(2);
var notIndexedParams = coder.decodeParams(this.types(false), notIndexedData);
var result = formatters.outputLogFormatter(data);
result.event = this.displayName();
result.address = data.address;
...
filter = function (requestManager, options, methods, formatter, callback, filterCreationErrorCallback) { var self = this; var implementation = {}; methods.forEach(function (method) { method.setRequestManager(requestManager); method.attachToObject(implementation); }); this.requestManager = requestManager; this.options = getOptions(options); this.implementation = implementation; this.filterId = null; this.callbacks = []; this.getLogsCallbacks = []; this.pollFilters = []; this.formatter = formatter; this.implementation.newFilter(this.options, function(error, id){ if(error) { self.callbacks.forEach(function(cb){ cb(error); }); filterCreationErrorCallback(error); } else { self.filterId = id; // check if there are get pending callbacks as a consequence // of calling get() with filterId unassigned. self.getLogsCallbacks.forEach(function (cb){ self.get(cb); }); self.getLogsCallbacks = []; // get filter logs for the already existing watch calls self.callbacks.forEach(function(cb){ getLogsAtStart(self, cb); }); if(self.callbacks.length > 0) pollFilter(self); // start to watch immediately if(typeof callback === 'function') { return self.watch(callback); } } }); return this; }
...
*
* @method _requireType
* @param {String} type
* @returns {SolidityType}
* @throws {Error} throws if no matching type is found
*/
SolidityCoder.prototype._requireType = function (type) {
var solidityType = this._types.filter(function (t) {
return t.isType(type);
})[0];
if (!solidityType) {
throw Error('invalid solidity type!: ' + type);
}
...
get = function (callback) { var self = this; if (utils.isFunction(callback)) { if (this.filterId === null) { // If filterId is not set yet, call it back // when newFilter() assigns it. this.getLogsCallbacks.push(callback); } else { this.implementation.getLogs(this.filterId, function(err, res){ if (err) { callback(err); } else { callback(null, res.map(function (log) { return self.formatter ? self.formatter(log) : log; })); } }); } } else { if (this.filterId === null) { throw new Error('Filter ID Error: filter().get() can\'t be chained synchronous, please provide a callback for the get () method.'); } var logs = this.implementation.getLogs(this.filterId); return logs.map(function (log) { return self.formatter ? self.formatter(log) : log; }); } return this; }
...
@method getLogsAtStart
@param {Object} self
@param {funciton}
*/
var getLogsAtStart = function(self, callback){
// call getFilterLogs for the first watch callback start
if (!utils.isString(self.options)) {
self.get(function (err, messages) {
// don't send all the responses to all the watches again... just to self one
if (err) {
callback(err);
}
if(utils.isArray(messages)) {
messages.forEach(function (message) {
...
stopWatching = function (callback) { this.requestManager.stopPolling(this.filterId); this.callbacks = []; // remove filter async if (callback) { this.implementation.uninstallFilter(this.filterId, callback); } else { return this.implementation.uninstallFilter(this.filterId); } }
...
var filter = contract._eth.filter('latest', function(e){
if (!e && !callbackFired) {
count++;
// stop watching after 50 blocks (timeout)
if (count > 50) {
filter.stopWatching(function() {});
callbackFired = true;
if (callback)
callback(new Error('Contract transaction couldn\'t be found after 50 blocks'));
else
throw new Error('Contract transaction couldn\'t be found after 50 blocks');
...
watch = function (callback) { this.callbacks.push(callback); if(this.filterId) { getLogsAtStart(this, callback); pollFilter(this); } return this; }
...
.pipe(gulp.dest( DEST ))
.pipe(streamify(uglify()))
.pipe(rename(dst + '.min.js'))
.pipe(gulp.dest( DEST ));
});
gulp.task('watch', function() {
gulp.watch(['./lib/*.js'], ['lint', 'build']);
});
gulp.task('default', ['version', 'lint', 'clean', 'light', 'standalone'
;]);
...
formatInputBool = function (value) { var result = '000000000000000000000000000000000000000000000000000000000000000' + (value ? '1' : '0'); return new SolidityParam(result); }
n/a
formatInputBytes = function (value) { var result = utils.toHex(value).substr(2); var l = Math.floor((result.length + 63) / 64); result = utils.padRight(result, l * 64); return new SolidityParam(result); }
n/a
formatInputDynamicBytes = function (value) { var result = utils.toHex(value).substr(2); var length = result.length / 2; var l = Math.floor((result.length + 63) / 64); result = utils.padRight(result, l * 64); return new SolidityParam(formatInputInt(length).value + result); }
n/a
formatInputInt = function (value) { BigNumber.config(c.ETH_BIGNUMBER_ROUNDING_MODE); var result = utils.padLeft(utils.toTwosComplement(value).toString(16), 64); return new SolidityParam(result); }
...
SolidityCoder.prototype.encodeMultiWithOffset = function (types, solidityTypes, encodeds, dynamicOffset) {
var result = "";
var self = this;
types.forEach(function (type, i) {
if (isDynamic(solidityTypes[i], types[i])) {
result += f.formatInputInt(dynamicOffset).encode();
var e = self.encodeWithOffset(types[i], solidityTypes[i], encodeds[i], dynamicOffset);
dynamicOffset += e.length / 2;
} else {
// don't add length to dynamicOffset. it's already counted
result += self.encodeWithOffset(types[i], solidityTypes[i], encodeds[i], dynamicOffset);
}
...
formatInputReal = function (value) { return formatInputInt(new BigNumber(value).times(new BigNumber(2).pow(128))); }
n/a
formatInputString = function (value) { var result = utils.fromUtf8(value).substr(2); var length = result.length / 2; var l = Math.floor((result.length + 63) / 64); result = utils.padRight(result, l * 64); return new SolidityParam(formatInputInt(length).value + result); }
n/a
formatOutputAddress = function (param) { var value = param.staticPart(); return "0x" + value.slice(value.length - 40, value.length); }
n/a
formatOutputBool = function (param) { return param.staticPart() === '0000000000000000000000000000000000000000000000000000000000000001' ? true : false; }
n/a
formatOutputBytes = function (param, name) { var matches = name.match(/^bytes([0-9]*)/); var size = parseInt(matches[1]); return '0x' + param.staticPart().slice(0, 2 * size); }
n/a
formatOutputDynamicBytes = function (param) { var length = (new BigNumber(param.dynamicPart().slice(0, 64), 16)).toNumber() * 2; return '0x' + param.dynamicPart().substr(64, length); }
n/a
formatOutputInt = function (param) { var value = param.staticPart() || "0"; // check if it's negative number // it it is, return two's complement if (signedIsNegative(value)) { return new BigNumber(value, 16).minus(new BigNumber('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16)).minus(1); } return new BigNumber(value, 16); }
n/a
formatOutputReal = function (param) { return formatOutputInt(param).dividedBy(new BigNumber(2).pow(128)); }
n/a
formatOutputString = function (param) { var length = (new BigNumber(param.dynamicPart().slice(0, 64), 16)).toNumber() * 2; return utils.toUtf8(param.dynamicPart().substr(64, length)); }
n/a
formatOutputUInt = function (param) { var value = param.staticPart() || "0"; return new BigNumber(value, 16); }
n/a
formatOutputUReal = function (param) { return formatOutputUInt(param).dividedBy(new BigNumber(2).pow(128)); }
n/a
function = function (eth, json, address) { this._eth = eth; this._inputTypes = json.inputs.map(function (i) { return i.type; }); this._outputTypes = json.outputs.map(function (i) { return i.type; }); this._constant = json.constant; this._payable = json.payable; this._name = utils.transformToFullName(json); this._address = address; }
n/a
attachToContract = function (contract) { var execute = this.execute.bind(this); execute.request = this.request.bind(this); execute.call = this.call.bind(this); execute.sendTransaction = this.sendTransaction.bind(this); execute.estimateGas = this.estimateGas.bind(this); execute.getData = this.getData.bind(this); var displayName = this.displayName(); if (!contract[displayName]) { contract[displayName] = execute; } contract[displayName][this.typeName()] = execute; // circular!!!! }
...
*/
var addFunctionsToContract = function (contract) {
contract.abi.filter(function (json) {
return json.type === 'function';
}).map(function (json) {
return new SolidityFunction(contract._eth, json, contract.address);
}).forEach(function (f) {
f.attachToContract(contract);
});
};
/**
* Should be called to add events to contract object
*
* @method addEventsToContract
...
call = function () { var args = Array.prototype.slice.call(arguments).filter(function (a) {return a !== undefined; }); var callback = this.extractCallback(args); var defaultBlock = this.extractDefaultBlock(args); var payload = this.toPayload(args); if (!callback) { var output = this._eth.call(payload, defaultBlock); return this.unpackOutput(output); } var self = this; this._eth.call(payload, defaultBlock, function (error, output) { if (error) return callback(error, null); var unpacked = null; try { unpacked = self.unpackOutput(output); } catch (e) { error = e; } callback(error, unpacked); }); }
...
itemsCopy = items.slice();
```
- To convert an array-like object to an array, use Array#slice.
```javascript
function trigger() {
var args = Array.prototype.slice.call(arguments);
...
}
```
**[⬆ back to top](#table-of-contents)**
...
displayName = function () { return utils.extractDisplayName(this._name); }
...
var indexedData = argTopics.map(function (topics) { return topics.slice(2); }).join("");
var indexedParams = coder.decodeParams(this.types(true), indexedData);
var notIndexedData = data.data.slice(2);
var notIndexedParams = coder.decodeParams(this.types(false), notIndexedData);
var result = formatters.outputLogFormatter(data);
result.event = this.displayName();
result.address = data.address;
result.args = this._params.reduce(function (acc, current) {
acc[current.name] = current.indexed ? indexedParams.shift() : notIndexedParams.shift();
return acc;
}, {});
...
estimateGas = function () { var args = Array.prototype.slice.call(arguments); var callback = this.extractCallback(args); var payload = this.toPayload(args); if (!callback) { return this._eth.estimateGas(payload); } this._eth.estimateGas(payload, callback); }
...
*/
SolidityFunction.prototype.estimateGas = function () {
var args = Array.prototype.slice.call(arguments);
var callback = this.extractCallback(args);
var payload = this.toPayload(args);
if (!callback) {
return this._eth.estimateGas(payload);
}
this._eth.estimateGas(payload, callback);
};
/**
* Return the encoded data of the call
...
execute = function () { var transaction = !this._constant; // send transaction if (transaction) { return this.sendTransaction.apply(this, Array.prototype.slice.call(arguments)); } // call return this.call.apply(this, Array.prototype.slice.call(arguments)); }
...
*
* @return {CipherParams} A cipher params object with the key, IV, and salt.
*
* @static
*
* @example
*
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password',
256/32, 128/32);
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
*/
execute: function (password, keySize, ivSize, salt) {
// Generate random salt
if (!salt) {
salt = WordArray.random(64/8);
}
...
extractCallback = function (args) { if (utils.isFunction(args[args.length - 1])) { return args.pop(); // modify the args array! } }
...
* @param {function} If the last argument is a function, the contract function
* call will be asynchronous, and the callback will be passed the
* error and result.
* @return {String} output bytes
*/
SolidityFunction.prototype.call = function () {
var args = Array.prototype.slice.call(arguments).filter(function (a) {return a !== undefined; });
var callback = this.extractCallback(args);
var defaultBlock = this.extractDefaultBlock(args);
var payload = this.toPayload(args);
if (!callback) {
var output = this._eth.call(payload, defaultBlock);
return this.unpackOutput(output);
...
extractDefaultBlock = function (args) { if (args.length > this._inputTypes.length && !utils.isObject(args[args.length -1])) { return formatters.inputDefaultBlockNumberFormatter(args.pop()); // modify the args array! } }
...
* call will be asynchronous, and the callback will be passed the
* error and result.
* @return {String} output bytes
*/
SolidityFunction.prototype.call = function () {
var args = Array.prototype.slice.call(arguments).filter(function (a) {return a !== undefined; });
var callback = this.extractCallback(args);
var defaultBlock = this.extractDefaultBlock(args);
var payload = this.toPayload(args);
if (!callback) {
var output = this._eth.call(payload, defaultBlock);
return this.unpackOutput(output);
}
...
getData = function () { var args = Array.prototype.slice.call(arguments); var payload = this.toPayload(args); return payload.data; }
n/a
request = function () { var args = Array.prototype.slice.call(arguments); var callback = this.extractCallback(args); var payload = this.toPayload(args); var format = this.unpackOutput.bind(this); return { method: this._constant ? 'eth_call' : 'eth_sendTransaction', callback: callback, params: [payload], format: format }; }
n/a
sendTransaction = function () { var args = Array.prototype.slice.call(arguments).filter(function (a) {return a !== undefined; }); var callback = this.extractCallback(args); var payload = this.toPayload(args); if (payload.value > 0 && !this._payable) { throw new Error('Cannot send value to non-payable function'); } if (!callback) { return this._eth.sendTransaction(payload); } this._eth.sendTransaction(payload, callback); }
...
var bytes = encodeConstructorParams(this.abi, args);
options.data += bytes;
if (callback) {
// wait for the contract address adn check if the code was deployed
this.eth.sendTransaction(options, function (err, hash) {
if (err) {
callback(err);
} else {
// add the transaction hash
contract.transactionHash = hash;
// call callback for the first time
...
signature = function () { return sha3(this._name).slice(0, 8); }
...
result[f] = formatters.inputBlockNumberFormatter(options[f]);
});
result.topics = [];
result.address = this._address;
if (!this._anonymous) {
result.topics.push('0x' + this.signature());
}
var indexedTopics = this._params.filter(function (i) {
return i.indexed === true;
}).map(function (i) {
var value = indexed[i.name];
if (value === undefined || value === null) {
...
toPayload = function (args) { var options = {}; if (args.length > this._inputTypes.length && utils.isObject(args[args.length -1])) { options = args[args.length - 1]; } options.to = this._address; options.data = '0x' + this.signature() + coder.encodeParams(this._inputTypes, args); return options; }
...
* error and result.
* @return {String} output bytes
*/
SolidityFunction.prototype.call = function () {
var args = Array.prototype.slice.call(arguments).filter(function (a) {return a !== undefined; });
var callback = this.extractCallback(args);
var defaultBlock = this.extractDefaultBlock(args);
var payload = this.toPayload(args);
if (!callback) {
var output = this._eth.call(payload, defaultBlock);
return this.unpackOutput(output);
}
...
typeName = function () { return utils.extractTypeName(this._name); }
...
*/
SolidityEvent.prototype.attachToContract = function (contract) {
var execute = this.execute.bind(this);
var displayName = this.displayName();
if (!contract[displayName]) {
contract[displayName] = execute;
}
contract[displayName][this.typeName()] = this.execute.bind(this, contract);
};
module.exports = SolidityEvent;
},{"../solidity/coder":7,"../utils/sha3":19,"../utils/utils":20,"./filter":29,"./formatters
":30,"./methods/watches":43}],28:[function(require,module,exports){
var formatters = require('./formatters');
...
unpackOutput = function (output) { if (!output) { return; } output = output.length >= 2 ? output.slice(2) : output; var result = coder.decodeParams(this._outputTypes, output); return result.length === 1 ? result[0] : result; }
...
var callback = this.extractCallback(args);
var defaultBlock = this.extractDefaultBlock(args);
var payload = this.toPayload(args);
if (!callback) {
var output = this._eth.call(payload, defaultBlock);
return this.unpackOutput(output);
}
var self = this;
this._eth.call(payload, defaultBlock, function (error, output) {
if (error) return callback(error, null);
var unpacked = null;
...
iban = function (iban) { this._iban = iban; }
n/a
createIndirect = function (options) { return Iban.fromBban('ETH' + options.institution + options.identifier); }
...
}
document.getElementById('ibanValidation').innerText = ' - IBAN number correct';
};
function updateIBAN(ok) {
var exchangeId = document.getElementById('exchange').value;
var clientId = document.getElementById('client').value;
iban = web3.eth.iban.createIndirect({
institution: exchangeId,
identifier: clientId
});
document.getElementById('iban').innerText = iban.toString();
validateIBAN();
};
...
fromAddress = function (address) { var asBn = new BigNumber(address, 16); var base36 = asBn.toString(36); var padded = padLeft(base36, 15); return Iban.fromBban(padded.toUpperCase()); }
n/a
fromBban = function (bban) { var countryCode = 'XE'; var remainder = mod9710(iso13616Prepare(countryCode + '00' + bban)); var checkDigit = ('0' + (98 - remainder)).slice(-2); return new Iban(countryCode + checkDigit + bban); }
...
* @param {String} address
* @return {Iban} the IBAN object
*/
Iban.fromAddress = function (address) {
var asBn = new BigNumber(address, 16);
var base36 = asBn.toString(36);
var padded = padLeft(base36, 15);
return Iban.fromBban(padded.toUpperCase());
};
/**
* Convert the passed BBAN to an IBAN for this country specification.
* Please note that <i>"generation of the IBAN shall be the exclusive responsibility of the bank/branch servicing
the account"</i>.
* This method implements the preferred algorithm described in http://en.wikipedia.org/wiki/International_Bank_Account_Number#Generating_IBAN_check_digits
*
...
isValid = function (iban) { var i = new Iban(iban); return i.isValid(); }
...
});
return post;
};
var inputAddressFormatter = function (address) {
var iban = new Iban(address);
if (iban.isValid() && iban.isDirect()) {
return '0x' + iban.address();
} else if (utils.isStrictAddress(address)) {
return address;
} else if (utils.isAddress(address)) {
return '0x' + address;
}
throw new Error('invalid address');
...
address = function () { if (this.isDirect()) { var base36 = this._iban.substr(4); var asBn = new BigNumber(base36, 36); return padLeft(asBn.toString(16), 20); } return ''; }
...
};
/**
* Transforms direct icap to address
*/
Web3.prototype.fromICAP = function (icap) {
var iban = new Iban(icap);
return iban.address();
};
var properties = function () {
return [
new Property({
name: 'version.node',
getter: 'web3_clientVersion'
...
checksum = function () { return this._iban.substr(2, 2); }
n/a
client = function () { return this.isIndirect() ? this._iban.substr(11) : ''; }
...
if (iban.isDirect()) {
return transferToAddress(eth, from, iban.address(), value, callback);
}
if (!callback) {
var address = eth.icapNamereg().addr(iban.institution());
return deposit(eth, from, address, value, iban.client());
}
eth.icapNamereg().addr(iban.institution(), function (err, address) {
return deposit(eth, from, address, value, iban.client(), callback);
});
};
...
institution = function () { return this.isIndirect() ? this._iban.substr(7, 4) : ''; }
...
}
if (iban.isDirect()) {
return transferToAddress(eth, from, iban.address(), value, callback);
}
if (!callback) {
var address = eth.icapNamereg().addr(iban.institution());
return deposit(eth, from, address, value, iban.client());
}
eth.icapNamereg().addr(iban.institution(), function (err, address) {
return deposit(eth, from, address, value, iban.client(), callback);
});
...
isDirect = function () { return this._iban.length === 34 || this._iban.length === 35; }
...
});
return post;
};
var inputAddressFormatter = function (address) {
var iban = new Iban(address);
if (iban.isValid() && iban.isDirect()) {
return '0x' + iban.address();
} else if (utils.isStrictAddress(address)) {
return address;
} else if (utils.isAddress(address)) {
return '0x' + address;
}
throw new Error('invalid address');
...
isIndirect = function () { return this._iban.length === 20; }
...
* Should be called to get institution identifier
* eg. XREG
*
* @method institution
* @returns {String} institution identifier
*/
Iban.prototype.institution = function () {
return this.isIndirect() ? this._iban.substr(7, 4) : '';
};
/**
* Should be called to get client identifier within institution
* eg. GAVOFYORK
*
* @method client
...
isValid = function () { return /^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$/.test(this._iban) && mod9710(iso13616Prepare(this._iban)) === 1; }
...
});
return post;
};
var inputAddressFormatter = function (address) {
var iban = new Iban(address);
if (iban.isValid() && iban.isDirect()) {
return '0x' + iban.address();
} else if (utils.isStrictAddress(address)) {
return address;
} else if (utils.isAddress(address)) {
return '0x' + address;
}
throw new Error('invalid address');
...
toString = function () { return this._iban; }
...
*
* @method formatInputInt
* @param {String|Number|BigNumber} value that needs to be formatted
* @returns {SolidityParam}
*/
var formatInputInt = function (value) {
BigNumber.config(c.ETH_BIGNUMBER_ROUNDING_MODE);
var result = utils.padLeft(utils.toTwosComplement(value).toString(16), 64);
return new SolidityParam(result);
};
/**
* Formats input bytes
*
* @method formatInputBytes
...
int = function () { this._inputFormatter = f.formatInputInt; this._outputFormatter = f.formatOutputInt; }
n/a
constructor = function () { this._inputFormatter = f.formatInputInt; this._outputFormatter = f.formatOutputInt; }
n/a
isType = function (name) { return !!name.match(/^int([0-9]*)?(\[([0-9]*)\])*$/); }
...
* @method _requireType
* @param {String} type
* @returns {SolidityType}
* @throws {Error} throws if no matching type is found
*/
SolidityCoder.prototype._requireType = function (type) {
var solidityType = this._types.filter(function (t) {
return t.isType(type);
})[0];
if (!solidityType) {
throw Error('invalid solidity type!: ' + type);
}
return solidityType;
...
isValidResponse = function (response) { return Array.isArray(response) ? response.every(validateSingleMessage) : validateSingleMessage(response); function validateSingleMessage(message){ return !!message && !message.error && message.jsonrpc === '2.0' && typeof message.id === 'number' && message.result !== undefined; // only undefined is not valid json object } }
...
this.requestManager.sendBatch(requests, function (err, results) {
results = results || [];
requests.map(function (request, index) {
return results[index] || {};
}).forEach(function (result, index) {
if (requests[index].callback) {
if (!Jsonrpc.isValidResponse(result)) {
return requests[index].callback(errors.InvalidResponse(result));
}
requests[index].callback(null, (requests[index].format ? requests[index].format(result.result) : result.result));
}
});
});
...
toBatchPayload = function (messages) { return messages.map(function (message) { return Jsonrpc.toPayload(message.method, message.params); }); }
...
* @param {Function} callback
*/
RequestManager.prototype.sendBatch = function (data, callback) {
if (!this.provider) {
return callback(errors.InvalidProvider());
}
var payload = Jsonrpc.toBatchPayload(data);
this.provider.sendAsync(payload, function (err, results) {
if (err) {
return callback(err);
}
if (!utils.isArray(results)) {
...
toPayload = function (method, params) { if (!method) console.error('jsonrpc method should be specified!'); // advance message ID Jsonrpc.messageId++; return { jsonrpc: '2.0', id: Jsonrpc.messageId, method: method, params: params || [] }; }
...
* error and result.
* @return {String} output bytes
*/
SolidityFunction.prototype.call = function () {
var args = Array.prototype.slice.call(arguments).filter(function (a) {return a !== undefined; });
var callback = this.extractCallback(args);
var defaultBlock = this.extractDefaultBlock(args);
var payload = this.toPayload(args);
if (!callback) {
var output = this._eth.call(payload, defaultBlock);
return this.unpackOutput(output);
}
...
method = function (options) { this.name = options.name; this.call = options.call; this.params = options.params || 0; this.inputFormatter = options.inputFormatter; this.outputFormatter = options.outputFormatter; this.requestManager = null; }
n/a
attachToObject = function (obj) { var func = this.buildCall(); func.call = this.call; // TODO!!! that's ugly. filter.js uses it var name = this.name.split('.'); if (name.length > 1) { obj[name[0]] = obj[name[0]] || {}; obj[name[0]][name[1]] = func; } else { obj[name[0]] = func; } }
...
extendedObject = web3[extension.property];
} else {
extendedObject = web3;
}
if (extension.methods) {
extension.methods.forEach(function (method) {
method.attachToObject(extendedObject);
method.setRequestManager(web3._requestManager);
});
}
if (extension.properties) {
extension.properties.forEach(function (property) {
property.attachToObject(extendedObject);
...
buildCall = function () { var method = this; var send = function () { var payload = method.toPayload(Array.prototype.slice.call(arguments)); if (payload.callback) { return method.requestManager.sendAsync(payload, function (err, result) { payload.callback(err, method.formatOutput(result)); }); } return method.formatOutput(method.requestManager.send(payload)); }; send.request = this.request.bind(this); return send; }
...
method: call,
params: params,
callback: callback
};
};
Method.prototype.attachToObject = function (obj) {
var func = this.buildCall();
func.call = this.call; // TODO!!! that's ugly. filter.js uses it
var name = this.name.split('.');
if (name.length > 1) {
obj[name[0]] = obj[name[0]] || {};
obj[name[0]][name[1]] = func;
} else {
obj[name[0]] = func;
...
extractCallback = function (args) { if (utils.isFunction(args[args.length - 1])) { return args.pop(); // modify the args array! } }
...
* @param {function} If the last argument is a function, the contract function
* call will be asynchronous, and the callback will be passed the
* error and result.
* @return {String} output bytes
*/
SolidityFunction.prototype.call = function () {
var args = Array.prototype.slice.call(arguments).filter(function (a) {return a !== undefined; });
var callback = this.extractCallback(args);
var defaultBlock = this.extractDefaultBlock(args);
var payload = this.toPayload(args);
if (!callback) {
var output = this._eth.call(payload, defaultBlock);
return this.unpackOutput(output);
...
formatInput = function (args) { if (!this.inputFormatter) { return args; } return this.inputFormatter.map(function (formatter, index) { return formatter ? formatter(args[index]) : args[index]; }); }
...
* @method toPayload
* @param {Array} args
* @return {Object}
*/
Method.prototype.toPayload = function (args) {
var call = this.getCall(args);
var callback = this.extractCallback(args);
var params = this.formatInput(args);
this.validateArgs(params);
return {
method: call,
params: params,
callback: callback
};
...
formatOutput = function (result) { return this.outputFormatter && result ? this.outputFormatter(result) : result; }
...
Method.prototype.buildCall = function() {
var method = this;
var send = function () {
var payload = method.toPayload(Array.prototype.slice.call(arguments));
if (payload.callback) {
return method.requestManager.sendAsync(payload, function (err, result) {
payload.callback(err, method.formatOutput(result));
});
}
return method.formatOutput(method.requestManager.send(payload));
};
send.request = this.request.bind(this);
return send;
};
...
getCall = function (args) { return utils.isFunction(this.call) ? this.call(args) : this.call; }
...
* Should create payload from given input args
*
* @method toPayload
* @param {Array} args
* @return {Object}
*/
Method.prototype.toPayload = function (args) {
var call = this.getCall(args);
var callback = this.extractCallback(args);
var params = this.formatInput(args);
this.validateArgs(params);
return {
method: call,
params: params,
...
request = function () { var payload = this.toPayload(Array.prototype.slice.call(arguments)); payload.format = this.formatOutput.bind(this); return payload; }
n/a
setRequestManager = function (rm) { this.requestManager = rm; }
...
} else {
extendedObject = web3;
}
if (extension.methods) {
extension.methods.forEach(function (method) {
method.attachToObject(extendedObject);
method.setRequestManager(web3._requestManager);
});
}
if (extension.properties) {
extension.properties.forEach(function (property) {
property.attachToObject(extendedObject);
property.setRequestManager(web3._requestManager);
...
toPayload = function (args) { var call = this.getCall(args); var callback = this.extractCallback(args); var params = this.formatInput(args); this.validateArgs(params); return { method: call, params: params, callback: callback }; }
...
* error and result.
* @return {String} output bytes
*/
SolidityFunction.prototype.call = function () {
var args = Array.prototype.slice.call(arguments).filter(function (a) {return a !== undefined; });
var callback = this.extractCallback(args);
var defaultBlock = this.extractDefaultBlock(args);
var payload = this.toPayload(args);
if (!callback) {
var output = this._eth.call(payload, defaultBlock);
return this.unpackOutput(output);
}
...
validateArgs = function (args) { if (args.length !== this.params) { throw errors.InvalidNumberOfParams(); } }
...
* @param {Array} args
* @return {Object}
*/
Method.prototype.toPayload = function (args) {
var call = this.getCall(args);
var callback = this.extractCallback(args);
var params = this.formatInput(args);
this.validateArgs(params);
return {
method: call,
params: params,
callback: callback
};
};
...
param = function (value, offset) { this.value = value || ''; this.offset = offset; // offset in bytes }
n/a
encodeList = function (params) { // updating offsets var totalOffset = params.length * 32; var offsetParams = params.map(function (param) { if (!param.isDynamic()) { return param; } var offset = totalOffset; totalOffset += param.dynamicPartLength(); return param.withOffset(offset); }); // encode everything! return offsetParams.reduce(function (result, param) { return result + param.dynamicPart(); }, offsetParams.reduce(function (result, param) { return result + param.staticPart(); }, '')); }
n/a
combine = function (param) { return new SolidityParam(this.value + param.value); }
n/a
dynamicPart = function () { return this.isDynamic() ? this.value : ''; }
...
* Should be used to format output bytes
*
* @method formatOutputDynamicBytes
* @param {SolidityParam} left-aligned hex representation of string
* @returns {String} hex string
*/
var formatOutputDynamicBytes = function (param) {
var length = (new BigNumber(param.dynamicPart().slice(0, 64), 16)).toNumber() * 2;
return '0x' + param.dynamicPart().substr(64, length);
};
/**
* Should be used to format output string
*
* @method formatOutputString
...
dynamicPartLength = function () { return this.dynamicPart().length / 2; }
...
// updating offsets
var totalOffset = params.length * 32;
var offsetParams = params.map(function (param) {
if (!param.isDynamic()) {
return param;
}
var offset = totalOffset;
totalOffset += param.dynamicPartLength();
return param.withOffset(offset);
});
// encode everything!
return offsetParams.reduce(function (result, param) {
return result + param.dynamicPart();
}, offsetParams.reduce(function (result, param) {
...
encode = function () { return this.staticPart() + this.dynamicPart(); }
...
* @param {Array} params
* @return {String} encoded list of params
*/
SolidityCoder.prototype.encodeParams = function (types, params) {
var solidityTypes = this.getSolidityTypes(types);
var encodeds = solidityTypes.map(function (solidityType, index) {
return solidityType.encode(params[index], types[index]);
});
var dynamicOffset = solidityTypes.reduce(function (acc, solidityType, index) {
var staticPartLength = solidityType.staticPartLength(types[index]);
var roundedStaticPartLength = Math.floor((staticPartLength + 31) / 32) * 32;
return acc + (isDynamic(solidityTypes[index], types[index]) ?
...
isDynamic = function () { return this.offset !== undefined; }
...
/**
* This method should be called to transform offset to bytes
*
* @method offsetAsBytes
* @returns {String} bytes representation of offset
*/
SolidityParam.prototype.offsetAsBytes = function () {
return !this.isDynamic() ? '' : utils.padLeft(utils.toTwosComplement(this
.offset).toString(16), 64);
};
/**
* This method should be called to get static part of param
*
* @method staticPart
* @returns {String} offset if it is a dynamic param, otherwise value
...
offsetAsBytes = function () { return !this.isDynamic() ? '' : utils.padLeft(utils.toTwosComplement(this.offset).toString(16), 64); }
...
* @method staticPart
* @returns {String} offset if it is a dynamic param, otherwise value
*/
SolidityParam.prototype.staticPart = function () {
if (!this.isDynamic()) {
return this.value;
}
return this.offsetAsBytes();
};
/**
* This method should be called to get dynamic part of param
*
* @method dynamicPart
* @returns {String} returns a value if it is a dynamic param, otherwise empty string
...
staticPart = function () { if (!this.isDynamic()) { return this.value; } return this.offsetAsBytes(); }
...
* Formats right-aligned output bytes to int
*
* @method formatOutputInt
* @param {SolidityParam} param
* @returns {BigNumber} right-aligned output bytes formatted to big number
*/
var formatOutputInt = function (param) {
var value = param.staticPart() || "0";
// check if it's negative number
// it it is, return two's complement
if (signedIsNegative(value)) {
return new BigNumber(value, 16).minus(new BigNumber('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
x27;, 16)).minus(1);
}
return new BigNumber(value, 16);
...
withOffset = function (offset) { return new SolidityParam(this.value, offset); }
...
var totalOffset = params.length * 32;
var offsetParams = params.map(function (param) {
if (!param.isDynamic()) {
return param;
}
var offset = totalOffset;
totalOffset += param.dynamicPartLength();
return param.withOffset(offset);
});
// encode everything!
return offsetParams.reduce(function (result, param) {
return result + param.dynamicPart();
}, offsetParams.reduce(function (result, param) {
return result + param.staticPart();
...
property = function (options) { this.name = options.name; this.getter = options.getter; this.setter = options.setter; this.outputFormatter = options.outputFormatter; this.inputFormatter = options.inputFormatter; this.requestManager = null; }
n/a
attachToObject = function (obj) { var proto = { get: this.buildGet(), enumerable: true }; var names = this.name.split('.'); var name = names[0]; if (names.length > 1) { obj[names[0]] = obj[names[0]] || {}; obj = obj[names[0]]; name = names[1]; } Object.defineProperty(obj, name, proto); obj[asyncGetterName(name)] = this.buildAsyncGet(); }
...
extendedObject = web3[extension.property];
} else {
extendedObject = web3;
}
if (extension.methods) {
extension.methods.forEach(function (method) {
method.attachToObject(extendedObject);
method.setRequestManager(web3._requestManager);
});
}
if (extension.properties) {
extension.properties.forEach(function (property) {
property.attachToObject(extendedObject);
...
buildAsyncGet = function () { var property = this; var get = function (callback) { property.requestManager.sendAsync({ method: property.getter }, function (err, result) { callback(err, property.formatOutput(result)); }); }; get.request = this.request.bind(this); return get; }
...
if (names.length > 1) {
obj[names[0]] = obj[names[0]] || {};
obj = obj[names[0]];
name = names[1];
}
Object.defineProperty(obj, name, proto);
obj[asyncGetterName(name)] = this.buildAsyncGet();
};
var asyncGetterName = function (name) {
return 'get' + name.charAt(0).toUpperCase() + name.slice(1);
};
Property.prototype.buildGet = function () {
...
buildGet = function () { var property = this; return function get() { return property.formatOutput(property.requestManager.send({ method: property.getter })); }; }
...
*
* @method attachToObject
* @param {Object}
* @param {Function}
*/
Property.prototype.attachToObject = function (obj) {
var proto = {
get: this.buildGet(),
enumerable: true
};
var names = this.name.split('.');
var name = names[0];
if (names.length > 1) {
obj[names[0]] = obj[names[0]] || {};
...
extractCallback = function (args) { if (utils.isFunction(args[args.length - 1])) { return args.pop(); // modify the args array! } }
...
* @param {function} If the last argument is a function, the contract function
* call will be asynchronous, and the callback will be passed the
* error and result.
* @return {String} output bytes
*/
SolidityFunction.prototype.call = function () {
var args = Array.prototype.slice.call(arguments).filter(function (a) {return a !== undefined; });
var callback = this.extractCallback(args);
var defaultBlock = this.extractDefaultBlock(args);
var payload = this.toPayload(args);
if (!callback) {
var output = this._eth.call(payload, defaultBlock);
return this.unpackOutput(output);
...
formatInput = function (arg) { return this.inputFormatter ? this.inputFormatter(arg) : arg; }
...
* @method toPayload
* @param {Array} args
* @return {Object}
*/
Method.prototype.toPayload = function (args) {
var call = this.getCall(args);
var callback = this.extractCallback(args);
var params = this.formatInput(args);
this.validateArgs(params);
return {
method: call,
params: params,
callback: callback
};
...
formatOutput = function (result) { return this.outputFormatter && result !== null && result !== undefined ? this.outputFormatter(result) : result; }
...
Method.prototype.buildCall = function() {
var method = this;
var send = function () {
var payload = method.toPayload(Array.prototype.slice.call(arguments));
if (payload.callback) {
return method.requestManager.sendAsync(payload, function (err, result) {
payload.callback(err, method.formatOutput(result));
});
}
return method.formatOutput(method.requestManager.send(payload));
};
send.request = this.request.bind(this);
return send;
};
...
request = function () { var payload = { method: this.getter, params: [], callback: this.extractCallback(Array.prototype.slice.call(arguments)) }; payload.format = this.formatOutput.bind(this); return payload; }
n/a
setRequestManager = function (rm) { this.requestManager = rm; }
...
} else {
extendedObject = web3;
}
if (extension.methods) {
extension.methods.forEach(function (method) {
method.attachToObject(extendedObject);
method.setRequestManager(web3._requestManager);
});
}
if (extension.properties) {
extension.properties.forEach(function (property) {
property.attachToObject(extendedObject);
property.setRequestManager(web3._requestManager);
...
HttpProvider = function (host, timeout) { this.host = host || 'http://localhost:8545'; this.timeout = timeout || 0; }
...
```js
console.log(web3); // {eth: .., shh: ...} // it's here!
```
Set a provider (HttpProvider)
```js
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
```
There you go, now you can use it:
```js
var coinbase = web3.eth.coinbase;
var balance = web3.eth.getBalance(coinbase);
...
IpcProvider = function (path, net) {
var _this = this;
this.responseCallbacks = {};
this.path = path;
this.connection = net.connect({path: this.path});
this.connection.on('error', function(e){
console.error('IPC Connection Error', e);
_this._timeout();
});
this.connection.on('end', function(){
_this._timeout();
});
// LISTEN FOR CONNECTION RESPONSES
this.connection.on('data', function(data) {
/*jshint maxcomplexity: 6 */
_this._parseResponse(data.toString()).forEach(function(result){
var id = null;
// get the id which matches the returned id
if(utils.isArray(result)) {
result.forEach(function(load){
if(_this.responseCallbacks[load.id])
id = load.id;
});
} else {
id = result.id;
}
// fire the callback
if(_this.responseCallbacks[id]) {
_this.responseCallbacks[id](null, result);
delete _this.responseCallbacks[id];
}
});
});
}
n/a
HttpProvider = function (host, timeout) { this.host = host || 'http://localhost:8545'; this.timeout = timeout || 0; }
...
```js
console.log(web3); // {eth: .., shh: ...} // it's here!
```
Set a provider (HttpProvider)
```js
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
```
There you go, now you can use it:
```js
var coinbase = web3.eth.coinbase;
var balance = web3.eth.getBalance(coinbase);
...
isConnected = function () { try { this.send({ id: 9999999999, jsonrpc: '2.0', method: 'net_listening', params: [] }); return true; } catch(e) { return false; } }
...
getter: 'shh_version',
inputFormatter: utils.toDecimal
})
];
};
Web3.prototype.isConnected = function(){
return (this.currentProvider && this.currentProvider.isConnected());
};
Web3.prototype.createBatch = function () {
return new Batch(this);
};
module.exports = Web3;
...
prepareRequest = function (async) { var request; if (async) { request = new XHR2(); request.timeout = this.timeout; }else { request = new XMLHttpRequest(); } request.open('POST', this.host, async); request.setRequestHeader('Content-Type','application/json'); return request; }
...
* Should be called to make sync request
*
* @method send
* @param {Object} payload
* @return {Object} result
*/
HttpProvider.prototype.send = function (payload) {
var request = this.prepareRequest(false);
try {
request.send(JSON.stringify(payload));
} catch(error) {
throw errors.InvalidConnection(this.host);
}
...
send = function (payload) { var request = this.prepareRequest(false); try { request.send(JSON.stringify(payload)); } catch(error) { throw errors.InvalidConnection(this.host); } var result = request.responseText; try { result = JSON.parse(result); } catch(e) { throw errors.InvalidResponse(request.responseText); } return result; }
...
* @param {Object} payload
* @return {Object} result
*/
HttpProvider.prototype.send = function (payload) {
var request = this.prepareRequest(false);
try {
request.send(JSON.stringify(payload));
} catch(error) {
throw errors.InvalidConnection(this.host);
}
var result = request.responseText;
try {
...
sendAsync = function (payload, callback) { var request = this.prepareRequest(true); request.onreadystatechange = function() { if (request.readyState === 4 && request.timeout !== 1) { var result = request.responseText; var error = null; try { result = JSON.parse(result); } catch(e) { error = errors.InvalidResponse(request.responseText); } callback(error, result); } }; request.ontimeout = function() { callback(errors.ConnectionTimeout(this.timeout)); }; try { request.send(JSON.stringify(payload)); } catch(error) { callback(errors.InvalidConnection(this.host)); } }
...
};
Method.prototype.buildCall = function() {
var method = this;
var send = function () {
var payload = method.toPayload(Array.prototype.slice.call(arguments));
if (payload.callback) {
return method.requestManager.sendAsync(payload, function (err, result) {
payload.callback(err, method.formatOutput(result));
});
}
return method.formatOutput(method.requestManager.send(payload));
};
send.request = this.request.bind(this);
return send;
...
IpcProvider = function (path, net) {
var _this = this;
this.responseCallbacks = {};
this.path = path;
this.connection = net.connect({path: this.path});
this.connection.on('error', function(e){
console.error('IPC Connection Error', e);
_this._timeout();
});
this.connection.on('end', function(){
_this._timeout();
});
// LISTEN FOR CONNECTION RESPONSES
this.connection.on('data', function(data) {
/*jshint maxcomplexity: 6 */
_this._parseResponse(data.toString()).forEach(function(result){
var id = null;
// get the id which matches the returned id
if(utils.isArray(result)) {
result.forEach(function(load){
if(_this.responseCallbacks[load.id])
id = load.id;
});
} else {
id = result.id;
}
// fire the callback
if(_this.responseCallbacks[id]) {
_this.responseCallbacks[id](null, result);
delete _this.responseCallbacks[id];
}
});
});
}
n/a
_addResponseCallback = function (payload, callback) { var id = payload.id || payload[0].id; var method = payload.method || payload[0].method; this.responseCallbacks[id] = callback; this.responseCallbacks[id].method = method; }
...
IpcProvider.prototype.sendAsync = function (payload, callback) {
// try reconnect, when connection is gone
if(!this.connection.writable)
this.connection.connect({path: this.path});
this.connection.write(JSON.stringify(payload));
this._addResponseCallback(payload, callback);
};
module.exports = IpcProvider;
},{"../utils/utils":20,"./errors":26}],35:[function(require,module,exports){
/*
...
_parseResponse = function (data) { var _this = this, returnValues = []; // DE-CHUNKER var dechunkedData = data .replace(/\}[\n\r]?\{/g,'}|--|{') // }{ .replace(/\}\][\n\r]?\[\{/g,'}]|--|[{') // }][{ .replace(/\}[\n\r]?\[\{/g,'}|--|[{') // }[{ .replace(/\}\][\n\r]?\{/g,'}]|--|{') // }]{ .split('|--|'); dechunkedData.forEach(function(data){ // prepend the last chunk if(_this.lastChunk) data = _this.lastChunk + data; var result = null; try { result = JSON.parse(data); } catch(e) { _this.lastChunk = data; // start timeout to cancel all requests clearTimeout(_this.lastChunkTimeout); _this.lastChunkTimeout = setTimeout(function(){ _this._timeout(); throw errors.InvalidResponse(data); }, 1000 * 15); return; } // cancel timeout and set chunk to null clearTimeout(_this.lastChunkTimeout); _this.lastChunk = null; if(result) returnValues.push(result); }); return returnValues; }
...
});
// LISTEN FOR CONNECTION RESPONSES
this.connection.on('data', function(data) {
/*jshint maxcomplexity: 6 */
_this._parseResponse(data.toString()).forEach(function(result){
var id = null;
// get the id which matches the returned id
if(utils.isArray(result)) {
result.forEach(function(load){
if(_this.responseCallbacks[load.id])
...
_timeout = function () { for(var key in this.responseCallbacks) { if(this.responseCallbacks.hasOwnProperty(key)){ this.responseCallbacks[key](errors.InvalidConnection('on IPC')); delete this.responseCallbacks[key]; } } }
...
this.responseCallbacks = {};
this.path = path;
this.connection = net.connect({path: this.path});
this.connection.on('error', function(e){
console.error('IPC Connection Error', e);
_this._timeout();
});
this.connection.on('end', function(){
_this._timeout();
});
...
isConnected = function () { var _this = this; // try reconnect, when connection is gone if(!_this.connection.writable) _this.connection.connect({path: _this.path}); return !!this.connection.writable; }
...
getter: 'shh_version',
inputFormatter: utils.toDecimal
})
];
};
Web3.prototype.isConnected = function(){
return (this.currentProvider && this.currentProvider.isConnected());
};
Web3.prototype.createBatch = function () {
return new Batch(this);
};
module.exports = Web3;
...
send = function (payload) { if(this.connection.writeSync) { var result; // try reconnect, when connection is gone if(!this.connection.writable) this.connection.connect({path: this.path}); var data = this.connection.writeSync(JSON.stringify(payload)); try { result = JSON.parse(data); } catch(e) { throw errors.InvalidResponse(data); } return result; } else { throw new Error('You tried to send "'+ payload.method +'" synchronously. Synchronous requests are not supported by the IPC provider.'); } }
...
* @param {Object} payload
* @return {Object} result
*/
HttpProvider.prototype.send = function (payload) {
var request = this.prepareRequest(false);
try {
request.send(JSON.stringify(payload));
} catch(error) {
throw errors.InvalidConnection(this.host);
}
var result = request.responseText;
try {
...
sendAsync = function (payload, callback) { // try reconnect, when connection is gone if(!this.connection.writable) this.connection.connect({path: this.path}); this.connection.write(JSON.stringify(payload)); this._addResponseCallback(payload, callback); }
...
};
Method.prototype.buildCall = function() {
var method = this;
var send = function () {
var payload = method.toPayload(Array.prototype.slice.call(arguments));
if (payload.callback) {
return method.requestManager.sendAsync(payload, function (err, result) {
payload.callback(err, method.formatOutput(result));
});
}
return method.formatOutput(method.requestManager.send(payload));
};
send.request = this.request.bind(this);
return send;
...
real = function () { this._inputFormatter = f.formatInputReal; this._outputFormatter = f.formatOutputReal; }
n/a
constructor = function () { this._inputFormatter = f.formatInputReal; this._outputFormatter = f.formatOutputReal; }
n/a
isType = function (name) { return !!name.match(/real([0-9]*)?(\[([0-9]*)\])?/); }
...
* @method _requireType
* @param {String} type
* @returns {SolidityType}
* @throws {Error} throws if no matching type is found
*/
SolidityCoder.prototype._requireType = function (type) {
var solidityType = this._types.filter(function (t) {
return t.isType(type);
})[0];
if (!solidityType) {
throw Error('invalid solidity type!: ' + type);
}
return solidityType;
...
requestmanager = function (provider) { this.provider = provider; this.polls = {}; this.timeout = null; }
n/a
poll = function () {
/*jshint maxcomplexity: 6 */
this.timeout = setTimeout(this.poll.bind(this), c.ETH_POLLING_TIMEOUT);
if (Object.keys(this.polls).length === 0) {
return;
}
if (!this.provider) {
console.error(errors.InvalidProvider());
return;
}
var pollsData = [];
var pollsIds = [];
for (var key in this.polls) {
pollsData.push(this.polls[key].data);
pollsIds.push(key);
}
if (pollsData.length === 0) {
return;
}
var payload = Jsonrpc.toBatchPayload(pollsData);
// map the request id to they poll id
var pollsIdMap = {};
payload.forEach(function(load, index){
pollsIdMap[load.id] = pollsIds[index];
});
var self = this;
this.provider.sendAsync(payload, function (error, results) {
// TODO: console log?
if (error) {
return;
}
if (!utils.isArray(results)) {
throw errors.InvalidResponse(results);
}
results.map(function (result) {
var id = pollsIdMap[result.id];
// make sure the filter is still installed after arrival of the request
if (self.polls[id]) {
result.callback = self.polls[id].callback;
return result;
} else
return false;
}).filter(function (result) {
return !!result;
}).filter(function (result) {
var valid = Jsonrpc.isValidResponse(result);
if (!valid) {
result.callback(errors.InvalidResponse(result));
}
return valid;
}).forEach(function (result) {
result.callback(null, result.result);
});
});
}
...
*/
RequestManager.prototype.startPolling = function (data, pollId, callback, uninstall) {
this.polls[pollId] = {data: data, id: pollId, callback: callback, uninstall: uninstall};
// start polling
if (!this.timeout) {
this.poll();
}
};
/**
* Should be used to stop polling for filter with given id
*
* @method stopPolling
...
reset = function (keepIsSyncing) {
/*jshint maxcomplexity:5 */
for (var key in this.polls) {
// remove all polls, except sync polls,
// they need to be removed manually by calling syncing.stopWatching()
if(!keepIsSyncing || key.indexOf('syncPoll_') === -1) {
this.polls[key].uninstall();
delete this.polls[key];
}
}
// stop polling
if(Object.keys(this.polls).length === 0 && this.timeout) {
clearTimeout(this.timeout);
this.timeout = null;
}
}
...
Web3.prototype.setProvider = function (provider) {
this._requestManager.setProvider(provider);
this.currentProvider = provider;
};
Web3.prototype.reset = function (keepIsSyncing) {
this._requestManager.reset(keepIsSyncing);
this.settings = new Settings();
};
Web3.prototype.BigNumber = BigNumber;
Web3.prototype.toHex = utils.toHex;
Web3.prototype.toAscii = utils.toAscii;
Web3.prototype.toUtf8 = utils.toUtf8;
...
send = function (data) { if (!this.provider) { console.error(errors.InvalidProvider()); return null; } var payload = Jsonrpc.toPayload(data.method, data.params); var result = this.provider.send(payload); if (!Jsonrpc.isValidResponse(result)) { throw errors.InvalidResponse(result); } return result.result; }
...
* @param {Object} payload
* @return {Object} result
*/
HttpProvider.prototype.send = function (payload) {
var request = this.prepareRequest(false);
try {
request.send(JSON.stringify(payload));
} catch(error) {
throw errors.InvalidConnection(this.host);
}
var result = request.responseText;
try {
...
sendAsync = function (data, callback) { if (!this.provider) { return callback(errors.InvalidProvider()); } var payload = Jsonrpc.toPayload(data.method, data.params); this.provider.sendAsync(payload, function (err, result) { if (err) { return callback(err); } if (!Jsonrpc.isValidResponse(result)) { return callback(errors.InvalidResponse(result)); } callback(null, result.result); }); }
...
};
Method.prototype.buildCall = function() {
var method = this;
var send = function () {
var payload = method.toPayload(Array.prototype.slice.call(arguments));
if (payload.callback) {
return method.requestManager.sendAsync(payload, function (err, result) {
payload.callback(err, method.formatOutput(result));
});
}
return method.formatOutput(method.requestManager.send(payload));
};
send.request = this.request.bind(this);
return send;
...
sendBatch = function (data, callback) { if (!this.provider) { return callback(errors.InvalidProvider()); } var payload = Jsonrpc.toBatchPayload(data); this.provider.sendAsync(payload, function (err, results) { if (err) { return callback(err); } if (!utils.isArray(results)) { return callback(errors.InvalidResponse(results)); } callback(err, results); }); }
...
/**
* Should be called to execute batch request
*
* @method execute
*/
Batch.prototype.execute = function () {
var requests = this.requests;
this.requestManager.sendBatch(requests, function (err, results) {
results = results || [];
requests.map(function (request, index) {
return results[index] || {};
}).forEach(function (result, index) {
if (requests[index].callback) {
if (!Jsonrpc.isValidResponse(result)) {
...
setProvider = function (p) { this.provider = p; }
...
```js
console.log(web3); // {eth: .., shh: ...} // it's here!
```
Set a provider (HttpProvider)
```js
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
```
There you go, now you can use it:
```js
var coinbase = web3.eth.coinbase;
var balance = web3.eth.getBalance(coinbase);
...
startPolling = function (data, pollId, callback, uninstall) { this.polls[pollId] = {data: data, id: pollId, callback: callback, uninstall: uninstall}; // start polling if (!this.timeout) { this.poll(); } }
...
self.callbacks.forEach(function (callback) {
callback(null, message);
});
});
}
};
self.requestManager.startPolling({
method: self.implementation.poll.call,
params: [self.filterId],
}, self.filterId, onMessage, self.stopWatching.bind(self));
};
var Filter = function (requestManager, options, methods, formatter, callback, filterCreationErrorCallback) {
...
stopPolling = function (pollId) { delete this.polls[pollId]; // stop polling if(Object.keys(this.polls).length === 0 && this.timeout) { clearTimeout(this.timeout); this.timeout = null; } }
...
pollFilter(this);
}
return this;
};
Filter.prototype.stopWatching = function (callback) {
this.requestManager.stopPolling(this.filterId);
this.callbacks = [];
// remove filter async
if (callback) {
this.implementation.uninstallFilter(this.filterId, callback);
} else {
return this.implementation.uninstallFilter(this.filterId);
}
...
shh = function (web3) { this._requestManager = web3._requestManager; var self = this; methods().forEach(function(method) { method.attachToObject(self); method.setRequestManager(self._requestManager); }); }
...
methods().forEach(function(method) {
method.attachToObject(self);
method.setRequestManager(self._requestManager);
});
};
Shh.prototype.filter = function (fil, callback) {
return new Filter(this._requestManager, fil, watches.shh(), formatters.outputPostFormatter
, callback);
};
var methods = function () {
var post = new Method({
name: 'post',
call: 'shh_post',
...
filter = function (fil, callback) { return new Filter(this._requestManager, fil, watches.shh(), formatters.outputPostFormatter, callback); }
...
*
* @method _requireType
* @param {String} type
* @returns {SolidityType}
* @throws {Error} throws if no matching type is found
*/
SolidityCoder.prototype._requireType = function (type) {
var solidityType = this._types.filter(function (t) {
return t.isType(type);
})[0];
if (!solidityType) {
throw Error('invalid solidity type!: ' + type);
}
...
string = function () { this._inputFormatter = f.formatInputString; this._outputFormatter = f.formatOutputString; }
n/a
constructor = function () { this._inputFormatter = f.formatInputString; this._outputFormatter = f.formatOutputString; }
n/a
isDynamicType = function () { return true; }
...
var SolidityTypeDynamicBytes = require('./dynamicbytes');
var SolidityTypeString = require('./string');
var SolidityTypeReal = require('./real');
var SolidityTypeUReal = require('./ureal');
var SolidityTypeBytes = require('./bytes');
var isDynamic = function (solidityType, type) {
return solidityType.isDynamicType(type) ||
solidityType.isDynamicArray(type);
};
/**
* SolidityCoder prototype should be used to encode/decode solidity params of any type
*/
var SolidityCoder = function (types) {
...
isType = function (name) { return !!name.match(/^string(\[([0-9]*)\])*$/); }
...
* @method _requireType
* @param {String} type
* @returns {SolidityType}
* @throws {Error} throws if no matching type is found
*/
SolidityCoder.prototype._requireType = function (type) {
var solidityType = this._types.filter(function (t) {
return t.isType(type);
})[0];
if (!solidityType) {
throw Error('invalid solidity type!: ' + type);
}
return solidityType;
...
syncing = function (requestManager, callback) { this.requestManager = requestManager; this.pollId = 'syncPoll_'+ count++; this.callbacks = []; this.addCallback(callback); this.lastSyncState = false; pollSyncing(this); return this; }
n/a
addCallback = function (callback) { if(callback) this.callbacks.push(callback); return this; }
...
};
var IsSyncing = function (requestManager, callback) {
this.requestManager = requestManager;
this.pollId = 'syncPoll_'+ count++;
this.callbacks = [];
this.addCallback(callback);
this.lastSyncState = false;
pollSyncing(this);
return this;
};
IsSyncing.prototype.addCallback = function (callback) {
...
stopWatching = function () { this.requestManager.stopPolling(this.pollId); this.callbacks = []; }
...
var filter = contract._eth.filter('latest', function(e){
if (!e && !callbackFired) {
count++;
// stop watching after 50 blocks (timeout)
if (count > 50) {
filter.stopWatching(function() {});
callbackFired = true;
if (callback)
callback(new Error('Contract transaction couldn\'t be found after 50 blocks'));
else
throw new Error('Contract transaction couldn\'t be found after 50 blocks');
...
type = function (config) { this._inputFormatter = config.inputFormatter; this._outputFormatter = config.outputFormatter; }
n/a
decode = function (bytes, offset, name) { var self = this; if (this.isDynamicArray(name)) { return (function () { var arrayOffset = parseInt('0x' + bytes.substr(offset * 2, 64)); // in bytes var length = parseInt('0x' + bytes.substr(arrayOffset * 2, 64)); // in int var arrayStart = arrayOffset + 32; // array starts after length; // in bytes var nestedName = self.nestedName(name); var nestedStaticPartLength = self.staticPartLength(nestedName); // in bytes var roundedNestedStaticPartLength = Math.floor((nestedStaticPartLength + 31) / 32) * 32; var result = []; for (var i = 0; i < length * roundedNestedStaticPartLength; i += roundedNestedStaticPartLength) { result.push(self.decode(bytes, arrayStart + i, nestedName)); } return result; })(); } else if (this.isStaticArray(name)) { return (function () { var length = self.staticArrayLength(name); // in int var arrayStart = offset; // in bytes var nestedName = self.nestedName(name); var nestedStaticPartLength = self.staticPartLength(nestedName); // in bytes var roundedNestedStaticPartLength = Math.floor((nestedStaticPartLength + 31) / 32) * 32; var result = []; for (var i = 0; i < length * roundedNestedStaticPartLength; i += roundedNestedStaticPartLength) { result.push(self.decode(bytes, arrayStart + i, nestedName)); } return result; })(); } else if (this.isDynamicType(name)) { return (function () { var dynamicOffset = parseInt('0x' + bytes.substr(offset * 2, 64)); // in bytes var length = parseInt('0x' + bytes.substr(dynamicOffset * 2, 64)); // in bytes var roundedLength = Math.floor((length + 31) / 32); // in int var param = new SolidityParam(bytes.substr(dynamicOffset * 2, ( 1 + roundedLength) * 64), 0); return self._outputFormatter(param, name); })(); } var length = this.staticPartLength(name); var param = new SolidityParam(bytes.substr(offset * 2, length * 2)); return this._outputFormatter(param, name); }
...
* @return {Array} array of plain params
*/
SolidityCoder.prototype.decodeParams = function (types, bytes) {
var solidityTypes = this.getSolidityTypes(types);
var offsets = this.getOffsets(types, solidityTypes);
return solidityTypes.map(function (solidityType, index) {
return solidityType.decode(bytes, offsets[index], types[index], index);
});
};
SolidityCoder.prototype.getOffsets = function (types, solidityTypes) {
var lengths = solidityTypes.map(function (solidityType, index) {
return solidityType.staticPartLength(types[index]);
});
...
encode = function (value, name) { var self = this; if (this.isDynamicArray(name)) { return (function () { var length = value.length; // in int var nestedName = self.nestedName(name); var result = []; result.push(f.formatInputInt(length).encode()); value.forEach(function (v) { result.push(self.encode(v, nestedName)); }); return result; })(); } else if (this.isStaticArray(name)) { return (function () { var length = self.staticArrayLength(name); // in int var nestedName = self.nestedName(name); var result = []; for (var i = 0; i < length; i++) { result.push(self.encode(value[i], nestedName)); } return result; })(); } return this._inputFormatter(value, name).encode(); }
...
* @param {Array} params
* @return {String} encoded list of params
*/
SolidityCoder.prototype.encodeParams = function (types, params) {
var solidityTypes = this.getSolidityTypes(types);
var encodeds = solidityTypes.map(function (solidityType, index) {
return solidityType.encode(params[index], types[index]);
});
var dynamicOffset = solidityTypes.reduce(function (acc, solidityType, index) {
var staticPartLength = solidityType.staticPartLength(types[index]);
var roundedStaticPartLength = Math.floor((staticPartLength + 31) / 32) * 32;
return acc + (isDynamic(solidityTypes[index], types[index]) ?
...
isDynamicArray = function (name) { var nestedTypes = this.nestedTypes(name); return !!nestedTypes && !nestedTypes[nestedTypes.length - 1].match(/[0-9]{1,}/g); }
...
var SolidityTypeString = require('./string');
var SolidityTypeReal = require('./real');
var SolidityTypeUReal = require('./ureal');
var SolidityTypeBytes = require('./bytes');
var isDynamic = function (solidityType, type) {
return solidityType.isDynamicType(type) ||
solidityType.isDynamicArray(type);
};
/**
* SolidityCoder prototype should be used to encode/decode solidity params of any type
*/
var SolidityCoder = function (types) {
this._types = types;
...
isDynamicType = function () { return false; }
...
var SolidityTypeDynamicBytes = require('./dynamicbytes');
var SolidityTypeString = require('./string');
var SolidityTypeReal = require('./real');
var SolidityTypeUReal = require('./ureal');
var SolidityTypeBytes = require('./bytes');
var isDynamic = function (solidityType, type) {
return solidityType.isDynamicType(type) ||
solidityType.isDynamicArray(type);
};
/**
* SolidityCoder prototype should be used to encode/decode solidity params of any type
*/
var SolidityCoder = function (types) {
...
isStaticArray = function (name) { var nestedTypes = this.nestedTypes(name); return !!nestedTypes && !!nestedTypes[nestedTypes.length - 1].match(/[0-9]{1,}/g); }
...
result += self.encodeWithOffset(nestedName, solidityType, encoded[i + 1], offset + additionalOffset);
}
})();
return result;
})();
} else if (solidityType.isStaticArray(type)) {
return (function () {
var nestedName = solidityType.nestedName(type);
var nestedStaticPartLength = solidityType.staticPartLength(nestedName);
var result = "";
if (solidityType.isDynamicArray(nestedName)) {
...
isType = function (name) { throw "this method should be overrwritten for type " + name; }
...
* @method _requireType
* @param {String} type
* @returns {SolidityType}
* @throws {Error} throws if no matching type is found
*/
SolidityCoder.prototype._requireType = function (type) {
var solidityType = this._types.filter(function (t) {
return t.isType(type);
})[0];
if (!solidityType) {
throw Error('invalid solidity type!: ' + type);
}
return solidityType;
...
nestedName = function (name) { // remove last [] in name var nestedTypes = this.nestedTypes(name); if (!nestedTypes) { return name; } return name.substr(0, name.length - nestedTypes[nestedTypes.length - 1].length); }
...
// TODO: refactor whole encoding!
SolidityCoder.prototype.encodeWithOffset = function (type, solidityType, encoded, offset) {
var self = this;
if (solidityType.isDynamicArray(type)) {
return (function () {
// offset was already set
var nestedName = solidityType.nestedName(type);
var nestedStaticPartLength = solidityType.staticPartLength(nestedName);
var result = encoded[0];
(function () {
var previousLength = 2; // in int
if (solidityType.isDynamicArray(nestedName)) {
for (var i = 1; i < encoded.length; i++) {
...
nestedTypes = function (name) { // return list of strings eg. "[]", "[3]", "[]", "[2]" return name.match(/(\[[0-9]*\])/g); }
...
*
* @method staticPartLength
* @param {String} name
* @return {Number} length of static part in bytes
*/
SolidityType.prototype.staticPartLength = function (name) {
// If name isn't an array then treat it like a single element array.
return (this.nestedTypes(name) || ['[1]'])
.map(function (type) {
// the length of the nested array
return parseInt(type.slice(1, -1), 10) || 1;
})
.reduce(function (previous, current) {
return previous * current;
// all basic types are 32 bytes long
...
staticArrayLength = function (name) { var nestedTypes = this.nestedTypes(name); if (nestedTypes) { return parseInt(nestedTypes[nestedTypes.length - 1].match(/[0-9]{1,}/g) || 1); } return 1; }
...
return result;
})();
} else if (this.isStaticArray(name)) {
return (function () {
var length = self.staticArrayLength(name); // in int
var nestedName = self.nestedName(name);
var result = [];
for (var i = 0; i < length; i++) {
result.push(self.encode(value[i], nestedName));
}
...
staticPartLength = function (name) { // If name isn't an array then treat it like a single element array. return (this.nestedTypes(name) || ['[1]']) .map(function (type) { // the length of the nested array return parseInt(type.slice(1, -1), 10) || 1; }) .reduce(function (previous, current) { return previous * current; // all basic types are 32 bytes long }, 32); }
...
var solidityTypes = this.getSolidityTypes(types);
var encodeds = solidityTypes.map(function (solidityType, index) {
return solidityType.encode(params[index], types[index]);
});
var dynamicOffset = solidityTypes.reduce(function (acc, solidityType, index) {
var staticPartLength = solidityType.staticPartLength(types[index]);
var roundedStaticPartLength = Math.floor((staticPartLength + 31) / 32) * 32;
return acc + (isDynamic(solidityTypes[index], types[index]) ?
32 :
roundedStaticPartLength);
}, 0);
...
uint = function () { this._inputFormatter = f.formatInputInt; this._outputFormatter = f.formatOutputUInt; }
n/a
constructor = function () { this._inputFormatter = f.formatInputInt; this._outputFormatter = f.formatOutputUInt; }
n/a
isType = function (name) { return !!name.match(/^uint([0-9]*)?(\[([0-9]*)\])*$/); }
...
* @method _requireType
* @param {String} type
* @returns {SolidityType}
* @throws {Error} throws if no matching type is found
*/
SolidityCoder.prototype._requireType = function (type) {
var solidityType = this._types.filter(function (t) {
return t.isType(type);
})[0];
if (!solidityType) {
throw Error('invalid solidity type!: ' + type);
}
return solidityType;
...
ureal = function () { this._inputFormatter = f.formatInputReal; this._outputFormatter = f.formatOutputUReal; }
n/a
constructor = function () { this._inputFormatter = f.formatInputReal; this._outputFormatter = f.formatOutputUReal; }
n/a
isType = function (name) { return !!name.match(/^ureal([0-9]*)?(\[([0-9]*)\])*$/); }
...
* @method _requireType
* @param {String} type
* @returns {SolidityType}
* @throws {Error} throws if no matching type is found
*/
SolidityCoder.prototype._requireType = function (type) {
var solidityType = this._types.filter(function (t) {
return t.isType(type);
})[0];
if (!solidityType) {
throw Error('invalid solidity type!: ' + type);
}
return solidityType;
...
extractDisplayName = function (name) { var length = name.indexOf('('); return length !== -1 ? name.substr(0, length) : name; }
...
/**
* Should be used to get event display name
*
* @method displayName
* @return {String} event display name
*/
SolidityEvent.prototype.displayName = function () {
return utils.extractDisplayName(this._name);
};
/**
* Should be used to get event type name
*
* @method typeName
* @return {String} event type name
...
extractTypeName = function (name) { /// TODO: make it invulnerable var length = name.indexOf('('); return length !== -1 ? name.substr(length + 1, name.length - 1 - (length + 1)).replace(' ', '') : ""; }
...
/**
* Should be used to get event type name
*
* @method typeName
* @return {String} event type name
*/
SolidityEvent.prototype.typeName = function () {
return utils.extractTypeName(this._name);
};
/**
* Should be used to get event signature
*
* @method signature
* @return {String} event signature
...
fromAscii = function (str) { var hex = ""; for(var i = 0; i < str.length; i++) { var code = str.charCodeAt(i); var n = code.toString(16); hex += n.length < 2 ? '0' + n : n; } return "0x" + hex; }
...
validateIBAN();
};
function transfer() {
var value = new BigNumber(document.getElementById('value').value);
var exchange = document.getElementById('exchange').value;
var client = document.getElementById('client').value;
deposit.deposit(web3.fromAscii(client), {value: value});
displayTransfer("deposited client's " + client + " funds " + value.toString(10) + " to exchange
" + exchange);
};
function displayTransfer(text) {
var node = document.createElement('li');
var textnode = document.createTextNode(text);
node.appendChild(textnode);
...
fromDecimal = function (value) { var number = toBigNumber(value); var result = number.toString(16); return number.lessThan(0) ? '-0x' + result.substr(1) : '0x' + result; }
...
if (options.to) { // it might be contract creation
options.to = inputAddressFormatter(options.to);
}
['gasPrice', 'gas', 'value', 'nonce'].filter(function (key) {
return options[key] !== undefined;
}).forEach(function(key){
options[key] = utils.fromDecimal(options[key]);
});
return options;
};
/**
* Formats the input of a transaction and converts all values to HEX
...
fromUtf8 = function (str) { str = utf8.encode(str); var hex = ""; for(var i = 0; i < str.length; i++) { var code = str.charCodeAt(i); if (code === 0) break; var n = code.toString(16); hex += n.length < 2 ? '0' + n : n; } return "0x" + hex; }
...
* Formats input value to byte representation of string
*
* @method formatInputString
* @param {String}
* @returns {SolidityParam}
*/
var formatInputString = function (value) {
var result = utils.fromUtf8(value).substr(2);
var length = result.length / 2;
var l = Math.floor((result.length + 63) / 64);
result = utils.padRight(result, l * 64);
return new SolidityParam(formatInputInt(length).value + result);
};
/**
...
fromWei = function (number, unit) { var returnValue = toBigNumber(number).dividedBy(getValueOfUnit(unit)); return isBigNumber(number) ? returnValue : returnValue.toString(10); }
n/a
isAddress = function (address) { if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) { // check if it has the basic requirements of an address return false; } else if (/^(0x)?[0-9a-f]{40}$/.test(address) || /^(0x)?[0-9A-F]{40}$/.test(address)) { // If it's all small caps or all all caps, return true return true; } else { // Otherwise check each case return isChecksumAddress(address); } }
...
var inputAddressFormatter = function (address) {
var iban = new Iban(address);
if (iban.isValid() && iban.isDirect()) {
return '0x' + iban.address();
} else if (utils.isStrictAddress(address)) {
return address;
} else if (utils.isAddress(address)) {
return '0x' + address;
}
throw new Error('invalid address');
};
var outputSyncingFormatter = function(result) {
...
isArray = function (object) { return object instanceof Array; }
...
var args = Array.prototype.slice.call(arguments);
if (utils.isFunction(args[args.length - 1])) {
callback = args.pop();
}
var last = args[args.length - 1];
if (utils.isObject(last) && !utils.isArray(last)) {
options = args.pop();
}
if (options.value > 0) {
var constructorAbi = abi.filter(function (json) {
return json.type === 'constructor' && json.inputs.length === args.length;
})[0] || {};
...
isBigNumber = function (object) { return object instanceof BigNumber || (object && object.constructor && object.constructor.name === 'BigNumber'); }
n/a
isBloom = function (bloom) { if (!/^(0x)?[0-9a-f]{512}$/i.test(bloom)) { return false; } else if (/^(0x)?[0-9a-f]{512}$/.test(bloom) || /^(0x)?[0-9A-F]{512}$/.test(bloom)) { return true; } return false; }
...
*
* @method testAddress
* @param {String} hex encoded bloom
* @param {String} address in hex notation
* @returns {Boolean} topic is (probably) part of the block
*/
var testAddress = function(bloom, address) {
if (!utils.isBloom(bloom)) throw "invalid bloom";
if (!utils.isAddress(address)) throw "invalid address";
return testBytes(bloom, address);
};
/**
* Returns true if the topic is part of the given bloom.
...
isBoolean = function (object) { return typeof object === 'boolean'; }
n/a
isChecksumAddress = function (address) { // Check each case address = address.replace('0x',''); var addressHash = sha3(address.toLowerCase()); for (var i = 0; i < 40; i++ ) { // the nth letter should be uppercase if the nth digit of casemap is 1 if ((parseInt(addressHash[i], 16) > 7 && address[i].toUpperCase() !== address[i]) || (parseInt(addressHash[i], 16) <= 7 && address[i].toLowerCase() !== address[i])) { return false; } } return true; }
n/a
isFunction = function (object) { return typeof object === 'function'; }
...
var event = new SolidityEvent(this._requestManager, match, this._address);
return event.decode(data);
};
AllSolidityEvents.prototype.execute = function (options, callback) {
if (utils.isFunction(arguments[arguments.length - 1])) {
callback = arguments[arguments.length - 1];
if(arguments.length === 1)
options = null;
}
var o = this.encode(options);
var formatter = this.decode.bind(this);
...
isJson = function (str) { try { return !!JSON.parse(str); } catch (e) { return false; } }
...
post.expiry = utils.toDecimal(post.expiry);
post.sent = utils.toDecimal(post.sent);
post.ttl = utils.toDecimal(post.ttl);
post.workProved = utils.toDecimal(post.workProved);
// post.payloadRaw = post.payload;
// post.payload = utils.toAscii(post.payload);
// if (utils.isJson(post.payload)) {
// post.payload = JSON.parse(post.payload);
// }
// format the following options
if (!post.topics) {
post.topics = [];
}
...
isObject = function (object) { return typeof object === 'object'; }
...
var args = Array.prototype.slice.call(arguments);
if (utils.isFunction(args[args.length - 1])) {
callback = args.pop();
}
var last = args[args.length - 1];
if (utils.isObject(last) && !utils.isArray(last)) {
options = args.pop();
}
if (options.value > 0) {
var constructorAbi = abi.filter(function (json) {
return json.type === 'constructor' && json.inputs.length === args.length;
})[0] || {};
...
isStrictAddress = function (address) { return /^0x[0-9a-f]{40}$/i.test(address); }
...
return post;
};
var inputAddressFormatter = function (address) {
var iban = new Iban(address);
if (iban.isValid() && iban.isDirect()) {
return '0x' + iban.address();
} else if (utils.isStrictAddress(address)) {
return address;
} else if (utils.isAddress(address)) {
return '0x' + address;
}
throw new Error('invalid address');
};
...
isString = function (object) { return typeof object === 'string' || (object && object.constructor && object.constructor.name === 'String'); }
...
};
/// This method should be called on options object, to verify deprecated properties && lazy load dynamic ones
/// @param should be string or object
/// @returns options string or object
var getOptions = function (options) {
if (utils.isString(options)) {
return options;
}
options = options || {};
// make sure topics, get converted to hex
options.topics = options.topics || [];
...
isTopic = function (topic) { if (!/^(0x)?[0-9a-f]{64}$/i.test(topic)) { return false; } else if (/^(0x)?[0-9a-f]{64}$/.test(topic) || /^(0x)?[0-9A-F]{64}$/.test(topic)) { return true; } return false; }
...
* @method hasTopic
* @param {String} hex encoded bloom
* @param {String} address in hex notation
* @returns {Boolean} topic is (probably) part of the block
*/
var testTopic = function(bloom, topic) {
if (!utils.isBloom(bloom)) throw "invalid bloom";
if (!utils.isTopic(topic)) throw "invalid topic";
return testBytes(bloom, topic);
};
module.exports = {
testAddress: testAddress,
testTopic: testTopic,
...
padLeft = function (string, chars, sign) { return new Array(chars - string.length + 1).join(sign ? sign : "0") + string; }
...
*
* @method formatInputInt
* @param {String|Number|BigNumber} value that needs to be formatted
* @returns {SolidityParam}
*/
var formatInputInt = function (value) {
BigNumber.config(c.ETH_BIGNUMBER_ROUNDING_MODE);
var result = utils.padLeft(utils.toTwosComplement(value).toString(16), 64);
return new SolidityParam(result);
};
/**
* Formats input bytes
*
* @method formatInputBytes
...
padRight = function (string, chars, sign) { return string + (new Array(chars - string.length + 1).join(sign ? sign : "0")); }
...
* @method formatInputBytes
* @param {String}
* @returns {SolidityParam}
*/
var formatInputBytes = function (value) {
var result = utils.toHex(value).substr(2);
var l = Math.floor((result.length + 63) / 64);
result = utils.padRight(result, l * 64);
return new SolidityParam(result);
};
/**
* Formats input bytes
*
* @method formatDynamicInputBytes
...
toAddress = function (address) { if (isStrictAddress(address)) { return address; } if (/^[0-9a-f]{40}$/.test(address)) { return '0x' + address; } return '0x' + padLeft(toHex(address).substr(2), 40); }
n/a
toAscii = function (hex) { // Find termination var str = ""; var i = 0, l = hex.length; if (hex.substring(0, 2) === '0x') { i = 2; } for (; i < l; i+=2) { var code = parseInt(hex.substr(i, 2), 16); str += String.fromCharCode(code); } return str; }
...
var outputPostFormatter = function(post){
post.expiry = utils.toDecimal(post.expiry);
post.sent = utils.toDecimal(post.sent);
post.ttl = utils.toDecimal(post.ttl);
post.workProved = utils.toDecimal(post.workProved);
// post.payloadRaw = post.payload;
// post.payload = utils.toAscii(post.payload);
// if (utils.isJson(post.payload)) {
// post.payload = JSON.parse(post.payload);
// }
// format the following options
if (!post.topics) {
...
toBigNumber = function (number) {
/*jshint maxcomplexity:5 */
number = number || 0;
if (isBigNumber(number))
return number;
if (isString(number) && (number.indexOf('0x') === 0 || number.indexOf('-0x') === 0)) {
return new BigNumber(number.replace('0x',''), 16);
}
return new BigNumber(number.toString(10), 10);
}
...
* Should the format output to a big number
*
* @method outputBigNumberFormatter
* @param {String|Number|BigNumber}
* @returns {BigNumber} object
*/
var outputBigNumberFormatter = function (number) {
return utils.toBigNumber(number);
};
var isPredefinedBlockNumber = function (blockNumber) {
return blockNumber === 'latest' || blockNumber === 'pending' || blockNumber === 'earliest';
};
var inputDefaultBlockNumberFormatter = function (blockNumber) {
...
toChecksumAddress = function (address) { if (typeof address === 'undefined') return ''; address = address.toLowerCase().replace('0x',''); var addressHash = sha3(address); var checksumAddress = '0x'; for (var i = 0; i < address.length; i++ ) { // If ith character is 9 to f then make it uppercase if (parseInt(addressHash[i], 16) > 7) { checksumAddress += address[i].toUpperCase(); } else { checksumAddress += address[i]; } } return checksumAddress; }
n/a
toDecimal = function (value) { return toBigNumber(value).toNumber(); }
...
*
* @method outputTransactionFormatter
* @param {Object} tx
* @returns {Object}
*/
var outputTransactionFormatter = function (tx){
if(tx.blockNumber !== null)
tx.blockNumber = utils.toDecimal(tx.blockNumber);
if(tx.transactionIndex !== null)
tx.transactionIndex = utils.toDecimal(tx.transactionIndex);
tx.nonce = utils.toDecimal(tx.nonce);
tx.gas = utils.toDecimal(tx.gas);
tx.gasPrice = utils.toBigNumber(tx.gasPrice);
tx.value = utils.toBigNumber(tx.value);
return tx;
...
toHex = function (val) {
/*jshint maxcomplexity: 8 */
if (isBoolean(val))
return fromDecimal(+val);
if (isBigNumber(val))
return fromDecimal(val);
if (isObject(val))
return fromUtf8(JSON.stringify(val));
// if its a negative number, pass it through fromDecimal
if (isString(val)) {
if (val.indexOf('-0x') === 0)
return fromDecimal(val);
else if(val.indexOf('0x') === 0)
return val;
else if (!isFinite(val))
return fromAscii(val);
}
return fromDecimal(val);
}
...
* Formats input bytes
*
* @method formatInputBytes
* @param {String}
* @returns {SolidityParam}
*/
var formatInputBytes = function (value) {
var result = utils.toHex(value).substr(2);
var l = Math.floor((result.length + 63) / 64);
result = utils.padRight(result, l * 64);
return new SolidityParam(result);
};
/**
* Formats input bytes
...
toTwosComplement = function (number) { var bigNumber = toBigNumber(number).round(); if (bigNumber.lessThan(0)) { return new BigNumber("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16).plus(bigNumber).plus(1); } return bigNumber; }
...
*
* @method formatInputInt
* @param {String|Number|BigNumber} value that needs to be formatted
* @returns {SolidityParam}
*/
var formatInputInt = function (value) {
BigNumber.config(c.ETH_BIGNUMBER_ROUNDING_MODE);
var result = utils.padLeft(utils.toTwosComplement(value).toString(16), 64);
return new SolidityParam(result);
};
/**
* Formats input bytes
*
* @method formatInputBytes
...
toUtf8 = function (hex) { // Find termination var str = ""; var i = 0, l = hex.length; if (hex.substring(0, 2) === '0x') { i = 2; } for (; i < l; i+=2) { var code = parseInt(hex.substr(i, 2), 16); if (code === 0) break; str += String.fromCharCode(code); } return utf8.decode(str); }
...
*
* @method formatOutputString
* @param {SolidityParam} left-aligned hex representation of string
* @returns {String} ascii string
*/
var formatOutputString = function (param) {
var length = (new BigNumber(param.dynamicPart().slice(0, 64), 16)).toNumber() * 2;
return utils.toUtf8(param.dynamicPart().substr(64, length));
};
/**
* Should be used to format output address
*
* @method formatOutputAddress
* @param {SolidityParam} right-aligned input bytes
...
toWei = function (number, unit) { var returnValue = toBigNumber(number).times(getValueOfUnit(unit)); return isBigNumber(number) ? returnValue : returnValue.toString(10); }
n/a
transformToFullName = function (json) { if (json.name.indexOf('(') !== -1) { return json.name; } var typeName = json.inputs.map(function(i){return i.type; }).join(); return json.name + '(' + typeName + ')'; }
...
AllSolidityEvents.prototype.decode = function (data) {
data.data = data.data || '';
data.topics = data.topics || [];
var eventTopic = data.topics[0].slice(2);
var match = this._json.filter(function (j) {
return eventTopic === sha3(utils.transformToFullName(j));
})[0];
if (!match) { // cannot find matching event?
console.warn('cannot find event for log');
return data;
}
...
eth = function () { var newFilterCall = function (args) { var type = args[0]; switch(type) { case 'latest': args.shift(); this.params = 0; return 'eth_newBlockFilter'; case 'pending': args.shift(); this.params = 0; return 'eth_newPendingTransactionFilter'; default: return 'eth_newFilter'; } }; var newFilter = new Method({ name: 'newFilter', call: newFilterCall, params: 1 }); var uninstallFilter = new Method({ name: 'uninstallFilter', call: 'eth_uninstallFilter', params: 1 }); var getLogs = new Method({ name: 'getLogs', call: 'eth_getFilterLogs', params: 1 }); var poll = new Method({ name: 'poll', call: 'eth_getFilterChanges', params: 1 }); return [ newFilter, uninstallFilter, getLogs, poll ]; }
...
callback = arguments[arguments.length - 1];
if(arguments.length === 1)
options = null;
}
var o = this.encode(options);
var formatter = this.decode.bind(this);
return new Filter(this._requestManager, o, watches.eth(), formatter, callback);
};
AllSolidityEvents.prototype.attachToContract = function (contract) {
var execute = this.execute.bind(this);
contract.allEvents = execute;
};
...
shh = function () { var newFilter = new Method({ name: 'newFilter', call: 'shh_newFilter', params: 1 }); var uninstallFilter = new Method({ name: 'uninstallFilter', call: 'shh_uninstallFilter', params: 1 }); var getLogs = new Method({ name: 'getLogs', call: 'shh_getMessages', params: 1 }); var poll = new Method({ name: 'poll', call: 'shh_getFilterChanges', params: 1 }); return [ newFilter, uninstallFilter, getLogs, poll ]; }
...
methods().forEach(function(method) {
method.attachToObject(self);
method.setRequestManager(self._requestManager);
});
};
Shh.prototype.filter = function (fil, callback) {
return new Filter(this._requestManager, fil, watches.shh(), formatters.outputPostFormatter
, callback);
};
var methods = function () {
var post = new Method({
name: 'post',
call: 'shh_post',
...
function Web3(provider) { this._requestManager = new RequestManager(provider); this.currentProvider = provider; this.eth = new Eth(this); this.db = new DB(this); this.shh = new Shh(this); this.net = new Net(this); this.personal = new Personal(this); this.bzz = new Swarm(this); this.settings = new Settings(); this.version = { api: version.version }; this.providers = { HttpProvider: HttpProvider, IpcProvider: IpcProvider }; this._extend = extend(this); this._extend({ properties: properties() }); }
n/a
function BigNumber( n, b ) { var c, e, i, num, len, str, x = this; // Enable constructor usage without new. if ( !( x instanceof BigNumber ) ) { // 'BigNumber() constructor call without new: {n}' if (ERRORS) raise( 26, 'constructor call without new', n ); return new BigNumber( n, b ); } // 'new BigNumber() base not an integer: {b}' // 'new BigNumber() base out of range: {b}' if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) { // Duplicate. if ( n instanceof BigNumber ) { x.s = n.s; x.e = n.e; x.c = ( n = n.c ) ? n.slice() : n; id = 0; return; } if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) { x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1; // Fast path for integers. if ( n === ~~n ) { for ( e = 0, i = n; i >= 10; i /= 10, e++ ); x.e = e; x.c = [n]; id = 0; return; } str = n + ''; } else { if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num ); x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1; } } else { b = b | 0; str = n + ''; // Ensure return value is rounded to DECIMAL_PLACES as with other bases. // Allow exponential notation to be used with base 10 argument. if ( b == 10 ) { x = new BigNumber( n instanceof BigNumber ? n : str ); return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE ); } // Avoid potential interpretation of Infinity and NaN as base 44+ values. // Any number in exponential form will fail due to the [Ee][+-]. if ( ( num = typeof n == 'number' ) && n * 0 != 0 || !( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) + '(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) { return parseNumeric( x, str, num, b ); } if (num) { x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1; if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) { // 'new BigNumber() number type has more than 15 significant digits: {n}' raise( id, tooManyDigits, n ); } // Prevent later check for length on converted number. num = false; } else { x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1; } str = convertBase( str, 10, b, x.s ); } // Decimal point? if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' ); // Exponential form? if ( ( i = str.search( /e/i ) ) > 0 ) { // Determine exponent. if ( e < 0 ) e = i; e += +str.slice( i + 1 ); str = str.substring( 0, i ); } else if ( e < 0 ) { // Integer. e = str.length; } // Determine leading zeros. for ( i = 0; str.charCodeAt(i) === 48; i++ ); // Determine trailing zeros. for ( len = str.length; str.charCodeAt(--len) === 48; ); str = str.slice( i, len + 1 ); if (str) { len = str.length; // Disallow numbers with over 15 significant digits if number type. // 'new BigNumber() number type has more than 15 significant digits: {n}' if ( num && ERRORS && len > 15 ) raise( id, tooManyDigits, x.s * n ); e = e - i - 1; // Overflow? if ( e > MAX_EXP ) { // Infinity. x.c = x.e = null; // Underflow? } else if ( e < MIN_EXP ) { // Zero. x.c = [ x.e = 0 ]; } else { x.e = e; x.c = []; // Transform base // e is the base 10 exponent. // i is where to slice str to get the first element of the coefficient array. i = ( e + 1 ) % LOG_BASE; if ( e < 0 ) i += LOG_BASE; if ( i < len ) { ...
n/a
createBatch = function () { return new Batch(this); }
n/a
fromAscii = function (str) { var hex = ""; for(var i = 0; i < str.length; i++) { var code = str.charCodeAt(i); var n = code.toString(16); hex += n.length < 2 ? '0' + n : n; } return "0x" + hex; }
...
validateIBAN();
};
function transfer() {
var value = new BigNumber(document.getElementById('value').value);
var exchange = document.getElementById('exchange').value;
var client = document.getElementById('client').value;
deposit.deposit(web3.fromAscii(client), {value: value});
displayTransfer("deposited client's " + client + " funds " + value.toString(10) + " to exchange
" + exchange);
};
function displayTransfer(text) {
var node = document.createElement('li');
var textnode = document.createTextNode(text);
node.appendChild(textnode);
...
fromDecimal = function (value) { var number = toBigNumber(value); var result = number.toString(16); return number.lessThan(0) ? '-0x' + result.substr(1) : '0x' + result; }
...
if (options.to) { // it might be contract creation
options.to = inputAddressFormatter(options.to);
}
['gasPrice', 'gas', 'value', 'nonce'].filter(function (key) {
return options[key] !== undefined;
}).forEach(function(key){
options[key] = utils.fromDecimal(options[key]);
});
return options;
};
/**
* Formats the input of a transaction and converts all values to HEX
...
fromICAP = function (icap) { var iban = new Iban(icap); return iban.address(); }
n/a
fromUtf8 = function (str) { str = utf8.encode(str); var hex = ""; for(var i = 0; i < str.length; i++) { var code = str.charCodeAt(i); if (code === 0) break; var n = code.toString(16); hex += n.length < 2 ? '0' + n : n; } return "0x" + hex; }
...
* Formats input value to byte representation of string
*
* @method formatInputString
* @param {String}
* @returns {SolidityParam}
*/
var formatInputString = function (value) {
var result = utils.fromUtf8(value).substr(2);
var length = result.length / 2;
var l = Math.floor((result.length + 63) / 64);
result = utils.padRight(result, l * 64);
return new SolidityParam(formatInputInt(length).value + result);
};
/**
...
fromWei = function (number, unit) { var returnValue = toBigNumber(number).dividedBy(getValueOfUnit(unit)); return isBigNumber(number) ? returnValue : returnValue.toString(10); }
n/a
isAddress = function (address) { if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) { // check if it has the basic requirements of an address return false; } else if (/^(0x)?[0-9a-f]{40}$/.test(address) || /^(0x)?[0-9A-F]{40}$/.test(address)) { // If it's all small caps or all all caps, return true return true; } else { // Otherwise check each case return isChecksumAddress(address); } }
...
var inputAddressFormatter = function (address) {
var iban = new Iban(address);
if (iban.isValid() && iban.isDirect()) {
return '0x' + iban.address();
} else if (utils.isStrictAddress(address)) {
return address;
} else if (utils.isAddress(address)) {
return '0x' + address;
}
throw new Error('invalid address');
};
var outputSyncingFormatter = function(result) {
...
isChecksumAddress = function (address) { // Check each case address = address.replace('0x',''); var addressHash = sha3(address.toLowerCase()); for (var i = 0; i < 40; i++ ) { // the nth letter should be uppercase if the nth digit of casemap is 1 if ((parseInt(addressHash[i], 16) > 7 && address[i].toUpperCase() !== address[i]) || (parseInt(addressHash[i], 16) <= 7 && address[i].toLowerCase() !== address[i])) { return false; } } return true; }
n/a
isConnected = function (){ return (this.currentProvider && this.currentProvider.isConnected()); }
...
getter: 'shh_version',
inputFormatter: utils.toDecimal
})
];
};
Web3.prototype.isConnected = function(){
return (this.currentProvider && this.currentProvider.isConnected());
};
Web3.prototype.createBatch = function () {
return new Batch(this);
};
module.exports = Web3;
...
reset = function (keepIsSyncing) { this._requestManager.reset(keepIsSyncing); this.settings = new Settings(); }
...
Web3.prototype.setProvider = function (provider) {
this._requestManager.setProvider(provider);
this.currentProvider = provider;
};
Web3.prototype.reset = function (keepIsSyncing) {
this._requestManager.reset(keepIsSyncing);
this.settings = new Settings();
};
Web3.prototype.BigNumber = BigNumber;
Web3.prototype.toHex = utils.toHex;
Web3.prototype.toAscii = utils.toAscii;
Web3.prototype.toUtf8 = utils.toUtf8;
...
setProvider = function (provider) { this._requestManager.setProvider(provider); this.currentProvider = provider; }
...
```js
console.log(web3); // {eth: .., shh: ...} // it's here!
```
Set a provider (HttpProvider)
```js
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
```
There you go, now you can use it:
```js
var coinbase = web3.eth.coinbase;
var balance = web3.eth.getBalance(coinbase);
...
sha3 = function (string, options) { return '0x' + sha3(string, options); }
n/a
toAscii = function (hex) { // Find termination var str = ""; var i = 0, l = hex.length; if (hex.substring(0, 2) === '0x') { i = 2; } for (; i < l; i+=2) { var code = parseInt(hex.substr(i, 2), 16); str += String.fromCharCode(code); } return str; }
...
var outputPostFormatter = function(post){
post.expiry = utils.toDecimal(post.expiry);
post.sent = utils.toDecimal(post.sent);
post.ttl = utils.toDecimal(post.ttl);
post.workProved = utils.toDecimal(post.workProved);
// post.payloadRaw = post.payload;
// post.payload = utils.toAscii(post.payload);
// if (utils.isJson(post.payload)) {
// post.payload = JSON.parse(post.payload);
// }
// format the following options
if (!post.topics) {
...
toBigNumber = function (number) {
/*jshint maxcomplexity:5 */
number = number || 0;
if (isBigNumber(number))
return number;
if (isString(number) && (number.indexOf('0x') === 0 || number.indexOf('-0x') === 0)) {
return new BigNumber(number.replace('0x',''), 16);
}
return new BigNumber(number.toString(10), 10);
}
...
* Should the format output to a big number
*
* @method outputBigNumberFormatter
* @param {String|Number|BigNumber}
* @returns {BigNumber} object
*/
var outputBigNumberFormatter = function (number) {
return utils.toBigNumber(number);
};
var isPredefinedBlockNumber = function (blockNumber) {
return blockNumber === 'latest' || blockNumber === 'pending' || blockNumber === 'earliest';
};
var inputDefaultBlockNumberFormatter = function (blockNumber) {
...
toChecksumAddress = function (address) { if (typeof address === 'undefined') return ''; address = address.toLowerCase().replace('0x',''); var addressHash = sha3(address); var checksumAddress = '0x'; for (var i = 0; i < address.length; i++ ) { // If ith character is 9 to f then make it uppercase if (parseInt(addressHash[i], 16) > 7) { checksumAddress += address[i].toUpperCase(); } else { checksumAddress += address[i]; } } return checksumAddress; }
n/a
toDecimal = function (value) { return toBigNumber(value).toNumber(); }
...
*
* @method outputTransactionFormatter
* @param {Object} tx
* @returns {Object}
*/
var outputTransactionFormatter = function (tx){
if(tx.blockNumber !== null)
tx.blockNumber = utils.toDecimal(tx.blockNumber);
if(tx.transactionIndex !== null)
tx.transactionIndex = utils.toDecimal(tx.transactionIndex);
tx.nonce = utils.toDecimal(tx.nonce);
tx.gas = utils.toDecimal(tx.gas);
tx.gasPrice = utils.toBigNumber(tx.gasPrice);
tx.value = utils.toBigNumber(tx.value);
return tx;
...
toHex = function (val) {
/*jshint maxcomplexity: 8 */
if (isBoolean(val))
return fromDecimal(+val);
if (isBigNumber(val))
return fromDecimal(val);
if (isObject(val))
return fromUtf8(JSON.stringify(val));
// if its a negative number, pass it through fromDecimal
if (isString(val)) {
if (val.indexOf('-0x') === 0)
return fromDecimal(val);
else if(val.indexOf('0x') === 0)
return val;
else if (!isFinite(val))
return fromAscii(val);
}
return fromDecimal(val);
}
...
* Formats input bytes
*
* @method formatInputBytes
* @param {String}
* @returns {SolidityParam}
*/
var formatInputBytes = function (value) {
var result = utils.toHex(value).substr(2);
var l = Math.floor((result.length + 63) / 64);
result = utils.padRight(result, l * 64);
return new SolidityParam(result);
};
/**
* Formats input bytes
...
toUtf8 = function (hex) { // Find termination var str = ""; var i = 0, l = hex.length; if (hex.substring(0, 2) === '0x') { i = 2; } for (; i < l; i+=2) { var code = parseInt(hex.substr(i, 2), 16); if (code === 0) break; str += String.fromCharCode(code); } return utf8.decode(str); }
...
*
* @method formatOutputString
* @param {SolidityParam} left-aligned hex representation of string
* @returns {String} ascii string
*/
var formatOutputString = function (param) {
var length = (new BigNumber(param.dynamicPart().slice(0, 64), 16)).toNumber() * 2;
return utils.toUtf8(param.dynamicPart().substr(64, length));
};
/**
* Should be used to format output address
*
* @method formatOutputAddress
* @param {SolidityParam} right-aligned input bytes
...
toWei = function (number, unit) { var returnValue = toBigNumber(number).times(getValueOfUnit(unit)); return isBigNumber(number) ? returnValue : returnValue.toString(10); }
n/a
function BigNumber( n, b ) { var c, e, i, num, len, str, x = this; // Enable constructor usage without new. if ( !( x instanceof BigNumber ) ) { // 'BigNumber() constructor call without new: {n}' if (ERRORS) raise( 26, 'constructor call without new', n ); return new BigNumber( n, b ); } // 'new BigNumber() base not an integer: {b}' // 'new BigNumber() base out of range: {b}' if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) { // Duplicate. if ( n instanceof BigNumber ) { x.s = n.s; x.e = n.e; x.c = ( n = n.c ) ? n.slice() : n; id = 0; return; } if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) { x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1; // Fast path for integers. if ( n === ~~n ) { for ( e = 0, i = n; i >= 10; i /= 10, e++ ); x.e = e; x.c = [n]; id = 0; return; } str = n + ''; } else { if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num ); x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1; } } else { b = b | 0; str = n + ''; // Ensure return value is rounded to DECIMAL_PLACES as with other bases. // Allow exponential notation to be used with base 10 argument. if ( b == 10 ) { x = new BigNumber( n instanceof BigNumber ? n : str ); return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE ); } // Avoid potential interpretation of Infinity and NaN as base 44+ values. // Any number in exponential form will fail due to the [Ee][+-]. if ( ( num = typeof n == 'number' ) && n * 0 != 0 || !( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) + '(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) { return parseNumeric( x, str, num, b ); } if (num) { x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1; if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) { // 'new BigNumber() number type has more than 15 significant digits: {n}' raise( id, tooManyDigits, n ); } // Prevent later check for length on converted number. num = false; } else { x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1; } str = convertBase( str, 10, b, x.s ); } // Decimal point? if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' ); // Exponential form? if ( ( i = str.search( /e/i ) ) > 0 ) { // Determine exponent. if ( e < 0 ) e = i; e += +str.slice( i + 1 ); str = str.substring( 0, i ); } else if ( e < 0 ) { // Integer. e = str.length; } // Determine leading zeros. for ( i = 0; str.charCodeAt(i) === 48; i++ ); // Determine trailing zeros. for ( len = str.length; str.charCodeAt(--len) === 48; ); str = str.slice( i, len + 1 ); if (str) { len = str.length; // Disallow numbers with over 15 significant digits if number type. // 'new BigNumber() number type has more than 15 significant digits: {n}' if ( num && ERRORS && len > 15 ) raise( id, tooManyDigits, x.s * n ); e = e - i - 1; // Overflow? if ( e > MAX_EXP ) { // Infinity. x.c = x.e = null; // Underflow? } else if ( e < MIN_EXP ) { // Zero. x.c = [ x.e = 0 ]; } else { x.e = e; x.c = []; // Transform base // e is the base 10 exponent. // i is where to slice str to get the first element of the coefficient array. i = ( e + 1 ) % LOG_BASE; if ( e < 0 ) i += LOG_BASE; if ( i < len ) { ...
n/a
function another(configObj) {
var div,
// id tracks the caller function, so its name can be included in error messages.
id = 0,
P = BigNumber.prototype,
ONE = new BigNumber(1),
/********************************* EDITABLE DEFAULTS **********************************/
/*
* The default values below must be integers within the inclusive ranges stated.
* The values can also be changed at run-time using BigNumber.config.
*/
// The maximum number of decimal places for operations involving division.
DECIMAL_PLACES = 20, // 0 to MAX
/*
* The rounding mode used when rounding to the above decimal places, and when using
* toExponential, toFixed, toFormat and toPrecision, and round (default value).
* UP 0 Away from zero.
* DOWN 1 Towards zero.
* CEIL 2 Towards +Infinity.
* FLOOR 3 Towards -Infinity.
* HALF_UP 4 Towards nearest neighbour. If equidistant, up.
* HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
* HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
* HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
* HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
*/
ROUNDING_MODE = 4, // 0 to 8
// EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]
// The exponent value at and beneath which toString returns exponential notation.
// Number type: -7
TO_EXP_NEG = -7, // 0 to -MAX
// The exponent value at and above which toString returns exponential notation.
// Number type: 21
TO_EXP_POS = 21, // 0 to MAX
// RANGE : [MIN_EXP, MAX_EXP]
// The minimum exponent value, beneath which underflow to zero occurs.
// Number type: -324 (5e-324)
MIN_EXP = -1e7, // -1 to -MAX
// The maximum exponent value, above which overflow to Infinity occurs.
// Number type: 308 (1.7976931348623157e+308)
// For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.
MAX_EXP = 1e7, // 1 to MAX
// Whether BigNumber Errors are ever thrown.
ERRORS = true, // true or false
// Change to intValidatorNoErrors if ERRORS is false.
isValidInt = intValidatorWithErrors, // intValidatorWithErrors/intValidatorNoErrors
// Whether to use cryptographically-secure random number generation, if available.
CRYPTO = false, // true or false
/*
* The modulo mode used when calculating the modulus: a mod n.
* The quotient (q = a / n) is calculated according to the corresponding rounding mode.
* The remainder (r) is calculated as: r = a - n * q.
*
* UP 0 The remainder is positive if the dividend is negative, else is negative.
* DOWN 1 The remainder has the same sign as the dividend.
* This modulo mode is commonly known as 'truncated division' and is
* equivalent to (a % n) in JavaScript.
* FLOOR 3 The remainder has the same sign as the divisor (Python %).
* HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.
* EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).
* The remainder is always positive.
*
* The truncated division, floored division, Euclidian division and IEEE 754 remainder
* modes are commonly used for the modulus operation.
* Although the other rounding modes can also be used, they may not give useful results.
*/
MODULO_MODE = 1, // 0 to 9
// The maximum number of significant digits of ...
n/a
function BigNumber( n, b ) { var c, e, i, num, len, str, x = this; // Enable constructor usage without new. if ( !( x instanceof BigNumber ) ) { // 'BigNumber() constructor call without new: {n}' if (ERRORS) raise( 26, 'constructor call without new', n ); return new BigNumber( n, b ); } // 'new BigNumber() base not an integer: {b}' // 'new BigNumber() base out of range: {b}' if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) { // Duplicate. if ( n instanceof BigNumber ) { x.s = n.s; x.e = n.e; x.c = ( n = n.c ) ? n.slice() : n; id = 0; return; } if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) { x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1; // Fast path for integers. if ( n === ~~n ) { for ( e = 0, i = n; i >= 10; i /= 10, e++ ); x.e = e; x.c = [n]; id = 0; return; } str = n + ''; } else { if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num ); x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1; } } else { b = b | 0; str = n + ''; // Ensure return value is rounded to DECIMAL_PLACES as with other bases. // Allow exponential notation to be used with base 10 argument. if ( b == 10 ) { x = new BigNumber( n instanceof BigNumber ? n : str ); return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE ); } // Avoid potential interpretation of Infinity and NaN as base 44+ values. // Any number in exponential form will fail due to the [Ee][+-]. if ( ( num = typeof n == 'number' ) && n * 0 != 0 || !( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) + '(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) { return parseNumeric( x, str, num, b ); } if (num) { x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1; if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) { // 'new BigNumber() number type has more than 15 significant digits: {n}' raise( id, tooManyDigits, n ); } // Prevent later check for length on converted number. num = false; } else { x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1; } str = convertBase( str, 10, b, x.s ); } // Decimal point? if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' ); // Exponential form? if ( ( i = str.search( /e/i ) ) > 0 ) { // Determine exponent. if ( e < 0 ) e = i; e += +str.slice( i + 1 ); str = str.substring( 0, i ); } else if ( e < 0 ) { // Integer. e = str.length; } // Determine leading zeros. for ( i = 0; str.charCodeAt(i) === 48; i++ ); // Determine trailing zeros. for ( len = str.length; str.charCodeAt(--len) === 48; ); str = str.slice( i, len + 1 ); if (str) { len = str.length; // Disallow numbers with over 15 significant digits if number type. // 'new BigNumber() number type has more than 15 significant digits: {n}' if ( num && ERRORS && len > 15 ) raise( id, tooManyDigits, x.s * n ); e = e - i - 1; // Overflow? if ( e > MAX_EXP ) { // Infinity. x.c = x.e = null; // Underflow? } else if ( e < MIN_EXP ) { // Zero. x.c = [ x.e = 0 ]; } else { x.e = e; x.c = []; // Transform base // e is the base 10 exponent. // i is where to slice str to get the first element of the coefficient array. i = ( e + 1 ) % LOG_BASE; if ( e < 0 ) i += LOG_BASE; if ( i < len ) { ...
n/a
config = function () { var v, p, i = 0, r = {}, a = arguments, o = a[0], has = o && typeof o == 'object' ? function () { if ( o.hasOwnProperty(p) ) return ( v = o[p] ) != null; } : function () { if ( a.length > i ) return ( v = a[i++] ) != null; }; // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. // 'config() DECIMAL_PLACES not an integer: {v}' // 'config() DECIMAL_PLACES out of range: {v}' if ( has( p = 'DECIMAL_PLACES' ) && isValidInt( v, 0, MAX, 2, p ) ) { DECIMAL_PLACES = v | 0; } r[p] = DECIMAL_PLACES; // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. // 'config() ROUNDING_MODE not an integer: {v}' // 'config() ROUNDING_MODE out of range: {v}' if ( has( p = 'ROUNDING_MODE' ) && isValidInt( v, 0, 8, 2, p ) ) { ROUNDING_MODE = v | 0; } r[p] = ROUNDING_MODE; // EXPONENTIAL_AT {number|number[]} // Integer, -MAX to MAX inclusive or [integer -MAX to 0 inclusive, 0 to MAX inclusive]. // 'config() EXPONENTIAL_AT not an integer: {v}' // 'config() EXPONENTIAL_AT out of range: {v}' if ( has( p = 'EXPONENTIAL_AT' ) ) { if ( isArray(v) ) { if ( isValidInt( v[0], -MAX, 0, 2, p ) && isValidInt( v[1], 0, MAX, 2, p ) ) { TO_EXP_NEG = v[0] | 0; TO_EXP_POS = v[1] | 0; } } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) { TO_EXP_NEG = -( TO_EXP_POS = ( v < 0 ? -v : v ) | 0 ); } } r[p] = [ TO_EXP_NEG, TO_EXP_POS ]; // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. // 'config() RANGE not an integer: {v}' // 'config() RANGE cannot be zero: {v}' // 'config() RANGE out of range: {v}' if ( has( p = 'RANGE' ) ) { if ( isArray(v) ) { if ( isValidInt( v[0], -MAX, -1, 2, p ) && isValidInt( v[1], 1, MAX, 2, p ) ) { MIN_EXP = v[0] | 0; MAX_EXP = v[1] | 0; } } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) { if ( v | 0 ) MIN_EXP = -( MAX_EXP = ( v < 0 ? -v : v ) | 0 ); else if (ERRORS) raise( 2, p + ' cannot be zero', v ); } } r[p] = [ MIN_EXP, MAX_EXP ]; // ERRORS {boolean|number} true, false, 1 or 0. // 'config() ERRORS not a boolean or binary digit: {v}' if ( has( p = 'ERRORS' ) ) { if ( v === !!v || v === 1 || v === 0 ) { id = 0; isValidInt = ( ERRORS = !!v ) ? intValidatorWithErrors : intValidatorNoErrors; } else if (ERRORS) { raise( 2, p + notBool, v ); } } r[p] = ERRORS; // CRYPTO {boolean|number} true, false, 1 or 0. // 'config() CRYPTO not a boolean or binary digit: {v}' // 'config() crypto unavailable: {crypto}' if ( has( p = 'CRYPTO' ) ) { if ( v === !!v || v === 1 || v === 0 ) { CRYPTO = !!( v && crypto && typeof crypto == 'object' ); if ( v && !CRYPTO && ERRORS ) raise( 2, 'crypto unavailable', crypto ); } else if (ERRORS) { raise( 2, p + notBool, v ); } } r[p] = CRYPTO; // MODULO_MODE {number} Integer, 0 to 9 inclusive. // 'config() MODULO_MODE not an integer: {v}' // 'config() MODULO_MODE out of range: {v}' if ( has( p = 'MODULO_MODE' ) && isValidInt( v, 0, 9, 2, p ) ) { MODULO_MODE = v | 0; } r[p] = MODULO_MODE; // POW_PRECISION {number} Integer, 0 to MAX inclusive. // 'config() POW_PRECISION not an integer: {v}' // 'config() POW_PRECISION out of range: {v}' if ( has( p = 'POW_PRECISION' ) && isValidInt( v, 0, MAX, 2, p ) ) { POW_PRECISION = v | 0; } r[p] = POW_PRECISION; // FORMAT {object} // 'config() FORMAT not an object: {v}' if ( has( p = 'FORMAT' ) ) { if ( typeof v == 'object' ) { FORMAT = v; } else if (ERRORS) { raise( 2, p + ' not an object', v ); } } r[p] = FORMAT; ...
...
* If the value is floating point, round it down
*
* @method formatInputInt
* @param {String|Number|BigNumber} value that needs to be formatted
* @returns {SolidityParam}
*/
var formatInputInt = function (value) {
BigNumber.config(c.ETH_BIGNUMBER_ROUNDING_MODE);
var result = utils.padLeft(utils.toTwosComplement(value).toString(16), 64);
return new SolidityParam(result);
};
/**
* Formats input bytes
*
...
max = function () { return maxOrMin( arguments, P.lt ); }
...
var nBlocksReady = dataSigBytes / blockSizeBytes;
if (doFlush) {
// Round up to include partial blocks
nBlocksReady = Math.ceil(nBlocksReady);
} else {
// Round down to include only full blocks,
// less the number of blocks that must remain in the buffer
nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
}
// Count words ready
var nWordsReady = nBlocksReady * blockSize;
// Count bytes ready
var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
...
min = function () { return maxOrMin( arguments, P.gt ); }
...
nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
}
// Count words ready
var nWordsReady = nBlocksReady * blockSize;
// Count bytes ready
var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
// Process blocks
if (nWordsReady) {
for (var offset = 0; offset < nWordsReady; offset += blockSize) {
// Perform concrete-algorithm logic
this._doProcessBlock(dataWords, offset);
}
...
random = function (dp) { var a, b, e, k, v, i = 0, c = [], rand = new BigNumber(ONE); dp = dp == null || !isValidInt( dp, 0, MAX, 14 ) ? DECIMAL_PLACES : dp | 0; k = mathceil( dp / LOG_BASE ); if (CRYPTO) { // Browsers supporting crypto.getRandomValues. if ( crypto && crypto.getRandomValues ) { a = crypto.getRandomValues( new Uint32Array( k *= 2 ) ); for ( ; i < k; ) { // 53 bits: // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) // 11111 11111111 11111111 11111111 11100000 00000000 00000000 // ((Math.pow(2, 32) - 1) >>> 11).toString(2) // 11111 11111111 11111111 // 0x20000 is 2^21. v = a[i] * 0x20000 + (a[i + 1] >>> 11); // Rejection sampling: // 0 <= v < 9007199254740992 // Probability that v >= 9e15, is // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 if ( v >= 9e15 ) { b = crypto.getRandomValues( new Uint32Array(2) ); a[i] = b[0]; a[i + 1] = b[1]; } else { // 0 <= v <= 8999999999999999 // 0 <= (v % 1e14) <= 99999999999999 c.push( v % 1e14 ); i += 2; } } i = k / 2; // Node.js supporting crypto.randomBytes. } else if ( crypto && crypto.randomBytes ) { // buffer a = crypto.randomBytes( k *= 7 ); for ( ; i < k; ) { // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 // 0x100000000 is 2^32, 0x1000000 is 2^24 // 11111 11111111 11111111 11111111 11111111 11111111 11111111 // 0 <= v < 9007199254740992 v = ( ( a[i] & 31 ) * 0x1000000000000 ) + ( a[i + 1] * 0x10000000000 ) + ( a[i + 2] * 0x100000000 ) + ( a[i + 3] * 0x1000000 ) + ( a[i + 4] << 16 ) + ( a[i + 5] << 8 ) + a[i + 6]; if ( v >= 9e15 ) { crypto.randomBytes(7).copy( a, i ); } else { // 0 <= (v % 1e14) <= 99999999999999 c.push( v % 1e14 ); i += 7; } } i = k / 7; } else if (ERRORS) { raise( 14, 'crypto unavailable', crypto ); } } // Use Math.random: CRYPTO is false or crypto is unavailable and ERRORS is false. if (!i) { for ( ; i < k; ) { v = random53bitInt(); if ( v < 9e15 ) c[i++] = v % 1e14; } } k = c[--i]; dp %= LOG_BASE; // Convert trailing digits to zeros according to dp. if ( k && dp ) { v = POWS_TEN[LOG_BASE - dp]; c[i] = mathfloor( k / v ) * v; } // Remove trailing elements which are zero. for ( ; c[i] === 0; c.pop(), i-- ); // Zero? if ( i < 0 ) { c = [ e = 0 ]; } else { // Remove leading elements which are zero and adjust exponent accordingly. for ( e = -1 ; c[0] === 0; c.shift(), e -= LOG_BASE); // Count the digits of the first element of c to determine leading zeros, and... for ( i = 1, v = c[0]; v >= 10; v /= 10, i++); // adjust the exponent accordingly. if ( i < LOG_BASE ) e -= LOG_BASE - i; } rand.e = e; rand.c = c; return rand; }
...
*
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
*/
execute: function (password, keySize, ivSize, salt) {
// Generate random salt
if (!salt) {
salt = WordArray.random(64/8);
}
// Derive key and IV
var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt);
// Separate key and IV
var iv = WordArray.create(key.words.slice(keySize), ivSize * 4);
...
abs = function () { var x = new BigNumber(this); if ( x.s < 0 ) x.s = 1; return x; }
...
// Constants table
var T = [];
// Compute constants
(function () {
for (var i = 0; i < 64; i++) {
T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0;
}
}());
/**
* MD5 hash algorithm.
*/
var MD5 = C_algo.MD5 = Hasher.extend({
...
absoluteValue = function () { var x = new BigNumber(this); if ( x.s < 0 ) x.s = 1; return x; }
n/a
add = function ( y, b ) { var t, x = this, a = x.s; id = 12; y = new BigNumber( y, b ); b = y.s; // Either NaN? if ( !a || !b ) return new BigNumber(NaN); // Signs differ? if ( a != b ) { y.s = -b; return x.minus(y); } var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c; if ( !xe || !ye ) { // Return ±Infinity if either ±Infinity. if ( !xc || !yc ) return new BigNumber( a / 0 ); // Either zero? // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 ); } xe = bitFloor(xe); ye = bitFloor(ye); xc = xc.slice(); // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. if ( a = xe - ye ) { if ( a > 0 ) { ye = xe; t = yc; } else { a = -a; t = xc; } t.reverse(); for ( ; a--; t.push(0) ); t.reverse(); } a = xc.length; b = yc.length; // Point xc to the longer array, and b to the shorter length. if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a; // Only start adding at yc.length - 1 as the further digits of xc can be ignored. for ( a = 0; b; ) { a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0; xc[b] %= BASE; } if (a) { xc.unshift(a); ++ye; } // No need to check for zero, as +x + +y != 0 && -x + -y != 0 // ye = MAX_EXP + 1 possible return normalise( y, xc, ye ); }
...
});
gulp.task('light', ['clean'], function () {
return browserify(browserifyOptions)
.require('./' + src + '.js', {expose: 'web3'})
.ignore('bignumber.js')
.require('./lib/utils/browser-bn.js', {expose: 'bignumber.js'}) // fake bignumber.js
.add('./' + src + '.js')
.bundle()
.pipe(exorcist(path.join( DEST, lightDst + '.js.map')))
.pipe(source(lightDst + '.js'))
.pipe(gulp.dest( DEST ))
.pipe(streamify(uglify()))
.pipe(rename(lightDst + '.min.js'))
.pipe(gulp.dest( DEST ));
...
ceil = function () { return round( new BigNumber(this), this.e + 1, 2 ); }
...
clamp: function () {
// Shortcuts
var words = this.words;
var sigBytes = this.sigBytes;
// Clamp
words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
words.length = Math.ceil(sigBytes / 4);
},
/**
* Creates a copy of this word array.
*
* @return {WordArray} The clone.
*
...
cmp = function ( y, b ) { id = 1; return compare( this, new BigNumber( y, b ) ); }
...
if ( !xc ) return x.toString();
s = coeffToString(xc);
// Determine initial denominator.
// d is a power of 10 and the minimum max denominator that specifies the value exactly.
e = d.e = s.length - x.e - 1;
d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ];
md = !md || n.cmp(d) > 0 ? ( e > 0 ? d : n1 ) : n;
exp = MAX_EXP;
MAX_EXP = 1 / 0;
n = new BigNumber(s);
// n0 = d1 = 0
n0.c[0] = 0;
...
comparedTo = function ( y, b ) { id = 1; return compare( this, new BigNumber( y, b ) ); }
n/a
decimalPlaces = function () { var n, v, c = this.c; if ( !c ) return null; n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE; // Subtract the number of trailing zeros of the last number. if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- ); if ( n < 0 ) n = 0; return n; }
n/a
div = function ( y, b ) { id = 3; return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE ); }
...
i = mathfloor( i / 2 );
if ( !i ) break;
x = x.times(x);
if ( k && x.c && x.c.length > k ) x.c.length = k;
}
if ( n < 0 ) y = ONE.div(y);
return k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y;
};
/*
* Return a string representing the value of this BigNumber rounded to sd significant digits
* using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits
...
divToInt = function ( y, b ) { id = 4; return div( this, new BigNumber( y, b ), 0, 1 ); }
n/a
dividedBy = function ( y, b ) { id = 3; return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE ); }
...
* Formats right-aligned output bytes to real
*
* @method formatOutputReal
* @param {SolidityParam}
* @returns {BigNumber} input bytes formatted to real
*/
var formatOutputReal = function (param) {
return formatOutputInt(param).dividedBy(new BigNumber(2).pow(128));
};
/**
* Formats right-aligned output bytes to ureal
*
* @method formatOutputUReal
* @param {SolidityParam}
...
dividedToIntegerBy = function ( y, b ) { id = 4; return div( this, new BigNumber( y, b ), 0, 1 ); }
n/a
dp = function () { var n, v, c = this.c; if ( !c ) return null; n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE; // Subtract the number of trailing zeros of the last number. if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- ); if ( n < 0 ) n = 0; return n; }
n/a
eq = function ( y, b ) { id = 5; return compare( this, new BigNumber( y, b ) ) === 0; }
...
if ( n == '9999' || !rep && n == '4999' ) {
// On the first iteration only, check to see if rounding up gives the
// exact result as the nines may infinitely repeat.
if ( !rep ) {
round( t, t.e + DECIMAL_PLACES + 2, 0 );
if ( t.times(t).eq(x) ) {
r = t;
break;
}
}
dp += 4;
s += 4;
...
equals = function ( y, b ) { id = 5; return compare( this, new BigNumber( y, b ) ) === 0; }
n/a
floor = function () { return round( new BigNumber(this), this.e + 1, 3 ); }
...
var encodeds = solidityTypes.map(function (solidityType, index) {
return solidityType.encode(params[index], types[index]);
});
var dynamicOffset = solidityTypes.reduce(function (acc, solidityType, index) {
var staticPartLength = solidityType.staticPartLength(types[index]);
var roundedStaticPartLength = Math.floor((staticPartLength + 31) / 32) * 32;
return acc + (isDynamic(solidityTypes[index], types[index]) ?
32 :
roundedStaticPartLength);
}, 0);
var result = this.encodeMultiWithOffset(types, solidityTypes, encodeds, dynamicOffset);
...
greaterThan = function ( y, b ) { id = 6; return compare( this, new BigNumber( y, b ) ) > 0; }
n/a
greaterThanOrEqualTo = function ( y, b ) { id = 7; return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0; }
n/a
gt = function ( y, b ) { id = 6; return compare( this, new BigNumber( y, b ) ) > 0; }
n/a
gte = function ( y, b ) { id = 7; return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0; }
...
if (ERRORS) {
raise( 22,
'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md );
}
// ERRORS is false:
// If md is a finite non-integer >= 1, round it to an integer and use it.
md = !k && n.c && round( n, n.e + 1, 1 ).gte(ONE) ? n : null
;
}
}
if ( !xc ) return x.toString();
s = coeffToString(xc);
// Determine initial denominator.
...
isFinite = function () { return !!this.c; }
n/a
isInt = function () { return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2; }
...
d1 = n0 = new BigNumber(ONE);
if ( md != null ) {
ERRORS = false;
n = new BigNumber(md);
ERRORS = k;
if ( !( k = n.isInt() ) || n.lt(ONE) ) {
if (ERRORS) {
raise( 22,
'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md );
}
// ERRORS is false:
...
isInteger = function () { return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2; }
n/a
isNaN = function () { return !this.s; }
n/a
isNeg = function () { return this.s < 0; }
n/a
isNegative = function () { return this.s < 0; }
n/a
isZero = function () { return !!this.c && this.c[0] == 0; }
n/a
lessThan = function ( y, b ) { id = 8; return compare( this, new BigNumber( y, b ) ) < 0; }
...
* @param {String|Number|BigNumber}
* @return {String}
*/
var fromDecimal = function (value) {
var number = toBigNumber(value);
var result = number.toString(16);
return number.lessThan(0) ? '-0x' + result.substr(1) : '0x' +
result;
};
/**
* Auto converts any given value into it's hex representation.
*
* And even stringifys objects before.
*
...
lessThanOrEqualTo = function ( y, b ) { id = 9; return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0; }
n/a
lt = function ( y, b ) { id = 8; return compare( this, new BigNumber( y, b ) ) < 0; }
...
d1 = n0 = new BigNumber(ONE);
if ( md != null ) {
ERRORS = false;
n = new BigNumber(md);
ERRORS = k;
if ( !( k = n.isInt() ) || n.lt(ONE) ) {
if (ERRORS) {
raise( 22,
'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md );
}
// ERRORS is false:
...
lte = function ( y, b ) { id = 9; return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0; }
n/a
minus = function ( y, b ) { var i, j, t, xLTy, x = this, a = x.s; id = 10; y = new BigNumber( y, b ); b = y.s; // Either NaN? if ( !a || !b ) return new BigNumber(NaN); // Signs differ? if ( a != b ) { y.s = -b; return x.plus(y); } var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c; if ( !xe || !ye ) { // Either Infinity? if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN ); // Either zero? if ( !xc[0] || !yc[0] ) { // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x : // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity ROUNDING_MODE == 3 ? -0 : 0 ); } } xe = bitFloor(xe); ye = bitFloor(ye); xc = xc.slice(); // Determine which is the bigger number. if ( a = xe - ye ) { if ( xLTy = a < 0 ) { a = -a; t = xc; } else { ye = xe; t = yc; } t.reverse(); // Prepend zeros to equalise exponents. for ( b = a; b--; t.push(0) ); t.reverse(); } else { // Exponents equal. Check digit by digit. j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b; for ( a = b = 0; b < j; b++ ) { if ( xc[b] != yc[b] ) { xLTy = xc[b] < yc[b]; break; } } } // x < y? Point xc to the array of the bigger number. if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s; b = ( j = yc.length ) - ( i = xc.length ); // Append zeros to xc if shorter. // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. if ( b > 0 ) for ( ; b--; xc[i++] = 0 ); b = BASE - 1; // Subtract yc from xc. for ( ; j > a; ) { if ( xc[--j] < yc[j] ) { for ( i = j; i && !xc[--i]; xc[i] = b ); --xc[i]; xc[j] += BASE; } xc[j] -= yc[j]; } // Remove leading zeros and adjust exponent accordingly. for ( ; xc[0] == 0; xc.shift(), --ye ); // Zero? if ( !xc[0] ) { // Following IEEE 754 (2008) 6.3, // n - n = +0 but n - n = -0 when rounding towards -Infinity. y.s = ROUNDING_MODE == 3 ? -1 : 1; y.c = [ y.e = 0 ]; return y; } // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity // for finite x and y. return normalise( y, xc, ye ); }
...
*/
var formatOutputInt = function (param) {
var value = param.staticPart() || "0";
// check if it's negative number
// it it is, return two's complement
if (signedIsNegative(value)) {
return new BigNumber(value, 16).minus(new BigNumber('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
', 16)).minus(1);
}
return new BigNumber(value, 16);
};
/**
* Formats right-aligned output bytes to uint
*
...
mod = function ( y, b ) { var q, s, x = this; id = 11; y = new BigNumber( y, b ); // Return NaN if x is Infinity or NaN, or y is NaN or zero. if ( !x.c || !y.s || y.c && !y.c[0] ) { return new BigNumber(NaN); // Return x if y is Infinity or x is zero. } else if ( !y.c || x.c && !x.c[0] ) { return new BigNumber(x); } if ( MODULO_MODE == 9 ) { // Euclidian division: q = sign(y) * floor(x / abs(y)) // r = x - qy where 0 <= r < abs(y) s = y.s; y.s = 1; q = div( x, y, 0, 3 ); y.s = s; q.s *= s; } else { q = div( x, y, 0, MODULO_MODE ); } return x.minus( q.times(y) ); }
n/a
modulo = function ( y, b ) { var q, s, x = this; id = 11; y = new BigNumber( y, b ); // Return NaN if x is Infinity or NaN, or y is NaN or zero. if ( !x.c || !y.s || y.c && !y.c[0] ) { return new BigNumber(NaN); // Return x if y is Infinity or x is zero. } else if ( !y.c || x.c && !x.c[0] ) { return new BigNumber(x); } if ( MODULO_MODE == 9 ) { // Euclidian division: q = sign(y) * floor(x / abs(y)) // r = x - qy where 0 <= r < abs(y) s = y.s; y.s = 1; q = div( x, y, 0, 3 ); y.s = s; q.s *= s; } else { q = div( x, y, 0, MODULO_MODE ); } return x.minus( q.times(y) ); }
n/a
mul = function ( y, b ) { var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, base, sqrtBase, x = this, xc = x.c, yc = ( id = 17, y = new BigNumber( y, b ) ).c; // Either NaN, ±Infinity or ±0? if ( !xc || !yc || !xc[0] || !yc[0] ) { // Return NaN if either is NaN, or one is 0 and the other is Infinity. if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) { y.c = y.e = y.s = null; } else { y.s *= x.s; // Return ±Infinity if either is ±Infinity. if ( !xc || !yc ) { y.c = y.e = null; // Return ±0 if either is ±0. } else { y.c = [0]; y.e = 0; } } return y; } e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE ); y.s *= x.s; xcL = xc.length; ycL = yc.length; // Ensure xc points to longer array and xcL to its length. if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i; // Initialise the result array with zeros. for ( i = xcL + ycL, zc = []; i--; zc.push(0) ); base = BASE; sqrtBase = SQRT_BASE; for ( i = ycL; --i >= 0; ) { c = 0; ylo = yc[i] % sqrtBase; yhi = yc[i] / sqrtBase | 0; for ( k = xcL, j = i + k; j > i; ) { xlo = xc[--k] % sqrtBase; xhi = xc[k] / sqrtBase | 0; m = yhi * xlo + xhi * ylo; xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c; c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi; zc[j--] = xlo % base; } zc[j] = c; } if (c) { ++e; } else { zc.shift(); } return normalise( y, zc, e ); }
n/a
neg = function () { var x = new BigNumber(this); x.s = -x.s || null; return x; }
n/a
negated = function () { var x = new BigNumber(this); x.s = -x.s || null; return x; }
n/a
plus = function ( y, b ) { var t, x = this, a = x.s; id = 12; y = new BigNumber( y, b ); b = y.s; // Either NaN? if ( !a || !b ) return new BigNumber(NaN); // Signs differ? if ( a != b ) { y.s = -b; return x.minus(y); } var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c; if ( !xe || !ye ) { // Return ±Infinity if either ±Infinity. if ( !xc || !yc ) return new BigNumber( a / 0 ); // Either zero? // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 ); } xe = bitFloor(xe); ye = bitFloor(ye); xc = xc.slice(); // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. if ( a = xe - ye ) { if ( a > 0 ) { ye = xe; t = yc; } else { a = -a; t = xc; } t.reverse(); for ( ; a--; t.push(0) ); t.reverse(); } a = xc.length; b = yc.length; // Point xc to the longer array, and b to the shorter length. if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a; // Only start adding at yc.length - 1 as the further digits of xc can be ignored. for ( a = 0; b; ) { a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0; xc[b] %= BASE; } if (a) { xc.unshift(a); ++ye; } // No need to check for zero, as +x + +y != 0 && -x + -y != 0 // ye = MAX_EXP + 1 possible return normalise( y, xc, ye ); }
...
* @method toTwosComplement
* @param {Number|String|BigNumber}
* @return {BigNumber}
*/
var toTwosComplement = function (number) {
var bigNumber = toBigNumber(number).round();
if (bigNumber.lessThan(0)) {
return new BigNumber("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16).plus(bigNumber).plus(1);
}
return bigNumber;
};
/**
* Checks if the given string is strictly an address
*
...
pow = function (n) { var k, y, i = mathfloor( n < 0 ? -n : +n ), x = this; // Pass ±Infinity to Math.pow if exponent is out of range. if ( !isValidInt( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 23, 'exponent' ) && ( !isFinite(n) || i > MAX_SAFE_INTEGER && ( n /= 0 ) || parseFloat(n) != n && !( n = NaN ) ) ) { return new BigNumber( Math.pow( +x, n ) ); } // Truncating each coefficient array to a length of k after each multiplication equates // to truncating significant digits to POW_PRECISION + [28, 41], i.e. there will be a // minimum of 28 guard digits retained. (Using + 1.5 would give [9, 21] guard digits.) k = POW_PRECISION ? mathceil( POW_PRECISION / LOG_BASE + 2 ) : 0; y = new BigNumber(ONE); for ( ; ; ) { if ( i % 2 ) { y = y.times(x); if ( !y.c ) break; if ( k && y.c.length > k ) y.c.length = k; } i = mathfloor( i / 2 ); if ( !i ) break; x = x.times(x); if ( k && x.c && x.c.length > k ) x.c.length = k; } if ( n < 0 ) y = ONE.div(y); return k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y; }
...
* Values are multiplied by 2^m and encoded as integers
*
* @method formatInputReal
* @param {String|Number|BigNumber}
* @returns {SolidityParam}
*/
var formatInputReal = function (value) {
return formatInputInt(new BigNumber(value).times(new BigNumber(2).pow(128)));
};
/**
* Check if input value is negative
*
* @method signedIsNegative
* @param {String} value is hex format
...
precision = function (z) { var n, v, x = this, c = x.c; // 'precision() argument not a boolean or binary digit: {z}' if ( z != null && z !== !!z && z !== 1 && z !== 0 ) { if (ERRORS) raise( 13, 'argument' + notBool, z ); if ( z != !!z ) z = null; } if ( !c ) return null; v = c.length - 1; n = v * LOG_BASE + 1; if ( v = c[v] ) { // Subtract the number of trailing zeros of the last element. for ( ; v % 10 == 0; v /= 10, n-- ); // Add the number of digits of the first element. for ( v = c[0]; v >= 10; v /= 10, n++ ); } if ( z && x.e + 1 > n ) n = x.e + 1; return n; }
n/a
round = function ( dp, rm ) { var n = new BigNumber(this); if ( dp == null || isValidInt( dp, 0, MAX, 15 ) ) { round( n, ~~dp + this.e + 1, rm == null || !isValidInt( rm, 0, 8, 15, roundingMode ) ? ROUNDING_MODE : rm | 0 ); } return n; }
...
* Takes and input transforms it into bignumber and if it is negative value, into two's complement
*
* @method toTwosComplement
* @param {Number|String|BigNumber}
* @return {BigNumber}
*/
var toTwosComplement = function (number) {
var bigNumber = toBigNumber(number).round();
if (bigNumber.lessThan(0)) {
return new BigNumber("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16).plus(bigNumber).plus
(1);
}
return bigNumber;
};
/**
...
sd = function (z) { var n, v, x = this, c = x.c; // 'precision() argument not a boolean or binary digit: {z}' if ( z != null && z !== !!z && z !== 1 && z !== 0 ) { if (ERRORS) raise( 13, 'argument' + notBool, z ); if ( z != !!z ) z = null; } if ( !c ) return null; v = c.length - 1; n = v * LOG_BASE + 1; if ( v = c[v] ) { // Subtract the number of trailing zeros of the last element. for ( ; v % 10 == 0; v /= 10, n-- ); // Add the number of digits of the first element. for ( v = c[0]; v >= 10; v /= 10, n++ ); } if ( z && x.e + 1 > n ) n = x.e + 1; return n; }
n/a
shift = function (k) { var n = this; return isValidInt( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, 'argument' ) // k < 1e+21, or truncate(k) will produce exponential notation. ? n.times( '1e' + truncate(k) ) : new BigNumber( n.c && n.c[0] && ( k < -MAX_SAFE_INTEGER || k > MAX_SAFE_INTEGER ) ? n.s * ( k < 0 ? 0 : 1 / 0 ) : n ); }
...
var notIndexedParams = coder.decodeParams(this.types(false), notIndexedData);
var result = formatters.outputLogFormatter(data);
result.event = this.displayName();
result.address = data.address;
result.args = this._params.reduce(function (acc, current) {
acc[current.name] = current.indexed ? indexedParams.shift() : notIndexedParams.shift
();
return acc;
}, {});
delete result.data;
delete result.topics;
return result;
...
sqrt = function () { var m, n, r, rep, t, x = this, c = x.c, s = x.s, e = x.e, dp = DECIMAL_PLACES + 4, half = new BigNumber('0.5'); // Negative/NaN/Infinity/zero? if ( s !== 1 || !c || !c[0] ) { return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 ); } // Initial estimate. s = Math.sqrt( +x ); // Math.sqrt underflow/overflow? // Pass x to Math.sqrt as integer, then adjust the exponent of the result. if ( s == 0 || s == 1 / 0 ) { n = coeffToString(c); if ( ( n.length + e ) % 2 == 0 ) n += '0'; s = Math.sqrt(n); e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 ); if ( s == 1 / 0 ) { n = '1e' + e; } else { n = s.toExponential(); n = n.slice( 0, n.indexOf('e') + 1 ) + e; } r = new BigNumber(n); } else { r = new BigNumber( s + '' ); } // Check for zero. // r could be zero if MIN_EXP is changed after the this value was created. // This would cause a division by zero (x/t) and hence Infinity below, which would cause // coeffToString to throw. if ( r.c[0] ) { e = r.e; s = e + dp; if ( s < 3 ) s = 0; // Newton-Raphson iteration. for ( ; ; ) { t = r; r = half.times( t.plus( div( x, t, dp, 1 ) ) ); if ( coeffToString( t.c ).slice( 0, s ) === ( n = coeffToString( r.c ) ).slice( 0, s ) ) { // The exponent of r may here be one less than the final result exponent, // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits // are indexed correctly. if ( r.e < e ) --s; n = n.slice( s - 3, s + 1 ); // The 4th rounding digit may be in error by -1 so if the 4 rounding digits // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the // iteration. if ( n == '9999' || !rep && n == '4999' ) { // On the first iteration only, check to see if rounding up gives the // exact result as the nines may infinitely repeat. if ( !rep ) { round( t, t.e + DECIMAL_PLACES + 2, 0 ); if ( t.times(t).eq(x) ) { r = t; break; } } dp += 4; s += 4; rep = 1; } else { // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact // result. If not, then there are further digits and m will be truthy. if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) { // Truncate to the first rounding digit. round( r, r.e + DECIMAL_PLACES + 2, 1 ); m = !r.times(r).eq(x); } break; } } } } return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m ); }
...
// Initialization and round constants tables
var H = [];
var K = [];
// Compute constants
(function () {
function isPrime(n) {
var sqrtN = Math.sqrt(n);
for (var factor = 2; factor <= sqrtN; factor++) {
if (!(n % factor)) {
return false;
}
}
return true;
...
squareRoot = function () { var m, n, r, rep, t, x = this, c = x.c, s = x.s, e = x.e, dp = DECIMAL_PLACES + 4, half = new BigNumber('0.5'); // Negative/NaN/Infinity/zero? if ( s !== 1 || !c || !c[0] ) { return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 ); } // Initial estimate. s = Math.sqrt( +x ); // Math.sqrt underflow/overflow? // Pass x to Math.sqrt as integer, then adjust the exponent of the result. if ( s == 0 || s == 1 / 0 ) { n = coeffToString(c); if ( ( n.length + e ) % 2 == 0 ) n += '0'; s = Math.sqrt(n); e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 ); if ( s == 1 / 0 ) { n = '1e' + e; } else { n = s.toExponential(); n = n.slice( 0, n.indexOf('e') + 1 ) + e; } r = new BigNumber(n); } else { r = new BigNumber( s + '' ); } // Check for zero. // r could be zero if MIN_EXP is changed after the this value was created. // This would cause a division by zero (x/t) and hence Infinity below, which would cause // coeffToString to throw. if ( r.c[0] ) { e = r.e; s = e + dp; if ( s < 3 ) s = 0; // Newton-Raphson iteration. for ( ; ; ) { t = r; r = half.times( t.plus( div( x, t, dp, 1 ) ) ); if ( coeffToString( t.c ).slice( 0, s ) === ( n = coeffToString( r.c ) ).slice( 0, s ) ) { // The exponent of r may here be one less than the final result exponent, // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits // are indexed correctly. if ( r.e < e ) --s; n = n.slice( s - 3, s + 1 ); // The 4th rounding digit may be in error by -1 so if the 4 rounding digits // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the // iteration. if ( n == '9999' || !rep && n == '4999' ) { // On the first iteration only, check to see if rounding up gives the // exact result as the nines may infinitely repeat. if ( !rep ) { round( t, t.e + DECIMAL_PLACES + 2, 0 ); if ( t.times(t).eq(x) ) { r = t; break; } } dp += 4; s += 4; rep = 1; } else { // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact // result. If not, then there are further digits and m will be truthy. if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) { // Truncate to the first rounding digit. round( r, r.e + DECIMAL_PLACES + 2, 1 ); m = !r.times(r).eq(x); } break; } } } } return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m ); }
n/a
sub = function ( y, b ) { var i, j, t, xLTy, x = this, a = x.s; id = 10; y = new BigNumber( y, b ); b = y.s; // Either NaN? if ( !a || !b ) return new BigNumber(NaN); // Signs differ? if ( a != b ) { y.s = -b; return x.plus(y); } var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c; if ( !xe || !ye ) { // Either Infinity? if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN ); // Either zero? if ( !xc[0] || !yc[0] ) { // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x : // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity ROUNDING_MODE == 3 ? -0 : 0 ); } } xe = bitFloor(xe); ye = bitFloor(ye); xc = xc.slice(); // Determine which is the bigger number. if ( a = xe - ye ) { if ( xLTy = a < 0 ) { a = -a; t = xc; } else { ye = xe; t = yc; } t.reverse(); // Prepend zeros to equalise exponents. for ( b = a; b--; t.push(0) ); t.reverse(); } else { // Exponents equal. Check digit by digit. j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b; for ( a = b = 0; b < j; b++ ) { if ( xc[b] != yc[b] ) { xLTy = xc[b] < yc[b]; break; } } } // x < y? Point xc to the array of the bigger number. if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s; b = ( j = yc.length ) - ( i = xc.length ); // Append zeros to xc if shorter. // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. if ( b > 0 ) for ( ; b--; xc[i++] = 0 ); b = BASE - 1; // Subtract yc from xc. for ( ; j > a; ) { if ( xc[--j] < yc[j] ) { for ( i = j; i && !xc[--i]; xc[i] = b ); --xc[i]; xc[j] += BASE; } xc[j] -= yc[j]; } // Remove leading zeros and adjust exponent accordingly. for ( ; xc[0] == 0; xc.shift(), --ye ); // Zero? if ( !xc[0] ) { // Following IEEE 754 (2008) 6.3, // n - n = +0 but n - n = -0 when rounding towards -Infinity. y.s = ROUNDING_MODE == 3 ? -1 : 1; y.c = [ y.e = 0 ]; return y; } // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity // for finite x and y. return normalise( y, xc, ye ); }
n/a
times = function ( y, b ) { var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, base, sqrtBase, x = this, xc = x.c, yc = ( id = 17, y = new BigNumber( y, b ) ).c; // Either NaN, ±Infinity or ±0? if ( !xc || !yc || !xc[0] || !yc[0] ) { // Return NaN if either is NaN, or one is 0 and the other is Infinity. if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) { y.c = y.e = y.s = null; } else { y.s *= x.s; // Return ±Infinity if either is ±Infinity. if ( !xc || !yc ) { y.c = y.e = null; // Return ±0 if either is ±0. } else { y.c = [0]; y.e = 0; } } return y; } e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE ); y.s *= x.s; xcL = xc.length; ycL = yc.length; // Ensure xc points to longer array and xcL to its length. if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i; // Initialise the result array with zeros. for ( i = xcL + ycL, zc = []; i--; zc.push(0) ); base = BASE; sqrtBase = SQRT_BASE; for ( i = ycL; --i >= 0; ) { c = 0; ylo = yc[i] % sqrtBase; yhi = yc[i] / sqrtBase | 0; for ( k = xcL, j = i + k; j > i; ) { xlo = xc[--k] % sqrtBase; xhi = xc[k] / sqrtBase | 0; m = yhi * xlo + xhi * ylo; xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c; c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi; zc[j--] = xlo % base; } zc[j] = c; } if (c) { ++e; } else { zc.shift(); } return normalise( y, zc, e ); }
...
* Values are multiplied by 2^m and encoded as integers
*
* @method formatInputReal
* @param {String|Number|BigNumber}
* @returns {SolidityParam}
*/
var formatInputReal = function (value) {
return formatInputInt(new BigNumber(value).times(new BigNumber(2).pow(128)));
};
/**
* Check if input value is negative
*
* @method signedIsNegative
* @param {String} value is hex format
...
toDigits = function ( sd, rm ) { var n = new BigNumber(this); sd = sd == null || !isValidInt( sd, 1, MAX, 18, 'precision' ) ? null : sd | 0; rm = rm == null || !isValidInt( rm, 0, 8, 18, roundingMode ) ? ROUNDING_MODE : rm | 0; return sd ? round( n, sd, rm ) : n; }
n/a
toExponential = function ( dp, rm ) { return format( this, dp != null && isValidInt( dp, 0, MAX, 19 ) ? ~~dp + 1 : null, rm, 19 ); }
...
if ( ( n.length + e ) % 2 == 0 ) n += '0';
s = Math.sqrt(n);
e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 );
if ( s == 1 / 0 ) {
n = '1e' + e;
} else {
n = s.toExponential();
n = n.slice( 0, n.indexOf('e') + 1 ) + e;
}
r = new BigNumber(n);
} else {
r = new BigNumber( s + '' );
}
...
toFixed = function ( dp, rm ) { return format( this, dp != null && isValidInt( dp, 0, MAX, 20 ) ? ~~dp + this.e + 1 : null, rm, 20 ); }
...
};
/*
* Return a string representing the value of this BigNumber in fixed-point notation rounding
* to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.
*
* Note: as with JavaScript's number type, (-0).toFixed(0) is '0',
* but e.g. (-0.00001).toFixed(0) is '-0'.
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'toFixed() decimal places not an integer: {dp}'
* 'toFixed() decimal places out of range: {dp}'
...
toFormat = function ( dp, rm ) { var str = format( this, dp != null && isValidInt( dp, 0, MAX, 21 ) ? ~~dp + this.e + 1 : null, rm, 21 ); if ( this.c ) { var i, arr = str.split('.'), g1 = +FORMAT.groupSize, g2 = +FORMAT.secondaryGroupSize, groupSeparator = FORMAT.groupSeparator, intPart = arr[0], fractionPart = arr[1], isNeg = this.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length; if (g2) i = g1, g1 = g2, g2 = i, len -= i; if ( g1 > 0 && len > 0 ) { i = len % g1 || g1; intPart = intDigits.substr( 0, i ); for ( ; i < len; i += g1 ) { intPart += groupSeparator + intDigits.substr( i, g1 ); } if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i); if (isNeg) intPart = '-' + intPart; } str = fractionPart ? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize ) ? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ), '$&' + FORMAT.fractionGroupSeparator ) : fractionPart ) : intPart; } return str; }
n/a
toFraction = function (md) { var arr, d0, d2, e, exp, n, n0, q, s, k = ERRORS, x = this, xc = x.c, d = new BigNumber(ONE), n1 = d0 = new BigNumber(ONE), d1 = n0 = new BigNumber(ONE); if ( md != null ) { ERRORS = false; n = new BigNumber(md); ERRORS = k; if ( !( k = n.isInt() ) || n.lt(ONE) ) { if (ERRORS) { raise( 22, 'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md ); } // ERRORS is false: // If md is a finite non-integer >= 1, round it to an integer and use it. md = !k && n.c && round( n, n.e + 1, 1 ).gte(ONE) ? n : null; } } if ( !xc ) return x.toString(); s = coeffToString(xc); // Determine initial denominator. // d is a power of 10 and the minimum max denominator that specifies the value exactly. e = d.e = s.length - x.e - 1; d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ]; md = !md || n.cmp(d) > 0 ? ( e > 0 ? d : n1 ) : n; exp = MAX_EXP; MAX_EXP = 1 / 0; n = new BigNumber(s); // n0 = d1 = 0 n0.c[0] = 0; for ( ; ; ) { q = div( n, d, 0, 1 ); d2 = d0.plus( q.times(d1) ); if ( d2.cmp(md) == 1 ) break; d0 = d1; d1 = d2; n1 = n0.plus( q.times( d2 = n1 ) ); n0 = d2; d = n.minus( q.times( d2 = d ) ); n = d2; } d2 = div( md.minus(d0), d1, 0, 1 ); n0 = n0.plus( d2.times(n1) ); d0 = d0.plus( d2.times(d1) ); n0.s = n1.s = x.s; e *= 2; // Determine which fraction is closer to x, n0/d0 or n1/d1 arr = div( n1, d1, e, ROUNDING_MODE ).minus(x).abs().cmp( div( n0, d0, e, ROUNDING_MODE ).minus(x).abs() ) < 1 ? [ n1.toString(), d1.toString() ] : [ n0.toString(), d0.toString() ]; MAX_EXP = exp; return arr; }
n/a
toJSON = function () { return this.toString(); }
n/a
toNumber = function () { var x = this; // Ensure zero has correct sign. return +x || ( x.s ? x.s * 0 : NaN ); }
...
* Should be used to format output bytes
*
* @method formatOutputDynamicBytes
* @param {SolidityParam} left-aligned hex representation of string
* @returns {String} hex string
*/
var formatOutputDynamicBytes = function (param) {
var length = (new BigNumber(param.dynamicPart().slice(0, 64), 16)).toNumber() * 2;
return '0x' + param.dynamicPart().substr(64, length);
};
/**
* Should be used to format output string
*
* @method formatOutputString
...
toPower = function (n) { var k, y, i = mathfloor( n < 0 ? -n : +n ), x = this; // Pass ±Infinity to Math.pow if exponent is out of range. if ( !isValidInt( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 23, 'exponent' ) && ( !isFinite(n) || i > MAX_SAFE_INTEGER && ( n /= 0 ) || parseFloat(n) != n && !( n = NaN ) ) ) { return new BigNumber( Math.pow( +x, n ) ); } // Truncating each coefficient array to a length of k after each multiplication equates // to truncating significant digits to POW_PRECISION + [28, 41], i.e. there will be a // minimum of 28 guard digits retained. (Using + 1.5 would give [9, 21] guard digits.) k = POW_PRECISION ? mathceil( POW_PRECISION / LOG_BASE + 2 ) : 0; y = new BigNumber(ONE); for ( ; ; ) { if ( i % 2 ) { y = y.times(x); if ( !y.c ) break; if ( k && y.c.length > k ) y.c.length = k; } i = mathfloor( i / 2 ); if ( !i ) break; x = x.times(x); if ( k && x.c && x.c.length > k ) x.c.length = k; } if ( n < 0 ) y = ONE.div(y); return k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y; }
n/a
toPrecision = function ( sd, rm ) { return format( this, sd != null && isValidInt( sd, 1, MAX, 24, 'precision' ) ? sd | 0 : null, rm, 24 ); }
n/a
toString = function (b) { var str, n = this, s = n.s, e = n.e; // Infinity or NaN? if ( e === null ) { if (s) { str = 'Infinity'; if ( s < 0 ) str = '-' + str; } else { str = 'NaN'; } } else { str = coeffToString( n.c ); if ( b == null || !isValidInt( b, 2, 64, 25, 'base' ) ) { str = e <= TO_EXP_NEG || e >= TO_EXP_POS ? toExponential( str, e ) : toFixedPoint( str, e ); } else { str = convertBase( toFixedPoint( str, e ), b | 0, 10, s ); } if ( s < 0 && n.c[0] ) str = '-' + str; } return str; }
...
*
* @method formatInputInt
* @param {String|Number|BigNumber} value that needs to be formatted
* @returns {SolidityParam}
*/
var formatInputInt = function (value) {
BigNumber.config(c.ETH_BIGNUMBER_ROUNDING_MODE);
var result = utils.padLeft(utils.toTwosComplement(value).toString(16), 64);
return new SolidityParam(result);
};
/**
* Formats input bytes
*
* @method formatInputBytes
...
trunc = function () { return round( new BigNumber(this), this.e + 1, 1 ); }
n/a
truncated = function () { return round( new BigNumber(this), this.e + 1, 1 ); }
n/a
valueOf = function () { return this.toString(); }
n/a