Code Monkey home page Code Monkey logo

coinbase's People

Contributors

astrohart avatar aymericnoel avatar bchavez avatar bheesbeen avatar elanhasson avatar granthoff1107 avatar mitchcapper avatar pethical avatar ryanmwilliams 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

coinbase's Issues

Architecture Discussion For v6

I was trying to integrate refresh tokens when I came across some issues.
The Architecture changes I'm going to propose should probably be for the next version v6 and not for now. I'm a bit confused on why the coinbase is inheriting from the FlurlClient.
This is creating a hard dependency on the FlurlClient. The client is subject to be changed (e.g) the last version was using RestSharp Client Perhaps their should be a protected property instead for the client, to abstract the depedency.

The current architecture makes it difficult to modify the request control flow, if someone wanted to catch an error such as expired_token, currently they would have to wrap every request made.

If the endpoints were made properties, and all inherited from the same base interface/ class, a builder could be used to construct the request, and the base class could have an execute function (similar to the prior version) which could be overridden to make it easier to change the control of each request.

For now I'm going to integrate the beta with my api.
lets discuss this more when you get a chance

Transfer between money accounts not possible

Version Information

Software Version(s)
NuGet Package 5.1.2
.NET Full Framework? 4.7.2
Windows OS? Win10
Visual Studio? 2019

What's the problem?

I try to transfer money from my bitcoin account to my etherium account. When i to this i get no exception but the response data are null. What i make wrong?
Now transfer of currency work in my fall. I alos tryed BTC to USDC.

I do this with follwing code:

CreateTransfer trans = new CreateTransfer();
trans.Amount = 1;
trans.Currency = "EUR";
trans.To = "accountID of ETH"

var transBTCToETC = await ApiClient.Transactions.TransferMoneyAsync("accountID of BTC",trans);

Also i have all permission in the api for this.
My Apikey and Secretkey also work. I can get my profile.

So what i make wrong by the transfer?

404 Not Found on Sells Endpoint

Hi,
I am getting

Call failed with status code 404 (Not Found): POST https://api.coinbase.com/v2/accounts/sells

from the server. I run the following code (assume the params have been initialized correctly):

var sellTask = _client.Sells.PlaceSellOrderAsync(e.AccountId,
    placeSell, CancellationToken.None);
sellTask.Wait();
var sell = sellTask.Result;

I think Coinbase may have updated their REST API syntax and the code in this library has not been updated yet. The docs say that the endpoint is:

POST https://api.coinbase.com/v2/accounts/**:account_id**/sells

I have a hunch that the code is not passing the account id.

Error when creating sell order

I'm trying to place sell order but I'm getting this error

Flurl.Http.FlurlParsingException: Response could not be deserialized to JSON: POST https://api.coinbase.com/v2/accounts/f456a09d-7116-5215-93f9-fba8e492967e/sells ---> Newtonsoft.Json.JsonSerializationException: Error converting value {null} to type 'System.DateTimeOffset'. Path 'data.created_at', line 1, position 177. ---> System.ArgumentException: Could not cast or convert from {null} to System.DateTimeOffset.

Version: 5.0.4
Newtonsoft.JSON version: 11.0.2 (also tried 12.0.1)

Error Handling should occur internally

This relates to Issue #33. I made a mistake in say that AllowAnyHttpStatus should be allowed.
When Making a request to an api endpoint, if the request succeeds the end user won't have anyway of knowing with out manually checking if there are errors.

    //pseudo
    var transactions = await client.Transactions.GetListAsync();
    if(false == transactions.Data.Any())
    {
          Print("No Transactions")
    }

This would be bad because if the user forgets to check the error like above, the application would be under the impression that you have no transactions, when in reality their could be an error/

Ideally we can implement an internal error handler which will parse the Errors json and throw an appropriate exception based on the error code e.g if the error Id = invalid_scope. the user would know to make its oauth request with the proper scopes next time.

This seems like a larger change so perhaps it might make sense to create a dummy global exception handler, e.g

    public CoinbaseApiException(Error[] errors) : Exception
    {
          Error[] errors
          public CoinbaseApiException(errors)
          {
             this.errors = errors;
          }
    } 

Error 404 when doing a TransferMoney

Hi! I'm programming a Small Application in VB.NET with coinbase DLL.
I want to convert my BTC currencies into ETH, and I use the TransferMoneyAsync function as follows:

Private Sub Transfer_Coin (Origin As String, Destinity As String, Qty As Double)

    Dim config As New ApiKeyConfig With {
        .ApiKey = "XXXX",
        .ApiSecret = "YYYY"
    }
    Dim client As New CoinbaseClient(config)

    Dim c As New CreateTransfer With {
        .Type = "transfer",
        .To = adressdir(Destinity),
        .Amount = Qty,
        .Currency = Origin
    }

    Try
        Dim ResultTrans = client.Transactions.TransferMoneyAsync(adressdir(Origin,c))
        ResultTrans.Wait ()
        Dim a = ResultTrans.Result
        Debug.Write(a.Data.Status)
    Catch ex As Exception
    End Try

End Sub

EXAMPLE: Transfer_Coin("BTC","ETH",0.0005)

when I get to the accountlist.result step, it gives me an exception 404 - NOT FOUND. Maybe i'm doing something wrong?
I appreciate any idea. Tank you very much!

Money class only handles currency amounts that are in decimal

Hi,

In the Money class, you put the type of the Amount property as Decimal. However, this is only valid for, e.g., USD, GBP, EUR etc. currencies. For Bitcoin, and other cryptos, the quantity of the currency you have is actually a floating-point number. You should change the type of this property to float or double.

FlurlParsingException when parsing created_at field from ListAccountsAsync()

In my application I am attempting to iterate over each account and read in transaction data. During the API call I am getting this exception when the 'created_at' field is being parsed:

Flurl.Http.FlurlParsingException

Response could not be deserialized to JSON: GET https://api.coinbase.com/v2/accounts

Newtonsoft.Json.JsonSerializationException

Error converting value {null} to type 'System.DateTimeOffset'. Path 'data[7].created_at', line 1, position 4571.
Flurl.Http.Configuration.NewtonsoftJsonSerializer in Deserialize within Flurl.Http, Version=2.4.0.0, Culture=neutral, PublicKeyToken=null
Flurl.Http.HttpResponseMessageExtensions+d__0`1 in MoveNext within Flurl.Http, Version=2.4.0.0, Culture=neutral, PublicKeyToken=null
System.ArgumentException

Could not cast or convert from {null} to System.DateTimeOffset.

In my code I am trying to retrieve the accounts by calling:
var accountsResponse = await client.Accounts.ListAccountsAsync();

Am I doing something incorrect with this usage?

Request Money is not working

The request money is not working. I tried this:

> var accounts = await client.Transactions.RequestMoneyAsync(accountId, new RequestMoney
>             {
>                 To = email,
>                 Type = "request",
>                 Amount = amount,
>                 Currency = coinType,
>                 Description = description
>             });
> var result = coinBase.RequestPayment("myaccountid", "[email protected]", 0.01, "BTC",null).Result;

It throwing an exception:

Unhandled Exception: System.AggregateException: One or more errors occurred. ---> Flurl.Http.FlurlHttpException: Call failed with status code 400 (Bad Request): POST https://api.coinbase.com/v2/accounts/******/transactions
at Flurl.Http.FlurlRequest.d__23.MoveNext()

OAuth Auth Refresh Tokens

I'll create a pull request for this this weekend, but lets discuss the specs,
Basically when a token expired 2 things should happen.

1. The Token internally refresh and replays the last request.
2. We need a call back or an external event so the user can update their user information appropriately.

Specs:

When a user's token expires the server will return 401 Error with an id  expired_token, 
Send a request to the Coinbase OAuthEndpoint 

    POST https://api.coinbase.com/oauth/token
    Body: {
         refresh_token  : "34t703948twdfuhgsdofigheiosfghsoidhgier"
         grant_type: "refresh_token"
    }

The Server will response:

"access_token": "regjworigjwoerigjpworegjodspfjgospfijgweoprijg",
"token_type": "bearer",
"expires_in": 7200,
"refresh_token": "lkdfgadlkgheaklrherthiuhidsuhidfuh",
"scope": "wallet:accounts:read wallet:addresses:read",
"created_at": 1541870695

Price is not Updating

What is the expected behavior?

The exchange rates change

What is the actual behavior?

The exchange rates are staying the same forever

Any possible solutions?

private async Task<decimal> GetSpotPrice(string selector)
        {
            //anonymousClient = new CoinbaseClient();
            Response<Money> buyPriceResponse = await anonymousClient.Data.GetBuyPriceAsync(selector);
            Response<Money> sellPriceonRateResponse = await anonymousClient.Data.GetSellPriceAsync(selector);
            decimal buyPrice = buyPriceResponse.Data.Amount;
            decimal sellPrice = sellPriceonRateResponse.Data.Amount;
            decimal midMarket = (buyPrice + sellPrice) / (decimal) 2;
            return midMarket;
        }

How do you reproduce the issue?

CoinbaseClient anonymousClient = new CoinbaseClient();
private static async void GetSpotPrices(string selector)
{
    while (true) 
    {
        CoinBaseClient coinBaseClient = new CoinBaseClient();
        Task<decimal> getPrice = coinBaseClient.GetSpotPrice(selector);
        decimal price = await Task<decimal>.Run(() =>getPrice);
        getPrice.Dispose();
        Tensor.AddPrice(price);
        Thread.Sleep(1000);
    }
}
private async Task<decimal> GetSpotPrice(string selector)
{
    Response<Money> conversionRateResponse = await anonymousClient.Data.GetSpotPriceAsync(selector);
    decimal conversionRate = conversionRateResponse.Data.Amount;
    return conversionRate;
}

Can you identify the location in the source code where the problem exists?

The Rest Api might cash the prices

If the bug is confirmed, would you be willing to submit a PR?

Yes / No (Help can be provided if you need assistance submitting a PR)

Api Maintains state when reusing endpoint

The Api Endpoint maintain the old URL Segments from past requests:

        var apiConfig = new ApiKeyConfig();
        apiConfig.ApiKey = apiKey;
        apiConfig.ApiSecret = apiSecret;

        var coinbaseApi = new CoinbaseApi(apiConfig);
        var apiAccounts = await coinbaseApi.Accounts.ListAccountsAsync();
        var apiAccount = apiAccounts.Data.FirstOrDefault(x => x.Name == "ETH Wallet");
        var apiAddresses = await coinbaseApi.Addresses.ListAddressesAsync(apiAccount.Id);
        var apiAddress = apiAddresses.Data.FirstOrDefault();
        var transactions = await coinbaseApi.Transactions.ListTransactionsAsync(apiAccount.Id);

In this senario transactions will 404 because Transactions internally uses the Accounts api,

     return this.AccountsEndpoint
        .AppendPathSegments(accountId, "transactions")
        .WithClient(this)
        .GetJsonAsync<PagedResponse<Transaction>>(cancellationToken);

AppendPathSegments will cause the internal endpoints to maintains the state, so the previous requests will have the old path segments. This seems like a larger architecture change but it probably could be solved by changing the Endpoint types from Url to Func

and then just initializing like so:

     this.AccountsEndpoint = () => this.config.ApiUrl.AppendPathSegment("accounts");
     this.PaymentMethodsEndpoint = () => this.config.ApiUrl.AppendPathSegment("payment-methods");
     //...

Coinbase : Callbacks status " Expired"

@bchavez:

In the current Coinbase API, under Coinbase\ObjectModel\Status.cs should have this option also as if the Coinbase didn't receive any payments for the Order within 10 minutes of its generation. Means if an "Expired" Order receives a payment, the Order will remain "Expired" but will have Mispayments associated with it.

And moreover Coinbase will not have sent the merchant any order-completed callbacks for "Expired" orders so if the merchant is counting on these callbacks to complete the order fulfilment or refund process, they'll have to MANUALLY perform this step.

Please think over it and if it should be there, then update the API.

Creating a new invoice

The implementation i have read is confusing, how do i create an invoice with asp.net core.
PS: Dynamic invoice

Suggestion to add a way to disable Fiddler proxy

Context

Sometimes I want to debug my bot by utilizing Fiddler to look at the HTTP proxy. My bot runs as a Windows Service. I detect if Fiddler.EXE process is running in my service, and if so, enable the proxy automatically.

API calls sometimes won't work if Fiddler proxy is enabled but then the Fiddler.EXE is closed. I want to be able to open and close the Fiddler.EXE GUI and have my service be able to detect this on the fly, and enable/disable the Fiddler proxy dynamically. It may be the case that I get done debugging and I want to then close the Fiddler GUI (since it IS decrypting my HTTPS traffic, after all!).

My concern is, after I'm done debugging with Fiddler but I want to keep my bot running, the bot will fail in its next API call because Fiddler is enabled on the CoinbaseClient (via a call to the CoinbaseClient.EnableFiddlerProxy method) but the Fiddler.EXE is not running.

My suggestion is to make a property FiddlerProxyEnabled (of type bool) and/or make a DisableFiddlerProxy method.

Alternatives

Of course, when I close Fiddler, I can always go in and restart my service via the Services control panel. Then it will detect that the Fiddler.EXE has been closed. However, this is a pain.

Has the feature been requested before?

Not to my knowledge.

If the feature request is approved, would you be willing to submit a PR?

Yes

Async support

I was unable to find async versions of methods in the library, am I missing them or has this not been added yet?

Question: How to work with PagedResponses?

My apologies if has been documented somewhere but I wasn't able to find an example or best practices when working with the PagedResponse object. Right now, I am trying to retrieve all Buys from an account that has more buys than can be returned in a single page.

Using this library, is the best approach to:

  1. Initially list the buys
  2. Get the NextUri from that response
  3. Make all subsequent requests using client.HttpClient

Or is it possible to do this in a more graceful way that has already been implemented?

var buyResponse = await client.Buys.ListBuysAsync(account.Id);
var nextUri = buyResponse.Pagination.NextUri;

while (!string.IsNullOrEmpty(nextUri))
{
    var nextPage = await client.HttpClient.GetAsync(nextUri);

    // Deserialize

    // Check For Next URL
}

Thanks!

Quick Run down of Webhooks

I'm a bit confused on how the webhooks work. I would like to subscribe to notifications for when a transaction completes.

I see there is a section for webhooks but I don't see where I would pass the callback url to coinbase.
If you have time can you give me a quick run down on how, webhooks work.

Adding Validations

We should Add validations for certain things such as creating transactions.
When creating transactions amounts should be fixed at 8 decimal places, etc

Sell Coins

Is there any work going forward to build in to sell coins and have them deposited to a bank account associated with a coinbase account? If not, what is the process to be able to contribute to the base? I have not ever done that before, but as you have helped with other parts would not mind giving some back.

Convert Between Coins With API

Has any api documentation been found that outlines how you can convert between coins? I have only seen this in the web and app interface and can find no API reference.

Mispaid fields

Hi Brian, could you please add a couple of fields to the Order object?

  • mispaid_btc
  • mispaid_native

Optionally, someone may benefit from the mispayments array too.

Thanks a lot!
Alex

iFrame - Stopped working within website suddenly

@bchavez :
Today we are getting strange issue, even with Live implementation for Coinbase, with iFrame binding in our website payment page. Instead of displaying the bitcoin address on which bitcoin payment accepted, it is displaying below message:

X This content cannot be displayed in a frame
To help protect the security of information you enter into this website, the publisher of this content does not allow it to be displayed in a frame.

What you can try:
Open this content in a new window

Attached the Actual and Strange behaviors of coinbase iFrame recently.

Please guide us to get over this behavior. Thanks in advance.
coinbase actual iframe
coinbase iframe

Support For DI

I know we briefly discussed this before, but I think we should reconsider support for DI. I have 3 projects I'm using the API and OAuth in. And I've found myself duplicating the class and interface definitions in each project. I'm tempted to move it into a shared assembly between the projects.

public interface ICoinbaseApiClient : ICoinbaseClient
{
}

public class CoinbaseApiClient: CoinbaseClient, ICoinbaseApiClient
{
    public CoinbaseApiClient(ApiKeyConfig config): base(config)
    {
    }
}

public interface ICoinbaseOAuthClient : ICoinbaseClient
{
}

public class CoinbaseOAuthClient : CoinbaseClient, ICoinbaseOAuthClient
{
    public CoinbaseOAuthClient(OAuthConfig config) : base(config)
    {
    }
}

I should have small pull request upcoming for notifications,
If you reconsider I'll add the support for DI,
let me know what you think.

Coinbase : Issue while checking Order Status using API's GetOrder method

As we recently completed Coinbase API integration in our website and tested locally and PRODUCTION also for the iFrame generation and integration within our website, it worked good. But suddenly raising exception when we are trying to get the Order status in the code using API's api.Getorder() . To cross check the behavior in dev environment locally, the issue is there too.

{
string inventCustomID = "CustID" ;---testing
var api = new CoinbaseApi(apiKey: "LIVEKEYID", apiSecret: "LIVEKEYSECRET");
var orderResult = api.GetOrder(inventCustomID);
..........
}
No clue on this sudden and strange behavior. Attached the screen-shots for this behavior. Please guide us to get over this behaviour.
coinbase api exception
coinbase api exception2

Thanks,MaruthiPrasad A

Can't place buy orders

I am utilizing the very latest version of this library. It's excellent! However, I try to place a buy order for an amount of Bitcoin with it, and I keep getting 400 Bad Request from the server.

I think I know why. The example on the site https://developers.coinbase.com/api/v2#place-buy-order says that the request body is supposed to be:

{
	"amount": "10",
	"currency": "BTC",
	"payment_method": "83562370-3e5c-51db-87da-752af5ab9559"
}

Notice how the quantity of BTC to buy is in quotes, i.e., is a string type. However, in your PlaceBuy object, I see that the Amount property is a decimal, and I did some digging in the exception and managed to dig up the request body that I am sending as such:

{
	"amount": 0.30807114,
	"currency": "BTC",
	"payment_method": "1cc4f84e-dee5-54e3-a226-c3f5ad1aae11",
	"agree_btc_amount_varies": true,
	"commit": true,
	"quote": false
}

The emphasis is mine, obviously. But notice the discrepancy. The docs want the amount of BTC as a JSON String, but your library is sending it out as a JSON number type. I think there is a bug.

How do we get this fixed? Thanks! :-)

Create New Address

i using code : api.SendRequest("wallet/MyWalletID/addresses", Method.POST);
but it return Address existing, this is not new address.
please help me.

Mispaid order status

When the amount paid is less than the order amount, then the callback status is "mispaid" which doesn't bind right.

Support for Expand

We should add support for Expand, which allows you to expanding the response data.
This will help api's create less latency when making requests.

e.g Say you want to obtain all the Accounts with the addresses.

Currently the only way to do so would be to make Several requests
First obtain the Accounts. => 10 Accounts.
Then obtain the Addresses which would require 10 additional requests.

But Ideally we should support expand to for all entities.
I have a suspicion that this will aid in obtaining user notification from the api, but I haven't tested yet.

This should go into consideration for v6.

-Grant

Access to the Raw response from the API

There is no way to access the request made by the api. e.g if I would like to obtain the response code and the Errors it difficult. e.g

If I were to make a request to obtain send money:

var resp = await this._coinbaseOAuthClient.AllowAnyHttpStatus()
                        .WithHeader("CB-2FA-TOKEN", paymentTransaction.TwoFactorCode)
                        .AllowAnyHttpStatus()
                                    .Transactions
                                    .SendMoneyAsync(paymentTransaction.AccountId, transaction);

The response returns a 402 requires payment. But if I allow any http status I'm not sure of a way to obtain the response or have access to the raw request.

If I were to wrap not allow any httpstatus:

try{
    var resp = await this._coinbaseOAuthClient.AllowAnyHttpStatus()
                        .WithHeader("CB-2FA-TOKEN", paymentTransaction.TwoFactorCode)
                        .AllowAnyHttpStatus()
                                    .Transactions
                                    .SendMoneyAsync(paymentTransaction.AccountId, transaction);
}
catch (FlurlHttpException ex) {
     
}

There's no easy way to obtain the error inside of the response.

Could not create SSL/TLS secure channel

Hi, we get this error on some orders in RegisterButton. Other orders go through fine. Do you know what could cause it?

The request was aborted: Could not create SSL/TLS secure channel.

Thanks!
Alex

I keep on getting invalid signature on coinbase api with curl php

`<?php
$time = time();
$method = "GET";
$path = '/v2/accounts';
$sign = base64_encode(hash_hmac("sha256", $time.$method.$path, $api_secret));

$headers = array(
"CB-VERSION: 2018-12-23"
"CB-ACCESS-SIGN: ".$sign,
"CB-ACCESS-TIMESTAMP: ".$time,
"CB-ACCESS-KEY: ".$api_key,
"Content-Type: application/json"
);

$ch = curl_init('https://api.coinbase.com'.$path);

curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);

if(curl_errno($ch))
{
echo ': '.curl_error($ch);
}
else
{
var_dump($result);
}

curl_close($ch);

?>`

Please help me fix this

Signature fails

I had a problem with some data which failed to sign correctly (refused by Coinbase), but I found the issue:
Lines 64+ of CoinbaseApi.cs should be rewritten as follow (UTF8 instead of ASCII):

    internal static string GetHMACInHex( string key, string data )
    {
        var hmacKey = Encoding.UTF8.GetBytes( key );

        using( var signatureStream = new MemoryStream( Encoding.UTF8.GetBytes( data ) ) )
        {
            var hex = new HMACSHA256( hmacKey ).ComputeHash( signatureStream )
                .Aggregate( new StringBuilder(), ( sb, b ) => sb.AppendFormat( "{0:x2}", b ), sb => sb.ToString() );

            return hex;
        }
    }

Coinbase : Issue with upgrade to latest version 0.3.11.

As suggested we tried to pull the coinbase latest using Nuget for version 0.3.11, we are experiencing the below issue while creating payment button programmaticlly for Live like below :
var api = new CoinbaseApi(CoinbaseApiKey,CoinbaseApiSecret,useSandbox:false,proxy:null);
var paymenRequest = new ButtonRequest
{
Name = "Sample Text",
Currency = currencySign,
Price = total,
Type = ButtonType.BuyNow,
Custom = inventID,
Description = "Sample Desc",
Style = ButtonStyle.CustomLarge,
CallbackUrl = CallbackURL,
CancelUrl = CancelURL,
InfoUrl = InfoURL,
SuccessUrl = SuccessURL,
};
var buttonResponse = api.RegisterButton(paymenRequest);
coinbase latest upgrade issue

Exception using WithAutomaticOAuthTokenRefresh

Version Information

Software Version(s)
NuGet Package 5.1.2
.NET Core? 5.1
.NET Full Framework?
Windows OS? 10
Linux OS?
Visual Studio? 2019

What is the expected behavior?

Pulling a refresh token due to unauthorized call.

What is the actual behavior?

System.NotSupportedException: Serialization and deserialization of 'System.Type' instances are not supported and should be avoided since they can lead to security issues. Path: $.Call.FlurlRequest.Client.Settings.BeforeCallAsync.Method.ReturnParameter.Member.DeclaringType.
 ---> System.NotSupportedException: Serialization and deserialization of 'System.Type' instances are not supported and should be avoided since they can lead to security issues.
   at System.Text.Json.Serialization.Converters.TypeConverter.Write(Utf8JsonWriter writer, Type value, JsonSerializerOptions options)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   --- End of inner exception stack trace ---
   at System.Text.Json.ThrowHelper.ThrowNotSupportedException(WriteStack& state, NotSupportedException ex)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCoreAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteCore[TValue](JsonConverter jsonConverter, Utf8JsonWriter writer, TValue& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteAsyncCore[TValue](Stream utf8Json, TValue value, Type inputType, JsonSerializerOptions options, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.Policy.AuthorizationMiddlewareResultHandler.HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Any possible solutions?

How do you reproduce the issue?

Do you have a unit test that can demonstrate the bug?

Can you identify the location in the source code where the problem exists?

If the bug is confirmed, would you be willing to submit a PR?

Yes / No (Help can be provided if you need assistance submitting a PR)

'Could not load type 'Flurl.Http.HttpCall' from assembly 'Flurl.Http

Version Information

Software Version(s)
NuGet Package 5.1.2.0
.NET Core? idk
.NET Full Framework? 4.7.2
Windows OS? last stable build
Linux OS? no
Visual Studio? last stable version

What's the problem?

'Could not load type 'Flurl.Http.HttpCall' from assembly 'Flurl.Http, Version=3.0.1.0, Culture=neutral, PublicKeyToken=null'.'

What possible solutions have you considered?

reinstalling framework, debugging to make sure the API key and secret API key is working

Do you have a sample code to show what you're trying to do?

image

What is the HTTP request JSON and response JSON?

image

GetNextPageAsync on ICoinbaseClient

Hi, I have just started using this library and I was wondering if there was any plan to include methods like GetNextPageAsync on the ICoinbaseClient interface?

GetNextPageAsync is quite useful, but it's not something that can be used when injecting a ICoinbaseClient instead of CoinbaseClient.

Thank you for this, it's been really nice to use so far!

Trying to expand your API and getting Signature Problems

Thanks for your work:) I figured I would work to add some more methods to it, starting with order listing:
https://github.com/mitchcapper/Coinbase/tree/ApiOrderListing / mitchcapper@14514ff

I am getting "authentication_error" with "invalid signature" on the request. Fetching time, or using your built in requests work but for some reason the order listing does not. The API key has permission (gives a different error otherwise) and the keys are correct for the other requests to work. Unfortunately I am not sure what I am missing. As it seems just doing the get request to orders using the system causes the error even looking at other apis I am not sure.

Parameter Ignored on Exchange-Rates Call

According to the Coinbase API, the call for current exchange rates
GET https://api.coinbase.com/v2/exchange-rates
allows an optional parameter to specify the base currency. If this parameter is not provided, the default is USD.

However when using this library to make such a call, any supplied "currency" value is ignored.

Here is example code using this Coinbase library (based on a similar example found in the README):

var api = new CoinbaseApi(ApiKey, ApiSecretKey, useSandbox: false, proxy: null, useTimeApi: false);
var options = new
{
    currency = "BTC"
};

var response = api.SendRequest("exchange-rates", options, Method.GET);

This returns a JSON object (in the data field of the response object) in this format:

{{
  "currency": "USD",
  "rates": {
    "AED": "3.67",
    "AFN": "68.45",
    "ALL": "113.80",
     .....
  }
}}

As you can see, the currency value of this response specifies USD, even though BTC was passed as a parameter.

Contrasting this with a request made using HttpWebRequest:

string url = $"https://api.coinbase.com/v2/exchange-rates?currency=BTC";
var request = (HttpWebRequest) WebRequest.Create(url);

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
    var returnText = reader.ReadToEnd();         
}

The value of returnText:

"{\"data\":{\"currency\":\"BTC\",\"rates\":{\"AED\":\"14379.85\",\"AFN\":\"267981.75\....}}}"

As you can see, the currency value is BTC, as specified in the request URL and all exchange rates use BTC as a base.

Am I mistaken or using this library incorrectly? I would expect the first method using this library to produce the results the second method did.

Errors running sample code.

The sample code:

var api = new CoinbaseApi( apiKey: "my_api_key" );

creates a compilation error due to the deprecation of this overload.

More significantly though, the sample code does not work even using the correct overload. On the line:

var buttonResponse = api.RegisterButton( paymenRequest );

an exception is thrown which says: "Input string '7999.0' is not a valid integer. Path 'button.price.cents', line 1, position 431."

Additionally, the API endpoint in the codebase is using a depreciated URL, see: https://www.coinbase.com/docs/api/overview

Automatic Refresh Tokens should have a callback to update Authentication.

OAuth should have a callback to update refresh and access tokens.

If the AutoRefresh Tokens is set as part of the config e.g

public class OAuthConfig : Config
{
    public Func<OAuthResponse, Task> OnRefresh { get; set; }
    public bool AutoRefresh { get; set; }
    protected internal override void Configure(CoinbaseClient client)
    {
          client.Configure(settings => { 
                 UseOAuth(settings, client);
                 if(AutoRefresh)
                 {
                      settings.OnErrorAsync = TokenExpiredErrorHandler
                 }
          });
    }

     private void UseOAuth(ClientFlurlHttpSettings settings, CoinbaseClient client)
     {
           async Task ApplyAuthorization(HttpCall call)
           {
              call.FlurlRequest.WithOAuthBearerToken(this.AccessToken);
         
           }
         settings.BeforeCallAsync = ApplyAuthorization;
     }        

When the API Refreshes the access tokens,
If you don't updated the access tokens/refresh tokens in the HTTP Context, your next login will result in Revoked Token exception.

If the Renew was moved to the Configuration, a user would be able to configure their own call back
e.g If the user is using Coinbase to Authenticate users

public async Task SetToken(RefreshResponse response)
{
    var auth = await HttpContext.AuthenticateAsync("Cookies");
    auth.Properties.StoreTokens(new List<AuthenticationToken>()
    {
        new AuthenticationToken()
        {
            Name = OpenIdConnectParameterNames.AccessToken,
            Value = response.AccessToken
       },
        new AuthenticationToken()
        {
            Name = OpenIdConnectParameterNames.RefreshToken,
            Value = response.RefreshToken
        }
    });

        await HttpContext.SignInAsync(auth.Principal, auth.Properties);
    }

Additionally then you could mask the clientId and Client secret by putting them in the Configuration

Buy Coins

I am confused as to how to buy coins with this API. Would I just use the SendRequest with the parameters in the data section? How would I format these parameters?
Thanks!

Coinbase : Callbacks to chcek if something succeeded or not

As we are unable to set up Sandbox for Coinbase since there are many exceptions with our piece of code, we are setting up Live Coinbase setup , in this we need some help from you on whether we are going correct way or not.

And with respect to live coinbase environment, i have below question:
Q1 : Are the 4 Redirect URLs required ? If mentioned all the 4 URLs, how will the flow in the application?
CallbackUrl = "http://localhost:50430/Checkout/Confirm",
CancelUrl = "http://localhost:50430/Checkout/Cancel",
InfoUrl = "http://localhost:50430/Checkout/Info",
SuccessUrl = "http://localhost:50430/Checkout/Success",

And if possible share the Sandbox sample in https://dotnetfiddle.net

Thanks

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.