Browse Source

Merge branch 'develop' into discovery

cl-refactor
subtly 10 years ago
parent
commit
41ded894ce
  1. 43
      docker/Dockerfile
  2. 31
      docker/README.md
  3. 23
      docker/supervisord.conf
  4. 1
      libjsqrc/ethereumjs/.travis.yml
  5. 34
      libjsqrc/ethereumjs/README.md
  6. 2
      libjsqrc/ethereumjs/bower.json
  7. 1598
      libjsqrc/ethereumjs/dist/web3-light.js
  8. 46
      libjsqrc/ethereumjs/dist/web3-light.js.map
  9. 3
      libjsqrc/ethereumjs/dist/web3-light.min.js
  10. 1646
      libjsqrc/ethereumjs/dist/web3.js
  11. 50
      libjsqrc/ethereumjs/dist/web3.js.map
  12. 4
      libjsqrc/ethereumjs/dist/web3.min.js
  13. 47
      libjsqrc/ethereumjs/example/contract.html
  14. 77
      libjsqrc/ethereumjs/example/contract_with_array.html
  15. 119
      libjsqrc/ethereumjs/example/event.html
  16. 65
      libjsqrc/ethereumjs/example/event_inc.html
  17. 141
      libjsqrc/ethereumjs/lib/solidity/abi.js
  18. 329
      libjsqrc/ethereumjs/lib/solidity/coder.js
  19. 112
      libjsqrc/ethereumjs/lib/solidity/formatters.js
  20. 105
      libjsqrc/ethereumjs/lib/solidity/param.js
  21. 77
      libjsqrc/ethereumjs/lib/solidity/types.js
  22. 30
      libjsqrc/ethereumjs/lib/solidity/utils.js
  23. 3
      libjsqrc/ethereumjs/lib/utils/config.js
  24. 42
      libjsqrc/ethereumjs/lib/utils/utils.js
  25. 2
      libjsqrc/ethereumjs/lib/version.json
  26. 17
      libjsqrc/ethereumjs/lib/web3.js
  27. 184
      libjsqrc/ethereumjs/lib/web3/contract.js
  28. 20
      libjsqrc/ethereumjs/lib/web3/errors.js
  29. 13
      libjsqrc/ethereumjs/lib/web3/eth.js
  30. 230
      libjsqrc/ethereumjs/lib/web3/event.js
  31. 51
      libjsqrc/ethereumjs/lib/web3/filter.js
  32. 13
      libjsqrc/ethereumjs/lib/web3/formatters.js
  33. 151
      libjsqrc/ethereumjs/lib/web3/function.js
  34. 14
      libjsqrc/ethereumjs/lib/web3/httpprovider.js
  35. 2
      libjsqrc/ethereumjs/lib/web3/method.js
  36. 6
      libjsqrc/ethereumjs/lib/web3/requestmanager.js
  37. 2
      libjsqrc/ethereumjs/lib/web3/shh.js
  38. 42
      libjsqrc/ethereumjs/lib/web3/signature.js
  39. 2
      libjsqrc/ethereumjs/package-init.js
  40. 7
      libjsqrc/ethereumjs/package.js
  41. 4
      libjsqrc/ethereumjs/package.json
  42. 14
      libjsqrc/ethereumjs/test/abi.inputParser.js
  43. 96
      libjsqrc/ethereumjs/test/abi.outputParser.js
  44. 68
      libjsqrc/ethereumjs/test/coder.decodeParam.js
  45. 91
      libjsqrc/ethereumjs/test/coder.encodeParam.js
  46. 145
      libjsqrc/ethereumjs/test/contract.js
  47. 180
      libjsqrc/ethereumjs/test/event.decode.js
  48. 206
      libjsqrc/ethereumjs/test/event.encode.js
  49. 113
      libjsqrc/ethereumjs/test/event.inputParser.js
  50. 81
      libjsqrc/ethereumjs/test/event.outputParser.js
  51. 3
      libjsqrc/ethereumjs/test/formatters.inputPostFormatter.js
  52. 5
      libjsqrc/ethereumjs/test/formatters.outputBlockFormatter.js
  53. 2
      libjsqrc/ethereumjs/test/formatters.outputTransactionFormatter.js
  54. 8
      libjsqrc/ethereumjs/test/helpers/FakeHttpProvider.js
  55. 27
      libjsqrc/ethereumjs/test/helpers/FakeHttpProvider2.js
  56. 23
      libjsqrc/ethereumjs/test/helpers/test.method.js
  57. 4
      libjsqrc/ethereumjs/test/method.validateArgs.js
  58. 48
      libjsqrc/ethereumjs/test/signature.js
  59. 49
      libjsqrc/ethereumjs/test/utils.filters.js
  60. 2
      libjsqrc/ethereumjs/test/web3.eth.contract.js
  61. 8
      libjsqrc/ethereumjs/test/web3.eth.getBlock.js
  62. 4
      libjsqrc/ethereumjs/test/web3.eth.getTransaction.js
  63. 4
      libjsqrc/ethereumjs/test/web3.eth.getTransactionFromBlock.js
  64. 8
      libjsqrc/ethereumjs/test/web3.eth.getUncle.js
  65. 39
      libjsqrc/ethereumjs/test/web3.shh.filter.js
  66. 49
      libjsqrc/ethereumjs/test/web3.shh.post.js
  67. 45
      libsolidity/ASTJsonConverter.cpp
  68. 8
      libsolidity/ASTJsonConverter.h
  69. 50
      libsolidity/ASTPrinter.cpp
  70. 8
      libsolidity/ASTPrinter.h
  71. 342
      libsolidity/ASTVisitor.h
  72. 11
      libsolidity/LValue.cpp
  73. 2
      libweb3jsonrpc/CMakeLists.txt
  74. 20
      test/libsolidity/SolidityEndToEndTest.cpp
  75. 2
      test/libsolidity/SolidityExpressionCompiler.cpp

43
docker/Dockerfile

@ -1,36 +1,31 @@
FROM ubuntu:14.04 FROM ubuntu:utopic
MAINTAINER caktux
ENV DEBIAN_FRONTEND noninteractive ENV DEBIAN_FRONTEND noninteractive
# Usual update / upgrade
RUN apt-get update RUN apt-get update
RUN apt-get upgrade -y RUN apt-get upgrade -q -y
RUN apt-get dist-upgrade -q -y
# Ethereum dependencies # Let our containers upgrade themselves
RUN apt-get install -qy build-essential g++-4.8 git cmake libboost-all-dev libcurl4-openssl-dev wget RUN apt-get install -q -y unattended-upgrades
RUN apt-get install -qy automake unzip libgmp-dev libtool libleveldb-dev yasm libminiupnpc-dev libreadline-dev scons
RUN apt-get install -qy libjsoncpp-dev libargtable2-dev
RUN apt-get install -qy libncurses5-dev libcurl4-openssl-dev wget
RUN apt-get install -qy libjsoncpp-dev libargtable2-dev libmicrohttpd-dev
# Ethereum PPA # Install Ethereum
RUN apt-get install -qy software-properties-common RUN apt-get install -q -y software-properties-common
RUN add-apt-repository ppa:ethereum/ethereum RUN add-apt-repository ppa:ethereum/ethereum
RUN add-apt-repository ppa:ethereum/ethereum-dev RUN add-apt-repository ppa:ethereum/ethereum-dev
RUN apt-get update RUN apt-get update
RUN apt-get install -qy libcryptopp-dev libjson-rpc-cpp-dev RUN apt-get install -q -y eth
# LLVM-3.5 # Install supervisor
RUN wget -O - http://llvm.org/apt/llvm-snapshot.gpg.key|sudo apt-key add - RUN apt-get install -q -y supervisor
RUN echo "deb http://llvm.org/apt/trusty/ llvm-toolchain-trusty-3.5 main\ndeb-src http://llvm.org/apt/trusty/ llvm-toolchain-trusty-3.5 main" > /etc/apt/sources.list.d/llvm-trusty.list
RUN apt-get update
RUN apt-get install -qy llvm-3.5 libedit-dev
# Fix llvm-3.5 cmake paths # Add supervisor configs
RUN mkdir -p /usr/lib/llvm-3.5/share/llvm && ln -s /usr/share/llvm-3.5/cmake /usr/lib/llvm-3.5/share/llvm/cmake ADD supervisord.conf supervisord.conf
# Build Ethereum (HEADLESS) EXPOSE 8080
RUN git clone --depth=1 https://github.com/ethereum/cpp-ethereum EXPOSE 30303
RUN mkdir -p cpp-ethereum/build
RUN cd cpp-ethereum/build && cmake .. -DHEADLESS=1 -DLLVM_DIR=/usr/share/llvm-3.5/cmake -DEVMJIT=1 && make -j $(cat /proc/cpuinfo | grep processor | wc -l) && make install
RUN ldconfig
ENTRYPOINT ["/usr/local/bin/eth"] CMD ["-n", "-c", "/supervisord.conf"]
ENTRYPOINT ["/usr/bin/supervisord"]

31
docker/README.md

@ -1,17 +1,30 @@
# Dockerfile for cpp-ethereum # Dockerfile for cpp-ethereum
Dockerfile to build a bleeding edge cpp-ethereum docker image from source
docker build -t cppeth < Dockerfile ### Quick usage
Run a simple peer server docker run -d ethereum/client-cpp
docker run -i cppeth -m off -o peer -x 256 ### Building
GUI is compiled but not exposed. You can mount /cpp-ethereum/build to access binaries: Dockerfile to build a cpp-ethereum docker image from source
cid = $(docker run -i -v /cpp-ethereum/build cppeth -m off -o peer -x 256) docker build -t cpp-ethereum .
docker inspect $cid # <-- Find volume path in JSON output
You may also modify the Docker image to run the GUI and expose a ### Running
ssh/VNC server in order to tunnel an X11 or VNC session.
docker run -d cpp-ethereum
### Usage
First enter the container:
docker exec -it <container name> bash
Inspect logs:
cat /var/log/cpp-ethereum.log
cat /var/log/cpp-ethereum.err
Restart supervisor service:
supervisorctl restart cpp-ethereum

23
docker/supervisord.conf

@ -0,0 +1,23 @@
[supervisord]
nodaemon=false
[program:eth]
priority=30
directory=/
command=eth --bootstrap --json-rpc
user=root
autostart=true
autorestart=true
startsecs=10
stopsignal=QUIT
stdout_logfile=/var/log/eth.log
stderr_logfile=/var/log/eth.err
[unix_http_server]
file=%(here)s/supervisor.sock
[supervisorctl]
serverurl=unix://%(here)s/supervisor.sock
[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

1
libjsqrc/ethereumjs/.travis.yml

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

34
libjsqrc/ethereumjs/README.md

@ -1,6 +1,6 @@
# Ethereum JavaScript API # 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) 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. 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.js
$ meteor add ethereum:js $ meteor add ethereum:web3
### As Browser module ### As Browser module
Bower Bower
@ -36,11 +36,7 @@ Component
* Include [bignumber.js](https://github.com/MikeMcl/bignumber.js/) (not required for the meteor package) * Include [bignumber.js](https://github.com/MikeMcl/bignumber.js/) (not required for the meteor package)
## Usage ## Usage
You can require the library (not required for the meteor package): Use the `web3` object directly from global namespace:
var web3 = require('ethereum.js');
Or use it directly from global namespace:
console.log(web3); // {eth: .., shh: ...} // it's here! console.log(web3); // {eth: .., shh: ...} // it's here!
@ -106,16 +102,16 @@ Install ethereum and spawn a node:
eth -j eth -j
``` ```
[npm-image]: https://badge.fury.io/js/ethereum.js.png [npm-image]: https://badge.fury.io/js/web3.png
[npm-url]: https://npmjs.org/package/ethereum.js [npm-url]: https://npmjs.org/package/web3
[travis-image]: https://travis-ci.org/ethereum/ethereum.js.svg [travis-image]: https://travis-ci.org/ethereum/web3.js.svg
[travis-url]: https://travis-ci.org/ethereum/ethereum.js [travis-url]: https://travis-ci.org/ethereum/web3.js
[dep-image]: https://david-dm.org/ethereum/ethereum.js.svg [dep-image]: https://david-dm.org/ethereum/web3.js.svg
[dep-url]: https://david-dm.org/ethereum/ethereum.js [dep-url]: https://david-dm.org/ethereum/web3.js
[dep-dev-image]: https://david-dm.org/ethereum/ethereum.js/dev-status.svg [dep-dev-image]: https://david-dm.org/ethereum/web.js/dev-status.svg
[dep-dev-url]: https://david-dm.org/ethereum/ethereum.js#info=devDependencies [dep-dev-url]: https://david-dm.org/ethereum/web3.js#info=devDependencies
[coveralls-image]: https://coveralls.io/repos/ethereum/ethereum.js/badge.svg?branch=master [coveralls-image]: https://coveralls.io/repos/ethereum/web3.js/badge.svg?branch=master
[coveralls-url]: https://coveralls.io/r/ethereum/ethereum.js?branch=master [coveralls-url]: https://coveralls.io/r/ethereum/web3.js?branch=master
[waffle-image]: https://badge.waffle.io/ethereum/ethereum.js.svg?label=ready&title=Ready [waffle-image]: https://badge.waffle.io/ethereum/web3.js.svg?label=ready&title=Ready
[waffle-url]: http://waffle.io/ethereum/ethereum.js [waffle-url]: http://waffle.io/ethereum/web3.js

2
libjsqrc/ethereumjs/bower.json

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

1598
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

1646
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

47
libjsqrc/ethereumjs/example/contract.html

@ -2,36 +2,34 @@
<html> <html>
<head> <head>
<script type="text/javascript" src="../dist/web3"></script> <script type="text/javascript" src="../dist/web3.js"></script>
<script type="text/javascript"> <script type="text/javascript">
var web3 = require('web3'); var web3 = require('web3');
web3.setProvider(new web3.providers.HttpProvider()); web3.setProvider(new web3.providers.HttpProvider("http://localhost:8545"));
// solidity source code // solidity source code
var source = "" + /*var source = "" +*/
"contract test {\n" + /*"contract test {\n" +*/
" function multiply(uint a) returns(uint d) {\n" + /*" function multiply(uint a) constant returns(uint d) {\n" +*/
" return a * 7;\n" + /*" return a * 7;\n" +*/
" }\n" + /*" }\n" +*/
"}\n"; /*"}\n";*/
var source = "605280600c6000396000f3006000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa114602e57005b60376004356041565b8060005260206000f35b6000600782029050604d565b91905056";
// contract description, this will be autogenerated somehow // contract description, this is autogenerated using solc CLI
var desc = [{ var desc = [{
"name": "multiply(uint256)", "constant" : true,
"type": "function", "inputs" : [{
"inputs": [
{
"name" : "a", "name" : "a",
"type" : "uint256" "type" : "uint256"
} }],
], "name" : "multiply",
"outputs": [ "outputs" : [{
{
"name" : "d", "name" : "d",
"type" : "uint256" "type" : "uint256"
} }],
] "type" : "function"
}]; }];
var myContract; var myContract;
@ -41,11 +39,12 @@
document.getElementById('create').style.visibility = 'hidden'; document.getElementById('create').style.visibility = 'hidden';
document.getElementById('source').innerText = source; document.getElementById('source').innerText = source;
// create contract // let's assume that coinbase is our account
var address = web3.eth.sendTransaction({data: web3.eth.compile.solidity(source)}), web3.eth.defaultAccount = web3.eth.coinbase;
Contract = web3.eth.contract(desc);
myContract = new Contract(address); // create contract
var Contract = web3.eth.contract(desc);
myContract = new Contract({data: source});
document.getElementById('call').style.visibility = 'visible'; document.getElementById('call').style.visibility = 'visible';
} }
@ -54,7 +53,7 @@
var param = parseInt(document.getElementById('value').value); var param = parseInt(document.getElementById('value').value);
// call the contract // call the contract
var res = myContract.call().multiply(param); var res = myContract.multiply(param);
document.getElementById('result').innerText = res.toString(10); 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" src="../dist/web3.js"></script>
<script type="text/javascript"> <script type="text/javascript">
var web3 = require('web3'); var web3 = require('web3');
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8080')); web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
var source = "" + /*var source = "" + */
"contract Contract { " + /*"contract Contract { " +*/
" event Incremented(bool indexed odd, uint x); " + /*" event Incremented(bool indexed odd, uint x); " +*/
" function Contract() { " + /*" function Contract() { " +*/
" x = 69; " + /*" x = 69; " +*/
" } " + /*" } " +*/
" function inc() { " + /*" function inc() { " +*/
" ++x; " + /*" ++x; " +*/
" Incremented(x % 2 == 1, x); " + /*" Incremented(x % 2 == 1, x); " +*/
" } " + /*" } " +*/
" uint x; " + /*" uint x; " +*/
"}"; /*"}";*/
var source = "5b60456000600050819055505b608c8060196000396000f3006000357c010000000000000000000000000000000000000000000000000000000090048063371303c014602e57005b6034603a565b60006000f35b6000600081815054600101919050819055506001600260006000505406147f6e61ef44ac2747ff8b84d353a908eb8bd5c3fb118334d57698c5cfc7041196ad600060006000505481526020016000a25b56";
var desc = [{ var desc = [{
"type":"event", "constant" : false,
"name":"Incremented",
"inputs": [{"name":"odd","type":"bool","indexed":true},{"name":"x","type":"uint","indexed":false}],
}, {
"type":"function",
"name":"inc",
"inputs" : [], "inputs" : [],
"outputs": [] "name" : "inc",
"outputs" : [],
"type" : "function"
}, {
"anonymous" : false,
"inputs" : [{
"indexed" : true,
"name" : "odd",
"type" : "bool"
}, {
"indexed" : false,
"name" : "x",
"type" : "uint256"
}],
"name" : "Incremented",
"type" : "event"
}]; }];
var address; var address;
var contract; var contract;
var update = function (x) { var update = function (err, x) {
document.getElementById('result').innerText = JSON.stringify(x); document.getElementById('result').innerText = JSON.stringify(x, null, 2);
}; };
var createContract = function () { var createContract = function () {
address = web3.eth.sendTransaction({data: web3.eth.compile.solidity(source)}); // let's assume that we have a private key to coinbase ;)
contract = web3.eth.contract(address, desc); web3.eth.defaultAccount = web3.eth.coinbase;
contract.Incremented({odd: true}).changed(update); var Contract = web3.eth.contract(desc);
contract = new Contract({data: source});
contract.Incremented({odd: true}).watch(update);
}; };
var callContract = function () { var callContract = function () {
contract.call().inc(); contract.inc();
}; };

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

@ -22,49 +22,9 @@
*/ */
var utils = require('../utils/utils'); var utils = require('../utils/utils');
var c = require('../utils/config'); var coder = require('./coder');
var types = require('./types');
var f = require('./formatters');
var solUtils = require('./utils'); 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 * Formats input params to bytes
* *
@ -74,57 +34,12 @@ var inputTypes = types.inputTypes();
* @returns bytes representation of input params * @returns bytes representation of input params
*/ */
var formatInput = function (inputs, params) { var formatInput = function (inputs, params) {
var bytes = ""; var i = inputs.map(function (input) {
var toAppendConstant = ""; return input.type;
var toAppendArrayContent = "";
/// first we iterate in search for dynamic
inputs.forEach(function (input, index) {
bytes += dynamicTypeBytes(input.type, params[index]);
}); });
return coder.encodeParams(i, params);
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;
}; };
var outputTypes = types.outputTypes();
/** /**
* Formats output bytes back to param list * Formats output bytes back to param list
* *
@ -133,52 +48,12 @@ var outputTypes = types.outputTypes();
* @param {String} bytes represention of output * @param {String} bytes represention of output
* @returns {Array} output params * @returns {Array} output params
*/ */
var formatOutput = function (outs, output) { var formatOutput = function (outs, bytes) {
var o = outs.map(function (out) {
output = output.slice(2); return out.type;
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);
}
}); });
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;

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

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

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

@ -64,6 +64,7 @@ module.exports = {
ETH_UNITS: ETH_UNITS, ETH_UNITS: ETH_UNITS,
ETH_BIGNUMBER_ROUNDING_MODE: { ROUNDING_MODE: BigNumber.ROUND_DOWN }, ETH_BIGNUMBER_ROUNDING_MODE: { ROUNDING_MODE: BigNumber.ROUND_DOWN },
ETH_POLLING_TIMEOUT: 1000, 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 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/>. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
*/ */
/** @file utils.js /**
* @authors: * @file utils.js
* Marek Kotewicz <marek@ethdev.com> * @author Marek Kotewicz <marek@ethdev.com>
* @date 2015 * @date 2015
*/ */
@ -67,22 +67,6 @@ var padLeft = function (string, chars, sign) {
return new Array(chars - string.length + 1).join(sign ? sign : "0") + string; 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 * 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 * Shold be called to get hex representation (prefixed by 0x) of ascii string
* *
* @method fromAscii * @method toHexNative
* @param {String} string * @param {String} string
* @returns {String} hex representation of input string * @returns {String} hex representation of input string
*/ */
@ -142,6 +126,22 @@ var fromAscii = function(str, pad) {
return "0x" + hex; 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 * Should be called to get display name of contract function
* *
@ -448,12 +448,12 @@ var isJson = function (str) {
module.exports = { module.exports = {
padLeft: padLeft, padLeft: padLeft,
findIndex: findIndex,
toHex: toHex, toHex: toHex,
toDecimal: toDecimal, toDecimal: toDecimal,
fromDecimal: fromDecimal, fromDecimal: fromDecimal,
toAscii: toAscii, toAscii: toAscii,
fromAscii: fromAscii, fromAscii: fromAscii,
transformToFullName: transformToFullName,
extractDisplayName: extractDisplayName, extractDisplayName: extractDisplayName,
extractTypeName: extractTypeName, extractTypeName: extractTypeName,
toWei: toWei, 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 () { web3.reset = function () {
RequestManager.getInstance().reset(); RequestManager.getInstance().reset();
c.defaultBlock = 'latest';
c.defaultAccount = undefined;
}; };
web3.toHex = utils.toHex; web3.toHex = utils.toHex;
web3.toAscii = utils.toAscii; web3.toAscii = utils.toAscii;
@ -131,14 +133,23 @@ web3.isAddress = utils.isAddress;
// ADD defaultblock // ADD defaultblock
Object.defineProperty(web3.eth, 'defaultBlock', { Object.defineProperty(web3.eth, 'defaultBlock', {
get: function () { get: function () {
return c.ETH_DEFAULTBLOCK; return c.defaultBlock;
}, },
set: function (val) { set: function (val) {
c.ETH_DEFAULTBLOCK = val; c.defaultBlock = val;
return c.ETH_DEFAULTBLOCK; return val;
} }
}); });
Object.defineProperty(web3.eth, 'defaultAccount', {
get: function () {
return c.defaultAccount;
},
set: function (val) {
c.defaultAccount = val;
return val;
}
});
/// setups all api methods /// setups all api methods
setupMethods(web3, web3Methods); 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 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/>. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
*/ */
/** @file contract.js /**
* @authors: * @file contract.js
* Marek Kotewicz <marek@ethdev.com> * @author Marek Kotewicz <marek@ethdev.com>
* @date 2014 * @date 2014
*/ */
var web3 = require('../web3'); var web3 = require('../web3');
var solAbi = require('../solidity/abi'); var solAbi = require('../solidity/abi');
var utils = require('../utils/utils'); var utils = require('../utils/utils');
var solUtils = require('../solidity/utils'); var SolidityEvent = require('./event');
var eventImpl = require('./event'); var SolidityFunction = require('./function');
var signature = require('./signature');
var addFunctionsToContract = function (contract, desc) {
var addFunctionRelatedPropertiesToContract = function (contract) { desc.filter(function (json) {
return json.type === 'function';
contract.call = function (options) { }).map(function (json) {
contract._isTransaction = false; return new SolidityFunction(json, contract.address);
contract._options = options; }).forEach(function (f) {
return contract; f.attachToContract(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 addEventRelatedPropertiesToContract = function (contract, desc, address) { var addEventsToContract = function (contract, desc) {
contract.address = address; desc.filter(function (json) {
contract._onWatchEventResult = function (data) { return json.type === 'event';
var matchingEvent = event.getMatchingEvent(solUtils.filterEvents(desc)); }).map(function (json) {
var parser = eventImpl.outputParser(matchingEvent); return new SolidityEvent(json, contract.address);
return parser(data); }).forEach(function (e) {
}; e.attachToContract(contract);
Object.defineProperty(contract, 'topics', {
get: function() {
return solUtils.filterEvents(desc).map(function (e) {
return signature.eventSignatureFromAscii(e.name);
});
}
});
};
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 * 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 * 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); 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)) { if (utils.isAddress(options)) {
address = options; this.address = options;
} else { // is a source code! } else { // is an object!
// TODO, parse the rest of the args // TODO, parse the rest of the args
var code = options; options = options || {};
var args = Array.prototype.slice.call(arguments, 2); var args = Array.prototype.slice.call(arguments, 2);
var bytes = solAbi.formatConstructorParams(abi, args); var bytes = solAbi.formatConstructorParams(abi, args);
address = web3.eth.sendTransaction({data: code + bytes}); options.data += bytes;
this.address = web3.eth.sendTransaction(options);
} }
var result = {}; addFunctionsToContract(this, abi);
addFunctionRelatedPropertiesToContract(result); addEventsToContract(this, abi);
addFunctionsToContract(result, abi, address); };
addEventRelatedPropertiesToContract(result, abi, address);
addEventsToContract(result, abi, address);
return result; Contract.prototype.call = function () {
} console.error('contract.call is deprecated');
return this;
};
Contract.prototype.sendTransaction = function () {
console.error('contract.sendTransact is deprecated');
return this;
};
module.exports = contract; module.exports = contract;

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

@ -20,18 +20,18 @@
* @date 2015 * @date 2015
*/ */
var utils = require('../utils/utils');
module.exports = { module.exports = {
InvalidNumberOfParams: new Error('Invalid number of input parameters'), InvalidNumberOfParams: function () {
InvalidProvider: new Error('Providor not set or invalid'), 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){ InvalidResponse: function (result){
var message = 'Invalid JSON RPC response'; var message = !!result && !!result.error && !!result.error.message ? result.error.message : 'Invalid JSON RPC response';
if(utils.isObject(result) && result.error && result.error.message) {
message = result.error.message;
}
return new Error(message); return new Error(message);
} }
}; };

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

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

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

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

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

@ -28,6 +28,25 @@ var RequestManager = require('./requestmanager');
var formatters = require('./formatters'); var formatters = require('./formatters');
var utils = require('../utils/utils'); 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 /// This method should be called on options object, to verify deprecated properties && lazy load dynamic ones
/// @param should be string or object /// @param should be string or object
/// @returns options string or object /// @returns options string or object
@ -42,7 +61,7 @@ var getOptions = function (options) {
// make sure topics, get converted to hex // make sure topics, get converted to hex
options.topics = options.topics || []; options.topics = options.topics || [];
options.topics = options.topics.map(function(topic){ options.topics = options.topics.map(function(topic){
return utils.toHex(topic); return (utils.isArray(topic)) ? topic.map(toTopic) : toTopic(topic);
}); });
// lazy load // 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({ RequestManager.getInstance().startPolling({
method: this.implementation.poll.call, method: this.implementation.poll.call,
params: [this.filterId], params: [this.filterId],
@ -98,12 +131,24 @@ Filter.prototype.stopWatching = function () {
this.callbacks = []; this.callbacks = [];
}; };
Filter.prototype.get = function () { Filter.prototype.get = function (callback) {
var logs = this.implementation.getLogs(this.filterId);
var self = this; var self = this;
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 logs.map(function (log) {
return self.formatter ? self.formatter(log) : log; return self.formatter ? self.formatter(log) : log;
}); });
}
}; };
module.exports = Filter; module.exports = Filter;

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

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

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

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

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

@ -66,7 +66,7 @@ Method.prototype.extractCallback = function (args) {
*/ */
Method.prototype.validateArgs = function (args) { Method.prototype.validateArgs = function (args) {
if (args.length !== this.params) { 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) { RequestManager.prototype.send = function (data) {
if (!this.provider) { if (!this.provider) {
console.error(errors.InvalidProvider); console.error(errors.InvalidProvider());
return null; return null;
} }
@ -88,7 +88,7 @@ RequestManager.prototype.send = function (data) {
*/ */
RequestManager.prototype.sendAsync = function (data, callback) { RequestManager.prototype.sendAsync = function (data, callback) {
if (!this.provider) { if (!this.provider) {
return callback(errors.InvalidProvider); return callback(errors.InvalidProvider());
} }
var payload = Jsonrpc.getInstance().toPayload(data.method, data.params); var payload = Jsonrpc.getInstance().toPayload(data.method, data.params);
@ -179,7 +179,7 @@ RequestManager.prototype.poll = function () {
} }
if (!this.provider) { if (!this.provider) {
console.error(errors.InvalidProvider); console.error(errors.InvalidProvider());
return; return;
} }

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

@ -27,7 +27,7 @@ var post = new Method({
name: 'post', name: 'post',
call: 'shh_post', call: 'shh_post',
params: 1, params: 1,
inputFormatter: formatters.inputPostFormatter inputFormatter: [formatters.inputPostFormatter]
}); });
var newIdentity = new Method({ 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 */ /* jshint ignore:start */
if(typeof web3 === 'undefined') { if(typeof web3 === 'undefined') {
web3 = require('ethereum.js'); web3 = require('web3');
BigNumber = require('bignumber.js'); BigNumber = require('bignumber.js');
} }

7
libjsqrc/ethereumjs/package.js

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

4
libjsqrc/ethereumjs/package.json

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

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

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

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

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

145
libjsqrc/ethereumjs/test/contract.js

@ -2,7 +2,9 @@ var chai = require('chai');
var assert = chai.assert; var assert = chai.assert;
var web3 = require('../index'); var web3 = require('../index');
var FakeHttpProvider = require('./helpers/FakeHttpProvider'); var FakeHttpProvider = require('./helpers/FakeHttpProvider');
var FakeHttpProvider2 = require('./helpers/FakeHttpProvider2');
var utils = require('../lib/utils/utils'); var utils = require('../lib/utils/utils');
var BigNumber = require('bignumber.js');
var desc = [{ var desc = [{
"name": "balance(address)", "name": "balance(address)",
@ -27,6 +29,18 @@ var desc = [{
"type": "uint256" "type": "uint256"
}], }],
"outputs": [] "outputs": []
}, {
"name": "testArr(int[])",
"type": "function",
"inputs": [{
"name": "value",
"type": "int[]"
}],
"constant": true,
"outputs": [{
"name": "d",
"type": "int"
}]
}, { }, {
"name":"Changed", "name":"Changed",
"type":"event", "type":"event",
@ -63,11 +77,27 @@ describe('web3.eth.contract', function () {
assert.deepEqual(payload.params[0], { assert.deepEqual(payload.params[0], {
topics: [ topics: [
sha3, sha3,
'0x1234567890123456789012345678901234567890' '0x0000000000000000000000001234567890123456789012345678901234567890',
null
], ],
address: '0x1234567890123456789012345678901234567890' 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([[{ provider.injectBatchResults([[{
address: address, address: address,
topics: [ topics: [
@ -89,12 +119,16 @@ describe('web3.eth.contract', function () {
var Contract = web3.eth.contract(desc); var Contract = web3.eth.contract(desc);
var contract = new Contract(address); var contract = new Contract(address);
var res = 0;
contract.Changed({from: address}).watch(function(err, result) { contract.Changed({from: address}).watch(function(err, result) {
assert.equal(result.args.from, address); assert.equal(result.args.from, address);
assert.equal(result.args.amount, 1); assert.equal(result.args.amount, 1);
assert.equal(result.args.t1, 1); assert.equal(result.args.t1, 1);
assert.equal(result.args.t2, 8); assert.equal(result.args.t2, 8);
res++;
if (res === 2) {
done(); done();
}
}); });
}); });
@ -187,7 +221,40 @@ describe('web3.eth.contract', function () {
var Contract = web3.eth.contract(desc); var Contract = web3.eth.contract(desc);
var contract = new Contract(address); 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 = web3.eth.contract(desc);
var contract = new Contract(address); 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', payload: '0x7b2274657374223a2274657374227d',
ttl: '0xc8', ttl: '0xc8',
priority: '0x3e8', 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 formatters = require('../lib/web3/formatters.js');
var BigNumber = require('bignumber.js'); var BigNumber = require('bignumber.js');
@ -16,7 +17,6 @@ describe('formatters', function () {
difficulty: '0x3e8', difficulty: '0x3e8',
totalDifficulty: '0x3e8', totalDifficulty: '0x3e8',
number: '0x3e8', number: '0x3e8',
minGasPrice: '0x3e8',
gasLimit: '0x3e8', gasLimit: '0x3e8',
gasUsed: '0x3e8', gasUsed: '0x3e8',
timestamp: '0x3e8', timestamp: '0x3e8',
@ -34,7 +34,6 @@ describe('formatters', function () {
difficulty: new BigNumber(1000), difficulty: new BigNumber(1000),
totalDifficulty: new BigNumber(1000), totalDifficulty: new BigNumber(1000),
number: 1000, number: 1000,
minGasPrice: new BigNumber(1000),
gasLimit: 1000, gasLimit: 1000,
gasUsed: 1000, gasUsed: 1000,
timestamp: 1000, timestamp: 1000,

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

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

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

@ -26,7 +26,7 @@ FakeHttpProvider.prototype.send = function (payload) {
// imitate plain json object // imitate plain json object
this.validation(JSON.parse(JSON.stringify(payload))); this.validation(JSON.parse(JSON.stringify(payload)));
} }
return this.response; return this.getResponse();
}; };
FakeHttpProvider.prototype.sendAsync = function (payload, callback) { FakeHttpProvider.prototype.sendAsync = function (payload, callback) {
@ -36,7 +36,7 @@ FakeHttpProvider.prototype.sendAsync = function (payload, callback) {
// imitate plain json object // imitate plain json object
this.validation(JSON.parse(JSON.stringify(payload)), callback); this.validation(JSON.parse(JSON.stringify(payload)), callback);
} }
callback(this.error, this.response); callback(this.error, this.getResponse());
}; };
FakeHttpProvider.prototype.injectResponse = function (response) { 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) { FakeHttpProvider.prototype.injectError = function (error) {
this.error = 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 assert = chai.assert;
var web3 = require('../../index'); var web3 = require('../../index');
var FakeHttpProvider = require('./FakeHttpProvider'); var FakeHttpProvider = require('./FakeHttpProvider');
var clone = function (object) { return JSON.parse(JSON.stringify(object)); };
var runTests = function (obj, method, tests) { var runTests = function (obj, method, tests) {
@ -22,10 +23,18 @@ var runTests = function (obj, method, tests) {
assert.deepEqual(payload.params, test.formattedArgs); 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 // when
var result = (obj) //var result = (obj)
? web3[obj][method].apply(null, test.args.slice(0)) //? web3[obj][method].apply(null, test.args.slice(0))
: web3[method].apply(null, test.args.slice(0)); //: web3[method].apply(null, test.args.slice(0));
// then // then
assert.deepEqual(test.formattedResult, result); assert.deepEqual(test.formattedResult, result);
@ -43,7 +52,8 @@ var runTests = function (obj, method, tests) {
assert.deepEqual(payload.params, test.formattedArgs); assert.deepEqual(payload.params, test.formattedArgs);
}); });
var args = test.args.slice(0); var args = clone(test.args);
// add callback // add callback
args.push(function (err, result) { args.push(function (err, result) {
assert.deepEqual(test.formattedResult, result); assert.deepEqual(test.formattedResult, result);
@ -51,10 +61,11 @@ var runTests = function (obj, method, tests) {
}); });
// when // when
if(obj) if (obj) {
web3[obj][method].apply(null, args); web3[obj][method].apply(null, args);
else } else {
web3[method].apply(null, args); 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); }; var test2 = function () { method.validateArgs(args2); };
// then // then
assert.throws(test, errors.InvalidNumberOfParams); assert.throws(test, errors.InvalidNumberOfParams().message);
assert.throws(test2, errors.InvalidNumberOfParams); 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 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", "size": "0x027f07",
"extraData": "0x0000000000000000000000000000000000000000000000000000000000000000", "extraData": "0x0000000000000000000000000000000000000000000000000000000000000000",
"gasLimit": "0x9f759", "gasLimit": "0x9f759",
"minGasPrice": "0x9f759",
"gasUsed": "0x9f759", "gasUsed": "0x9f759",
"timestamp": "0x54e34e8e", "timestamp": "0x54e34e8e",
"transactions": ['0x460cfb8472af2c5fd05b5a2','0x460cfb8472af2c5fd05b5a2'], "transactions": ['0x460cfb8472af2c5fd05b5a2','0x460cfb8472af2c5fd05b5a2'],
@ -40,7 +39,6 @@ var formattedBlockResult = {
"size": 163591, "size": 163591,
"extraData": "0x0000000000000000000000000000000000000000000000000000000000000000", "extraData": "0x0000000000000000000000000000000000000000000000000000000000000000",
"gasLimit": 653145, "gasLimit": 653145,
"minGasPrice": new BigNumber(653145),
"gasUsed": 653145, "gasUsed": 653145,
"timestamp": 1424182926, "timestamp": 1424182926,
"transactions": ['0x460cfb8472af2c5fd05b5a2','0x460cfb8472af2c5fd05b5a2'], "transactions": ['0x460cfb8472af2c5fd05b5a2','0x460cfb8472af2c5fd05b5a2'],
@ -61,13 +59,12 @@ var blockResultWithTx = {
"size": "0x027f07", "size": "0x027f07",
"extraData": "0x0000000000000000000000000000000000000000000000000000000000000000", "extraData": "0x0000000000000000000000000000000000000000000000000000000000000000",
"gasLimit": "0x9f759", "gasLimit": "0x9f759",
"minGasPrice": "0x9f759",
"gasUsed": "0x9f759", "gasUsed": "0x9f759",
"timestamp": "0x54e34e8e", "timestamp": "0x54e34e8e",
"transactions": [{ "transactions": [{
"status": "mined", "status": "mined",
"hash":"0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b", "hash":"0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b",
"nonce":"0x", "nonce":"0x2",
"blockHash": "0x6fd9e2a26ab", "blockHash": "0x6fd9e2a26ab",
"blockNumber": "0x15df", "blockNumber": "0x15df",
"transactionIndex": "0x1", "transactionIndex": "0x1",
@ -95,13 +92,12 @@ var formattedBlockResultWithTx = {
"size": 163591, "size": 163591,
"extraData": "0x0000000000000000000000000000000000000000000000000000000000000000", "extraData": "0x0000000000000000000000000000000000000000000000000000000000000000",
"gasLimit": 653145, "gasLimit": 653145,
"minGasPrice": new BigNumber(653145),
"gasUsed": 653145, "gasUsed": 653145,
"timestamp": 1424182926, "timestamp": 1424182926,
"transactions": [{ "transactions": [{
"status": "mined", "status": "mined",
"hash":"0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b", "hash":"0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b",
"nonce":"0x", "nonce": 2,
"blockHash": "0x6fd9e2a26ab", "blockHash": "0x6fd9e2a26ab",
"blockNumber": 5599, "blockNumber": 5599,
"transactionIndex": 1, "transactionIndex": 1,

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

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

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

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

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

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

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

@ -17,6 +17,45 @@ var tests = [{
result: '0xf', result: '0xf',
formattedResult: '0xf', formattedResult: '0xf',
call: 'shh_newFilter' 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 () { 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);

45
libsolidity/ASTJsonConverter.cpp

@ -151,12 +151,6 @@ bool ASTJsonConverter::visit(Mapping const&)
return true; return true;
} }
bool ASTJsonConverter::visit(Statement const&)
{
addJsonNode("Statement", {}, true);
return true;
}
bool ASTJsonConverter::visit(Block const&) bool ASTJsonConverter::visit(Block const&)
{ {
addJsonNode("Block", {}, true); addJsonNode("Block", {}, true);
@ -169,11 +163,6 @@ bool ASTJsonConverter::visit(IfStatement const&)
return true; return true;
} }
bool ASTJsonConverter::visit(BreakableStatement const&)
{
return true;
}
bool ASTJsonConverter::visit(WhileStatement const&) bool ASTJsonConverter::visit(WhileStatement const&)
{ {
addJsonNode("WhileStatement", {}, true); addJsonNode("WhileStatement", {}, true);
@ -216,17 +205,6 @@ bool ASTJsonConverter::visit(ExpressionStatement const&)
return true; return true;
} }
bool ASTJsonConverter::visit(Expression const& _node)
{
addJsonNode(
"Expression",
{ make_pair("type", getType(_node)),
make_pair("lvalue", boost::lexical_cast<std::string>(_node.isLValue())) },
true
);
return true;
}
bool ASTJsonConverter::visit(Assignment const& _node) bool ASTJsonConverter::visit(Assignment const& _node)
{ {
addJsonNode("Assignment", addJsonNode("Assignment",
@ -285,11 +263,6 @@ bool ASTJsonConverter::visit(IndexAccess const& _node)
return true; return true;
} }
bool ASTJsonConverter::visit(PrimaryExpression const&)
{
return true;
}
bool ASTJsonConverter::visit(Identifier const& _node) bool ASTJsonConverter::visit(Identifier const& _node)
{ {
addJsonNode("Identifier", addJsonNode("Identifier",
@ -358,11 +331,6 @@ void ASTJsonConverter::endVisit(Mapping const&)
{ {
} }
void ASTJsonConverter::endVisit(Statement const&)
{
goUp();
}
void ASTJsonConverter::endVisit(Block const&) void ASTJsonConverter::endVisit(Block const&)
{ {
goUp(); goUp();
@ -373,10 +341,6 @@ void ASTJsonConverter::endVisit(IfStatement const&)
goUp(); goUp();
} }
void ASTJsonConverter::endVisit(BreakableStatement const&)
{
}
void ASTJsonConverter::endVisit(WhileStatement const&) void ASTJsonConverter::endVisit(WhileStatement const&)
{ {
goUp(); goUp();
@ -410,11 +374,6 @@ void ASTJsonConverter::endVisit(ExpressionStatement const&)
goUp(); goUp();
} }
void ASTJsonConverter::endVisit(Expression const&)
{
goUp();
}
void ASTJsonConverter::endVisit(Assignment const&) void ASTJsonConverter::endVisit(Assignment const&)
{ {
goUp(); goUp();
@ -450,10 +409,6 @@ void ASTJsonConverter::endVisit(IndexAccess const&)
goUp(); goUp();
} }
void ASTJsonConverter::endVisit(PrimaryExpression const&)
{
}
void ASTJsonConverter::endVisit(Identifier const&) void ASTJsonConverter::endVisit(Identifier const&)
{ {
} }

8
libsolidity/ASTJsonConverter.h

@ -56,10 +56,8 @@ public:
bool visit(ElementaryTypeName const& _node) override; bool visit(ElementaryTypeName const& _node) override;
bool visit(UserDefinedTypeName const& _node) override; bool visit(UserDefinedTypeName const& _node) override;
bool visit(Mapping const& _node) override; bool visit(Mapping const& _node) override;
bool visit(Statement const& _node) override;
bool visit(Block const& _node) override; bool visit(Block const& _node) override;
bool visit(IfStatement const& _node) override; bool visit(IfStatement const& _node) override;
bool visit(BreakableStatement const& _node) override;
bool visit(WhileStatement const& _node) override; bool visit(WhileStatement const& _node) override;
bool visit(ForStatement const& _node) override; bool visit(ForStatement const& _node) override;
bool visit(Continue const& _node) override; bool visit(Continue const& _node) override;
@ -67,7 +65,6 @@ public:
bool visit(Return const& _node) override; bool visit(Return const& _node) override;
bool visit(VariableDeclarationStatement const& _node) override; bool visit(VariableDeclarationStatement const& _node) override;
bool visit(ExpressionStatement const& _node) override; bool visit(ExpressionStatement const& _node) override;
bool visit(Expression const& _node) override;
bool visit(Assignment const& _node) override; bool visit(Assignment const& _node) override;
bool visit(UnaryOperation const& _node) override; bool visit(UnaryOperation const& _node) override;
bool visit(BinaryOperation const& _node) override; bool visit(BinaryOperation const& _node) override;
@ -75,7 +72,6 @@ public:
bool visit(NewExpression const& _node) override; bool visit(NewExpression const& _node) override;
bool visit(MemberAccess const& _node) override; bool visit(MemberAccess const& _node) override;
bool visit(IndexAccess const& _node) override; bool visit(IndexAccess const& _node) override;
bool visit(PrimaryExpression const& _node) override;
bool visit(Identifier const& _node) override; bool visit(Identifier const& _node) override;
bool visit(ElementaryTypeNameExpression const& _node) override; bool visit(ElementaryTypeNameExpression const& _node) override;
bool visit(Literal const& _node) override; bool visit(Literal const& _node) override;
@ -90,10 +86,8 @@ public:
void endVisit(ElementaryTypeName const&) override; void endVisit(ElementaryTypeName const&) override;
void endVisit(UserDefinedTypeName const&) override; void endVisit(UserDefinedTypeName const&) override;
void endVisit(Mapping const&) override; void endVisit(Mapping const&) override;
void endVisit(Statement const&) override;
void endVisit(Block const&) override; void endVisit(Block const&) override;
void endVisit(IfStatement const&) override; void endVisit(IfStatement const&) override;
void endVisit(BreakableStatement const&) override;
void endVisit(WhileStatement const&) override; void endVisit(WhileStatement const&) override;
void endVisit(ForStatement const&) override; void endVisit(ForStatement const&) override;
void endVisit(Continue const&) override; void endVisit(Continue const&) override;
@ -101,7 +95,6 @@ public:
void endVisit(Return const&) override; void endVisit(Return const&) override;
void endVisit(VariableDeclarationStatement const&) override; void endVisit(VariableDeclarationStatement const&) override;
void endVisit(ExpressionStatement const&) override; void endVisit(ExpressionStatement const&) override;
void endVisit(Expression const&) override;
void endVisit(Assignment const&) override; void endVisit(Assignment const&) override;
void endVisit(UnaryOperation const&) override; void endVisit(UnaryOperation const&) override;
void endVisit(BinaryOperation const&) override; void endVisit(BinaryOperation const&) override;
@ -109,7 +102,6 @@ public:
void endVisit(NewExpression const&) override; void endVisit(NewExpression const&) override;
void endVisit(MemberAccess const&) override; void endVisit(MemberAccess const&) override;
void endVisit(IndexAccess const&) override; void endVisit(IndexAccess const&) override;
void endVisit(PrimaryExpression const&) override;
void endVisit(Identifier const&) override; void endVisit(Identifier const&) override;
void endVisit(ElementaryTypeNameExpression const&) override; void endVisit(ElementaryTypeNameExpression const&) override;
void endVisit(Literal const&) override; void endVisit(Literal const&) override;

50
libsolidity/ASTPrinter.cpp

@ -162,13 +162,6 @@ bool ASTPrinter::visit(ArrayTypeName const& _node)
return goDeeper(); return goDeeper();
} }
bool ASTPrinter::visit(Statement const& _node)
{
writeLine("Statement");
printSourcePart(_node);
return goDeeper();
}
bool ASTPrinter::visit(Block const& _node) bool ASTPrinter::visit(Block const& _node)
{ {
writeLine("Block"); writeLine("Block");
@ -190,13 +183,6 @@ bool ASTPrinter::visit(IfStatement const& _node)
return goDeeper(); return goDeeper();
} }
bool ASTPrinter::visit(BreakableStatement const& _node)
{
writeLine("BreakableStatement");
printSourcePart(_node);
return goDeeper();
}
bool ASTPrinter::visit(WhileStatement const& _node) bool ASTPrinter::visit(WhileStatement const& _node)
{ {
writeLine("WhileStatement"); writeLine("WhileStatement");
@ -246,14 +232,6 @@ bool ASTPrinter::visit(ExpressionStatement const& _node)
return goDeeper(); return goDeeper();
} }
bool ASTPrinter::visit(Expression const& _node)
{
writeLine("Expression");
printType(_node);
printSourcePart(_node);
return goDeeper();
}
bool ASTPrinter::visit(Assignment const& _node) bool ASTPrinter::visit(Assignment const& _node)
{ {
writeLine(string("Assignment using operator ") + Token::toString(_node.getAssignmentOperator())); writeLine(string("Assignment using operator ") + Token::toString(_node.getAssignmentOperator()));
@ -311,14 +289,6 @@ bool ASTPrinter::visit(IndexAccess const& _node)
return goDeeper(); return goDeeper();
} }
bool ASTPrinter::visit(PrimaryExpression const& _node)
{
writeLine("PrimaryExpression");
printType(_node);
printSourcePart(_node);
return goDeeper();
}
bool ASTPrinter::visit(Identifier const& _node) bool ASTPrinter::visit(Identifier const& _node)
{ {
writeLine(string("Identifier ") + _node.getName()); writeLine(string("Identifier ") + _node.getName());
@ -431,11 +401,6 @@ void ASTPrinter::endVisit(ArrayTypeName const&)
m_indentation--; m_indentation--;
} }
void ASTPrinter::endVisit(Statement const&)
{
m_indentation--;
}
void ASTPrinter::endVisit(Block const&) void ASTPrinter::endVisit(Block const&)
{ {
m_indentation--; m_indentation--;
@ -451,11 +416,6 @@ void ASTPrinter::endVisit(IfStatement const&)
m_indentation--; m_indentation--;
} }
void ASTPrinter::endVisit(BreakableStatement const&)
{
m_indentation--;
}
void ASTPrinter::endVisit(WhileStatement const&) void ASTPrinter::endVisit(WhileStatement const&)
{ {
m_indentation--; m_indentation--;
@ -491,11 +451,6 @@ void ASTPrinter::endVisit(ExpressionStatement const&)
m_indentation--; m_indentation--;
} }
void ASTPrinter::endVisit(Expression const&)
{
m_indentation--;
}
void ASTPrinter::endVisit(Assignment const&) void ASTPrinter::endVisit(Assignment const&)
{ {
m_indentation--; m_indentation--;
@ -531,11 +486,6 @@ void ASTPrinter::endVisit(IndexAccess const&)
m_indentation--; m_indentation--;
} }
void ASTPrinter::endVisit(PrimaryExpression const&)
{
m_indentation--;
}
void ASTPrinter::endVisit(Identifier const&) void ASTPrinter::endVisit(Identifier const&)
{ {
m_indentation--; m_indentation--;

8
libsolidity/ASTPrinter.h

@ -59,11 +59,9 @@ public:
bool visit(UserDefinedTypeName const& _node) override; bool visit(UserDefinedTypeName const& _node) override;
bool visit(Mapping const& _node) override; bool visit(Mapping const& _node) override;
bool visit(ArrayTypeName const& _node) override; bool visit(ArrayTypeName const& _node) override;
bool visit(Statement const& _node) override;
bool visit(Block const& _node) override; bool visit(Block const& _node) override;
bool visit(PlaceholderStatement const& _node) override; bool visit(PlaceholderStatement const& _node) override;
bool visit(IfStatement const& _node) override; bool visit(IfStatement const& _node) override;
bool visit(BreakableStatement const& _node) override;
bool visit(WhileStatement const& _node) override; bool visit(WhileStatement const& _node) override;
bool visit(ForStatement const& _node) override; bool visit(ForStatement const& _node) override;
bool visit(Continue const& _node) override; bool visit(Continue const& _node) override;
@ -71,7 +69,6 @@ public:
bool visit(Return const& _node) override; bool visit(Return const& _node) override;
bool visit(VariableDeclarationStatement const& _node) override; bool visit(VariableDeclarationStatement const& _node) override;
bool visit(ExpressionStatement const& _node) override; bool visit(ExpressionStatement const& _node) override;
bool visit(Expression const& _node) override;
bool visit(Assignment const& _node) override; bool visit(Assignment const& _node) override;
bool visit(UnaryOperation const& _node) override; bool visit(UnaryOperation const& _node) override;
bool visit(BinaryOperation const& _node) override; bool visit(BinaryOperation const& _node) override;
@ -79,7 +76,6 @@ public:
bool visit(NewExpression const& _node) override; bool visit(NewExpression const& _node) override;
bool visit(MemberAccess const& _node) override; bool visit(MemberAccess const& _node) override;
bool visit(IndexAccess const& _node) override; bool visit(IndexAccess const& _node) override;
bool visit(PrimaryExpression const& _node) override;
bool visit(Identifier const& _node) override; bool visit(Identifier const& _node) override;
bool visit(ElementaryTypeNameExpression const& _node) override; bool visit(ElementaryTypeNameExpression const& _node) override;
bool visit(Literal const& _node) override; bool visit(Literal const& _node) override;
@ -101,11 +97,9 @@ public:
void endVisit(UserDefinedTypeName const&) override; void endVisit(UserDefinedTypeName const&) override;
void endVisit(Mapping const&) override; void endVisit(Mapping const&) override;
void endVisit(ArrayTypeName const&) override; void endVisit(ArrayTypeName const&) override;
void endVisit(Statement const&) override;
void endVisit(Block const&) override; void endVisit(Block const&) override;
void endVisit(PlaceholderStatement const&) override; void endVisit(PlaceholderStatement const&) override;
void endVisit(IfStatement const&) override; void endVisit(IfStatement const&) override;
void endVisit(BreakableStatement const&) override;
void endVisit(WhileStatement const&) override; void endVisit(WhileStatement const&) override;
void endVisit(ForStatement const&) override; void endVisit(ForStatement const&) override;
void endVisit(Continue const&) override; void endVisit(Continue const&) override;
@ -113,7 +107,6 @@ public:
void endVisit(Return const&) override; void endVisit(Return const&) override;
void endVisit(VariableDeclarationStatement const&) override; void endVisit(VariableDeclarationStatement const&) override;
void endVisit(ExpressionStatement const&) override; void endVisit(ExpressionStatement const&) override;
void endVisit(Expression const&) override;
void endVisit(Assignment const&) override; void endVisit(Assignment const&) override;
void endVisit(UnaryOperation const&) override; void endVisit(UnaryOperation const&) override;
void endVisit(BinaryOperation const&) override; void endVisit(BinaryOperation const&) override;
@ -121,7 +114,6 @@ public:
void endVisit(NewExpression const&) override; void endVisit(NewExpression const&) override;
void endVisit(MemberAccess const&) override; void endVisit(MemberAccess const&) override;
void endVisit(IndexAccess const&) override; void endVisit(IndexAccess const&) override;
void endVisit(PrimaryExpression const&) override;
void endVisit(Identifier const&) override; void endVisit(Identifier const&) override;
void endVisit(ElementaryTypeNameExpression const&) override; void endVisit(ElementaryTypeNameExpression const&) override;
void endVisit(Literal const&) override; void endVisit(Literal const&) override;

342
libsolidity/ASTVisitor.h

@ -22,8 +22,8 @@
#pragma once #pragma once
#include <libsolidity/ASTForward.h>
#include <string> #include <string>
#include <libsolidity/AST.h>
namespace dev namespace dev
{ {
@ -41,185 +41,181 @@ namespace solidity
class ASTVisitor class ASTVisitor
{ {
public: public:
virtual bool visit(ASTNode&) { return true; } virtual bool visit(SourceUnit& _node) { return visitNode(_node); }
virtual bool visit(SourceUnit&) { return true; } virtual bool visit(ImportDirective& _node) { return visitNode(_node); }
virtual bool visit(ImportDirective&) { return true; } virtual bool visit(ContractDefinition& _node) { return visitNode(_node); }
virtual bool visit(ContractDefinition&) { return true; } virtual bool visit(InheritanceSpecifier& _node) { return visitNode(_node); }
virtual bool visit(InheritanceSpecifier&) { return true; } virtual bool visit(StructDefinition& _node) { return visitNode(_node); }
virtual bool visit(StructDefinition&) { return true; } virtual bool visit(EnumDefinition& _node) { return visitNode(_node); }
virtual bool visit(EnumDefinition&) { return true; } virtual bool visit(EnumValue& _node) { return visitNode(_node); }
virtual bool visit(EnumValue&) { return true; } virtual bool visit(ParameterList& _node) { return visitNode(_node); }
virtual bool visit(ParameterList&) { return true; } virtual bool visit(FunctionDefinition& _node) { return visitNode(_node); }
virtual bool visit(FunctionDefinition&) { return true; } virtual bool visit(VariableDeclaration& _node) { return visitNode(_node); }
virtual bool visit(VariableDeclaration&) { return true; } virtual bool visit(ModifierDefinition& _node) { return visitNode(_node); }
virtual bool visit(ModifierDefinition&) { return true; } virtual bool visit(ModifierInvocation& _node) { return visitNode(_node); }
virtual bool visit(ModifierInvocation&) { return true; } virtual bool visit(EventDefinition& _node) { return visitNode(_node); }
virtual bool visit(EventDefinition&) { return true; } virtual bool visit(TypeName& _node) { return visitNode(_node); }
virtual bool visit(TypeName&) { return true; } virtual bool visit(ElementaryTypeName& _node) { return visitNode(_node); }
virtual bool visit(ElementaryTypeName&) { return true; } virtual bool visit(UserDefinedTypeName& _node) { return visitNode(_node); }
virtual bool visit(UserDefinedTypeName&) { return true; } virtual bool visit(Mapping& _node) { return visitNode(_node); }
virtual bool visit(Mapping&) { return true; } virtual bool visit(ArrayTypeName& _node) { return visitNode(_node); }
virtual bool visit(ArrayTypeName&) { return true; } virtual bool visit(Block& _node) { return visitNode(_node); }
virtual bool visit(Statement&) { return true; } virtual bool visit(PlaceholderStatement& _node) { return visitNode(_node); }
virtual bool visit(Block&) { return true; } virtual bool visit(IfStatement& _node) { return visitNode(_node); }
virtual bool visit(PlaceholderStatement&) { return true; } virtual bool visit(WhileStatement& _node) { return visitNode(_node); }
virtual bool visit(IfStatement&) { return true; } virtual bool visit(ForStatement& _node) { return visitNode(_node); }
virtual bool visit(BreakableStatement&) { return true; } virtual bool visit(Continue& _node) { return visitNode(_node); }
virtual bool visit(WhileStatement&) { return true; } virtual bool visit(Break& _node) { return visitNode(_node); }
virtual bool visit(ForStatement&) { return true; } virtual bool visit(Return& _node) { return visitNode(_node); }
virtual bool visit(Continue&) { return true; } virtual bool visit(VariableDeclarationStatement& _node) { return visitNode(_node); }
virtual bool visit(Break&) { return true; } virtual bool visit(ExpressionStatement& _node) { return visitNode(_node); }
virtual bool visit(Return&) { return true; } virtual bool visit(Assignment& _node) { return visitNode(_node); }
virtual bool visit(VariableDeclarationStatement&) { return true; } virtual bool visit(UnaryOperation& _node) { return visitNode(_node); }
virtual bool visit(ExpressionStatement&) { return true; } virtual bool visit(BinaryOperation& _node) { return visitNode(_node); }
virtual bool visit(Expression&) { return true; } virtual bool visit(FunctionCall& _node) { return visitNode(_node); }
virtual bool visit(Assignment&) { return true; } virtual bool visit(NewExpression& _node) { return visitNode(_node); }
virtual bool visit(UnaryOperation&) { return true; } virtual bool visit(MemberAccess& _node) { return visitNode(_node); }
virtual bool visit(BinaryOperation&) { return true; } virtual bool visit(IndexAccess& _node) { return visitNode(_node); }
virtual bool visit(FunctionCall&) { return true; } virtual bool visit(Identifier& _node) { return visitNode(_node); }
virtual bool visit(NewExpression&) { return true; } virtual bool visit(ElementaryTypeNameExpression& _node) { return visitNode(_node); }
virtual bool visit(MemberAccess&) { return true; } virtual bool visit(Literal& _node) { return visitNode(_node); }
virtual bool visit(IndexAccess&) { return true; }
virtual bool visit(PrimaryExpression&) { return true; }
virtual bool visit(Identifier&) { return true; }
virtual bool visit(ElementaryTypeNameExpression&) { return true; }
virtual bool visit(Literal&) { return true; }
virtual void endVisit(ASTNode&) { } virtual void endVisit(SourceUnit& _node) { endVisitNode(_node); }
virtual void endVisit(SourceUnit&) { } virtual void endVisit(ImportDirective& _node) { endVisitNode(_node); }
virtual void endVisit(ImportDirective&) { } virtual void endVisit(ContractDefinition& _node) { endVisitNode(_node); }
virtual void endVisit(ContractDefinition&) { } virtual void endVisit(InheritanceSpecifier& _node) { endVisitNode(_node); }
virtual void endVisit(InheritanceSpecifier&) { } virtual void endVisit(StructDefinition& _node) { endVisitNode(_node); }
virtual void endVisit(StructDefinition&) { } virtual void endVisit(EnumDefinition& _node) { endVisitNode(_node); }
virtual void endVisit(EnumDefinition&) { } virtual void endVisit(EnumValue& _node) { endVisitNode(_node); }
virtual void endVisit(EnumValue&) { } virtual void endVisit(ParameterList& _node) { endVisitNode(_node); }
virtual void endVisit(ParameterList&) { } virtual void endVisit(FunctionDefinition& _node) { endVisitNode(_node); }
virtual void endVisit(FunctionDefinition&) { } virtual void endVisit(VariableDeclaration& _node) { endVisitNode(_node); }
virtual void endVisit(VariableDeclaration&) { } virtual void endVisit(ModifierDefinition& _node) { endVisitNode(_node); }
virtual void endVisit(ModifierDefinition&) { } virtual void endVisit(ModifierInvocation& _node) { endVisitNode(_node); }
virtual void endVisit(ModifierInvocation&) { } virtual void endVisit(EventDefinition& _node) { endVisitNode(_node); }
virtual void endVisit(EventDefinition&) { } virtual void endVisit(TypeName& _node) { endVisitNode(_node); }
virtual void endVisit(TypeName&) { } virtual void endVisit(ElementaryTypeName& _node) { endVisitNode(_node); }
virtual void endVisit(ElementaryTypeName&) { } virtual void endVisit(UserDefinedTypeName& _node) { endVisitNode(_node); }
virtual void endVisit(UserDefinedTypeName&) { } virtual void endVisit(Mapping& _node) { endVisitNode(_node); }
virtual void endVisit(Mapping&) { } virtual void endVisit(ArrayTypeName& _node) { endVisitNode(_node); }
virtual void endVisit(ArrayTypeName&) { } virtual void endVisit(Block& _node) { endVisitNode(_node); }
virtual void endVisit(Statement&) { } virtual void endVisit(PlaceholderStatement& _node) { endVisitNode(_node); }
virtual void endVisit(Block&) { } virtual void endVisit(IfStatement& _node) { endVisitNode(_node); }
virtual void endVisit(PlaceholderStatement&) { } virtual void endVisit(WhileStatement& _node) { endVisitNode(_node); }
virtual void endVisit(IfStatement&) { } virtual void endVisit(ForStatement& _node) { endVisitNode(_node); }
virtual void endVisit(BreakableStatement&) { } virtual void endVisit(Continue& _node) { endVisitNode(_node); }
virtual void endVisit(WhileStatement&) { } virtual void endVisit(Break& _node) { endVisitNode(_node); }
virtual void endVisit(ForStatement&) { } virtual void endVisit(Return& _node) { endVisitNode(_node); }
virtual void endVisit(Continue&) { } virtual void endVisit(VariableDeclarationStatement& _node) { endVisitNode(_node); }
virtual void endVisit(Break&) { } virtual void endVisit(ExpressionStatement& _node) { endVisitNode(_node); }
virtual void endVisit(Return&) { } virtual void endVisit(Assignment& _node) { endVisitNode(_node); }
virtual void endVisit(VariableDeclarationStatement&) { } virtual void endVisit(UnaryOperation& _node) { endVisitNode(_node); }
virtual void endVisit(ExpressionStatement&) { } virtual void endVisit(BinaryOperation& _node) { endVisitNode(_node); }
virtual void endVisit(Expression&) { } virtual void endVisit(FunctionCall& _node) { endVisitNode(_node); }
virtual void endVisit(Assignment&) { } virtual void endVisit(NewExpression& _node) { endVisitNode(_node); }
virtual void endVisit(UnaryOperation&) { } virtual void endVisit(MemberAccess& _node) { endVisitNode(_node); }
virtual void endVisit(BinaryOperation&) { } virtual void endVisit(IndexAccess& _node) { endVisitNode(_node); }
virtual void endVisit(FunctionCall&) { } virtual void endVisit(Identifier& _node) { endVisitNode(_node); }
virtual void endVisit(NewExpression&) { } virtual void endVisit(ElementaryTypeNameExpression& _node) { endVisitNode(_node); }
virtual void endVisit(MemberAccess&) { } virtual void endVisit(Literal& _node) { endVisitNode(_node); }
virtual void endVisit(IndexAccess&) { }
virtual void endVisit(PrimaryExpression&) { } protected:
virtual void endVisit(Identifier&) { } /// Generic function called by default for each node, to be overridden by derived classes
virtual void endVisit(ElementaryTypeNameExpression&) { } /// if behaviour unspecific to a node type is desired.
virtual void endVisit(Literal&) { } virtual bool visitNode(ASTNode&) { return true; }
/// Generic function called by default for each node, to be overridden by derived classes
/// if behaviour unspecific to a node type is desired.
virtual void endVisitNode(ASTNode&) { }
}; };
class ASTConstVisitor class ASTConstVisitor
{ {
public: public:
virtual bool visit(ASTNode const&) { return true; } virtual bool visit(SourceUnit const& _node) { return visitNode(_node); }
virtual bool visit(SourceUnit const&) { return true; } virtual bool visit(ImportDirective const& _node) { return visitNode(_node); }
virtual bool visit(ImportDirective const&) { return true; } virtual bool visit(ContractDefinition const& _node) { return visitNode(_node); }
virtual bool visit(ContractDefinition const&) { return true; } virtual bool visit(InheritanceSpecifier const& _node) { return visitNode(_node); }
virtual bool visit(InheritanceSpecifier const&) { return true; } virtual bool visit(StructDefinition const& _node) { return visitNode(_node); }
virtual bool visit(StructDefinition const&) { return true; } virtual bool visit(EnumDefinition const& _node) { return visitNode(_node); }
virtual bool visit(EnumDefinition const&) { return true; } virtual bool visit(EnumValue const& _node) { return visitNode(_node); }
virtual bool visit(EnumValue const&) { return true; } virtual bool visit(ParameterList const& _node) { return visitNode(_node); }
virtual bool visit(ParameterList const&) { return true; } virtual bool visit(FunctionDefinition const& _node) { return visitNode(_node); }
virtual bool visit(FunctionDefinition const&) { return true; } virtual bool visit(VariableDeclaration const& _node) { return visitNode(_node); }
virtual bool visit(VariableDeclaration const&) { return true; } virtual bool visit(ModifierDefinition const& _node) { return visitNode(_node); }
virtual bool visit(ModifierDefinition const&) { return true; } virtual bool visit(ModifierInvocation const& _node) { return visitNode(_node); }
virtual bool visit(ModifierInvocation const&) { return true; } virtual bool visit(EventDefinition const& _node) { return visitNode(_node); }
virtual bool visit(EventDefinition const&) { return true; } virtual bool visit(TypeName const& _node) { return visitNode(_node); }
virtual bool visit(TypeName const&) { return true; } virtual bool visit(ElementaryTypeName const& _node) { return visitNode(_node); }
virtual bool visit(ElementaryTypeName const&) { return true; } virtual bool visit(UserDefinedTypeName const& _node) { return visitNode(_node); }
virtual bool visit(UserDefinedTypeName const&) { return true; } virtual bool visit(Mapping const& _node) { return visitNode(_node); }
virtual bool visit(Mapping const&) { return true; } virtual bool visit(ArrayTypeName const& _node) { return visitNode(_node); }
virtual bool visit(ArrayTypeName const&) { return true; } virtual bool visit(Block const& _node) { return visitNode(_node); }
virtual bool visit(Statement const&) { return true; } virtual bool visit(PlaceholderStatement const& _node) { return visitNode(_node); }
virtual bool visit(Block const&) { return true; } virtual bool visit(IfStatement const& _node) { return visitNode(_node); }
virtual bool visit(PlaceholderStatement const&) { return true; } virtual bool visit(WhileStatement const& _node) { return visitNode(_node); }
virtual bool visit(IfStatement const&) { return true; } virtual bool visit(ForStatement const& _node) { return visitNode(_node); }
virtual bool visit(BreakableStatement const&) { return true; } virtual bool visit(Continue const& _node) { return visitNode(_node); }
virtual bool visit(WhileStatement const&) { return true; } virtual bool visit(Break const& _node) { return visitNode(_node); }
virtual bool visit(ForStatement const&) { return true; } virtual bool visit(Return const& _node) { return visitNode(_node); }
virtual bool visit(Continue const&) { return true; } virtual bool visit(VariableDeclarationStatement const& _node) { return visitNode(_node); }
virtual bool visit(Break const&) { return true; } virtual bool visit(ExpressionStatement const& _node) { return visitNode(_node); }
virtual bool visit(Return const&) { return true; } virtual bool visit(Assignment const& _node) { return visitNode(_node); }
virtual bool visit(VariableDeclarationStatement const&) { return true; } virtual bool visit(UnaryOperation const& _node) { return visitNode(_node); }
virtual bool visit(ExpressionStatement const&) { return true; } virtual bool visit(BinaryOperation const& _node) { return visitNode(_node); }
virtual bool visit(Expression const&) { return true; } virtual bool visit(FunctionCall const& _node) { return visitNode(_node); }
virtual bool visit(Assignment const&) { return true; } virtual bool visit(NewExpression const& _node) { return visitNode(_node); }
virtual bool visit(UnaryOperation const&) { return true; } virtual bool visit(MemberAccess const& _node) { return visitNode(_node); }
virtual bool visit(BinaryOperation const&) { return true; } virtual bool visit(IndexAccess const& _node) { return visitNode(_node); }
virtual bool visit(FunctionCall const&) { return true; } virtual bool visit(Identifier const& _node) { return visitNode(_node); }
virtual bool visit(NewExpression const&) { return true; } virtual bool visit(ElementaryTypeNameExpression const& _node) { return visitNode(_node); }
virtual bool visit(MemberAccess const&) { return true; } virtual bool visit(Literal const& _node) { return visitNode(_node); }
virtual bool visit(IndexAccess const&) { return true; }
virtual bool visit(PrimaryExpression const&) { return true; } virtual void endVisit(SourceUnit const& _node) { endVisitNode(_node); }
virtual bool visit(Identifier const&) { return true; } virtual void endVisit(ImportDirective const& _node) { endVisitNode(_node); }
virtual bool visit(ElementaryTypeNameExpression const&) { return true; } virtual void endVisit(ContractDefinition const& _node) { endVisitNode(_node); }
virtual bool visit(Literal const&) { return true; } virtual void endVisit(InheritanceSpecifier const& _node) { endVisitNode(_node); }
virtual void endVisit(StructDefinition const& _node) { endVisitNode(_node); }
virtual void endVisit(EnumDefinition const& _node) { endVisitNode(_node); }
virtual void endVisit(EnumValue const& _node) { endVisitNode(_node); }
virtual void endVisit(ParameterList const& _node) { endVisitNode(_node); }
virtual void endVisit(FunctionDefinition const& _node) { endVisitNode(_node); }
virtual void endVisit(VariableDeclaration const& _node) { endVisitNode(_node); }
virtual void endVisit(ModifierDefinition const& _node) { endVisitNode(_node); }
virtual void endVisit(ModifierInvocation const& _node) { endVisitNode(_node); }
virtual void endVisit(EventDefinition const& _node) { endVisitNode(_node); }
virtual void endVisit(TypeName const& _node) { endVisitNode(_node); }
virtual void endVisit(ElementaryTypeName const& _node) { endVisitNode(_node); }
virtual void endVisit(UserDefinedTypeName const& _node) { endVisitNode(_node); }
virtual void endVisit(Mapping const& _node) { endVisitNode(_node); }
virtual void endVisit(ArrayTypeName const& _node) { endVisitNode(_node); }
virtual void endVisit(Block const& _node) { endVisitNode(_node); }
virtual void endVisit(PlaceholderStatement const& _node) { endVisitNode(_node); }
virtual void endVisit(IfStatement const& _node) { endVisitNode(_node); }
virtual void endVisit(WhileStatement const& _node) { endVisitNode(_node); }
virtual void endVisit(ForStatement const& _node) { endVisitNode(_node); }
virtual void endVisit(Continue const& _node) { endVisitNode(_node); }
virtual void endVisit(Break const& _node) { endVisitNode(_node); }
virtual void endVisit(Return const& _node) { endVisitNode(_node); }
virtual void endVisit(VariableDeclarationStatement const& _node) { endVisitNode(_node); }
virtual void endVisit(ExpressionStatement const& _node) { endVisitNode(_node); }
virtual void endVisit(Assignment const& _node) { endVisitNode(_node); }
virtual void endVisit(UnaryOperation const& _node) { endVisitNode(_node); }
virtual void endVisit(BinaryOperation const& _node) { endVisitNode(_node); }
virtual void endVisit(FunctionCall const& _node) { endVisitNode(_node); }
virtual void endVisit(NewExpression const& _node) { endVisitNode(_node); }
virtual void endVisit(MemberAccess const& _node) { endVisitNode(_node); }
virtual void endVisit(IndexAccess const& _node) { endVisitNode(_node); }
virtual void endVisit(Identifier const& _node) { endVisitNode(_node); }
virtual void endVisit(ElementaryTypeNameExpression const& _node) { endVisitNode(_node); }
virtual void endVisit(Literal const& _node) { endVisitNode(_node); }
virtual void endVisit(ASTNode const&) { } protected:
virtual void endVisit(SourceUnit const&) { } /// Generic function called by default for each node, to be overridden by derived classes
virtual void endVisit(ImportDirective const&) { } /// if behaviour unspecific to a node type is desired.
virtual void endVisit(ContractDefinition const&) { } virtual bool visitNode(ASTNode const&) { return true; }
virtual void endVisit(InheritanceSpecifier const&) { } /// Generic function called by default for each node, to be overridden by derived classes
virtual void endVisit(StructDefinition const&) { } /// if behaviour unspecific to a node type is desired.
virtual void endVisit(EnumDefinition const&) { } virtual void endVisitNode(ASTNode const&) { }
virtual void endVisit(EnumValue const&) { }
virtual void endVisit(ParameterList const&) { }
virtual void endVisit(FunctionDefinition const&) { }
virtual void endVisit(VariableDeclaration const&) { }
virtual void endVisit(ModifierDefinition const&) { }
virtual void endVisit(ModifierInvocation const&) { }
virtual void endVisit(EventDefinition const&) { }
virtual void endVisit(TypeName const&) { }
virtual void endVisit(ElementaryTypeName const&) { }
virtual void endVisit(UserDefinedTypeName const&) { }
virtual void endVisit(Mapping const&) { }
virtual void endVisit(ArrayTypeName const&) { }
virtual void endVisit(Statement const&) { }
virtual void endVisit(Block const&) { }
virtual void endVisit(PlaceholderStatement const&) { }
virtual void endVisit(IfStatement const&) { }
virtual void endVisit(BreakableStatement const&) { }
virtual void endVisit(WhileStatement const&) { }
virtual void endVisit(ForStatement const&) { }
virtual void endVisit(Continue const&) { }
virtual void endVisit(Break const&) { }
virtual void endVisit(Return const&) { }
virtual void endVisit(VariableDeclarationStatement const&) { }
virtual void endVisit(ExpressionStatement const&) { }
virtual void endVisit(Expression const&) { }
virtual void endVisit(Assignment const&) { }
virtual void endVisit(UnaryOperation const&) { }
virtual void endVisit(BinaryOperation const&) { }
virtual void endVisit(FunctionCall const&) { }
virtual void endVisit(NewExpression const&) { }
virtual void endVisit(MemberAccess const&) { }
virtual void endVisit(IndexAccess const&) { }
virtual void endVisit(PrimaryExpression const&) { }
virtual void endVisit(Identifier const&) { }
virtual void endVisit(ElementaryTypeNameExpression const&) { }
virtual void endVisit(Literal const&) { }
}; };
} }

11
libsolidity/LValue.cpp

@ -311,8 +311,6 @@ void StorageByteArrayElement::retrieveValue(SourceLocation const&, bool _remove)
void StorageByteArrayElement::storeValue(Type const&, SourceLocation const&, bool _move) const void StorageByteArrayElement::storeValue(Type const&, SourceLocation const&, bool _move) const
{ {
//@todo optimize this
// stack: value ref byte_number // stack: value ref byte_number
m_context << u256(31) << eth::Instruction::SUB << u256(0x100) << eth::Instruction::EXP; m_context << u256(31) << eth::Instruction::SUB << u256(0x100) << eth::Instruction::EXP;
// stack: value ref (1<<(8*(31-byte_number))) // stack: value ref (1<<(8*(31-byte_number)))
@ -335,19 +333,16 @@ void StorageByteArrayElement::setToZero(SourceLocation const&, bool _removeRefer
{ {
// stack: ref byte_number // stack: ref byte_number
if (!_removeReference) if (!_removeReference)
m_context << eth::Instruction::SWAP1 << eth::Instruction::DUP2; m_context << eth::Instruction::DUP2 << eth::Instruction::DUP2;
m_context << u256(31) << eth::Instruction::SUB << u256(0x100) << eth::Instruction::EXP; m_context << u256(31) << eth::Instruction::SUB << u256(0x100) << eth::Instruction::EXP;
// stack: ref (1<<(8*(31-byte_number))) // stack: ref (1<<(8*(31-byte_number)))
m_context << eth::Instruction::DUP2 << eth::Instruction::SLOAD; m_context << eth::Instruction::DUP2 << eth::Instruction::SLOAD;
// stack: ref (1<<(8*(31-byte_number))) old_full_value // stack: ref (1<<(8*(31-byte_number))) old_full_value
// clear byte in old value // clear byte in old value
m_context << eth::Instruction::SWAP1 << u256(0xff) << eth::Instruction::MUL << eth::Instruction::AND; m_context << eth::Instruction::SWAP1 << u256(0xff) << eth::Instruction::MUL;
m_context << eth::Instruction::NOT << eth::Instruction::AND;
// stack: ref old_full_value_with_cleared_byte // stack: ref old_full_value_with_cleared_byte
m_context << eth::Instruction::SWAP1 << eth::Instruction::SSTORE; m_context << eth::Instruction::SWAP1 << eth::Instruction::SSTORE;
if (!_removeReference)
m_context << eth::Instruction::SWAP1;
else
m_context << eth::Instruction::POP;
} }
StorageArrayLength::StorageArrayLength(CompilerContext& _compilerContext, const ArrayType& _arrayType): StorageArrayLength::StorageArrayLength(CompilerContext& _compilerContext, const ArrayType& _arrayType):

2
libweb3jsonrpc/CMakeLists.txt

@ -43,7 +43,7 @@ if (ETH_JSON_RPC_STUB)
POST_BUILD POST_BUILD
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
COMMAND ${CMAKE_COMMAND} -DETH_SPEC_PATH="${CMAKE_CURRENT_SOURCE_DIR}/spec.json" -DETH_SOURCE_DIR="${CMAKE_SOURCE_DIR}" COMMAND ${CMAKE_COMMAND} -DETH_SPEC_PATH="${CMAKE_CURRENT_SOURCE_DIR}/spec.json" -DETH_SOURCE_DIR="${CMAKE_SOURCE_DIR}"
-DETH_SERVER_DIR="${CMAKE_CURRENT_SOURCE_DIR}" -DETH_CLIENT_DIR="${CMAKE_SOURCE_DIR}/test" -DETH_SERVER_DIR="${CMAKE_CURRENT_SOURCE_DIR}" -DETH_CLIENT_DIR="${CMAKE_SOURCE_DIR}/test/libweb3jsonrpc"
-DETH_SERVER_NAME=AbstractWebThreeStubServer -DETH_CLIENT_NAME=WebThreeStubClient -DETH_SERVER_NAME=AbstractWebThreeStubServer -DETH_CLIENT_NAME=WebThreeStubClient
-DETH_JSON_RPC_STUB="${ETH_JSON_RPC_STUB}" -DETH_JSON_RPC_STUB="${ETH_JSON_RPC_STUB}"
-P "${ETH_SCRIPTS_DIR}/jsonrpcstub.cmake" -P "${ETH_SCRIPTS_DIR}/jsonrpcstub.cmake"

20
test/libsolidity/SolidityEndToEndTest.cpp

@ -3381,6 +3381,26 @@ BOOST_AUTO_TEST_CASE(bytes_index_access)
BOOST_CHECK(callContractFunction("storageWrite()") == encodeArgs(0x193)); BOOST_CHECK(callContractFunction("storageWrite()") == encodeArgs(0x193));
} }
BOOST_AUTO_TEST_CASE(bytes_delete_element)
{
char const* sourceCode = R"(
contract c {
bytes data;
function test1() external returns (bool) {
data.length = 100;
for (uint i = 0; i < data.length; i++)
data[i] = byte(i);
delete data[94];
delete data[96];
delete data[98];
return data[94] == 0 && data[95] == 95 && data[96] == 0 && data[97] == 97;
}
}
)";
compileAndRun(sourceCode);
BOOST_CHECK(callContractFunction("test1()") == encodeArgs(true));
}
BOOST_AUTO_TEST_CASE(array_copy_calldata_storage) BOOST_AUTO_TEST_CASE(array_copy_calldata_storage)
{ {
char const* sourceCode = R"( char const* sourceCode = R"(

2
test/libsolidity/SolidityExpressionCompiler.cpp

@ -50,14 +50,12 @@ public:
FirstExpressionExtractor(ASTNode& _node): m_expression(nullptr) { _node.accept(*this); } FirstExpressionExtractor(ASTNode& _node): m_expression(nullptr) { _node.accept(*this); }
Expression* getExpression() const { return m_expression; } Expression* getExpression() const { return m_expression; }
private: private:
virtual bool visit(Expression& _expression) override { return checkExpression(_expression); }
virtual bool visit(Assignment& _expression) override { return checkExpression(_expression); } virtual bool visit(Assignment& _expression) override { return checkExpression(_expression); }
virtual bool visit(UnaryOperation& _expression) override { return checkExpression(_expression); } virtual bool visit(UnaryOperation& _expression) override { return checkExpression(_expression); }
virtual bool visit(BinaryOperation& _expression) override { return checkExpression(_expression); } virtual bool visit(BinaryOperation& _expression) override { return checkExpression(_expression); }
virtual bool visit(FunctionCall& _expression) override { return checkExpression(_expression); } virtual bool visit(FunctionCall& _expression) override { return checkExpression(_expression); }
virtual bool visit(MemberAccess& _expression) override { return checkExpression(_expression); } virtual bool visit(MemberAccess& _expression) override { return checkExpression(_expression); }
virtual bool visit(IndexAccess& _expression) override { return checkExpression(_expression); } virtual bool visit(IndexAccess& _expression) override { return checkExpression(_expression); }
virtual bool visit(PrimaryExpression& _expression) override { return checkExpression(_expression); }
virtual bool visit(Identifier& _expression) override { return checkExpression(_expression); } virtual bool visit(Identifier& _expression) override { return checkExpression(_expression); }
virtual bool visit(ElementaryTypeNameExpression& _expression) override { return checkExpression(_expression); } virtual bool visit(ElementaryTypeNameExpression& _expression) override { return checkExpression(_expression); }
virtual bool visit(Literal& _expression) override { return checkExpression(_expression); } virtual bool visit(Literal& _expression) override { return checkExpression(_expression); }

Loading…
Cancel
Save