Code Monkey home page Code Monkey logo

coinbase-node's Introduction

Coinbase

The official Node.js library for the Coinbase API.

Features

  • Full Test coverage.
  • Support for both API Key + Secret and OAuth 2 authentication.
  • Convenient methods for making calls to the API.
  • Automatic parsing of API responses into relevant Javascript objects.
  • Adheres to the nodejs error-first callback protocol.
  • Continuous Integration testing against node 0.10, 0.11, and 0.12.

Installation

npm install coinbase

Version Compatibility

Version GitHub repository
2.0.x This repository
0.1.x mateodelnorte/coinbase

Npm coinbase package name used to refer to the unofficial coinbase library maintained by Matt Walters. Matt graciously allowed us to use the name for this package instead. You can still find that package on Github. Thanks, Matt.

Quick Start

The first thing you'll need to do is sign up for coinbase.

API Key

If you're writing code for your own Coinbase account, enable an API key. Next, create a Client object for interacting with the API:

var Client = require('coinbase').Client;
var client = new Client({'apiKey': mykey, 'apiSecret': mysecret});

OAuth2

If you're writing code that will act on behalf of another user, start by creating a new OAuth 2 application. You will need to do some work to obtain OAuth credentials for your users; while outside the scope of this document, please refer to our OAuth 2 tutorial and documentation. Once you have these credentials, create a client:

var Client = require('coinbase').Client;
var client = new Client({'accessToken': accessToken, 'refreshToken': refreshToken});

Making API Calls

With a client instance, you can now make API calls. We've included some examples below, but in general the library has Javascript prototypes for each of the objects described in our REST API documentation. These classes each have methods for making the relevant API calls; for instance, coinbase.model.Transaction.complete maps to the complete bitcoin request API endpoint. The comments of each method in the code references the endpoint it implements. Each API method returns an object representing the JSON response from the API.

Listing available accounts

var coinbase = require('coinbase');
var client   = new coinbase.Client({'apiKey': mykey, 'apiSecret': mysecret});

client.getAccounts({}, function(err, accounts) {
  accounts.forEach(function(acct) {
    console.log('my bal: ' + acct.balance.amount + ' for ' + acct.name);
  });
});

Get Balance from an Account Id

var coinbase = require('coinbase');
var client   = new coinbase.Client({'apiKey': mykey, 'apiSecret': mysecret});

client.getAccount('<ACCOUNT ID>', function(err, account) {
  console.log('bal: ' + account.balance.amount + ' currency: ' + account.balance.currency);
});

Selling bitcoin

var args = {
  "amount": "12",
  "currency": "BTC"
};
account.sell(args, function(err, xfer) {
  console.log('my xfer id is: ' + xfer.id);
});

Sending bitcoin

var args = {
  "to": "[email protected]",
  "amount": "1.234",
  "currency": "BTC",
  "description": "Sample transaction for you"
};
account.sendMoney(args, function(err, txn) {
  console.log('my txn id is: ' + txn.id);
});

Requesting bitcoin

var args = {
  "to": "[email protected]",
  "amount": "1.234",
  "currency": "BTC",
  "description": "Sample transaction for you"
};
account.requestMoney(args, function(err, txn) {
  console.log('my txn id is: ' + txn.id);
});

Listing current transactions

account.getTransactions(null, function(err, txns) {
  txns.forEach(function(txn) {
    console.log('my txn status: ' + txn.status);
  });
});

Using pagination

account.getTransactions(null, function(err, txns, pagination) {
  txns.forEach(function(txn) {
    console.log('my txn: ' + txn.id);
  });
  console.log(pagination.next_uri);
  account.getTransactions(pagination, function(err, txns) {
    txns.forEach(function(txn) {
      console.log('my txn: ' + txn.id);
    });
  });
});

Checking bitcoin prices

client.getBuyPrice({'currencyPair': 'BTC-USD'}, function(err, obj) {
  console.log('total amount: ' + obj.data.amount);
});

Verifying merchant callback authenticity

if (client.verifyCallback(req.raw_body, req.headers['CB-SIGNATURE'])) {
  // Process callback
}

Error Handling

Errors are thrown for invalid arguments but are otherwise returned as the first argument to callback functions using http-errors module.

Errors contain name, status, and message fields for error handling. You can find more information about error types here

Testing / Contributing

Any and all contributions are welcome! The process is simple:

  1. Fork this repo
  2. Make your changes and add tests
  3. Run the test suite
  4. Submit a pull request.

Tests are run via mocha and nock. To run the tests, clone the repository and then:

npm install

npm test

Please also scan the packages for known vulnerabilities.

npm install -g nsp
nsp check --output summary

You can also run the tests against various node environments using the Dockerfile.example file.

  1. cp Dockerfile.example Dockerfile
  2. edit Dockerfile and uncomment the node version that interests you
  3. [sudo] docker build -t coinbase-node .
  4. [sudo] docker run -it coinbase-node

coinbase-node's People

Contributors

aianus avatar amingilani avatar cjs77 avatar jborseth avatar jorilallo avatar kbcbhq avatar leeduc avatar maksim-s avatar matthewmueller avatar sds avatar sh6khan avatar tracend avatar ziggamon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

coinbase-node's Issues

client.getTransactions is not a function

Trying out the package in ES6 /react environment.
I've gotten getAccounts,sell,send,getBuyPrice working similar to this example, but getTransactions throws an error.... is this a namespace thing? Its a bit confusing, and worse in ES6.

import { Client as coinbase} from 'coinbase';

var coinbaseGetTransactions = (coinbaseAccount)=>{
  var client = new coinbase(coinbaseKeys[coinbaseAccount]);
  console.log(client);
  client.getTransactions({},Meteor.bindEnvironment((err,txns)=>{
    txns.forEach((txn)=>{
      console.log('my txn status : ' + txn.status);
    }); 
  }))
}
TypeError: client.getTransactions is not a function
    at _coinbaseGetTransactions (server/coinbaseServer.js:121:10)
    at [object Object].coinbaseGetTransactions (server/coinbaseServer.js:142:12)

Also using meteor but I doubt its causing the issue.

verifyCallback doesn't accept buffer from express body-parser verify

It is not working after all.
The code:

app.post('/coinbase/notifications', bodyParser.json({ verify: function(req, res, buf) {
  if (!coinbaseClient.verifyCallback(buf, req.headers['X-Signature'])) {
    throw new Error('Coinbase notification did not verify');
  }
}}));

The error:

TypeError: Not a string or buffer
  at TypeError (native)
  at Verify.verify (crypto.js:307:23)
  at Base.Client.verifyCallback (/Users/user/Work/express/node_modules/coinbase/lib/Client.js:250:19)
  at verifyCoinbaseNotification (/Users/user/Work/express/src/app.coffee:17:18)
  at /Users/user/Work/express/node_modules/body-parser/lib/read.js:100:9
  at invokeCallback (/Users/user/Work/express/node_modules/body-parser/node_modules/raw-body/index.js:262:16)
  at done (/Users/user/Work/express/node_modules/body-parser/node_modules/raw-body/index.js:251:7)
  at IncomingMessage.onEnd (/Users/user/Work/express/node_modules/body-parser/node_modules/raw-body/index.js:308:7)
  at emitNone (events.js:67:13)
  at IncomingMessage.emit (events.js:166:7)
  at endReadableNT (_stream_readable.js:905:12)
  at nextTickCallbackWith2Args (node.js:474:9)
  at process._tickCallback (node.js:388:17)

AccountBase errors on getTransaction for USDWallet Account

When I query getTransactions for my USD Wallet Account id, this line throws an error since the result data returned is an empty array (see below):

Result from API:

{ pagination:
   { ending_before: null,
     starting_after: null,
     limit: 25,
     order: 'desc',
     previous_uri: null,
     next_uri: null },
  data: [],
  warnings:
   [ { id: 'invalid_version',
       message: 'Please supply a valid API version in YYYY-MM-DD format',
       url: 'https://developers.coinbase.com/api#versioning' } ] }

Is AccountBase expecting data[0] to always have an object returned from the API? If not, can we add something like this to AccountBase:

  this.client._getHttp(path, args, function onGet(err, result) {
    if (!handleError(err, result, callback)) {

      // Handle empty data response from API:
      if (!result.data.length) {
        return callback(null, result.data)
      }

      var ObjFunc = self.client._stringToClass(result.data[0].resource);
      var objs = _.map(result.data, function onMap(obj) {
        return new ObjFunc(self.client, obj, self);
      });
      callback(null, objs, result.pagination);
    }
  }, headers);

I'm happy to submit a PR -- just getting my feet wet with the library, so I wanted to check in on intent first before submitting anything.

Thanks!

🍍

Update readme: callback verification permissions

verifyCallback is called on the client, and you can't create a client without an API keypair. Is a keypair actually necessary for callback verification? If yes, what are the minimum permissions needed on that keypair? Thanks!

Verifying merchant callback authenticity

if (client.verifyCallback(req.raw_body, req.headers['X-Signature'])) {
  // Process callback
}

Add sandbox support

If I set the API keys of mine sandbox account, coinbase gives the error "AuthenticationError".
Instead, with the API keys of the standard account, it works.

Error getting deposits list

I obtain this error when I call to getDeposits method:

TypeError: Cannot read property 'resource' of undefined
at onGet (/var/lib/openshift/5562dcd5500446389000024c/app-root/runtime/repo/node_modules/coinbase/lib/model/AccountBase.js:61:62)
at Request.onGet as _callback
at Request.self.callback (/var/lib/openshift/5562dcd5500446389000024c/app-root/runtime/repo/node_modules/coinbase/node_modules/request/request.js:344:22)
at Request.emit (events.js:98:17)
at Request. (/var/lib/openshift/5562dcd5500446389000024c/app-root/runtime/repo/node_modules/coinbase/node_modules/request/request.js:1239:14)
at Request.emit (events.js:117:20)
at IncomingMessage. (/var/lib/openshift/5562dcd5500446389000024c/app-root/runtime/repo/node_modules/coinbase/node_modules/request/request.js:1187:12)
at IncomingMessage.emit (events.js:117:20)
at _stream_readable.js:944:16
at process._tickCallback (node.js:442:13)

And the code is:

    var client   = new coinbase.Client({'apiKey': clientAcc.KEY1, 'apiSecret': clientAcc.KEY2});
    client.getAccounts({}, function(err, accounts) {
      accounts.forEach(function(acct) {
        console.log('matchAccountTxWithRequests. Balance: ' + acct.balance.amount + ' para ' + acct.name);
              var args = {
                'colName'  : 'deposits',
                'ObjFunc'  : Deposit,
              };
            acct.getDeposits(args,function(err, txs) {
              txs.forEach(function(txn) {
                console.log('matchAccountTxWithRequests. txn details (' +  clientAcc.ClientId + ',' +  acct.name + ') : ' + JSON.stringify(txn));
              });
            });
      });
    });

Any Idea?

GetAccounts always returns 403

I am trying to use client.getAccounts with OAuth accessToken and refreshToken, using wallet:accounts:read, but I am always getting a 403 error.

I tried to add the scopes wallet:accounts:create, wallet:accounts:delete, and wallet:accounts:update, but none of them allow me to retrieve the accounts.

var client = new Coinbase.Client({
    //_db is a json object containing the accessToken and the refreshToken

    "accessToken": _db.accessToken, 
    "refreshToken": _db.refreshToken,
    'baseApiUri': 'https://api.sandbox.coinbase.com/v1/',
    'tokenUri': 'https://api.sandbox.coinbase.com/oauth/token'
});

"The transaction fee has expired" on all transactions

coinbase-node 2.0.5

Every time I attempt to send BTC:

        account.sendMoney({
          to: payment.recipient,
          amount: payment.amount,
          fee: '0.0006',
          description: payment.note,
          currency: 'USD',
          idem: payment.idem
        }, cb)

I get this error:

 ValidationError: The transaction fee has expired.
     at handleHttpError (/app/node_modules/coinbase/lib/errorHandler.js:46:15)
     at Request.onPost [as _callback] (/app/node_modules/coinbase/lib/ClientBase.js:174:10)
     at Request.self.callback (/app/node_modules/coinbase/node_modules/request/request.js:344:22)
     at emitTwo (events.js:106:13)
     at Request.emit (events.js:191:7)
     at Request.<anonymous> (/app/node_modules/coinbase/node_modules/request/request.js:1239:14)
     at emitOne (events.js:101:20)
     at Request.emit (events.js:188:7)
     at IncomingMessage.<anonymous> (/app/node_modules/coinbase/node_modules/request/request.js:1187:12)
     at emitNone (events.js:91:20)
     at IncomingMessage.emit (events.js:185:7)
     at endReadableNT (_stream_readable.js:974:12)
     at _combinedTickCallback (internal/process/next_tick.js:74:11)
     at process._tickDomainCallback (internal/process/next_tick.js:122:9)

I thought at first perhaps the transaction fee was too low, so I upped it from 0.0001 to 0.0006. Also tried 0.0016. Same result.

Coinbase Status is all green when this is happening.

getSpotPrice ignores parameters.

Client.prototype.getSpotPrice calls an http request with only the currenceyPair paramter and forgets about the date parameter if it was included.

Do not require apikey and apisecret when using oauth in Client constructor

I use oauth for requests to the API via the Client object.

If i create a Client object like:

var Client = require('coinbase').Client;
var client = new Client({
                          'apiKey'       : " ",
                          'apiSecret'    : " ",
                          'accessToken'  : accessToken,
                          'refreshToken' : refreshToken
                        });

All calls work fine, meaning that the apiKey and apiSecret is ignored.

When I do:

var Client = require('coinbase').Client;
var client = new Client({
                          'accessToken'  : accessToken,
                          'refreshToken' : refreshToken
                        });

The "no apiKey" Error is thrown. To be honest the Error is not very helpful. I would appreciate a "CoinbaseError" Object to be thrown here. But anyhow. If an accessToken is set, why bother requiring a key 'apiKey' to be set? That does not really make sense to me.

Error getting accounts

I obtain this error when I get accounts listing:

no callback - check method signature

Any idea?

Thanks.

Put full docs online

You can generate html documentation by running the command:

npm install && npm run docs

Open generated html files in docs/ dir with a browser.

It would be nice if there was a public website with this, linked to in the README

ES6 Example

I was trying to get this to work with ES6 - Heres how:
Might be helpful for others if in the readme.

import { Client as client} from 'coinbase';

var coinbase = new client({
    <connection stuff here>
});

How to sell to USD wallet?

So I have the following

account.sell({"amount": account.balance.amount, "currency": account.balance.currency}, function(err, xfer) {

It works like a charm except for the whole bank processing wait. How do I tell it to gimme USD to a coinbase wallet?

Path fix

All paths should start with /path-name so base URI should lack trailing /

Cancel a recurring payment (subscription)

There doesn't seem to be a way to programmatically end a subscription through the API.

This is mostly useful for merchants if they want to manage their subscriptions on their end.

Please point me in the right direction if this functionality is somewhere available.

verifyCallback with Express

Hi, I'm trying to use the verifyCallback with Express.

The problem seems to be that I'm using bodyParser.json() app wide which populates req.body, but it doesn't make the raw_body available. Any way around this, like JSON.strigify(req.body)? Other ideas?

Thanks!

Missing query in the requestPath.

I have issue for pagination of package. I found it when generate CB-ACCESS-SIGN. We had missing query path for it.

Please update it.

Regards.

The new v.2.0.1 has a little bug

myAppPath\node_modules\coinbase\lib\model\Notification.js:
14
function Notification(client, data) {
^^^^^^^^

SyntaxError: Unexpected token function

It will be thrown just with:

var Client = require('coinbase').Client,

client = new Client({
    'apiKey': "apiKey", 
    'apiSecret': "apiSecret"
});

Pull request: #47

On buy, choose the address

An enhancement request I guess.

Is this possible? To instantly get your purchase in the wallet of your choice? (Local wallet)

json.parse not wrapped in try catch

Sometimes an html page is getting loaded instead of json as expected. Maybe the app is hitting a limit or it's proxy thing.

undefined:1
<!DOCTYPE html>
^
SyntaxError: Unexpected token <
    at Object.parse (native)
    at handleHttpError (/node_modules/coinbase/lib/errorHandler.js:43:38)
at Request.onGet [as _callback] (/node_modules/coinbase/lib/ClientBase.js:153:10)

etypes is not defined

I'm calling the refresh() method from the client using the access_token and refresh_token from a user, I want to refresh and store the new tokens.

I'm getting an HTTP error but the library cannot call the callback as it's expecting an import called etypes that's not there.

if (err) {
  err.type = etypes.TokenRefreshError;
  callback(err, result);
  return;
}

Module requires api key for first run on oAuth2

I've discovered a strange pattern, where the module has to be launched the first time with the apiKey and apiSecret, even if oAuth2 used.

Failure to includes these 2 leads to the infamous no apiKey error.

However after using the module with these parameters for the first time, the error goes away, i.e.:

return new Client({
 'apiKey'       : CLIENT_ID,
 'apiSecret'    : CLIENT_SECRET,
 'accessToken'  : accessToken,
 'refreshToken' : refreshToken
 });

That said, these parameters have to be removed on the next run, as otherwise it fails again with another error.

It seems as either Coinbase has to verify the machine the first time, or the module needs to cache some local data, to get it working?

getTransactions throw error

I want to get all of the transactions but when I try to do it get the error while doing everything by example

coinbase.getAccount('<My account id>', function(err, account) {
	account.getTransactions(function(err, txs) {
		//...
	});
});

Error

/root/coinbase/node_modules/coinbase/lib/errorHandler.js:60
  if (!callback) {throw "no callback - check method signature";}
                  ^
no callback - check method signature

getAddresses internal error

client.getAccount(id, function(err, account) {
account.getAddresses(function(err, addresses) {
console.log(addresses);
});
});
I'm trying to get all of my addresses for a wallet , the account is return correct but after that I get this error:
internal implementation error..

if i will use

account.getAddresses(null, function(err, addresses) {
console.log(addresses);
});
just found out is working but I can't convert the addresses object using JSON.parse() method.

SSL Error: https://api.coinbase.com/v2/accounts does not support SSL

I get this by following the accounts example in the README.

Error: SSL Error: https://api.coinbase.com/v2/accounts does not support SSL
    at Request.onRequestResponse (request.js:844)
    at module.exports.EventEmitter.emit (events.js:81)
    at module.exports.ClientRequest._connect (request.js:235)
    at request.js:128

Promisification trouble: TypeError: Cannot read property '_getOneHttp' of undefined

When I try to promisify this library with bluebird, I get the following error:

Unhandled rejection TypeError: Cannot read property '_getOneHttp' of undefined

This happens from bluebird's promisifyAll, and from manual promisification:

Unhandled rejection TypeError: Cannot read property '_getOneHttp' of undefined
    at Client.getAccount (/Users/dsernst/Documents/coinbase-fu/node_modules/coinbase/lib/Client.js:65:7)
    at tryCatcher (/Users/dsernst/Documents/coinbase-fu/node_modules/bluebird/js/release/util.js:11:23)
    at ret (eval at <anonymous> (/Users/dsernst/Documents/coinbase-fu/node_modules/bluebird/js/release/promisify.js:184:12), <anonymous>:13:39)
    at useCoinbase (/Users/dsernst/Documents/coinbase-fu/send-payments.js:123:45)

Here's the invoked line 123, the final line listed in the above stack trace, that leads to this problem:

return Promise.promisify(coinbase.getAccount)(coinbaseAccountId)
  .then(account => {

I've found I was able to fix this by changing it to:

return Promise.fromCallback(function(cb) {
  coinbase.getAccount(coinbaseAccountId, cb)
})
.then(account => {

The issue is resolved if I use this manual Promise.fromCallback method every time, but it would still be nice if this library could be improved to not require this, and we could just use .promisifyAll once when the library is first imported.

I also wanted to post this issue in case anyone else runs into the same problem.

Thanks 😄

OAuth creds to get application token

This is more of a question than a report.

I know you can use API creds to get an application level token:

var client = new Client({'apiKey': mykey, 'apiSecret': mysecret});

But when using OAuth, the same key names are used for client_id & client_secret

var client = new Client({
                          'apiKey'       : client_id,
                          'apiSecret'    : client_secret,
                          'accessToken'  : accessToken,
                          'refreshToken' : refreshToken
});

Does that mean you can use client_id & client_secret to get an application level token?

var client = new Client({'apiKey': client_id, 'apiSecret': client_secret});

Thanks

No cb-version?

Hi, noticed a few odd things:

  1. The notification header X-Signature described in the README does not exist, but instead a cb-signature header contains the signature.
  2. The notification header cb-version says BETA
  3. No default API verison seems to be set unless it is provided by the user, yet nothing in the README suggests this. I would expect the version to automatically be set to the date that the version of coinbase-node I'm using was released, or to a version which is known to work with that library version.
  4. Tried to set the version of the API to 2016-01-04 (the date version 2.0.2 was released), but the callback notification is still sent back with the same headers described in 1) and 2)

Am I doing something wrong?

Error in createAddress: typo in the coinbase doc

This API call will throw the following error, both with sandbox mode and not:

App\node_modules\coinbase\lib\errorHandler.js:55
if (!callback) {throw "no callback - check method signature";}

Test code:

client.getAccount('accountID', function(err, account) {
    if (err) return console.error(err);

    account.createAddress(function(err, address) { //the error is thrown here
        console.log(arguments); //debug
    });
});

Update:

I saw in the code that account.createAddress() requires the first argument to be null but your doc shows a different code, so there is a little typo in the API reference

Separate api access code base from oauth code base completely

Just a suggestion: Why don't you create two packages in npm for coinbase? One that does solely oauth requests and the other one with apikey / secret.

Currently it is really confusing when trying to set it up with using oauth because for example one has to set the param "apiKey" to what is actually the "Client ID" (at least I guess so).

Please elaborate a little on how the design is envisioned to be. I think there might be even security reasons not to mix the functionality.

How to create an address

This is how I tried to prototype the method:

var coinbase = require("coinbase");

coinbase.Client.prototype.createAddress = function(args, callback) {
    var opts = {
        'path' : 'accounts/' + args.userId + "/addresses",
        'params'  : args
    };

    this._postOneHttp(opts, callback);
};

var client = new coinbase.Client({
    'apiKey': "myApiKey",
    'apiSecret': "MyApiSecret",
    'baseApiUri': 'https://api.sandbox.coinbase.com/v2/',
    'tokenUri': 'https://api.sandbox.coinbase.com/oauth/token'
});

var args = {
    "userId": "MyAccountID",
    "name": "MyAddressName"
};

client.createAddress(args, function(err, response) {
    if (err) return console.log(err);

    console.log(response);
});

And the error I got:

 undefined:1
 <!DOCTYPE html>
 ^

SyntaxError: Unexpected token <

Upgrade to API v2

Hi,

Do you plan to switch to the v2 API? The coinbase developers docs recommend to switch to it. Is there an issue to keep using the library in v1?

Thanks! :)

Node supported versions upgrade (ES6 & Promises)

Node 0.10, 0.11 and 0.12 have reached end-of-life.

The ES6 features that Node 4 does not support is small. The repo could be using ES6 classes.

$ node -v
v4.0.0

node --v8-options | grep "in progress"
  --harmony_modules (enable "harmony modules" (in progress))
  --harmony_array_includes (enable "harmony Array.prototype.includes" (in progress))
  --harmony_regexps (enable "harmony regular expression extensions" (in progress))
  --harmony_proxies (enable "harmony proxies" (in progress))
  --harmony_sloppy (enable "harmony features in sloppy mode" (in progress))
  --harmony_unicode_regexps (enable "harmony unicode regexps" (in progress))
  --harmony_reflect (enable "harmony Reflect API" (in progress))
  --harmony_destructuring (enable "harmony destructuring" (in progress))
  --harmony_sharedarraybuffer (enable "harmony sharedarraybuffer" (in progress))
  --harmony_atomics (enable "harmony atomics" (in progress))
  --harmony_new_target (enable "harmony new.target" (in progress))

And Promises are almost fully supported since v4. features table

I could find the time to submit a PR if this sounds good.

Status Code 504 from coinbase causes uncaught error.

Hey, I'm getting a 504 from Coinbase on a rare occasion and it crashes my stack. Obviously, I could just wrap the call in a try catch but the underlying issue should be fixed.

I ran the request module in debug mode to find find the issue and here's the relevant parts.

REQUEST finish init function https://api.coinbase.com/v2/accounts/<MY UUID>
REQUEST response end https://api.coinbase.com/v2/accounts/<MY UUID> 504 { server: 'cloudflare-nginx',
  date: 'Sun, 28 Feb 2016 03:07:39 GMT',
  'content-type': 'text/html; charset=UTF-8',
  'transfer-encoding': 'chunked',
  connection: 'keep-alive',
  'set-cookie': [ '__cfduid=aoeu; expires=Mon, 27-Feb-17 03:07:39 GMT; path=/; domain=.coinbase.com; HttpOnly' ],
  pragma: 'no-cache',
  'x-frame-options': 'SAMEORIGIN',
  'strict-transport-security': 'max-age=15552000; includeSubDomains; preload',
  'x-content-type-options': 'nosniff',
  'cf-ray': '27b8eba251800874-IAD' }
REQUEST end event https://api.coinbase.com/v2/accounts/<MY UUID>
REQUEST has body https://api.coinbase.com/v2/accounts/<MY UUID> 197830
REQUEST emitting complete https://api.coinbase.com/v2/accounts/<MY UUID>

SyntaxError: Unexpected token <
    at Object.parse (native)
    at handleHttpError (/home/ec2-user/server/node_modules/coinbase/lib/errorHandler.js:43:38)
    at Request.onGet [as _callback] (/home/ec2-user/server/node_modules/coinbase/lib/ClientBase.js:155:10)
    at Request.self.callback (/home/ec2-user/server/node_modules/coinbase/node_modules/request/request.js:344:22)
    at Request.emit (events.js:98:17)
    at Request.<anonymous> (/home/ec2-user/server/node_modules/coinbase/node_modules/request/request.js:1239:14)
    at Request.emit (events.js:117:20)
    at IncomingMessage.<anonymous> (/home/ec2-user/server/node_modules/coinbase/node_modules/request/request.js:1187:12)
    at IncomingMessage.emit (events.js:117:20)
    at _stream_readable.js:944:16

The coinbase-ruby project seemed to have this issue a while back (coinbase/coinbase-ruby#16)

The issue is that at:
https://github.com/coinbase/coinbase-node/blob/master/lib/errorHandler.js#L40, the error case assumes that the content-type is text/json when it's text/html.

I'll probably just submit a pull request to fix this in a few days.

transferMoney return a 404 error

When calls to transferMoney method in Account class I obtain a statuscode 404 error.

I'm trying to send BTC to an address in other account of coinbase.

Can't get notifications

Code:

coinbase = new require('coinbase')
client = coinbase.Client({
    apiKey: process.env.COINBASE_API_KEY
    apiSecret: process.env.COINBASE_API_SECRET
})
client.getNotifications({}, (err, notifications) ->
    console.log(notifications)
)

Error:

/Users/user/Work/smoothkeyscroll-node-server/node_modules/coinbase/lib/ClientBase.js:250
        return new ObjFunc(self, obj);
               ^

TypeError: ObjFunc is not a function
  at onMap (/Users/user/Work/smoothkeyscroll-node-server/node_modules/coinbase/lib/ClientBase.js:250:16)
  at arrayMap (/Users/user/Work/smoothkeyscroll-node-server/node_modules/coinbase/node_modules/lodash/index.js:1377:25)
  at Function.map (/Users/user/Work/smoothkeyscroll-node-server/node_modules/coinbase/node_modules/lodash/index.js:5891:14)
  at onGet (/Users/user/Work/smoothkeyscroll-node-server/node_modules/coinbase/lib/ClientBase.js:249:20)
  at Request.onGet [as _callback] (/Users/user/Work/smoothkeyscroll-node-server/node_modules/coinbase/lib/ClientBase.js:158:9)
  at Request.self.callback (/Users/user/Work/smoothkeyscroll-node-server/node_modules/request/request.js:344:22)
  at emitTwo (events.js:87:13)
  at Request.emit (events.js:172:7)
  at Request.<anonymous> (/Users/user/Work/smoothkeyscroll-node-server/node_modules/request/request.js:1239:14)
  at emitOne (events.js:82:20)
  at Request.emit (events.js:169:7)
  at IncomingMessage.<anonymous> (/Users/user/Work/smoothkeyscroll-node-server/node_modules/request/request.js:1187:12)
  at emitNone (events.js:72:20)
  at IncomingMessage.emit (events.js:166:7)
  at endReadableNT (_stream_readable.js:905:12)
  at nextTickCallbackWith2Args (node.js:474:9)
  at process._tickCallback (node.js:388:17)

ERROR: exit status 1

Any idea why this is happening? Also having problems with the python client: coinbase/coinbase-python#18

Client.refresh should set internal params to new values

The refresh function on the Client uses the refreshToken to get a new pair of tokens. It does return an object with the values so the user can use it. If the user continues to use the same Client object, it will however use the old token pair. It should (additionally to returning) be set to the new values by the refresh function. I cannot see any use case were the old pair needs to be stored.

How to send bitcoins from multiple accounts to multiple addresses in one call ?

This feature seems to not to be implemented in the APIs.
Is there a plan date to when to add it? Maybe V3 ?

This may help to reduce TX fees for sendings from multiple accounts to multiple bitcoin addresses

Example call:

client.getAccounts('account1,account2', function(err, accounts) {
    accounts.sendMoney({'to': 'address1,address2,address3',
            'amounts': '0.1,0.05,1.8',
            'currency': 'BTC'}, function(err, tx) {
                console.log(tx);
            });
    });
});

Address.getTransactions is bugged

This is how I tried:

var Address = require('coinbase').model.Address,

client.getAccount("myAccountID", function(err, account) {
    if (err) return console.log(err);

    var address = new Address(client, {id: "myAddress"}, account);

    address.getTransactions(null, function(err, transactions) {
        if (err) return console.log(err);

        console.log(transactions);
    });
});

The error I got:

myAppPath\node_modules\coinbase\lib\model\Address.js:33
    'ObjFunc'  : Transaction,
             ^

ReferenceError: Transaction is not defined
    at Base.Address.getTransactions (myAppPath\node_modules\coinbase\lib\model\Address.js:33:18)
etc..

Due that the method seems to be bugged, I tried to prototyping a new similar method with:

var Address = require('coinbase').model.Address,
    Transaction = require('coinbase').model.Transaction,
    _           = require('lodash');

Address.prototype.getAllTransactions = function(args, callback) {
    var opts = {
        'colName'  : 'addresses/' + this.id + '/transactions',
        'ObjFunc'  : Transaction,
    };

    this.account._getAll(_.assign(args || {}, opts), callback)
};

This time, the error got is:

myAppPath\node_modules\coinbase\lib\model\AccountBase.js:61
  var ObjFunc = self.client._stringToClass(result.data[0].resource);
                                                         ^

TypeError: Cannot read property 'resource' of undefined
    at onGet (myAppPath\node_modules\coinbase\lib\model\AccountBase.js:61:62)
    at Request.onGet [as _callback] (myAppPath\node_modules\coinbase\lib\ClientBase.js:158:9)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.