Browse Source

Merge pull request #1725 from debris/web3.js-v3.1

Web3.js v3.3
cl-refactor
Gav Wood 10 years ago
parent
commit
40396de020
  1. 1
      libjsqrc/ethereumjs/.travis.yml
  2. 34
      libjsqrc/ethereumjs/README.md
  3. 2
      libjsqrc/ethereumjs/bower.json
  4. 1644
      libjsqrc/ethereumjs/dist/web3-light.js
  5. 46
      libjsqrc/ethereumjs/dist/web3-light.js.map
  6. 3
      libjsqrc/ethereumjs/dist/web3-light.min.js
  7. 6998
      libjsqrc/ethereumjs/dist/web3.js
  8. 50
      libjsqrc/ethereumjs/dist/web3.js.map
  9. 4
      libjsqrc/ethereumjs/dist/web3.min.js
  10. 57
      libjsqrc/ethereumjs/example/contract.html
  11. 77
      libjsqrc/ethereumjs/example/contract_with_array.html
  12. 119
      libjsqrc/ethereumjs/example/event.html
  13. 65
      libjsqrc/ethereumjs/example/event_inc.html
  14. 143
      libjsqrc/ethereumjs/lib/solidity/abi.js
  15. 329
      libjsqrc/ethereumjs/lib/solidity/coder.js
  16. 114
      libjsqrc/ethereumjs/lib/solidity/formatters.js
  17. 105
      libjsqrc/ethereumjs/lib/solidity/param.js
  18. 77
      libjsqrc/ethereumjs/lib/solidity/types.js
  19. 30
      libjsqrc/ethereumjs/lib/solidity/utils.js
  20. 3
      libjsqrc/ethereumjs/lib/utils/config.js
  21. 42
      libjsqrc/ethereumjs/lib/utils/utils.js
  22. 2
      libjsqrc/ethereumjs/lib/version.json
  23. 17
      libjsqrc/ethereumjs/lib/web3.js
  24. 184
      libjsqrc/ethereumjs/lib/web3/contract.js
  25. 22
      libjsqrc/ethereumjs/lib/web3/errors.js
  26. 13
      libjsqrc/ethereumjs/lib/web3/eth.js
  27. 246
      libjsqrc/ethereumjs/lib/web3/event.js
  28. 57
      libjsqrc/ethereumjs/lib/web3/filter.js
  29. 15
      libjsqrc/ethereumjs/lib/web3/formatters.js
  30. 151
      libjsqrc/ethereumjs/lib/web3/function.js
  31. 18
      libjsqrc/ethereumjs/lib/web3/httpprovider.js
  32. 2
      libjsqrc/ethereumjs/lib/web3/method.js
  33. 6
      libjsqrc/ethereumjs/lib/web3/requestmanager.js
  34. 2
      libjsqrc/ethereumjs/lib/web3/shh.js
  35. 42
      libjsqrc/ethereumjs/lib/web3/signature.js
  36. 2
      libjsqrc/ethereumjs/package-init.js
  37. 7
      libjsqrc/ethereumjs/package.js
  38. 4
      libjsqrc/ethereumjs/package.json
  39. 14
      libjsqrc/ethereumjs/test/abi.inputParser.js
  40. 96
      libjsqrc/ethereumjs/test/abi.outputParser.js
  41. 68
      libjsqrc/ethereumjs/test/coder.decodeParam.js
  42. 91
      libjsqrc/ethereumjs/test/coder.encodeParam.js
  43. 147
      libjsqrc/ethereumjs/test/contract.js
  44. 180
      libjsqrc/ethereumjs/test/event.decode.js
  45. 206
      libjsqrc/ethereumjs/test/event.encode.js
  46. 113
      libjsqrc/ethereumjs/test/event.inputParser.js
  47. 81
      libjsqrc/ethereumjs/test/event.outputParser.js
  48. 3
      libjsqrc/ethereumjs/test/formatters.inputPostFormatter.js
  49. 5
      libjsqrc/ethereumjs/test/formatters.outputBlockFormatter.js
  50. 2
      libjsqrc/ethereumjs/test/formatters.outputTransactionFormatter.js
  51. 8
      libjsqrc/ethereumjs/test/helpers/FakeHttpProvider.js
  52. 27
      libjsqrc/ethereumjs/test/helpers/FakeHttpProvider2.js
  53. 23
      libjsqrc/ethereumjs/test/helpers/test.method.js
  54. 4
      libjsqrc/ethereumjs/test/method.validateArgs.js
  55. 48
      libjsqrc/ethereumjs/test/signature.js
  56. 49
      libjsqrc/ethereumjs/test/utils.filters.js
  57. 2
      libjsqrc/ethereumjs/test/web3.eth.contract.js
  58. 8
      libjsqrc/ethereumjs/test/web3.eth.getBlock.js
  59. 4
      libjsqrc/ethereumjs/test/web3.eth.getTransaction.js
  60. 4
      libjsqrc/ethereumjs/test/web3.eth.getTransactionFromBlock.js
  61. 8
      libjsqrc/ethereumjs/test/web3.eth.getUncle.js
  62. 39
      libjsqrc/ethereumjs/test/web3.shh.filter.js
  63. 49
      libjsqrc/ethereumjs/test/web3.shh.post.js

1
libjsqrc/ethereumjs/.travis.yml

@ -2,7 +2,6 @@ language: node_js
node_js:
- "0.12"
- "0.11"
- "0.10"
before_script:
- npm install
- npm install jshint

34
libjsqrc/ethereumjs/README.md

@ -1,6 +1,6 @@
# Ethereum JavaScript API
[![Join the chat at https://gitter.im/ethereum/ethereum.js](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/ethereum/ethereum.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Join the chat at https://gitter.im/ethereum/web3.js](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/ethereum/web3.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
This is the Ethereum compatible [JavaScript API](https://github.com/ethereum/wiki/wiki/JavaScript-API)
which implements the [Generic JSON RPC](https://github.com/ethereum/wiki/wiki/JSON-RPC) spec. It's available on npm as a node module, for bower and component as an embeddable js and as a meteor.js package.
@ -21,7 +21,7 @@ You need to run a local ethrereum node to use this library.
### Meteor.js
$ meteor add ethereum:js
$ meteor add ethereum:web3
### As Browser module
Bower
@ -36,11 +36,7 @@ Component
* Include [bignumber.js](https://github.com/MikeMcl/bignumber.js/) (not required for the meteor package)
## Usage
You can require the library (not required for the meteor package):
var web3 = require('ethereum.js');
Or use it directly from global namespace:
Use the `web3` object directly from global namespace:
console.log(web3); // {eth: .., shh: ...} // it's here!
@ -106,16 +102,16 @@ Install ethereum and spawn a node:
eth -j
```
[npm-image]: https://badge.fury.io/js/ethereum.js.png
[npm-url]: https://npmjs.org/package/ethereum.js
[travis-image]: https://travis-ci.org/ethereum/ethereum.js.svg
[travis-url]: https://travis-ci.org/ethereum/ethereum.js
[dep-image]: https://david-dm.org/ethereum/ethereum.js.svg
[dep-url]: https://david-dm.org/ethereum/ethereum.js
[dep-dev-image]: https://david-dm.org/ethereum/ethereum.js/dev-status.svg
[dep-dev-url]: https://david-dm.org/ethereum/ethereum.js#info=devDependencies
[coveralls-image]: https://coveralls.io/repos/ethereum/ethereum.js/badge.svg?branch=master
[coveralls-url]: https://coveralls.io/r/ethereum/ethereum.js?branch=master
[waffle-image]: https://badge.waffle.io/ethereum/ethereum.js.svg?label=ready&title=Ready
[waffle-url]: http://waffle.io/ethereum/ethereum.js
[npm-image]: https://badge.fury.io/js/web3.png
[npm-url]: https://npmjs.org/package/web3
[travis-image]: https://travis-ci.org/ethereum/web3.js.svg
[travis-url]: https://travis-ci.org/ethereum/web3.js
[dep-image]: https://david-dm.org/ethereum/web3.js.svg
[dep-url]: https://david-dm.org/ethereum/web3.js
[dep-dev-image]: https://david-dm.org/ethereum/web.js/dev-status.svg
[dep-dev-url]: https://david-dm.org/ethereum/web3.js#info=devDependencies
[coveralls-image]: https://coveralls.io/repos/ethereum/web3.js/badge.svg?branch=master
[coveralls-url]: https://coveralls.io/r/ethereum/web3.js?branch=master
[waffle-image]: https://badge.waffle.io/ethereum/web3.js.svg?label=ready&title=Ready
[waffle-url]: http://waffle.io/ethereum/web3.js

2
libjsqrc/ethereumjs/bower.json

@ -1,7 +1,7 @@
{
"name": "web3",
"namespace": "ethereum",
"version": "0.2.6",
"version": "0.3.3",
"description": "Ethereum Compatible JavaScript API",
"main": [
"./dist/web3.js",

1644
libjsqrc/ethereumjs/dist/web3-light.js

File diff suppressed because it is too large

46
libjsqrc/ethereumjs/dist/web3-light.js.map

File diff suppressed because one or more lines are too long

3
libjsqrc/ethereumjs/dist/web3-light.min.js

File diff suppressed because one or more lines are too long

6998
libjsqrc/ethereumjs/dist/web3.js

File diff suppressed because it is too large

50
libjsqrc/ethereumjs/dist/web3.js.map

File diff suppressed because one or more lines are too long

4
libjsqrc/ethereumjs/dist/web3.min.js

File diff suppressed because one or more lines are too long

57
libjsqrc/ethereumjs/example/contract.html

@ -2,36 +2,34 @@
<html>
<head>
<script type="text/javascript" src="../dist/web3"></script>
<script type="text/javascript" src="../dist/web3.js"></script>
<script type="text/javascript">
var web3 = require('web3');
web3.setProvider(new web3.providers.HttpProvider());
web3.setProvider(new web3.providers.HttpProvider("http://localhost:8545"));
// solidity source code
var source = "" +
"contract test {\n" +
" function multiply(uint a) returns(uint d) {\n" +
" return a * 7;\n" +
" }\n" +
"}\n";
/*var source = "" +*/
/*"contract test {\n" +*/
/*" function multiply(uint a) constant returns(uint d) {\n" +*/
/*" return a * 7;\n" +*/
/*" }\n" +*/
/*"}\n";*/
var source = "605280600c6000396000f3006000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa114602e57005b60376004356041565b8060005260206000f35b6000600782029050604d565b91905056";
// contract description, this will be autogenerated somehow
var desc = [{
"name": "multiply(uint256)",
"type": "function",
"inputs": [
{
"name": "a",
"type": "uint256"
}
],
"outputs": [
{
"name": "d",
"type": "uint256"
}
]
// contract description, this is autogenerated using solc CLI
var desc = [{
"constant" : true,
"inputs" : [{
"name" : "a",
"type" : "uint256"
}],
"name" : "multiply",
"outputs" : [{
"name" : "d",
"type" : "uint256"
}],
"type" : "function"
}];
var myContract;
@ -41,11 +39,12 @@
document.getElementById('create').style.visibility = 'hidden';
document.getElementById('source').innerText = source;
// create contract
var address = web3.eth.sendTransaction({data: web3.eth.compile.solidity(source)}),
Contract = web3.eth.contract(desc);
// let's assume that coinbase is our account
web3.eth.defaultAccount = web3.eth.coinbase;
myContract = new Contract(address);
// create contract
var Contract = web3.eth.contract(desc);
myContract = new Contract({data: source});
document.getElementById('call').style.visibility = 'visible';
}
@ -54,7 +53,7 @@
var param = parseInt(document.getElementById('value').value);
// call the contract
var res = myContract.call().multiply(param);
var res = myContract.multiply(param);
document.getElementById('result').innerText = res.toString(10);
}

77
libjsqrc/ethereumjs/example/contract_with_array.html

@ -1,77 +0,0 @@
<!doctype>
<html>
<head>
<script type="text/javascript" src="../dist/web3.js"></script>
<script type="text/javascript">
var web3 = require('web3');
web3.setProvider(new web3.providers.HttpProvider());
// solidity source code
var source = "" +
"contract test {\n" +
" function multiply(uint[] a) returns(uint d) {\n" +
" return a[0] + a[1];\n" +
" }\n" +
"}\n";
// contract description, this will be autogenerated somehow
var desc = [{
"name": "multiply(uint256[])",
"type": "function",
"inputs": [
{
"name": "a",
"type": "uint256[]"
}
],
"outputs": [
{
"name": "d",
"type": "uint256"
}
]
}];
var myContract;
function createExampleContract() {
// hide create button
document.getElementById('create').style.visibility = 'hidden';
document.getElementById('source').innerText = source;
// create contract
var address = web3.eth.sendTransaction({data: web3.eth.compile.solidity(source)}),
Contract = web3.eth.contract(desc);
myContract = new Contract(address);
document.getElementById('call').style.visibility = 'visible';
}
function callExampleContract() {
// this should be generated by ethereum
var param = parseInt(document.getElementById('value').value);
var param2 = parseInt(document.getElementById('value2').value);
// call the contract
var res = myContract.call().multiply([param, param2]);
document.getElementById('result').innerText = res.toString(10);
}
</script>
</head>
<body>
<h1>contract</h1>
<div id="source"></div>
<div id='create'>
<button type="button" onClick="createExampleContract();">create example contract</button>
</div>
<div id='call' style='visibility: hidden;'>
<input type="number" id="value" onkeyup='callExampleContract()'></input>
<input type="number" id="value2" onkeyup='callExampleContract()'></input>
</div>
<div id="result"></div>
</body>
</html>

119
libjsqrc/ethereumjs/example/event.html

@ -1,119 +0,0 @@
<!doctype>
<html>
<head>
<script type="text/javascript" src="../dist/web3.js"></script>
<script type="text/javascript">
var web3 = require('web3');
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8080'));
var desc = [{
"type":"event",
"inputs": [{"name":"a","type":"uint256","indexed":true},{"name":"b","type":"hash256","indexed":false}],
"name":"Event"
}, {
"type":"event",
"inputs": [{"name":"a","type":"uint256","indexed":true},{"name":"b","type":"hash256","indexed":false}],
"name":"Event2"
}, {
"type":"function",
"inputs": [{"name":"a","type":"uint256"}],
"name":"foo",
"outputs": []
}];
var address = '0x01';
var contract = web3.eth.contract(address, desc);
function test1() {
// "{"topic":["0x83c9849c","0xc4d76332"],"address":"0x01"}"
web3.eth.watch(contract).changed(function (res) {
});
};
function test2() {
// "{"topic":["0x83c9849c"],"address":"0x01"}"
web3.eth.watch(contract.Event).changed(function (res) {
});
};
function test3() {
// "{"topic":["0x83c9849c"],"address":"0x01"}"
contract.Event().changed(function (res) {
});
};
function test4() {
// "{"topic":["0x83c9849c","0000000000000000000000000000000000000000000000000000000000000045"],"address":"0x01"}"
contract.Event({a: 69}).changed(function (res) {
});
};
function test5() {
// "{"topic":["0x83c9849c",["0000000000000000000000000000000000000000000000000000000000000045","000000000000000000000000000000000000000000000000000000000000002a"]],"address":"0x01"}"
contract.Event({a: [69, 42]}).changed(function (res) {
});
};
function test6() {
// "{"topic":["0x83c9849c","000000000000000000000000000000000000000000000000000000000000001e"],"max":100,"address":"0x01"}"
contract.Event({a: 30}, {max: 100}).changed(function (res) {
});
};
function test7() {
// "{"topic":["0x83c9849c","000000000000000000000000000000000000000000000000000000000000001e"],"address":"0x01"}"
web3.eth.watch(contract.Event, {a: 30}).changed(function (res) {
});
};
function test8() {
// "{"topic":["0x83c9849c","000000000000000000000000000000000000000000000000000000000000001e"],"max":100,"address":"0x01"}"
web3.eth.watch(contract.Event, {a: 30}, {max: 100}).changed(function (res) {
});
};
// not valid
// function testX() {
// web3.eth.watch([contract.Event, contract.Event2]).changed(function (res) {
// });
// };
</script>
</head>
<body>
<div>
<button type="button" onClick="test1();">test1</button>
</div>
<div>
<button type="button" onClick="test2();">test2</button>
</div>
<div>
<button type="button" onClick="test3();">test3</button>
</div>
<div>
<button type="button" onClick="test4();">test4</button>
</div>
<div>
<button type="button" onClick="test5();">test5</button>
</div>
<div>
<button type="button" onClick="test6();">test6</button>
</div>
<div>
<button type="button" onClick="test7();">test7</button>
</div>
<div>
<button type="button" onClick="test8();">test8</button>
</div>
</body>
</html>

65
libjsqrc/ethereumjs/example/event_inc.html

@ -4,48 +4,61 @@
<script type="text/javascript" src="../dist/web3.js"></script>
<script type="text/javascript">
var web3 = require('web3');
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8080'));
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
var source = "" +
"contract Contract { " +
" event Incremented(bool indexed odd, uint x); " +
" function Contract() { " +
" x = 69; " +
" } " +
" function inc() { " +
" ++x; " +
" Incremented(x % 2 == 1, x); " +
" } " +
" uint x; " +
"}";
/*var source = "" + */
/*"contract Contract { " +*/
/*" event Incremented(bool indexed odd, uint x); " +*/
/*" function Contract() { " +*/
/*" x = 69; " +*/
/*" } " +*/
/*" function inc() { " +*/
/*" ++x; " +*/
/*" Incremented(x % 2 == 1, x); " +*/
/*" } " +*/
/*" uint x; " +*/
/*"}";*/
var source = "5b60456000600050819055505b608c8060196000396000f3006000357c010000000000000000000000000000000000000000000000000000000090048063371303c014602e57005b6034603a565b60006000f35b6000600081815054600101919050819055506001600260006000505406147f6e61ef44ac2747ff8b84d353a908eb8bd5c3fb118334d57698c5cfc7041196ad600060006000505481526020016000a25b56";
var desc = [{
"type":"event",
"name":"Incremented",
"inputs": [{"name":"odd","type":"bool","indexed":true},{"name":"x","type":"uint","indexed":false}],
"constant" : false,
"inputs" : [],
"name" : "inc",
"outputs" : [],
"type" : "function"
}, {
"type":"function",
"name":"inc",
"inputs": [],
"outputs": []
"anonymous" : false,
"inputs" : [{
"indexed" : true,
"name" : "odd",
"type" : "bool"
}, {
"indexed" : false,
"name" : "x",
"type" : "uint256"
}],
"name" : "Incremented",
"type" : "event"
}];
var address;
var contract;
var update = function (x) {
document.getElementById('result').innerText = JSON.stringify(x);
var update = function (err, x) {
document.getElementById('result').innerText = JSON.stringify(x, null, 2);
};
var createContract = function () {
address = web3.eth.sendTransaction({data: web3.eth.compile.solidity(source)});
contract = web3.eth.contract(address, desc);
contract.Incremented({odd: true}).changed(update);
// let's assume that we have a private key to coinbase ;)
web3.eth.defaultAccount = web3.eth.coinbase;
var Contract = web3.eth.contract(desc);
contract = new Contract({data: source});
contract.Incremented({odd: true}).watch(update);
};
var callContract = function () {
contract.call().inc();
contract.inc();
};

143
libjsqrc/ethereumjs/lib/solidity/abi.js

@ -22,49 +22,9 @@
*/
var utils = require('../utils/utils');
var c = require('../utils/config');
var types = require('./types');
var f = require('./formatters');
var coder = require('./coder');
var solUtils = require('./utils');
/**
* throw incorrect type error
*
* @method throwTypeError
* @param {String} type
* @throws incorrect type error
*/
var throwTypeError = function (type) {
throw new Error('parser does not support type: ' + type);
};
/** This method should be called if we want to check if givent type is an array type
*
* @method isArrayType
* @param {String} type name
* @returns {Boolean} true if it is, otherwise false
*/
var isArrayType = function (type) {
return type.slice(-2) === '[]';
};
/**
* This method should be called to return dynamic type length in hex
*
* @method dynamicTypeBytes
* @param {String} type
* @param {String|Array} dynamic type
* @return {String} length of dynamic type in hex or empty string if type is not dynamic
*/
var dynamicTypeBytes = function (type, value) {
// TODO: decide what to do with array of strings
if (isArrayType(type) || type === 'bytes')
return f.formatInputInt(value.length);
return "";
};
var inputTypes = types.inputTypes();
/**
* Formats input params to bytes
*
@ -74,57 +34,12 @@ var inputTypes = types.inputTypes();
* @returns bytes representation of input params
*/
var formatInput = function (inputs, params) {
var bytes = "";
var toAppendConstant = "";
var toAppendArrayContent = "";
/// first we iterate in search for dynamic
inputs.forEach(function (input, index) {
bytes += dynamicTypeBytes(input.type, params[index]);
var i = inputs.map(function (input) {
return input.type;
});
inputs.forEach(function (input, i) {
/*jshint maxcomplexity:5 */
var typeMatch = false;
for (var j = 0; j < inputTypes.length && !typeMatch; j++) {
typeMatch = inputTypes[j].type(inputs[i].type, params[i]);
}
if (!typeMatch) {
throwTypeError(inputs[i].type);
}
var formatter = inputTypes[j - 1].format;
if (isArrayType(inputs[i].type))
toAppendArrayContent += params[i].reduce(function (acc, curr) {
return acc + formatter(curr);
}, "");
else if (inputs[i].type === 'bytes')
toAppendArrayContent += formatter(params[i]);
else
toAppendConstant += formatter(params[i]);
});
bytes += toAppendConstant + toAppendArrayContent;
return bytes;
};
/**
* This method should be called to predict the length of dynamic type
*
* @method dynamicBytesLength
* @param {String} type
* @returns {Number} length of dynamic type, 0 or multiplication of ETH_PADDING (32)
*/
var dynamicBytesLength = function (type) {
if (isArrayType(type) || type === 'bytes')
return c.ETH_PADDING * 2;
return 0;
return coder.encodeParams(i, params);
};
var outputTypes = types.outputTypes();
/**
* Formats output bytes back to param list
*
@ -133,52 +48,12 @@ var outputTypes = types.outputTypes();
* @param {String} bytes represention of output
* @returns {Array} output params
*/
var formatOutput = function (outs, output) {
output = output.slice(2);
var result = [];
var padding = c.ETH_PADDING * 2;
var dynamicPartLength = outs.reduce(function (acc, curr) {
return acc + dynamicBytesLength(curr.type);
}, 0);
var dynamicPart = output.slice(0, dynamicPartLength);
output = output.slice(dynamicPartLength);
outs.forEach(function (out, i) {
/*jshint maxcomplexity:6 */
var typeMatch = false;
for (var j = 0; j < outputTypes.length && !typeMatch; j++) {
typeMatch = outputTypes[j].type(outs[i].type);
}
if (!typeMatch) {
throwTypeError(outs[i].type);
}
var formatter = outputTypes[j - 1].format;
if (isArrayType(outs[i].type)) {
var size = f.formatOutputUInt(dynamicPart.slice(0, padding));
dynamicPart = dynamicPart.slice(padding);
var array = [];
for (var k = 0; k < size; k++) {
array.push(formatter(output.slice(0, padding)));
output = output.slice(padding);
}
result.push(array);
}
else if (types.prefixedType('bytes')(outs[i].type)) {
dynamicPart = dynamicPart.slice(padding);
result.push(formatter(output.slice(0, padding)));
output = output.slice(padding);
} else {
result.push(formatter(output.slice(0, padding)));
output = output.slice(padding);
}
var formatOutput = function (outs, bytes) {
var o = outs.map(function (out) {
return out.type;
});
return result;
return coder.decodeParams(o, bytes);
};
/**

329
libjsqrc/ethereumjs/lib/solidity/coder.js

@ -0,0 +1,329 @@
/*
This file is part of ethereum.js.
ethereum.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ethereum.js is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file coder.js
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
var BigNumber = require('bignumber.js');
var utils = require('../utils/utils');
var f = require('./formatters');
var SolidityParam = require('./param');
/**
* Should be used to check if a type is an array type
*
* @method isArrayType
* @param {String} type
* @return {Bool} true is the type is an array, otherwise false
*/
var isArrayType = function (type) {
return type.slice(-2) === '[]';
};
/**
* SolidityType prototype is used to encode/decode solidity params of certain type
*/
var SolidityType = function (config) {
this._name = config.name;
this._match = config.match;
this._mode = config.mode;
this._inputFormatter = config.inputFormatter;
this._outputFormatter = config.outputFormatter;
};
/**
* Should be used to determine if this SolidityType do match given type
*
* @method isType
* @param {String} name
* @return {Bool} true if type match this SolidityType, otherwise false
*/
SolidityType.prototype.isType = function (name) {
if (this._match === 'strict') {
return this._name === name || (name.indexOf(this._name) === 0 && name.slice(this._name.length) === '[]');
} else if (this._match === 'prefix') {
// TODO better type detection!
return name.indexOf(this._name) === 0;
}
};
/**
* Should be used to transform plain param to SolidityParam object
*
* @method formatInput
* @param {Object} param - plain object, or an array of objects
* @param {Bool} arrayType - true if a param should be encoded as an array
* @return {SolidityParam} encoded param wrapped in SolidityParam object
*/
SolidityType.prototype.formatInput = function (param, arrayType) {
if (utils.isArray(param) && arrayType) { // TODO: should fail if this two are not the same
var self = this;
return param.map(function (p) {
return self._inputFormatter(p);
}).reduce(function (acc, current) {
acc.appendArrayElement(current);
return acc;
}, new SolidityParam('', f.formatInputInt(param.length).value));
}
return this._inputFormatter(param);
};
/**
* Should be used to transoform SolidityParam to plain param
*
* @method formatOutput
* @param {SolidityParam} byteArray
* @param {Bool} arrayType - true if a param should be decoded as an array
* @return {Object} plain decoded param
*/
SolidityType.prototype.formatOutput = function (param, arrayType) {
if (arrayType) {
// let's assume, that we solidity will never return long arrays :P
var result = [];
var length = new BigNumber(param.prefix, 16);
for (var i = 0; i < length * 64; i += 64) {
result.push(this._outputFormatter(new SolidityParam(param.suffix.slice(i, i + 64))));
}
return result;
}
return this._outputFormatter(param);
};
/**
* Should be used to check if a type is variadic
*
* @method isVariadicType
* @param {String} type
* @returns {Bool} true if the type is variadic
*/
SolidityType.prototype.isVariadicType = function (type) {
return isArrayType(type) || this._mode === 'bytes';
};
/**
* Should be used to shift param from params group
*
* @method shiftParam
* @param {String} type
* @returns {SolidityParam} shifted param
*/
SolidityType.prototype.shiftParam = function (type, param) {
if (this._mode === 'bytes') {
return param.shiftBytes();
} else if (isArrayType(type)) {
var length = new BigNumber(param.prefix.slice(0, 64), 16);
return param.shiftArray(length);
}
return param.shiftValue();
};
/**
* SolidityCoder prototype should be used to encode/decode solidity params of any type
*/
var SolidityCoder = function (types) {
this._types = types;
};
/**
* This method should be used to transform type to SolidityType
*
* @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;
};
/**
* Should be used to transform plain bytes to SolidityParam object
*
* @method _bytesToParam
* @param {Array} types of params
* @param {String} bytes to be transformed to SolidityParam
* @return {SolidityParam} SolidityParam for this group of params
*/
SolidityCoder.prototype._bytesToParam = function (types, bytes) {
var self = this;
var prefixTypes = types.reduce(function (acc, type) {
return self._requireType(type).isVariadicType(type) ? acc + 1 : acc;
}, 0);
var valueTypes = types.length - prefixTypes;
var prefix = bytes.slice(0, prefixTypes * 64);
bytes = bytes.slice(prefixTypes * 64);
var value = bytes.slice(0, valueTypes * 64);
var suffix = bytes.slice(valueTypes * 64);
return new SolidityParam(value, prefix, suffix);
};
/**
* Should be used to transform plain param of given type to SolidityParam
*
* @method _formatInput
* @param {String} type of param
* @param {Object} plain param
* @return {SolidityParam}
*/
SolidityCoder.prototype._formatInput = function (type, param) {
return this._requireType(type).formatInput(param, isArrayType(type));
};
/**
* Should be used to encode plain param
*
* @method encodeParam
* @param {String} type
* @param {Object} plain param
* @return {String} encoded plain param
*/
SolidityCoder.prototype.encodeParam = function (type, param) {
return this._formatInput(type, param).encode();
};
/**
* Should be used to encode list of params
*
* @method encodeParams
* @param {Array} types
* @param {Array} params
* @return {String} encoded list of params
*/
SolidityCoder.prototype.encodeParams = function (types, params) {
var self = this;
return types.map(function (type, index) {
return self._formatInput(type, params[index]);
}).reduce(function (acc, solidityParam) {
acc.append(solidityParam);
return acc;
}, new SolidityParam()).encode();
};
/**
* Should be used to transform SolidityParam to plain param
*
* @method _formatOutput
* @param {String} type
* @param {SolidityParam} param
* @return {Object} plain param
*/
SolidityCoder.prototype._formatOutput = function (type, param) {
return this._requireType(type).formatOutput(param, isArrayType(type));
};
/**
* Should be used to decode bytes to plain param
*
* @method decodeParam
* @param {String} type
* @param {String} bytes
* @return {Object} plain param
*/
SolidityCoder.prototype.decodeParam = function (type, bytes) {
return this._formatOutput(type, this._bytesToParam([type], bytes));
};
/**
* Should be used to decode list of params
*
* @method decodeParam
* @param {Array} types
* @param {String} bytes
* @return {Array} array of plain params
*/
SolidityCoder.prototype.decodeParams = function (types, bytes) {
var self = this;
var param = this._bytesToParam(types, bytes);
return types.map(function (type) {
var solidityType = self._requireType(type);
var p = solidityType.shiftParam(type, param);
return solidityType.formatOutput(p, isArrayType(type));
});
};
var coder = new SolidityCoder([
new SolidityType({
name: 'address',
match: 'strict',
mode: 'value',
inputFormatter: f.formatInputInt,
outputFormatter: f.formatOutputAddress
}),
new SolidityType({
name: 'bool',
match: 'strict',
mode: 'value',
inputFormatter: f.formatInputBool,
outputFormatter: f.formatOutputBool
}),
new SolidityType({
name: 'int',
match: 'prefix',
mode: 'value',
inputFormatter: f.formatInputInt,
outputFormatter: f.formatOutputInt,
}),
new SolidityType({
name: 'uint',
match: 'prefix',
mode: 'value',
inputFormatter: f.formatInputInt,
outputFormatter: f.formatOutputUInt
}),
new SolidityType({
name: 'bytes',
match: 'strict',
mode: 'bytes',
inputFormatter: f.formatInputDynamicBytes,
outputFormatter: f.formatOutputDynamicBytes
}),
new SolidityType({
name: 'bytes',
match: 'prefix',
mode: 'value',
inputFormatter: f.formatInputBytes,
outputFormatter: f.formatOutputBytes
}),
new SolidityType({
name: 'real',
match: 'prefix',
mode: 'value',
inputFormatter: f.formatInputReal,
outputFormatter: f.formatOutputReal
}),
new SolidityType({
name: 'ureal',
match: 'prefix',
mode: 'value',
inputFormatter: f.formatInputReal,
outputFormatter: f.formatOutputUReal
})
]);
module.exports = coder;

114
libjsqrc/ethereumjs/lib/solidity/formatters.js

@ -14,15 +14,17 @@
You should have received a copy of the GNU Lesser General Public License
along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file formatters.js
* @authors:
* Marek Kotewicz <marek@ethdev.com>
/**
* @file formatters.js
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
var BigNumber = require('bignumber.js');
var utils = require('../utils/utils');
var c = require('../utils/config');
var SolidityParam = require('./param');
/**
* Formats input value to byte representation of int
@ -31,23 +33,37 @@ var c = require('../utils/config');
*
* @method formatInputInt
* @param {String|Number|BigNumber} value that needs to be formatted
* @returns {String} right-aligned byte representation of int
* @returns {SolidityParam}
*/
var formatInputInt = function (value) {
var padding = c.ETH_PADDING * 2;
BigNumber.config(c.ETH_BIGNUMBER_ROUNDING_MODE);
return utils.padLeft(utils.toTwosComplement(value).round().toString(16), padding);
var result = utils.padLeft(utils.toTwosComplement(value).round().toString(16), padding);
return new SolidityParam(result);
};
/**
* Formats input value to byte representation of string
*
* @method formatInputString
* @method formatInputBytes
* @param {String}
* @returns {String} left-algined byte representation of string
* @returns {SolidityParam}
*/
var formatInputString = function (value) {
return utils.fromAscii(value, c.ETH_PADDING).substr(2);
var formatInputBytes = function (value) {
var result = utils.fromAscii(value, c.ETH_PADDING).substr(2);
return new SolidityParam(result);
};
/**
* Formats input value to byte representation of string
*
* @method formatInputDynamicBytes
* @param {String}
* @returns {SolidityParam}
*/
var formatInputDynamicBytes = function (value) {
var result = utils.fromAscii(value, c.ETH_PADDING).substr(2);
return new SolidityParam('', formatInputInt(value.length).value, result);
};
/**
@ -55,10 +71,11 @@ var formatInputString = function (value) {
*
* @method formatInputBool
* @param {Boolean}
* @returns {String} right-aligned byte representation bool
* @returns {SolidityParam}
*/
var formatInputBool = function (value) {
return '000000000000000000000000000000000000000000000000000000000000000' + (value ? '1' : '0');
var result = '000000000000000000000000000000000000000000000000000000000000000' + (value ? '1' : '0');
return new SolidityParam(result);
};
/**
@ -67,10 +84,10 @@ var formatInputBool = function (value) {
*
* @method formatInputReal
* @param {String|Number|BigNumber}
* @returns {String} byte representation of real
* @returns {SolidityParam}
*/
var formatInputReal = function (value) {
return formatInputInt(new BigNumber(value).times(new BigNumber(2).pow(128)));
return formatInputInt(new BigNumber(value).times(new BigNumber(2).pow(128)));
};
/**
@ -88,12 +105,11 @@ var signedIsNegative = function (value) {
* Formats right-aligned output bytes to int
*
* @method formatOutputInt
* @param {String} bytes
* @param {SolidityParam} param
* @returns {BigNumber} right-aligned output bytes formatted to big number
*/
var formatOutputInt = function (value) {
value = value || "0";
var formatOutputInt = function (param) {
var value = param.value || "0";
// check if it's negative number
// it it is, return two's complement
@ -107,11 +123,11 @@ var formatOutputInt = function (value) {
* Formats right-aligned output bytes to uint
*
* @method formatOutputUInt
* @param {String} bytes
* @param {SolidityParam}
* @returns {BigNumeber} right-aligned output bytes formatted to uint
*/
var formatOutputUInt = function (value) {
value = value || "0";
var formatOutputUInt = function (param) {
var value = param.value || "0";
return new BigNumber(value, 16);
};
@ -119,80 +135,84 @@ var formatOutputUInt = function (value) {
* Formats right-aligned output bytes to real
*
* @method formatOutputReal
* @param {String}
* @param {SolidityParam}
* @returns {BigNumber} input bytes formatted to real
*/
var formatOutputReal = function (value) {
return formatOutputInt(value).dividedBy(new BigNumber(2).pow(128));
var formatOutputReal = function (param) {
return formatOutputInt(param).dividedBy(new BigNumber(2).pow(128));
};
/**
* Formats right-aligned output bytes to ureal
*
* @method formatOutputUReal
* @param {String}
* @param {SolidityParam}
* @returns {BigNumber} input bytes formatted to ureal
*/
var formatOutputUReal = function (value) {
return formatOutputUInt(value).dividedBy(new BigNumber(2).pow(128));
var formatOutputUReal = function (param) {
return formatOutputUInt(param).dividedBy(new BigNumber(2).pow(128));
};
/**
* Should be used to format output hash
* Should be used to format output bool
*
* @method formatOutputHash
* @param {String}
* @returns {String} right-aligned output bytes formatted to hex
* @method formatOutputBool
* @param {SolidityParam}
* @returns {Boolean} right-aligned input bytes formatted to bool
*/
var formatOutputHash = function (value) {
return "0x" + value;
var formatOutputBool = function (param) {
return param.value === '0000000000000000000000000000000000000000000000000000000000000001' ? true : false;
};
/**
* Should be used to format output bool
* Should be used to format output string
*
* @method formatOutputBool
* @param {String}
* @returns {Boolean} right-aligned input bytes formatted to bool
* @method formatOutputBytes
* @param {SolidityParam} left-aligned hex representation of string
* @returns {String} ascii string
*/
var formatOutputBool = function (value) {
return value === '0000000000000000000000000000000000000000000000000000000000000001' ? true : false;
var formatOutputBytes = function (param) {
// length might also be important!
return utils.toAscii(param.value);
};
/**
* Should be used to format output string
*
* @method formatOutputString
* @param {Sttring} left-aligned hex representation of string
* @method formatOutputDynamicBytes
* @param {SolidityParam} left-aligned hex representation of string
* @returns {String} ascii string
*/
var formatOutputString = function (value) {
return utils.toAscii(value);
var formatOutputDynamicBytes = function (param) {
// length might also be important!
return utils.toAscii(param.suffix);
};
/**
* Should be used to format output address
*
* @method formatOutputAddress
* @param {String} right-aligned input bytes
* @param {SolidityParam} right-aligned input bytes
* @returns {String} address
*/
var formatOutputAddress = function (value) {
var formatOutputAddress = function (param) {
var value = param.value;
return "0x" + value.slice(value.length - 40, value.length);
};
module.exports = {
formatInputInt: formatInputInt,
formatInputString: formatInputString,
formatInputBytes: formatInputBytes,
formatInputDynamicBytes: formatInputDynamicBytes,
formatInputBool: formatInputBool,
formatInputReal: formatInputReal,
formatOutputInt: formatOutputInt,
formatOutputUInt: formatOutputUInt,
formatOutputReal: formatOutputReal,
formatOutputUReal: formatOutputUReal,
formatOutputHash: formatOutputHash,
formatOutputBool: formatOutputBool,
formatOutputString: formatOutputString,
formatOutputBytes: formatOutputBytes,
formatOutputDynamicBytes: formatOutputDynamicBytes,
formatOutputAddress: formatOutputAddress
};

105
libjsqrc/ethereumjs/lib/solidity/param.js

@ -0,0 +1,105 @@
/*
This file is part of ethereum.js.
ethereum.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ethereum.js is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file param.js
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
/**
* SolidityParam object prototype.
* Should be used when encoding, decoding solidity bytes
*/
var SolidityParam = function (value, prefix, suffix) {
this.prefix = prefix || '';
this.value = value || '';
this.suffix = suffix || '';
};
/**
* This method should be used to encode two params one after another
*
* @method append
* @param {SolidityParam} param that it appended after this
*/
SolidityParam.prototype.append = function (param) {
this.prefix += param.prefix;
this.value += param.value;
this.suffix += param.suffix;
};
/**
* This method should be used to encode next param in an array
*
* @method appendArrayElement
* @param {SolidityParam} param that is appended to an array
*/
SolidityParam.prototype.appendArrayElement = function (param) {
this.suffix += param.value;
this.prefix += param.prefix;
// TODO: suffix not supported = it's required for nested arrays;
};
/**
* This method should be used to create bytearrays from param
*
* @method encode
* @return {String} encoded param(s)
*/
SolidityParam.prototype.encode = function () {
return this.prefix + this.value + this.suffix;
};
/**
* This method should be used to shift first param from group of params
*
* @method shiftValue
* @return {SolidityParam} first value param
*/
SolidityParam.prototype.shiftValue = function () {
var value = this.value.slice(0, 64);
this.value = this.value.slice(64);
return new SolidityParam(value);
};
/**
* This method should be used to first bytes param from group of params
*
* @method shiftBytes
* @return {SolidityParam} first bytes param
*/
SolidityParam.prototype.shiftBytes = function () {
return this.shiftArray(1);
};
/**
* This method should be used to shift an array from group of params
*
* @method shiftArray
* @param {Number} size of an array to shift
* @return {SolidityParam} first array param
*/
SolidityParam.prototype.shiftArray = function (length) {
var prefix = this.prefix.slice(0, 64);
this.prefix = this.value.slice(64);
var suffix = this.suffix.slice(0, 64 * length);
this.suffix = this.suffix.slice(64 * length);
return new SolidityParam('', prefix, suffix);
};
module.exports = SolidityParam;

77
libjsqrc/ethereumjs/lib/solidity/types.js

@ -1,77 +0,0 @@
/*
This file is part of ethereum.js.
ethereum.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ethereum.js is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file types.js
* @authors:
* Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
var f = require('./formatters');
/// @param expected type prefix (string)
/// @returns function which checks if type has matching prefix. if yes, returns true, otherwise false
var prefixedType = function (prefix) {
return function (type) {
return type.indexOf(prefix) === 0;
};
};
/// @param expected type name (string)
/// @returns function which checks if type is matching expected one. if yes, returns true, otherwise false
var namedType = function (name) {
return function (type) {
return name === type;
};
};
/// Setups input formatters for solidity types
/// @returns an array of input formatters
var inputTypes = function () {
return [
{ type: prefixedType('uint'), format: f.formatInputInt },
{ type: prefixedType('int'), format: f.formatInputInt },
{ type: prefixedType('bytes'), format: f.formatInputString },
{ type: prefixedType('real'), format: f.formatInputReal },
{ type: prefixedType('ureal'), format: f.formatInputReal },
{ type: namedType('address'), format: f.formatInputInt },
{ type: namedType('bool'), format: f.formatInputBool }
];
};
/// Setups output formaters for solidity types
/// @returns an array of output formatters
var outputTypes = function () {
return [
{ type: prefixedType('uint'), format: f.formatOutputUInt },
{ type: prefixedType('int'), format: f.formatOutputInt },
{ type: prefixedType('bytes'), format: f.formatOutputString },
{ type: prefixedType('real'), format: f.formatOutputReal },
{ type: prefixedType('ureal'), format: f.formatOutputUReal },
{ type: namedType('address'), format: f.formatOutputAddress },
{ type: namedType('bool'), format: f.formatOutputBool }
];
};
module.exports = {
prefixedType: prefixedType,
namedType: namedType,
inputTypes: inputTypes,
outputTypes: outputTypes
};

30
libjsqrc/ethereumjs/lib/solidity/utils.js

@ -34,35 +34,7 @@ var getConstructor = function (abi, numberOfArgs) {
})[0];
};
/**
* Filters all functions from input abi
*
* @method filterFunctions
* @param {Array} abi
* @returns {Array} abi array with filtered objects of type 'function'
*/
var filterFunctions = function (json) {
return json.filter(function (current) {
return current.type === 'function';
});
};
/**
* Filters all events from input abi
*
* @method filterEvents
* @param {Array} abi
* @returns {Array} abi array with filtered objects of type 'event'
*/
var filterEvents = function (json) {
return json.filter(function (current) {
return current.type === 'event';
});
};
module.exports = {
getConstructor: getConstructor,
filterFunctions: filterFunctions,
filterEvents: filterEvents
getConstructor: getConstructor
};

3
libjsqrc/ethereumjs/lib/utils/config.js

@ -64,6 +64,7 @@ module.exports = {
ETH_UNITS: ETH_UNITS,
ETH_BIGNUMBER_ROUNDING_MODE: { ROUNDING_MODE: BigNumber.ROUND_DOWN },
ETH_POLLING_TIMEOUT: 1000,
ETH_DEFAULTBLOCK: 'latest'
defaultBlock: 'latest',
defaultAccount: undefined
};

42
libjsqrc/ethereumjs/lib/utils/utils.js

@ -14,9 +14,9 @@
You should have received a copy of the GNU Lesser General Public License
along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file utils.js
* @authors:
* Marek Kotewicz <marek@ethdev.com>
/**
* @file utils.js
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
@ -67,22 +67,6 @@ var padLeft = function (string, chars, sign) {
return new Array(chars - string.length + 1).join(sign ? sign : "0") + string;
};
/** Finds first index of array element matching pattern
*
* @method findIndex
* @param {Array}
* @param {Function} pattern
* @returns {Number} index of element
*/
var findIndex = function (array, callback) {
var end = false;
var i = 0;
for (; i < array.length && !end; i++) {
end = callback(array[i]);
}
return end ? i - 1 : -1;
};
/**
* Should be called to get sting from it's hex representation
*
@ -112,7 +96,7 @@ var toAscii = function(hex) {
/**
* Shold be called to get hex representation (prefixed by 0x) of ascii string
*
* @method fromAscii
* @method toHexNative
* @param {String} string
* @returns {String} hex representation of input string
*/
@ -142,6 +126,22 @@ var fromAscii = function(str, pad) {
return "0x" + hex;
};
/**
* Should be used to create full function/event name from json abi
*
* @method transformToFullName
* @param {Object} json-abi
* @return {String} full fnction/event name
*/
var 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 + ')';
};
/**
* Should be called to get display name of contract function
*
@ -448,12 +448,12 @@ var isJson = function (str) {
module.exports = {
padLeft: padLeft,
findIndex: findIndex,
toHex: toHex,
toDecimal: toDecimal,
fromDecimal: fromDecimal,
toAscii: toAscii,
fromAscii: fromAscii,
transformToFullName: transformToFullName,
extractDisplayName: extractDisplayName,
extractTypeName: extractTypeName,
toWei: toWei,

2
libjsqrc/ethereumjs/lib/version.json

@ -1,3 +1,3 @@
{
"version": "0.2.6"
"version": "0.3.3"
}

17
libjsqrc/ethereumjs/lib/web3.js

@ -117,6 +117,8 @@ web3.setProvider = function (provider) {
};
web3.reset = function () {
RequestManager.getInstance().reset();
c.defaultBlock = 'latest';
c.defaultAccount = undefined;
};
web3.toHex = utils.toHex;
web3.toAscii = utils.toAscii;
@ -131,14 +133,23 @@ web3.isAddress = utils.isAddress;
// ADD defaultblock
Object.defineProperty(web3.eth, 'defaultBlock', {
get: function () {
return c.ETH_DEFAULTBLOCK;
return c.defaultBlock;
},
set: function (val) {
c.ETH_DEFAULTBLOCK = val;
return c.ETH_DEFAULTBLOCK;
c.defaultBlock = val;
return val;
}
});
Object.defineProperty(web3.eth, 'defaultAccount', {
get: function () {
return c.defaultAccount;
},
set: function (val) {
c.defaultAccount = val;
return val;
}
});
/// setups all api methods
setupMethods(web3, web3Methods);

184
libjsqrc/ethereumjs/lib/web3/contract.js

@ -14,138 +14,38 @@
You should have received a copy of the GNU Lesser General Public License
along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file contract.js
* @authors:
* Marek Kotewicz <marek@ethdev.com>
/**
* @file contract.js
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2014
*/
var web3 = require('../web3');
var solAbi = require('../solidity/abi');
var utils = require('../utils/utils');
var solUtils = require('../solidity/utils');
var eventImpl = require('./event');
var signature = require('./signature');
var addFunctionRelatedPropertiesToContract = function (contract) {
contract.call = function (options) {
contract._isTransaction = false;
contract._options = options;
return contract;
};
contract.sendTransaction = function (options) {
contract._isTransaction = true;
contract._options = options;
return contract;
};
};
var addFunctionsToContract = function (contract, desc, address) {
var inputParser = solAbi.inputParser(desc);
var outputParser = solAbi.outputParser(desc);
// create contract functions
solUtils.filterFunctions(desc).forEach(function (method) {
var displayName = utils.extractDisplayName(method.name);
var typeName = utils.extractTypeName(method.name);
var impl = function () {
/*jshint maxcomplexity:7 */
var params = Array.prototype.slice.call(arguments);
var sign = signature.functionSignatureFromAscii(method.name);
var parsed = inputParser[displayName][typeName].apply(null, params);
var options = contract._options || {};
options.to = address;
options.data = sign + parsed;
var isTransaction = contract._isTransaction === true || (contract._isTransaction !== false && !method.constant);
var collapse = options.collapse !== false;
// reset
contract._options = {};
contract._isTransaction = null;
if (isTransaction) {
// transactions do not have any output, cause we do not know, when they will be processed
web3.eth.sendTransaction(options);
return;
}
var output = web3.eth.call(options);
var ret = outputParser[displayName][typeName](output);
if (collapse)
{
if (ret.length === 1)
ret = ret[0];
else if (ret.length === 0)
ret = null;
}
return ret;
};
if (contract[displayName] === undefined) {
contract[displayName] = impl;
}
contract[displayName][typeName] = impl;
var SolidityEvent = require('./event');
var SolidityFunction = require('./function');
var addFunctionsToContract = function (contract, desc) {
desc.filter(function (json) {
return json.type === 'function';
}).map(function (json) {
return new SolidityFunction(json, contract.address);
}).forEach(function (f) {
f.attachToContract(contract);
});
};
var addEventRelatedPropertiesToContract = function (contract, desc, address) {
contract.address = address;
contract._onWatchEventResult = function (data) {
var matchingEvent = event.getMatchingEvent(solUtils.filterEvents(desc));
var parser = eventImpl.outputParser(matchingEvent);
return parser(data);
};
Object.defineProperty(contract, 'topics', {
get: function() {
return solUtils.filterEvents(desc).map(function (e) {
return signature.eventSignatureFromAscii(e.name);
});
}
var addEventsToContract = function (contract, desc) {
desc.filter(function (json) {
return json.type === 'event';
}).map(function (json) {
return new SolidityEvent(json, contract.address);
}).forEach(function (e) {
e.attachToContract(contract);
});
};
var addEventsToContract = function (contract, desc, address) {
// create contract events
solUtils.filterEvents(desc).forEach(function (e) {
var impl = function () {
var params = Array.prototype.slice.call(arguments);
var sign = signature.eventSignatureFromAscii(e.name);
var event = eventImpl.inputParser(address, sign, e);
var o = event.apply(null, params);
var outputFormatter = function (data) {
var parser = eventImpl.outputParser(e);
return parser(data);
};
return web3.eth.filter(o, undefined, undefined, outputFormatter);
};
// this property should be used by eth.filter to check if object is an event
impl._isEvent = true;
var displayName = utils.extractDisplayName(e.name);
var typeName = utils.extractTypeName(e.name);
if (contract[displayName] === undefined) {
contract[displayName] = impl;
}
contract[displayName][typeName] = impl;
});
};
/**
* This method should be called when we want to call / transact some solidity method from javascript
* it returns an object which has same methods available as solidity contract description
@ -174,39 +74,33 @@ var contract = function (abi) {
return Contract.bind(null, abi);
};
function Contract(abi, options) {
var Contract = function (abi, options) {
// workaround for invalid assumption that method.name is the full anonymous prototype of the method.
// it's not. it's just the name. the rest of the code assumes it's actually the anonymous
// prototype, so we make it so as a workaround.
// TODO: we may not want to modify input params, maybe use copy instead?
abi.forEach(function (method) {
if (method.name.indexOf('(') === -1) {
var displayName = method.name;
var typeName = method.inputs.map(function(i){return i.type; }).join();
method.name = displayName + '(' + typeName + ')';
}
});
var address = '';
this.address = '';
if (utils.isAddress(options)) {
address = options;
} else { // is a source code!
this.address = options;
} else { // is an object!
// TODO, parse the rest of the args
var code = options;
options = options || {};
var args = Array.prototype.slice.call(arguments, 2);
var bytes = solAbi.formatConstructorParams(abi, args);
address = web3.eth.sendTransaction({data: code + bytes});
options.data += bytes;
this.address = web3.eth.sendTransaction(options);
}
var result = {};
addFunctionRelatedPropertiesToContract(result);
addFunctionsToContract(result, abi, address);
addEventRelatedPropertiesToContract(result, abi, address);
addEventsToContract(result, abi, address);
addFunctionsToContract(this, abi);
addEventsToContract(this, abi);
};
Contract.prototype.call = function () {
console.error('contract.call is deprecated');
return this;
};
return result;
}
Contract.prototype.sendTransaction = function () {
console.error('contract.sendTransact is deprecated');
return this;
};
module.exports = contract;

22
libjsqrc/ethereumjs/lib/web3/errors.js

@ -20,18 +20,18 @@
* @date 2015
*/
var utils = require('../utils/utils');
module.exports = {
InvalidNumberOfParams: new Error('Invalid number of input parameters'),
InvalidProvider: new Error('Providor not set or invalid'),
InvalidResponse: function(result){
var message = 'Invalid JSON RPC response';
if(utils.isObject(result) && result.error && result.error.message) {
message = result.error.message;
}
InvalidNumberOfParams: function () {
return new Error('Invalid number of input parameters');
},
InvalidConnection: function (host){
return new Error('CONNECTION ERROR: Couldn\'t connect to node '+ host +', is it running?');
},
InvalidProvider: function () {
return new Error('Providor not set or invalid');
},
InvalidResponse: function (result){
var message = !!result && !!result.error && !!result.error.message ? result.error.message : 'Invalid JSON RPC response';
return new Error(message);
}
};

13
libjsqrc/ethereumjs/lib/web3/eth.js

@ -102,7 +102,7 @@ var getBlock = new Method({
name: 'getBlock',
call: blockCall,
params: 2,
inputFormatter: [utils.toHex, function (val) { return !!val; }],
inputFormatter: [formatters.inputBlockNumberFormatter, function (val) { return !!val; }],
outputFormatter: formatters.outputBlockFormatter
});
@ -110,7 +110,7 @@ var getUncle = new Method({
name: 'getUncle',
call: uncleCall,
params: 2,
inputFormatter: [utils.toHex, utils.toHex],
inputFormatter: [formatters.inputBlockNumberFormatter, utils.toHex],
outputFormatter: formatters.outputBlockFormatter,
});
@ -148,7 +148,7 @@ var getTransactionFromBlock = new Method({
name: 'getTransactionFromBlock',
call: transactionFromBlockCall,
params: 2,
inputFormatter: [utils.toHex, utils.toHex],
inputFormatter: [formatters.inputBlockNumberFormatter, utils.toHex],
outputFormatter: formatters.outputTransactionFormatter
});
@ -192,12 +192,6 @@ var compileSerpent = new Method({
params: 1
});
var flush = new Method({
name: 'flush',
call: 'eth_flush',
params: 0
});
var methods = [
getBalance,
getStorageAt,
@ -215,7 +209,6 @@ var methods = [
compileSolidity,
compileLLL,
compileSerpent,
flush
];
/// @returns an array of objects describing web3.eth api properties

246
libjsqrc/ethereumjs/lib/web3/event.js

@ -14,125 +14,181 @@
You should have received a copy of the GNU Lesser General Public License
along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file event.js
* @authors:
* Marek Kotewicz <marek@ethdev.com>
/**
* @file event.js
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2014
*/
var abi = require('../solidity/abi');
var utils = require('../utils/utils');
var signature = require('./signature');
/// filter inputs array && returns only indexed (or not) inputs
/// @param inputs array
/// @param bool if result should be an array of indexed params on not
/// @returns array of (not?) indexed params
var filterInputs = function (inputs, indexed) {
return inputs.filter(function (current) {
return current.indexed === indexed;
});
var coder = require('../solidity/coder');
var web3 = require('../web3');
var formatters = require('./formatters');
/**
* This prototype should be used to create event filters
*/
var SolidityEvent = function (json, address) {
this._params = json.inputs;
this._name = utils.transformToFullName(json);
this._address = address;
this._anonymous = json.anonymous;
};
var inputWithName = function (inputs, name) {
var index = utils.findIndex(inputs, function (input) {
return input.name === name;
/**
* Should be used to get filtered param types
*
* @method types
* @param {Bool} decide if returned typed should be indexed
* @return {Array} array of types
*/
SolidityEvent.prototype.types = function (indexed) {
return this._params.filter(function (i) {
return i.indexed === indexed;
}).map(function (i) {
return i.type;
});
if (index === -1) {
console.error('indexed param with name ' + name + ' not found');
return undefined;
}
return inputs[index];
};
var indexedParamsToTopics = function (event, indexed) {
// sort keys?
return Object.keys(indexed).map(function (key) {
var inputs = [inputWithName(filterInputs(event.inputs, true), key)];
/**
* 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
*/
SolidityEvent.prototype.typeName = function () {
return utils.extractTypeName(this._name);
};
/**
* Should be used to get event signature
*
* @method signature
* @return {String} event signature
*/
SolidityEvent.prototype.signature = function () {
return web3.sha3(web3.fromAscii(this._name)).slice(2);
};
/**
* Should be used to encode indexed params and options to one final object
*
* @method encode
* @param {Object} indexed
* @param {Object} options
* @return {Object} everything combined together and encoded
*/
SolidityEvent.prototype.encode = function (indexed, options) {
indexed = indexed || {};
options = options || {};
var result = {};
['fromBlock', 'toBlock'].filter(function (f) {
return options[f] !== undefined;
}).forEach(function (f) {
result[f] = utils.toHex(options[f]);
});
result.topics = [];
if (!this._anonymous) {
result.address = this._address;
result.topics.push('0x' + this.signature());
}
var value = indexed[key];
if (value instanceof Array) {
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 abi.formatInput(inputs, [v]);
});
return '0x' + coder.encodeParam(i.type, v);
});
}
return '0x' + abi.formatInput(inputs, [value]);
return '0x' + coder.encodeParam(i.type, value);
});
};
var inputParser = function (address, sign, event) {
// valid options are 'earliest', 'latest', 'offset' and 'max', as defined for 'eth.filter'
return function (indexed, options) {
var o = options || {};
o.address = address;
o.topics = [];
o.topics.push(sign);
if (indexed) {
o.topics = o.topics.concat(indexedParamsToTopics(event, indexed));
}
return o;
};
};
result.topics = result.topics.concat(indexedTopics);
var getArgumentsObject = function (inputs, indexed, notIndexed) {
var indexedCopy = indexed.slice();
var notIndexedCopy = notIndexed.slice();
return inputs.reduce(function (acc, current) {
var value;
if (current.indexed)
value = indexedCopy.splice(0, 1)[0];
else
value = notIndexedCopy.splice(0, 1)[0];
acc[current.name] = value;
return acc;
}, {});
return result;
};
/**
* Should be used to decode indexed params and options
*
* @method decode
* @param {Object} data
* @return {Object} result object with decoded indexed && not indexed params
*/
SolidityEvent.prototype.decode = function (data) {
var outputParser = function (event) {
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);
return function (output) {
var result = {
event: utils.extractDisplayName(event.name),
number: output.number,
hash: output.hash,
args: {}
};
if (!output.topics) {
return result;
}
output.data = output.data || '';
var indexedOutputs = filterInputs(event.inputs, true);
var indexedData = "0x" + output.topics.slice(1, output.topics.length).map(function (topics) { return topics.slice(2); }).join("");
var indexedRes = abi.formatOutput(indexedOutputs, indexedData);
var result = formatters.outputLogFormatter(data);
result.event = this.displayName();
result.address = data.address;
var notIndexedOutputs = filterInputs(event.inputs, false);
var notIndexedRes = abi.formatOutput(notIndexedOutputs, output.data);
result.args = this._params.reduce(function (acc, current) {
acc[current.name] = current.indexed ? indexedParams.shift() : notIndexedParams.shift();
return acc;
}, {});
result.args = getArgumentsObject(event.inputs, indexedRes, notIndexedRes);
delete result.data;
delete result.topics;
return result;
};
return result;
};
var getMatchingEvent = function (events, payload) {
for (var i = 0; i < events.length; i++) {
var sign = signature.eventSignatureFromAscii(events[i].name);
if (sign === payload.topics[0]) {
return events[i];
}
}
return undefined;
/**
* Should be used to create new filter object from event
*
* @method execute
* @param {Object} indexed
* @param {Object} options
* @return {Object} filter object
*/
SolidityEvent.prototype.execute = function (indexed, options) {
var o = this.encode(indexed, options);
var formatter = this.decode.bind(this);
return web3.eth.filter(o, undefined, undefined, formatter);
};
module.exports = {
inputParser: inputParser,
outputParser: outputParser,
getMatchingEvent: getMatchingEvent
/**
* Should be used to attach event to contract object
*
* @method attachToContract
* @param {Contract}
*/
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;

57
libjsqrc/ethereumjs/lib/web3/filter.js

@ -28,6 +28,25 @@ var RequestManager = require('./requestmanager');
var formatters = require('./formatters');
var utils = require('../utils/utils');
/**
* Converts a given topic to a hex string, but also allows null values.
*
* @param {Mixed} value
* @return {String}
*/
var toTopic = function(value){
if(value === null || typeof value === 'undefined')
return null;
value = String(value);
if(value.indexOf('0x') === 0)
return value;
else
return utils.fromAscii(value);
};
/// 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
@ -42,7 +61,7 @@ var getOptions = function (options) {
// make sure topics, get converted to hex
options.topics = options.topics || [];
options.topics = options.topics.map(function(topic){
return utils.toHex(topic);
return (utils.isArray(topic)) ? topic.map(toTopic) : toTopic(topic);
});
// lazy load
@ -86,6 +105,20 @@ Filter.prototype.watch = function (callback) {
});
};
// call getFilterLogs on start
if (!utils.isString(this.options)) {
this.get(function (err, messages) {
// don't send all the responses to all the watches again... just to this one
if (err) {
callback(err);
}
messages.forEach(function (message) {
callback(null, message);
});
});
}
RequestManager.getInstance().startPolling({
method: this.implementation.poll.call,
params: [this.filterId],
@ -98,12 +131,24 @@ Filter.prototype.stopWatching = function () {
this.callbacks = [];
};
Filter.prototype.get = function () {
var logs = this.implementation.getLogs(this.filterId);
Filter.prototype.get = function (callback) {
var self = this;
return logs.map(function (log) {
return self.formatter ? self.formatter(log) : log;
});
if (utils.isFunction(callback)) {
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 {
var logs = this.implementation.getLogs(this.filterId);
return logs.map(function (log) {
return self.formatter ? self.formatter(log) : log;
});
}
};
module.exports = Filter;

15
libjsqrc/ethereumjs/lib/web3/formatters.js

@ -41,7 +41,7 @@ var isPredefinedBlockNumber = function (blockNumber) {
var inputDefaultBlockNumberFormatter = function (blockNumber) {
if (blockNumber === undefined) {
return config.ETH_DEFAULTBLOCK;
return config.defaultBlock;
}
return inputBlockNumberFormatter(blockNumber);
};
@ -64,6 +64,8 @@ var inputBlockNumberFormatter = function (blockNumber) {
*/
var inputTransactionFormatter = function (options){
options.from = options.from || config.defaultAccount;
// make code -> data
if (options.code) {
options.data = options.code;
@ -89,6 +91,7 @@ var inputTransactionFormatter = function (options){
var outputTransactionFormatter = function (tx){
tx.blockNumber = utils.toDecimal(tx.blockNumber);
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);
@ -111,7 +114,6 @@ var outputBlockFormatter = function(block) {
block.timestamp = utils.toDecimal(block.timestamp);
block.number = utils.toDecimal(block.number);
block.minGasPrice = utils.toBigNumber(block.minGasPrice);
block.difficulty = utils.toBigNumber(block.difficulty);
block.totalDifficulty = utils.toBigNumber(block.totalDifficulty);
@ -155,10 +157,12 @@ var inputPostFormatter = function(post) {
post.payload = utils.toHex(post.payload);
post.ttl = utils.fromDecimal(post.ttl);
post.workToProve = utils.fromDecimal(post.workToProve);
post.priority = utils.fromDecimal(post.priority);
if(!utils.isArray(post.topics)) {
post.topics = [post.topics];
// fallback
if (!utils.isArray(post.topics)) {
post.topics = post.topics ? [post.topics] : [];
}
// format the following options
@ -190,6 +194,9 @@ var outputPostFormatter = function(post){
}
// format the following options
if (!post.topics) {
post.topics = [];
}
post.topics = post.topics.map(function(topic){
return utils.toAscii(topic);
});

151
libjsqrc/ethereumjs/lib/web3/function.js

@ -0,0 +1,151 @@
/*
This file is part of ethereum.js.
ethereum.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ethereum.js is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file function.js
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
var web3 = require('../web3');
var coder = require('../solidity/coder');
var utils = require('../utils/utils');
/**
* This prototype should be used to call/sendTransaction to solidity functions
*/
var SolidityFunction = function (json, address) {
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._name = utils.transformToFullName(json);
this._address = address;
};
/**
* Should be used to create payload from arguments
*
* @method toPayload
* @param {...} solidity function params
* @param {Object} optional payload options
*/
SolidityFunction.prototype.toPayload = function () {
var args = Array.prototype.slice.call(arguments);
var options = {};
if (args.length > this._inputTypes.length && utils.isObject(args[args.length -1])) {
options = args.pop();
}
options.to = this._address;
options.data = '0x' + this.signature() + coder.encodeParams(this._inputTypes, args);
return options;
};
/**
* Should be used to get function signature
*
* @method signature
* @return {String} function signature
*/
SolidityFunction.prototype.signature = function () {
return web3.sha3(web3.fromAscii(this._name)).slice(2, 10);
};
/**
* Should be used to call function
*
* @method call
* @param {Object} options
* @return {String} output bytes
*/
SolidityFunction.prototype.call = function () {
var payload = this.toPayload.apply(this, Array.prototype.slice.call(arguments));
var output = web3.eth.call(payload);
output = output.length >= 2 ? output.slice(2) : output;
var result = coder.decodeParams(this._outputTypes, output);
return result.length === 1 ? result[0] : result;
};
/**
* Should be used to sendTransaction to solidity function
*
* @method sendTransaction
* @param {Object} options
*/
SolidityFunction.prototype.sendTransaction = function () {
var payload = this.toPayload.apply(this, Array.prototype.slice.call(arguments));
web3.eth.sendTransaction(payload);
};
/**
* Should be used to get function display name
*
* @method displayName
* @return {String} display name of the function
*/
SolidityFunction.prototype.displayName = function () {
return utils.extractDisplayName(this._name);
};
/**
* Should be used to get function type name
*
* @method typeName
* @return {String} type name of the function
*/
SolidityFunction.prototype.typeName = function () {
return utils.extractTypeName(this._name);
};
/**
* Should be called to execute function
*
* @method execute
*/
SolidityFunction.prototype.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));
};
/**
* Should be called to attach function to contract
*
* @method attachToContract
* @param {Contract}
*/
SolidityFunction.prototype.attachToContract = function (contract) {
var execute = this.execute.bind(this);
execute.call = this.call.bind(this);
execute.sendTransaction = this.sendTransaction.bind(this);
var displayName = this.displayName();
if (!contract[displayName]) {
contract[displayName] = execute;
}
contract[displayName][this.typeName()] = execute; // circular!!!!
};
module.exports = SolidityFunction;

18
libjsqrc/ethereumjs/lib/web3/httpprovider.js

@ -25,16 +25,23 @@
"use strict";
var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; // jshint ignore:line
var errors = require('./errors');
var HttpProvider = function (host) {
this.host = host || 'http://localhost:8080';
this.host = host || 'http://localhost:8545';
};
HttpProvider.prototype.send = function (payload) {
var request = new XMLHttpRequest();
request.open('POST', this.host, false);
request.send(JSON.stringify(payload));
try {
request.send(JSON.stringify(payload));
} catch(error) {
throw errors.InvalidConnection(this.host);
}
// check request.status
// TODO: throw an error here! it cannot silently fail!!!
@ -54,7 +61,12 @@ HttpProvider.prototype.sendAsync = function (payload, callback) {
};
request.open('POST', this.host, true);
request.send(JSON.stringify(payload));
try {
request.send(JSON.stringify(payload));
} catch(error) {
callback(errors.InvalidConnection(this.host));
}
};
module.exports = HttpProvider;

2
libjsqrc/ethereumjs/lib/web3/method.js

@ -66,7 +66,7 @@ Method.prototype.extractCallback = function (args) {
*/
Method.prototype.validateArgs = function (args) {
if (args.length !== this.params) {
throw errors.InvalidNumberOfParams;
throw errors.InvalidNumberOfParams();
}
};

6
libjsqrc/ethereumjs/lib/web3/requestmanager.js

@ -65,7 +65,7 @@ RequestManager.getInstance = function () {
*/
RequestManager.prototype.send = function (data) {
if (!this.provider) {
console.error(errors.InvalidProvider);
console.error(errors.InvalidProvider());
return null;
}
@ -88,7 +88,7 @@ RequestManager.prototype.send = function (data) {
*/
RequestManager.prototype.sendAsync = function (data, callback) {
if (!this.provider) {
return callback(errors.InvalidProvider);
return callback(errors.InvalidProvider());
}
var payload = Jsonrpc.getInstance().toPayload(data.method, data.params);
@ -179,7 +179,7 @@ RequestManager.prototype.poll = function () {
}
if (!this.provider) {
console.error(errors.InvalidProvider);
console.error(errors.InvalidProvider());
return;
}

2
libjsqrc/ethereumjs/lib/web3/shh.js

@ -27,7 +27,7 @@ var post = new Method({
name: 'post',
call: 'shh_post',
params: 1,
inputFormatter: formatters.inputPostFormatter
inputFormatter: [formatters.inputPostFormatter]
});
var newIdentity = new Method({

42
libjsqrc/ethereumjs/lib/web3/signature.js

@ -1,42 +0,0 @@
/*
This file is part of ethereum.js.
ethereum.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ethereum.js is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file signature.js
* @authors:
* Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
var web3 = require('../web3');
var c = require('../utils/config');
/// @param function name for which we want to get signature
/// @returns signature of function with given name
var functionSignatureFromAscii = function (name) {
return web3.sha3(web3.fromAscii(name)).slice(0, 2 + c.ETH_SIGNATURE_LENGTH * 2);
};
/// @param event name for which we want to get signature
/// @returns signature of event with given name
var eventSignatureFromAscii = function (name) {
return web3.sha3(web3.fromAscii(name));
};
module.exports = {
functionSignatureFromAscii: functionSignatureFromAscii,
eventSignatureFromAscii: eventSignatureFromAscii
};

2
libjsqrc/ethereumjs/package-init.js

@ -1,7 +1,7 @@
/* jshint ignore:start */
if(typeof web3 === 'undefined') {
web3 = require('ethereum.js');
web3 = require('web3');
BigNumber = require('bignumber.js');
}

7
libjsqrc/ethereumjs/package.js

@ -1,7 +1,7 @@
/* jshint ignore:start */
Package.describe({
name: 'ethereum:js',
version: '0.2.6',
name: 'ethereum:web3',
version: '0.3.3',
summary: 'Ethereum JavaScript API, middleware to talk to a ethreum node over RPC',
git: 'https://github.com/ethereum/ethereum.js',
// By default, Meteor will default to using README.md for documentation.
@ -14,10 +14,9 @@ Package.onUse(function(api) {
// api.use('3stack:bignumber@2.0.0', 'client');
// api.export('BigNumber', 'client');
api.export(['web3', 'BigNumber'], 'client');
api.addFiles('dist/ethereum.js', 'client');
api.addFiles('dist/web3.js', 'client');
api.addFiles('package-init.js', 'client');
});

4
libjsqrc/ethereumjs/package.json

@ -1,14 +1,14 @@
{
"name": "web3",
"namespace": "ethereum",
"version": "0.2.6",
"version": "0.3.3",
"description": "Ethereum JavaScript API, middleware to talk to a ethereum node over RPC",
"main": "./index.js",
"directories": {
"lib": "./lib"
},
"dependencies": {
"bignumber.js": ">=2.0.0",
"bignumber.js": "debris/bignumber.js#master",
"xmlhttprequest": "*"
},
"browser": {

14
libjsqrc/ethereumjs/test/abi.inputParser.js

@ -469,10 +469,10 @@ describe('lib/solidity/abi', function () {
var parser = abi.inputParser(d);
// then
assert.equal(parser.test([1]), "0000000000000000000000000000000100000000000000000000000000000000");
assert.equal(parser.test([2.125]), "0000000000000000000000000000000220000000000000000000000000000000");
assert.equal(parser.test([8.5]), "0000000000000000000000000000000880000000000000000000000000000000");
assert.equal(parser.test([-1]), "ffffffffffffffffffffffffffffffff00000000000000000000000000000000");
assert.equal(parser.test(1), "0000000000000000000000000000000100000000000000000000000000000000");
assert.equal(parser.test(2.125), "0000000000000000000000000000000220000000000000000000000000000000");
assert.equal(parser.test(8.5), "0000000000000000000000000000000880000000000000000000000000000000");
assert.equal(parser.test(-1), "ffffffffffffffffffffffffffffffff00000000000000000000000000000000");
});
@ -489,9 +489,9 @@ describe('lib/solidity/abi', function () {
var parser = abi.inputParser(d);
// then
assert.equal(parser.test([1]), "0000000000000000000000000000000100000000000000000000000000000000");
assert.equal(parser.test([2.125]), "0000000000000000000000000000000220000000000000000000000000000000");
assert.equal(parser.test([8.5]), "0000000000000000000000000000000880000000000000000000000000000000");
assert.equal(parser.test(1), "0000000000000000000000000000000100000000000000000000000000000000");
assert.equal(parser.test(2.125), "0000000000000000000000000000000220000000000000000000000000000000");
assert.equal(parser.test(8.5), "0000000000000000000000000000000880000000000000000000000000000000");
});

96
libjsqrc/ethereumjs/test/abi.outputParser.js

@ -35,13 +35,13 @@ describe('lib/solidity/abi', function() {
// then
assert.equal(
parser.test("0x" +
parser.test(
"0000000000000000000000000000000000000000000000000000000000000005" +
"68656c6c6f000000000000000000000000000000000000000000000000000000")[0],
'hello'
);
assert.equal(
parser.test("0x" +
parser.test(
"0000000000000000000000000000000000000000000000000000000000000005" +
"776f726c64000000000000000000000000000000000000000000000000000000")[0],
'world'
@ -62,14 +62,14 @@ describe('lib/solidity/abi', function() {
var parser = abi.outputParser(d);
// then
assert.equal(parser.test("0x0000000000000000000000000000000000000000000000000000000000000001")[0], 1);
assert.equal(parser.test("0x000000000000000000000000000000000000000000000000000000000000000a")[0], 10);
assert.equal(parser.test("0000000000000000000000000000000000000000000000000000000000000001")[0], 1);
assert.equal(parser.test("000000000000000000000000000000000000000000000000000000000000000a")[0], 10);
assert.equal(
parser.test("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")[0].toString(10),
parser.test("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")[0].toString(10),
new BigNumber("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16).toString(10)
);
assert.equal(
parser.test("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0")[0].toString(10),
parser.test("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0")[0].toString(10),
new BigNumber("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0", 16).toString(10)
);
});
@ -87,14 +87,14 @@ describe('lib/solidity/abi', function() {
var parser = abi.outputParser(d);
// then
assert.equal(parser.test("0x0000000000000000000000000000000000000000000000000000000000000001")[0], 1);
assert.equal(parser.test("0x000000000000000000000000000000000000000000000000000000000000000a")[0], 10);
assert.equal(parser.test("0000000000000000000000000000000000000000000000000000000000000001")[0], 1);
assert.equal(parser.test("000000000000000000000000000000000000000000000000000000000000000a")[0], 10);
assert.equal(
parser.test("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")[0].toString(10),
parser.test("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")[0].toString(10),
new BigNumber("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16).toString(10)
);
assert.equal(
parser.test("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0")[0].toString(10),
parser.test("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0")[0].toString(10),
new BigNumber("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0", 16).toString(10)
);
});
@ -112,14 +112,14 @@ describe('lib/solidity/abi', function() {
var parser = abi.outputParser(d);
// then
assert.equal(parser.test("0x0000000000000000000000000000000000000000000000000000000000000001")[0], 1);
assert.equal(parser.test("0x000000000000000000000000000000000000000000000000000000000000000a")[0], 10);
assert.equal(parser.test("0000000000000000000000000000000000000000000000000000000000000001")[0], 1);
assert.equal(parser.test("000000000000000000000000000000000000000000000000000000000000000a")[0], 10);
assert.equal(
parser.test("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")[0].toString(10),
parser.test("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")[0].toString(10),
new BigNumber("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16).toString(10)
);
assert.equal(
parser.test("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0")[0].toString(10),
parser.test("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0")[0].toString(10),
new BigNumber("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0", 16).toString(10)
);
});
@ -137,10 +137,10 @@ describe('lib/solidity/abi', function() {
var parser = abi.outputParser(d);
// then
assert.equal(parser.test("0x0000000000000000000000000000000000000000000000000000000000000001")[0], 1);
assert.equal(parser.test("0x000000000000000000000000000000000000000000000000000000000000000a")[0], 10);
assert.equal(parser.test("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")[0], -1);
assert.equal(parser.test("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0")[0], -16);
assert.equal(parser.test("0000000000000000000000000000000000000000000000000000000000000001")[0], 1);
assert.equal(parser.test("000000000000000000000000000000000000000000000000000000000000000a")[0], 10);
assert.equal(parser.test("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")[0], -1);
assert.equal(parser.test("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0")[0], -16);
});
it('should parse output int256', function() {
@ -156,10 +156,10 @@ describe('lib/solidity/abi', function() {
var parser = abi.outputParser(d);
// then
assert.equal(parser.test("0x0000000000000000000000000000000000000000000000000000000000000001")[0], 1);
assert.equal(parser.test("0x000000000000000000000000000000000000000000000000000000000000000a")[0], 10);
assert.equal(parser.test("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")[0], -1);
assert.equal(parser.test("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0")[0], -16);
assert.equal(parser.test("0000000000000000000000000000000000000000000000000000000000000001")[0], 1);
assert.equal(parser.test("000000000000000000000000000000000000000000000000000000000000000a")[0], 10);
assert.equal(parser.test("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")[0], -1);
assert.equal(parser.test("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0")[0], -16);
});
it('should parse output int128', function() {
@ -175,10 +175,10 @@ describe('lib/solidity/abi', function() {
var parser = abi.outputParser(d);
// then
assert.equal(parser.test("0x0000000000000000000000000000000000000000000000000000000000000001")[0], 1);
assert.equal(parser.test("0x000000000000000000000000000000000000000000000000000000000000000a")[0], 10);
assert.equal(parser.test("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")[0], -1);
assert.equal(parser.test("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0")[0], -16);
assert.equal(parser.test("0000000000000000000000000000000000000000000000000000000000000001")[0], 1);
assert.equal(parser.test("000000000000000000000000000000000000000000000000000000000000000a")[0], 10);
assert.equal(parser.test("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")[0], -1);
assert.equal(parser.test("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0")[0], -16);
});
it('should parse output address', function() {
@ -195,7 +195,7 @@ describe('lib/solidity/abi', function() {
// then
assert.equal(
parser.test("0x000000000000000000000000407d73d8a49eeb85d32cf465507dd71d507100c1")[0],
parser.test("000000000000000000000000407d73d8a49eeb85d32cf465507dd71d507100c1")[0],
"0x407d73d8a49eeb85d32cf465507dd71d507100c1"
);
});
@ -213,8 +213,8 @@ describe('lib/solidity/abi', function() {
var parser = abi.outputParser(d);
// then
assert.equal(parser.test("0x0000000000000000000000000000000000000000000000000000000000000001")[0], true);
assert.equal(parser.test("0x0000000000000000000000000000000000000000000000000000000000000000")[0], false);
assert.equal(parser.test("0000000000000000000000000000000000000000000000000000000000000001")[0], true);
assert.equal(parser.test("0000000000000000000000000000000000000000000000000000000000000000")[0], false);
});
@ -232,10 +232,10 @@ describe('lib/solidity/abi', function() {
var parser = abi.outputParser(d);
// then
assert.equal(parser.test("0x0000000000000000000000000000000100000000000000000000000000000000")[0], 1);
assert.equal(parser.test("0x0000000000000000000000000000000220000000000000000000000000000000")[0], 2.125);
assert.equal(parser.test("0x0000000000000000000000000000000880000000000000000000000000000000")[0], 8.5);
assert.equal(parser.test("0xffffffffffffffffffffffffffffffff00000000000000000000000000000000")[0], -1);
assert.equal(parser.test("0000000000000000000000000000000100000000000000000000000000000000")[0], 1);
assert.equal(parser.test("0000000000000000000000000000000220000000000000000000000000000000")[0], 2.125);
assert.equal(parser.test("0000000000000000000000000000000880000000000000000000000000000000")[0], 8.5);
assert.equal(parser.test("ffffffffffffffffffffffffffffffff00000000000000000000000000000000")[0], -1);
});
@ -252,9 +252,9 @@ describe('lib/solidity/abi', function() {
var parser = abi.outputParser(d);
// then
assert.equal(parser.test("0x0000000000000000000000000000000100000000000000000000000000000000")[0], 1);
assert.equal(parser.test("0x0000000000000000000000000000000220000000000000000000000000000000")[0], 2.125);
assert.equal(parser.test("0x0000000000000000000000000000000880000000000000000000000000000000")[0], 8.5);
assert.equal(parser.test("0000000000000000000000000000000100000000000000000000000000000000")[0], 1);
assert.equal(parser.test("0000000000000000000000000000000220000000000000000000000000000000")[0], 2.125);
assert.equal(parser.test("0000000000000000000000000000000880000000000000000000000000000000")[0], 8.5);
});
@ -274,7 +274,7 @@ describe('lib/solidity/abi', function() {
// then
assert.equal(
parser.test("0x" +
parser.test(
"0000000000000000000000000000000000000000000000000000000000000005" +
"0000000000000000000000000000000000000000000000000000000000000005" +
"68656c6c6f000000000000000000000000000000000000000000000000000000" +
@ -282,7 +282,7 @@ describe('lib/solidity/abi', function() {
'hello'
);
assert.equal(
parser.test("0x" +
parser.test(
"0000000000000000000000000000000000000000000000000000000000000005" +
"0000000000000000000000000000000000000000000000000000000000000005" +
"68656c6c6f000000000000000000000000000000000000000000000000000000" +
@ -305,8 +305,8 @@ describe('lib/solidity/abi', function() {
var parser = abi.outputParser(d);
// then
assert.equal(parser.helloworld("0x0000000000000000000000000000000000000000000000000000000000000001")[0], 1);
assert.equal(parser.helloworld['int']("0x0000000000000000000000000000000000000000000000000000000000000001")[0], 1);
assert.equal(parser.helloworld("0000000000000000000000000000000000000000000000000000000000000001")[0], 1);
assert.equal(parser.helloworld['int']("0000000000000000000000000000000000000000000000000000000000000001")[0], 1);
});
@ -330,8 +330,8 @@ describe('lib/solidity/abi', function() {
var parser = abi.outputParser(d);
//then
assert.equal(parser.test("0000000000000000000000000000000000000000000000000000000000000001")[0], 1);
assert.equal(parser.test2("0x" +
assert.equal(parser.test("00000000000000000000000000000000000000000000000000000000000001")[0], 1);
assert.equal(parser.test2(
"0000000000000000000000000000000000000000000000000000000000000005" +
"68656c6c6f000000000000000000000000000000000000000000000000000000")[0],
"hello"
@ -351,13 +351,13 @@ describe('lib/solidity/abi', function() {
var parser = abi.outputParser(d);
// then
assert.equal(parser.test("0x" +
assert.equal(parser.test(
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000005" +
"0000000000000000000000000000000000000000000000000000000000000006")[0][0],
5
);
assert.equal(parser.test("0x" +
assert.equal(parser.test(
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000005" +
"0000000000000000000000000000000000000000000000000000000000000006")[0][1],
@ -366,7 +366,7 @@ describe('lib/solidity/abi', function() {
});
it('should parse 0x value', function () {
it('should parse 0x0 value', function () {
// given
var d = clone(description);
@ -378,11 +378,11 @@ describe('lib/solidity/abi', function() {
var parser = abi.outputParser(d);
// then
assert.equal(parser.test("0x")[0], 0);
assert.equal(parser.test("0x0")[0], 0);
});
it('should parse 0x value', function () {
it('should parse 0x0 value', function () {
// given
var d = clone(description);
@ -394,7 +394,7 @@ describe('lib/solidity/abi', function() {
var parser = abi.outputParser(d);
// then
assert.equal(parser.test("0x")[0], 0);
assert.equal(parser.test("0x0")[0], 0);
});

68
libjsqrc/ethereumjs/test/coder.decodeParam.js

@ -0,0 +1,68 @@
var chai = require('chai');
var assert = chai.assert;
var coder = require('../lib/solidity/coder');
var BigNumber = require('bignumber.js');
var bn = BigNumber;
describe('lib/solidity/coder', function () {
describe('decodeParam', function () {
var test = function (t) {
it('should turn ' + t.value + ' to ' + t.expected, function () {
assert.deepEqual(coder.decodeParam(t.type, t.value), t.expected);
});
};
test({ type: 'int', expected: new bn(1), value: '0000000000000000000000000000000000000000000000000000000000000001'});
test({ type: 'int', expected: new bn(16), value: '0000000000000000000000000000000000000000000000000000000000000010'});
test({ type: 'int', expected: new bn(-1), value: 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'});
test({ type: 'int256', expected: new bn(1), value: '0000000000000000000000000000000000000000000000000000000000000001'});
test({ type: 'int256', expected: new bn(16), value: '0000000000000000000000000000000000000000000000000000000000000010'});
test({ type: 'int256', expected: new bn(-1), value: 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'});
test({ type: 'bytes32', expected: 'gavofyork', value: '6761766f66796f726b0000000000000000000000000000000000000000000000'});
test({ type: 'bytes', expected: 'gavofyork', value: '0000000000000000000000000000000000000000000000000000000000000009' +
'6761766f66796f726b0000000000000000000000000000000000000000000000'});
test({ type: 'int[]', expected: [new bn(3)], value: '0000000000000000000000000000000000000000000000000000000000000001' +
'0000000000000000000000000000000000000000000000000000000000000003'});
test({ type: 'int256[]', expected: [new bn(3)], value: '0000000000000000000000000000000000000000000000000000000000000001' +
'0000000000000000000000000000000000000000000000000000000000000003'});
test({ type: 'int[]', expected: [new bn(1), new bn(2), new bn(3)],
value: '0000000000000000000000000000000000000000000000000000000000000003' +
'0000000000000000000000000000000000000000000000000000000000000001' +
'0000000000000000000000000000000000000000000000000000000000000002' +
'0000000000000000000000000000000000000000000000000000000000000003'});
});
});
describe('lib/solidity/coder', function () {
describe('decodeParams', function () {
var test = function (t) {
it('should turn ' + t.values + ' to ' + t.expected, function () {
assert.deepEqual(coder.decodeParams(t.types, t.values), t.expected);
});
};
test({ types: ['int'], expected: [new bn(1)], values: '0000000000000000000000000000000000000000000000000000000000000001'});
test({ types: ['bytes32', 'int'], expected: ['gavofyork', new bn(5)],
values: '6761766f66796f726b0000000000000000000000000000000000000000000000' +
'0000000000000000000000000000000000000000000000000000000000000005'});
test({ types: ['int', 'bytes32'], expected: [new bn(5), 'gavofyork'],
values: '0000000000000000000000000000000000000000000000000000000000000005' +
'6761766f66796f726b0000000000000000000000000000000000000000000000'});
test({ types: ['int', 'bytes', 'int', 'int', 'int', 'int[]'], expected: [new bn(1), 'gavofyork', new bn(2), new bn(3), new bn(4),
[new bn(5), new bn(6), new bn(7)]],
values: '0000000000000000000000000000000000000000000000000000000000000009' +
'0000000000000000000000000000000000000000000000000000000000000003' +
'0000000000000000000000000000000000000000000000000000000000000001' +
'0000000000000000000000000000000000000000000000000000000000000002' +
'0000000000000000000000000000000000000000000000000000000000000003' +
'0000000000000000000000000000000000000000000000000000000000000004' +
'6761766f66796f726b0000000000000000000000000000000000000000000000' +
'0000000000000000000000000000000000000000000000000000000000000005' +
'0000000000000000000000000000000000000000000000000000000000000006' +
'0000000000000000000000000000000000000000000000000000000000000007'});
});
});

91
libjsqrc/ethereumjs/test/coder.encodeParam.js

@ -0,0 +1,91 @@
var chai = require('chai');
var assert = chai.assert;
var coder = require('../lib/solidity/coder');
describe('lib/solidity/coder', function () {
describe('encodeParam', function () {
var test = function (t) {
it('should turn ' + t.value + ' to ' + t.expected, function () {
assert.equal(coder.encodeParam(t.type, t.value), t.expected);
});
};
test({ type: 'int', value: 1, expected: '0000000000000000000000000000000000000000000000000000000000000001'});
test({ type: 'int', value: 16, expected: '0000000000000000000000000000000000000000000000000000000000000010'});
test({ type: 'int', value: -1, expected: 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'});
test({ type: 'int256', value: 1, expected: '0000000000000000000000000000000000000000000000000000000000000001'});
test({ type: 'int256', value: 16, expected: '0000000000000000000000000000000000000000000000000000000000000010'});
test({ type: 'int256', value: -1, expected: 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'});
test({ type: 'bytes32', value: 'gavofyork', expected: '6761766f66796f726b0000000000000000000000000000000000000000000000'});
test({ type: 'bytes', value: 'gavofyork', expected: '0000000000000000000000000000000000000000000000000000000000000009' +
'6761766f66796f726b0000000000000000000000000000000000000000000000'});
test({ type: 'int[]', value: [3], expected: '0000000000000000000000000000000000000000000000000000000000000001' +
'0000000000000000000000000000000000000000000000000000000000000003'});
test({ type: 'int256[]', value: [3], expected: '0000000000000000000000000000000000000000000000000000000000000001' +
'0000000000000000000000000000000000000000000000000000000000000003'});
test({ type: 'int[]', value: [1,2,3], expected: '0000000000000000000000000000000000000000000000000000000000000003' +
'0000000000000000000000000000000000000000000000000000000000000001' +
'0000000000000000000000000000000000000000000000000000000000000002' +
'0000000000000000000000000000000000000000000000000000000000000003'});
});
});
describe('lib/solidity/coder', function () {
describe('encodeParams', function () {
var test = function (t) {
it('should turn ' + t.values + ' to ' + t.expected, function () {
assert.equal(coder.encodeParams(t.types, t.values), t.expected);
});
};
test({ types: ['int'], values: [1], expected: '0000000000000000000000000000000000000000000000000000000000000001'});
test({ types: ['int'], values: [16], expected: '0000000000000000000000000000000000000000000000000000000000000010'});
test({ types: ['int'], values: [-1], expected: 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'});
test({ types: ['int256'], values: [1], expected: '0000000000000000000000000000000000000000000000000000000000000001'});
test({ types: ['int256'], values: [16], expected: '0000000000000000000000000000000000000000000000000000000000000010'});
test({ types: ['int256'], values: [-1], expected: 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'});
test({ types: ['bytes32'], values: ['gavofyork'], expected: '6761766f66796f726b0000000000000000000000000000000000000000000000'});
test({ types: ['bytes'], values: ['gavofyork'], expected: '0000000000000000000000000000000000000000000000000000000000000009' +
'6761766f66796f726b0000000000000000000000000000000000000000000000'});
test({ types: ['int[]'], values: [[3]], expected: '0000000000000000000000000000000000000000000000000000000000000001' +
'0000000000000000000000000000000000000000000000000000000000000003'});
test({ types: ['int256[]'], values: [[3]], expected: '0000000000000000000000000000000000000000000000000000000000000001' +
'0000000000000000000000000000000000000000000000000000000000000003'});
test({ types: ['int256[]'], values: [[1,2,3]], expected: '0000000000000000000000000000000000000000000000000000000000000003' +
'0000000000000000000000000000000000000000000000000000000000000001' +
'0000000000000000000000000000000000000000000000000000000000000002' +
'0000000000000000000000000000000000000000000000000000000000000003'});
test({ types: ['bytes32', 'int'], values: ['gavofyork', 5],
expected: '6761766f66796f726b0000000000000000000000000000000000000000000000' +
'0000000000000000000000000000000000000000000000000000000000000005'});
test({ types: ['int', 'bytes32'], values: [5, 'gavofyork'],
expected: '0000000000000000000000000000000000000000000000000000000000000005' +
'6761766f66796f726b0000000000000000000000000000000000000000000000'});
test({ types: ['bytes', 'int'], values: ['gavofyork', 5],
expected: '0000000000000000000000000000000000000000000000000000000000000009' +
'0000000000000000000000000000000000000000000000000000000000000005' +
'6761766f66796f726b0000000000000000000000000000000000000000000000'});
test({ types: ['int', 'bytes'], values: [5, 'gavofyork'],
expected: '0000000000000000000000000000000000000000000000000000000000000009' +
'0000000000000000000000000000000000000000000000000000000000000005' +
'6761766f66796f726b0000000000000000000000000000000000000000000000'});
test({ types: ['int', 'bytes', 'int', 'int', 'int', 'int[]'], values: [1, 'gavofyork', 2, 3, 4, [5, 6, 7]],
expected: '0000000000000000000000000000000000000000000000000000000000000009' +
'0000000000000000000000000000000000000000000000000000000000000003' +
'0000000000000000000000000000000000000000000000000000000000000001' +
'0000000000000000000000000000000000000000000000000000000000000002' +
'0000000000000000000000000000000000000000000000000000000000000003' +
'0000000000000000000000000000000000000000000000000000000000000004' +
'6761766f66796f726b0000000000000000000000000000000000000000000000' +
'0000000000000000000000000000000000000000000000000000000000000005' +
'0000000000000000000000000000000000000000000000000000000000000006' +
'0000000000000000000000000000000000000000000000000000000000000007'});
});
});

147
libjsqrc/ethereumjs/test/contract.js

@ -2,7 +2,9 @@ var chai = require('chai');
var assert = chai.assert;
var web3 = require('../index');
var FakeHttpProvider = require('./helpers/FakeHttpProvider');
var FakeHttpProvider2 = require('./helpers/FakeHttpProvider2');
var utils = require('../lib/utils/utils');
var BigNumber = require('bignumber.js');
var desc = [{
"name": "balance(address)",
@ -27,6 +29,18 @@ var desc = [{
"type": "uint256"
}],
"outputs": []
}, {
"name": "testArr(int[])",
"type": "function",
"inputs": [{
"name": "value",
"type": "int[]"
}],
"constant": true,
"outputs": [{
"name": "d",
"type": "int"
}]
}, {
"name":"Changed",
"type":"event",
@ -63,11 +77,27 @@ describe('web3.eth.contract', function () {
assert.deepEqual(payload.params[0], {
topics: [
sha3,
'0x1234567890123456789012345678901234567890'
'0x0000000000000000000000001234567890123456789012345678901234567890',
null
],
address: '0x1234567890123456789012345678901234567890'
});
} else if (step === 2 && utils.isArray(payload)) {
} else if (step === 2) {
step = 3;
provider.injectResult([{
address: address,
topics: [
sha3,
'0x0000000000000000000000001234567890123456789012345678901234567890',
'0x0000000000000000000000000000000000000000000000000000000000000001'
],
number: 2,
data: '0x0000000000000000000000000000000000000000000000000000000000000001' +
'0000000000000000000000000000000000000000000000000000000000000008'
}]);
assert.equal(payload.jsonrpc, '2.0');
assert.equal(payload.method, 'eth_getFilterLogs');
} else if (step === 3 && utils.isArray(payload)) {
provider.injectBatchResults([[{
address: address,
topics: [
@ -89,12 +119,16 @@ describe('web3.eth.contract', function () {
var Contract = web3.eth.contract(desc);
var contract = new Contract(address);
var res = 0;
contract.Changed({from: address}).watch(function(err, result) {
assert.equal(result.args.from, address);
assert.equal(result.args.amount, 1);
assert.equal(result.args.t1, 1);
assert.equal(result.args.t2, 8);
done();
res++;
if (res === 2) {
done();
}
});
});
@ -187,7 +221,40 @@ describe('web3.eth.contract', function () {
var Contract = web3.eth.contract(desc);
var contract = new Contract(address);
contract.call({from: address, gas: 50000}).balance(address);
contract.balance(address, {from: address, gas: 50000});
});
it('should explicitly make a call with optional params', function () {
var provider = new FakeHttpProvider();
web3.setProvider(provider);
web3.reset();
var sha3 = '0x5131231231231231231231';
var address = '0x1234567890123456789012345678901234567890';
provider.injectResult(sha3);
var step = 0;
provider.injectValidation(function (payload) {
if (step === 0) {
step = 1;
assert.equal(payload.jsonrpc, '2.0');
assert.equal(payload.method, 'web3_sha3');
assert.equal(payload.params[0], web3.fromAscii('balance(address)'));
} else if (step === 1) {
assert.equal(payload.method, 'eth_call');
assert.deepEqual(payload.params, [{
data: sha3.slice(0, 10) + '0000000000000000000000001234567890123456789012345678901234567890',
to: address,
from: address,
gas: '0xc350'
}, 'latest']);
}
});
var Contract = web3.eth.contract(desc);
var contract = new Contract(address);
contract.balance.call(address, {from: address, gas: 50000});
});
@ -223,7 +290,77 @@ describe('web3.eth.contract', function () {
var Contract = web3.eth.contract(desc);
var contract = new Contract(address);
contract.sendTransaction({from: address, gas: 50000, gasPrice: 3000, value: 10000}).send(address, 17);
contract.send(address, 17, {from: address, gas: 50000, gasPrice: 3000, value: 10000});
});
it('should explicitly sendTransaction with optional params', function () {
var provider = new FakeHttpProvider();
web3.setProvider(provider);
web3.reset();
var sha3 = '0x5131231231231231231231';
var address = '0x1234567890123456789012345678901234567890';
provider.injectResult(sha3);
var step = 0;
provider.injectValidation(function (payload) {
if (step === 0) {
step = 1;
assert.equal(payload.jsonrpc, '2.0');
assert.equal(payload.method, 'web3_sha3');
assert.equal(payload.params[0], web3.fromAscii('send(address,uint256)'));
} else if (step === 1) {
assert.equal(payload.method, 'eth_sendTransaction');
assert.deepEqual(payload.params, [{
data: sha3.slice(0, 10) +
'0000000000000000000000001234567890123456789012345678901234567890' +
'0000000000000000000000000000000000000000000000000000000000000011' ,
to: address,
from: address,
gas: '0xc350',
gasPrice: '0xbb8',
value: '0x2710'
}]);
}
});
var Contract = web3.eth.contract(desc);
var contract = new Contract(address);
contract.send.sendTransaction(address, 17, {from: address, gas: 50000, gasPrice: 3000, value: 10000});
});
it('should call testArr method and properly parse result', function () {
var provider = new FakeHttpProvider2();
web3.setProvider(provider);
web3.reset();
var sha3 = '0x5131231231231231231231';
var address = '0x1234567890123456789012345678901234567890';
provider.injectResultList([{
result: sha3
}, {
result: '0x0000000000000000000000000000000000000000000000000000000000000005'
}]);
var step = 0;
provider.injectValidation(function (payload) {
if (step === 1) { // getting sha3 is first
assert.equal(payload.method, 'eth_call');
assert.deepEqual(payload.params, [{
data: sha3.slice(0, 10) +
'0000000000000000000000000000000000000000000000000000000000000001' +
'0000000000000000000000000000000000000000000000000000000000000003',
to: address
},
'latest'
]);
}
step++;
});
var Contract = web3.eth.contract(desc);
var contract = new Contract(address);
var result = contract.testArr([3]);
assert.deepEqual(new BigNumber(5), result);
});
});
});

180
libjsqrc/ethereumjs/test/event.decode.js

@ -0,0 +1,180 @@
var chai = require('chai');
var assert = chai.assert;
var BigNumber = require('bignumber.js');
var SolidityEvent = require('../lib/web3/event');
var name = 'event1';
var address = '0x1234567890123456789012345678901234567890';
var tests = [{
abi: {
name: name,
inputs: []
},
data: {
logIndex: '0x1',
transactionIndex: '0x10',
transactionHash: '0x1234567890',
address: address,
blockHash: '0x1234567890',
blockNumber: '0x1'
},
expected: {
event: name,
args: {},
logIndex: 1,
transactionIndex: 16,
transactionHash: '0x1234567890',
address: address,
blockHash: '0x1234567890',
blockNumber: 1
}
}, {
abi: {
name: name,
inputs: [{
name: 'a',
type: 'int',
indexed: false
}]
},
data: {
logIndex: '0x1',
transactionIndex: '0x10',
transactionHash: '0x1234567890',
address: address,
blockHash: '0x1234567890',
blockNumber: '0x1',
data: '0x0000000000000000000000000000000000000000000000000000000000000001'
},
expected: {
event: name,
args: {
a: new BigNumber(1)
},
logIndex: 1,
transactionIndex: 16,
transactionHash: '0x1234567890',
address: address,
blockHash: '0x1234567890',
blockNumber: 1
}
}, {
abi: {
name: name,
inputs: [{
name: 'a',
type: 'int',
indexed: false
}, {
name: 'b',
type: 'int',
indexed: true
}, {
name: 'c',
type: 'int',
indexed: false
}, {
name: 'd',
type: 'int',
indexed: true
}]
},
data: {
logIndex: '0x1',
transactionIndex: '0x10',
transactionHash: '0x1234567890',
address: address,
blockHash: '0x1234567890',
blockNumber: '0x1',
data: '0x' +
'0000000000000000000000000000000000000000000000000000000000000001' +
'0000000000000000000000000000000000000000000000000000000000000004',
topics: [
address,
'0x000000000000000000000000000000000000000000000000000000000000000a',
'0x0000000000000000000000000000000000000000000000000000000000000010'
]
},
expected: {
event: name,
args: {
a: new BigNumber(1),
b: new BigNumber(10),
c: new BigNumber(4),
d: new BigNumber(16)
},
logIndex: 1,
transactionIndex: 16,
transactionHash: '0x1234567890',
address: address,
blockHash: '0x1234567890',
blockNumber: 1
}
}, {
abi: {
name: name,
anonymous: true,
inputs: [{
name: 'a',
type: 'int',
indexed: false
}, {
name: 'b',
type: 'int',
indexed: true
}, {
name: 'c',
type: 'int',
indexed: false
}, {
name: 'd',
type: 'int',
indexed: true
}]
},
data: {
logIndex: '0x1',
transactionIndex: '0x10',
transactionHash: '0x1234567890',
address: address,
blockHash: '0x1234567890',
blockNumber: '0x1',
data: '0x' +
'0000000000000000000000000000000000000000000000000000000000000001' +
'0000000000000000000000000000000000000000000000000000000000000004',
topics: [
'0x000000000000000000000000000000000000000000000000000000000000000a',
'0x0000000000000000000000000000000000000000000000000000000000000010'
]
},
expected: {
event: name,
args: {
a: new BigNumber(1),
b: new BigNumber(10),
c: new BigNumber(4),
d: new BigNumber(16)
},
logIndex: 1,
transactionIndex: 16,
transactionHash: '0x1234567890',
address: address,
blockHash: '0x1234567890',
blockNumber: 1
}
}];
describe('lib/web3/event', function () {
describe('decode', function () {
tests.forEach(function (test, index) {
it('test no: ' + index, function () {
var event = new SolidityEvent(test.abi, address);
var result = event.decode(test.data);
assert.deepEqual(result, test.expected);
});
});
});
});

206
libjsqrc/ethereumjs/test/event.encode.js

@ -0,0 +1,206 @@
var chai = require('chai');
var assert = chai.assert;
var SolidityEvent = require('../lib/web3/event');
var address = '0x1234567890123456789012345678901234567890';
var signature = '0xffff';
var tests = [{
abi: {
name: 'event1',
inputs: []
},
indexed: {},
options: {},
expected: {
address: address,
topics: [
signature
]
}
}, {
abi: {
name: 'event1',
inputs: [{
type: 'int',
name: 'a',
indexed: true
}]
},
indexed: {
a: 16
},
options: {},
expected: {
address: address,
topics: [
signature,
'0x0000000000000000000000000000000000000000000000000000000000000010'
]
}
},{
abi: {
name: 'event1',
inputs: [{
type: 'int',
name: 'a',
indexed: true
}, {
type: 'int',
name: 'b',
indexed: true
}, {
type: 'int',
name: 'c',
indexed: false
}, {
type: 'int',
name: 'd',
indexed: true
}]
},
indexed: {
b: 4
},
options: {},
expected: {
address: address,
topics: [
signature, // signature
null, // a
'0x0000000000000000000000000000000000000000000000000000000000000004', // b
null // d
]
}
}, {
abi: {
name: 'event1',
inputs: [{
type: 'int',
name: 'a',
indexed: true
}, {
type: 'int',
name: 'b',
indexed: true
}]
},
indexed: {
a: [16, 1],
b: 2
},
options: {},
expected: {
address: address,
topics: [
signature,
['0x0000000000000000000000000000000000000000000000000000000000000010', '0x0000000000000000000000000000000000000000000000000000000000000001'],
'0x0000000000000000000000000000000000000000000000000000000000000002'
]
}
}, {
abi: {
name: 'event1',
inputs: [{
type: 'int',
name: 'a',
indexed: true
}]
},
indexed: {
a: null
},
options: {},
expected: {
address: address,
topics: [
signature,
null
]
}
}, {
abi: {
name: 'event1',
inputs: [{
type: 'int',
name: 'a',
indexed: true
}]
},
indexed: {
a: 1
},
options: {
fromBlock: 4,
toBlock: 10
},
expected: {
address: address,
fromBlock: '0x4',
toBlock: '0xa',
topics: [
signature,
'0x0000000000000000000000000000000000000000000000000000000000000001'
]
}
}, {
abi: {
name: 'event1',
inputs: [{
type: 'int',
name: 'a',
indexed: true
}],
anonymous: true
},
indexed: {
a: 1
},
options: {},
expected: {
topics: [
'0x0000000000000000000000000000000000000000000000000000000000000001'
]
}
}, {
abi: {
name: 'event1',
inputs: [{
type: 'int',
name: 'a',
indexed: true
}, {
type: 'int',
name: 'b',
indexed: true
}],
anonymous: true
},
indexed: {
b: 1
},
options: {},
expected: {
topics: [
null,
'0x0000000000000000000000000000000000000000000000000000000000000001'
]
}
}];
describe('lib/web3/event', function () {
describe('encode', function () {
tests.forEach(function (test, index) {
it('test no: ' + index, function () {
var event = new SolidityEvent(test.abi, address);
event.signature = function () { // inject signature
return signature.slice(2);
};
var result = event.encode(test.indexed, test.options);
assert.deepEqual(result, test.expected);
});
});
});
});

113
libjsqrc/ethereumjs/test/event.inputParser.js

@ -1,113 +0,0 @@
var assert = require('assert');
var event = require('../lib/web3/event.js');
var f = require('../lib/solidity/formatters.js');
describe('lib/web3/event', function () {
describe('inputParser', function () {
it('should create basic filter input object', function () {
// given
var address = '0x012345';
var signature = '0x987654';
var e = {
name: 'Event',
inputs: [{"name":"a","type":"uint256","indexed":true},{"name":"b","type":"hash256","indexed":false}]
};
// when
var impl = event.inputParser(address, signature, e);
var result = impl();
// then
assert.equal(result.address, address);
assert.equal(result.topics.length, 1);
assert.equal(result.topics[0], signature);
});
it('should create filter input object with options', function () {
// given
var address = '0x012345';
var signature = '0x987654';
var options = {
fromBlock: 1,
toBlock: 2,
};
var e = {
name: 'Event',
inputs: [{"name":"a","type":"uint256","indexed":true},{"name":"b","type":"hash256","indexed":false}]
};
// when
var impl = event.inputParser(address, signature, e);
var result = impl({}, options);
// then
assert.equal(result.address, address);
assert.equal(result.topics.length, 1);
assert.equal(result.topics[0], signature);
assert.equal(result.fromBlock, options.fromBlock);
assert.equal(result.toBlock, options.toBlock);
});
it('should create filter input object with indexed params', function () {
// given
var address = '0x012345';
var signature = '0x987654';
var options = {
fromBlock: 1,
toBlock: 2
};
var e = {
name: 'Event',
inputs: [{"name":"a","type":"uint256","indexed":true},{"name":"b","type":"hash256","indexed":false}]
};
// when
var impl = event.inputParser(address, signature, e);
var result = impl({a: 4}, options);
// then
assert.equal(result.address, address);
assert.equal(result.topics.length, 2);
assert.equal(result.topics[0], signature);
assert.equal(result.topics[1], '0x' + f.formatInputInt(4));
assert.equal(result.fromBlock, options.fromBlock);
assert.equal(result.toBlock, options.toBlock);
});
it('should create filter input object with an array of indexed params', function () {
// given
var address = '0x012345';
var signature = '0x987654';
var options = {
fromBlock: 1,
toBlock: 2,
};
var e = {
name: 'Event',
inputs: [{"name":"a","type":"uint256","indexed":true},{"name":"b","type":"hash256","indexed":false}]
};
// when
var impl = event.inputParser(address, signature, e);
var result = impl({a: [4, 69]}, options);
// then
assert.equal(result.address, address);
assert.equal(result.topics.length, 2);
assert.equal(result.topics[0], signature);
assert.equal(result.topics[1][0], f.formatInputInt(4));
assert.equal(result.topics[1][1], f.formatInputInt(69));
assert.equal(result.fromBlock, options.fromBlock);
assert.equal(result.toBlock, options.toBlock);
});
});
});

81
libjsqrc/ethereumjs/test/event.outputParser.js

@ -1,81 +0,0 @@
var assert = require('assert');
var event = require('../lib/web3/event.js');
describe('lib/web3/event', function () {
describe('outputParser', function () {
it('should parse basic event output object', function () {
// given
var output = {
"address":"0x78dfc5983baecf65f73e3de3a96cee24e6b7981e",
"data":"0x000000000000000000000000000000000000000000000000000000000000004b",
"number":2,
"topics":[
"0x6e61ef44ac2747ff8b84d353a908eb8bd5c3fb118334d57698c5cfc7041196ad",
"0x0000000000000000000000000000000000000000000000000000000000000001"
]
};
var e = {
name: 'Event',
inputs: [{"name":"a","type":"bool","indexed":true},{"name":"b","type":"uint256","indexed":false}]
};
// when
var impl = event.outputParser(e);
var result = impl(output);
// then
assert.equal(result.event, 'Event');
assert.equal(result.number, 2);
assert.equal(Object.keys(result.args).length, 2);
assert.equal(result.args.a, true);
assert.equal(result.args.b, 75);
});
it('should parse event output object arguments in correct order', function () {
// given
var output = {
"address":"0x78dfc5983baecf65f73e3de3a96cee24e6b7981e",
"data": "0x" +
"000000000000000000000000000000000000000000000000000000000000004b" +
"000000000000000000000000000000000000000000000000000000000000004c" +
"0000000000000000000000000000000000000000000000000000000000000001",
"number":3,
"topics":[
"0x6e61ef44ac2747ff8b84d353a908eb8bd5c3fb118334d57698c5cfc7041196ad",
"0x0000000000000000000000000000000000000000000000000000000000000001",
"0x0000000000000000000000000000000000000000000000000000000000000005"
]
};
var e = {
name: 'Event2',
inputs: [
{"name":"a","type":"bool","indexed":true},
{"name":"b","type":"int","indexed":false},
{"name":"c","type":"int","indexed":false},
{"name":"d","type":"int","indexed":true},
{"name":"e","type":"bool","indexed":false}
]
};
// when
var impl = event.outputParser(e);
var result = impl(output);
// then
assert.equal(result.event, 'Event2');
assert.equal(result.number, 3);
assert.equal(Object.keys(result.args).length, 5);
assert.equal(result.args.a, true);
assert.equal(result.args.b, 75);
assert.equal(result.args.c, 76);
assert.equal(result.args.d, 5);
assert.equal(result.args.e, true);
});
});
});

3
libjsqrc/ethereumjs/test/formatters.inputPostFormatter.js

@ -20,7 +20,8 @@ describe('formatters', function () {
payload: '0x7b2274657374223a2274657374227d',
ttl: '0xc8',
priority: '0x3e8',
topics: ['0x68656c6c6f','0x6d79746f70696373']
topics: ['0x68656c6c6f','0x6d79746f70696373'],
workToProve: '0x0'
});
});

5
libjsqrc/ethereumjs/test/formatters.outputBlockFormatter.js

@ -1,4 +1,5 @@
var assert = require('assert');
var chai = require('chai');
var assert = chai.assert;
var formatters = require('../lib/web3/formatters.js');
var BigNumber = require('bignumber.js');
@ -16,7 +17,6 @@ describe('formatters', function () {
difficulty: '0x3e8',
totalDifficulty: '0x3e8',
number: '0x3e8',
minGasPrice: '0x3e8',
gasLimit: '0x3e8',
gasUsed: '0x3e8',
timestamp: '0x3e8',
@ -34,7 +34,6 @@ describe('formatters', function () {
difficulty: new BigNumber(1000),
totalDifficulty: new BigNumber(1000),
number: 1000,
minGasPrice: new BigNumber(1000),
gasLimit: 1000,
gasUsed: 1000,
timestamp: 1000,

2
libjsqrc/ethereumjs/test/formatters.outputTransactionFormatter.js

@ -13,6 +13,7 @@ describe('formatters', function () {
value: '0x3e8',
gas: '0x3e8',
gasPrice: '0x3e8',
nonce: '0xb',
transactionIndex: '0x1',
blockNumber: '0x3e8',
blockHash: '0x34234bf23bf4234'
@ -23,6 +24,7 @@ describe('formatters', function () {
value: new BigNumber(1000),
gas: 1000,
gasPrice: new BigNumber(1000),
nonce: 11,
blockNumber: 1000,
blockHash: '0x34234bf23bf4234',
transactionIndex: 1

8
libjsqrc/ethereumjs/test/helpers/FakeHttpProvider.js

@ -26,7 +26,7 @@ FakeHttpProvider.prototype.send = function (payload) {
// imitate plain json object
this.validation(JSON.parse(JSON.stringify(payload)));
}
return this.response;
return this.getResponse();
};
FakeHttpProvider.prototype.sendAsync = function (payload, callback) {
@ -36,7 +36,7 @@ FakeHttpProvider.prototype.sendAsync = function (payload, callback) {
// imitate plain json object
this.validation(JSON.parse(JSON.stringify(payload)), callback);
}
callback(this.error, this.response);
callback(this.error, this.getResponse());
};
FakeHttpProvider.prototype.injectResponse = function (response) {
@ -56,6 +56,10 @@ FakeHttpProvider.prototype.injectBatchResults = function (results) {
});
};
FakeHttpProvider.prototype.getResponse = function () {
return this.response;
};
FakeHttpProvider.prototype.injectError = function (error) {
this.error = error;
};

27
libjsqrc/ethereumjs/test/helpers/FakeHttpProvider2.js

@ -0,0 +1,27 @@
var FakeHttpProvider = require('./FakeHttpProvider');
var FakeHttpProvider2 = function () {
this.counter = 0;
this.resultList = [];
};
FakeHttpProvider2.prototype = new FakeHttpProvider();
FakeHttpProvider2.prototype.constructor = FakeHttpProvider2;
FakeHttpProvider2.prototype.injectResultList = function (list) {
this.resultList = list;
};
FakeHttpProvider2.prototype.getResponse = function () {
var result = this.resultList[this.counter];
this.counter++;
if (result.type === 'batch') {
this.injectBatchResults(result.result);
} else {
this.injectResult(result.result);
}
return this.response;
};
module.exports = FakeHttpProvider2;

23
libjsqrc/ethereumjs/test/helpers/test.method.js

@ -2,6 +2,7 @@ var chai = require('chai');
var assert = chai.assert;
var web3 = require('../../index');
var FakeHttpProvider = require('./FakeHttpProvider');
var clone = function (object) { return JSON.parse(JSON.stringify(object)); };
var runTests = function (obj, method, tests) {
@ -22,10 +23,18 @@ var runTests = function (obj, method, tests) {
assert.deepEqual(payload.params, test.formattedArgs);
});
var args = clone(test.args)
// when
if (obj) {
var result = web3[obj][method].apply(null, args);
} else {
var result = web3[method].apply(null, args);
}
// when
var result = (obj)
? web3[obj][method].apply(null, test.args.slice(0))
: web3[method].apply(null, test.args.slice(0));
//var result = (obj)
//? web3[obj][method].apply(null, test.args.slice(0))
//: web3[method].apply(null, test.args.slice(0));
// then
assert.deepEqual(test.formattedResult, result);
@ -43,7 +52,8 @@ var runTests = function (obj, method, tests) {
assert.deepEqual(payload.params, test.formattedArgs);
});
var args = test.args.slice(0);
var args = clone(test.args);
// add callback
args.push(function (err, result) {
assert.deepEqual(test.formattedResult, result);
@ -51,10 +61,11 @@ var runTests = function (obj, method, tests) {
});
// when
if(obj)
if (obj) {
web3[obj][method].apply(null, args);
else
} else {
web3[method].apply(null, args);
}
});
});
});

4
libjsqrc/ethereumjs/test/method.validateArgs.js

@ -39,8 +39,8 @@ describe('lib/web3/method', function () {
var test2 = function () { method.validateArgs(args2); };
// then
assert.throws(test, errors.InvalidNumberOfParams);
assert.throws(test2, errors.InvalidNumberOfParams);
assert.throws(test, errors.InvalidNumberOfParams().message);
assert.throws(test2, errors.InvalidNumberOfParams().message);
});
});
});

48
libjsqrc/ethereumjs/test/signature.js

@ -1,48 +0,0 @@
var chai = require('chai');
var assert = chai.assert;
var utils = require('../lib/utils/utils');
var FakeHttpProvider = require('./helpers/FakeHttpProvider');
var signature = require('../lib/web3/signature');
var web3 = require('../index');
var tests = [{
method: 'functionSignatureFromAscii',
call: 'web3_sha3',
request: 'multiply',
formattedRequest: utils.fromAscii('multiply'),
result: '0x255d31552d29a21e93334e96055c6dca7cd329f5420ae74ec166d0c47f9f9843',
formattedResult: '0x255d3155'
},{
method: 'eventSignatureFromAscii',
call: 'web3_sha3',
request: 'multiply',
formattedRequest: utils.fromAscii('multiply'),
result: '0x255d31552d29a21e93334e96055c6dca7cd329f5420ae74ec166d0c47f9f9843',
formattedResult: '0x255d31552d29a21e93334e96055c6dca7cd329f5420ae74ec166d0c47f9f9843'
}];
describe('lib/web3/signature', function () {
tests.forEach(function (test, index) {
describe(test.method, function () {
it('should properly format and return signature of solidity functioni ' + index, function () {
// given
var provider = new FakeHttpProvider();
web3.setProvider(provider);
provider.injectResult(test.result);
provider.injectValidation(function (payload) {
assert.equal(payload.method, test.call);
assert.equal(payload.jsonrpc, '2.0');
assert.equal(payload.params[0], test.formattedRequest);
});
// when
var result = signature[test.method].call(null, test.request);
// then
assert.equal(result, test.formattedResult);
});
});
});
});

49
libjsqrc/ethereumjs/test/utils.filters.js

@ -1,49 +0,0 @@
var assert = require('assert');
var utils = require('../lib/solidity/utils');
describe('lib/utils/utils', function() {
it('should filter functions and events from input array properly', function () {
// given
var description = [{
"name": "test",
"type": "function",
"inputs": [{
"name": "a",
"type": "uint256"
}
],
"outputs": [
{
"name": "d",
"type": "uint256"
}
],
}, {
"name": "test2",
"type": "event",
"inputs": [{
"name": "a",
"type": "uint256"
}
],
"outputs": [
{
"name": "d",
"type": "uint256"
}
]
}];
// when
var events = utils.filterEvents(description);
var functions = utils.filterFunctions(description);
// then
assert.equal(events.length, 1);
assert.equal(events[0].name, 'test2');
assert.equal(functions.length, 1);
assert.equal(functions[0].name, 'test');
});
});

2
libjsqrc/ethereumjs/test/web3.eth.contract.js

@ -234,7 +234,7 @@ describe('web3.eth.contract', function() {
});
var Con = contract(description);
var myCon = new Con(code, 2);
var myCon = new Con({data: code}, 2);
});
});

8
libjsqrc/ethereumjs/test/web3.eth.getBlock.js

@ -19,7 +19,6 @@ var blockResult = {
"size": "0x027f07",
"extraData": "0x0000000000000000000000000000000000000000000000000000000000000000",
"gasLimit": "0x9f759",
"minGasPrice": "0x9f759",
"gasUsed": "0x9f759",
"timestamp": "0x54e34e8e",
"transactions": ['0x460cfb8472af2c5fd05b5a2','0x460cfb8472af2c5fd05b5a2'],
@ -40,7 +39,6 @@ var formattedBlockResult = {
"size": 163591,
"extraData": "0x0000000000000000000000000000000000000000000000000000000000000000",
"gasLimit": 653145,
"minGasPrice": new BigNumber(653145),
"gasUsed": 653145,
"timestamp": 1424182926,
"transactions": ['0x460cfb8472af2c5fd05b5a2','0x460cfb8472af2c5fd05b5a2'],
@ -61,13 +59,12 @@ var blockResultWithTx = {
"size": "0x027f07",
"extraData": "0x0000000000000000000000000000000000000000000000000000000000000000",
"gasLimit": "0x9f759",
"minGasPrice": "0x9f759",
"gasUsed": "0x9f759",
"timestamp": "0x54e34e8e",
"transactions": [{
"status": "mined",
"hash":"0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b",
"nonce":"0x",
"nonce":"0x2",
"blockHash": "0x6fd9e2a26ab",
"blockNumber": "0x15df",
"transactionIndex": "0x1",
@ -95,13 +92,12 @@ var formattedBlockResultWithTx = {
"size": 163591,
"extraData": "0x0000000000000000000000000000000000000000000000000000000000000000",
"gasLimit": 653145,
"minGasPrice": new BigNumber(653145),
"gasUsed": 653145,
"timestamp": 1424182926,
"transactions": [{
"status": "mined",
"hash":"0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b",
"nonce":"0x",
"nonce": 2,
"blockHash": "0x6fd9e2a26ab",
"blockNumber": 5599,
"transactionIndex": 1,

4
libjsqrc/ethereumjs/test/web3.eth.getTransaction.js

@ -8,7 +8,7 @@ var method = 'getTransaction';
var txResult = {
"status": "mined",
"hash":"0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b",
"nonce":"0x",
"nonce":"0x5",
"blockHash": "0x6fd9e2a26ab",
"blockNumber": "0x15df",
"transactionIndex": "0x1",
@ -22,7 +22,7 @@ var txResult = {
var formattedTxResult = {
"status": "mined",
"hash":"0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b",
"nonce":"0x",
"nonce":5,
"blockHash": "0x6fd9e2a26ab",
"blockNumber": 5599,
"transactionIndex": 1,

4
libjsqrc/ethereumjs/test/web3.eth.getTransactionFromBlock.js

@ -8,7 +8,7 @@ var method = 'getTransactionFromBlock';
var txResult = {
"status": "mined",
"hash":"0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b",
"nonce":"0x",
"nonce":"0xb",
"blockHash": "0x6fd9e2a26ab",
"blockNumber": "0x15df",
"transactionIndex": "0x1",
@ -22,7 +22,7 @@ var txResult = {
var formattedTxResult = {
"status": "mined",
"hash":"0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b",
"nonce":"0x",
"nonce":11,
"blockHash": "0x6fd9e2a26ab",
"blockNumber": 5599,
"transactionIndex": 1,

8
libjsqrc/ethereumjs/test/web3.eth.getUncle.js

@ -20,7 +20,6 @@ var blockResult = {
"size": "0x027f07",
"extraData": "0x0000000000000000000000000000000000000000000000000000000000000000",
"gasLimit": "0x9f759",
"minGasPrice": "0x9f759",
"gasUsed": "0x9f759",
"timestamp": "0x54e34e8e",
"transactions": ['0x460cfb8472af2c5fd05b5a2','0x460cfb8472af2c5fd05b5a2'],
@ -41,7 +40,6 @@ var formattedBlockResult = {
"size": 163591,
"extraData": "0x0000000000000000000000000000000000000000000000000000000000000000",
"gasLimit": 653145,
"minGasPrice": new BigNumber(653145),
"gasUsed": 653145,
"timestamp": 1424182926,
"transactions": ['0x460cfb8472af2c5fd05b5a2','0x460cfb8472af2c5fd05b5a2'],
@ -62,13 +60,12 @@ var blockResultWithTx = {
"size": "0x027f07",
"extraData": "0x0000000000000000000000000000000000000000000000000000000000000000",
"gasLimit": "0x9f759",
"minGasPrice": "0x9f759",
"gasUsed": "0x9f759",
"timestamp": "0x54e34e8e",
"transactions": [{
"status": "mined",
"hash":"0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b",
"nonce":"0x",
"nonce":"0x2",
"blockHash": "0x6fd9e2a26ab",
"blockNumber": "0x15df",
"transactionIndex": "0x1",
@ -96,13 +93,12 @@ var formattedBlockResultWithTx = {
"size": 163591,
"extraData": "0x0000000000000000000000000000000000000000000000000000000000000000",
"gasLimit": 653145,
"minGasPrice": new BigNumber(653145),
"gasUsed": 653145,
"timestamp": 1424182926,
"transactions": [{
"status": "mined",
"hash":"0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b",
"nonce":"0x",
"nonce": 2,
"blockHash": "0x6fd9e2a26ab",
"blockNumber": 5599,
"transactionIndex": 1,

39
libjsqrc/ethereumjs/test/shh.filter.js → libjsqrc/ethereumjs/test/web3.shh.filter.js

@ -17,6 +17,45 @@ var tests = [{
result: '0xf',
formattedResult: '0xf',
call: 'shh_newFilter'
},
{
args: [{
to: '0x47d33b27bb249a2dbab4c0612bf9caf4c1950855',
topics: ['0x324f5435', ['0x564b4566f3453', '0x345345343453']]
}],
formattedArgs: [{
to: '0x47d33b27bb249a2dbab4c0612bf9caf4c1950855',
topics: ['0x324f5435', ['0x564b4566f3453', '0x345345343453']]
}],
result: '0xf',
formattedResult: '0xf',
call: 'shh_newFilter'
},
{
args: [{
to: '0x47d33b27bb249a2dbab4c0612bf9caf4c1950855',
topics: ['0x324f5435', null, ['0x564b4566f3453', '0x345345343453']]
}],
formattedArgs: [{
to: '0x47d33b27bb249a2dbab4c0612bf9caf4c1950855',
topics: ['0x324f5435', null, ['0x564b4566f3453', '0x345345343453']]
}],
result: '0xf',
formattedResult: '0xf',
call: 'shh_newFilter'
},
{
args: [{
to: '0x47d33b27bb249a2dbab4c0612bf9caf4c1950855',
topics: ['myString', 11, '23', null]
}],
formattedArgs: [{
to: '0x47d33b27bb249a2dbab4c0612bf9caf4c1950855',
topics: ['0x6d79537472696e67', '0x3131', '0x3233', null]
}],
result: '0xf',
formattedResult: '0xf',
call: 'shh_newFilter'
}];
describe('shh', function () {

49
libjsqrc/ethereumjs/test/web3.shh.post.js

@ -0,0 +1,49 @@
var chai = require('chai');
var web3 = require('../index');
var testMethod = require('./helpers/test.method.js');
var method = 'post';
var tests = [{
args: [{
from: '0x123123123',
topics: ['hello_world'],
payload: '12345',
ttl: 100,
workToProve: 101
}],
formattedArgs: [{
from: '0x123123123',
topics: [web3.fromAscii('hello_world')],
payload: web3.toHex('12345'),
ttl: web3.toHex('100'),
workToProve: web3.toHex('101'),
priority: '0x0'
}],
result: true,
formattedResult: true,
call: 'shh_'+ method
}, {
args: [{
from: '0x21312',
topics: ['hello_world'],
payload: '0x12345',
ttl: 0x100,
workToProve: 0x101,
priority: 0x15
}],
formattedArgs: [{
from: '0x21312',
topics: [web3.fromAscii('hello_world')],
payload: '0x12345',
ttl: '0x100',
workToProve: '0x101',
priority: '0x15'
}],
result: true,
formattedResult: true,
call: 'shh_'+ method
}];
testMethod.runTests('shh', method, tests);
Loading…
Cancel
Save