Skip to content

Commit

Permalink
Add support for big numbers
Browse files Browse the repository at this point in the history
  • Loading branch information
Pedro Branco committed Feb 8, 2017
1 parent a19a615 commit 0382821
Show file tree
Hide file tree
Showing 5 changed files with 18 additions and 2 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,10 @@ client.getInfo().then(([body, headers]) => console.log(body, headers));
const [body, headers] = await client.getInfo();
```

### Floating point number precision in JavaScript

Due to [Javascript floating point precision](http://floating-point-gui.de/), to prevent precision loss when using `bitcoin-core` we should pass all big numbers (numbers with more than 15 significant digits) as string instead of using `Number` data type.

### Version Checking
By default, all methods are exposed on the client independently of the version it is connecting to. This is the most flexible option as defining methods for unavailable RPC calls does not cause any harm and the library is capable of handling a `Method not found` response error correctly.

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
},
"dependencies": {
"bluebird": "^3.4.1",
"json-bigint": "^0.2.0",
"lodash": "^4.0.0",
"request": "^2.53.0",
"semver": "^5.1.0",
Expand Down
3 changes: 2 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,8 @@ class Client {

return this.request.postAsync({
auth: _.pickBy(this.auth, _.identity),
body,
body: JSON.stringify(body),
json: false,
uri: '/'
})
.bind(this)
Expand Down
10 changes: 10 additions & 0 deletions src/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,16 @@
* Module dependencies.
*/

import JSONBigInt from 'json-bigint';
import RpcError from './errors/rpc-error';
import _ from 'lodash';

/**
* JSONBigInt parser.
*/

const { parse } = JSONBigInt({ storeAsString: true, strict: true }); // eslint-disable-line new-cap

/**
* Get response result and errors.
*/
Expand Down Expand Up @@ -52,6 +59,9 @@ export default class Parser {
throw new RpcError(response.statusCode);
}

// Parsing the body with custom parser to support BigNumbers.
body = parse(body);

if (!Array.isArray(body)) {
return get(body, { headers: this.headers, response });
}
Expand Down
2 changes: 1 addition & 1 deletion test/index_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ describe('Client', () => {
it('should return the proof-of-work difficulty', async () => {
const difficulty = await new Client(config.bitcoind).getDifficulty();

difficulty.should.be.a.Number();
difficulty.should.be.a.String();
});
});

Expand Down

0 comments on commit 0382821

Please sign in to comment.