Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
682 views
in Technique[技术] by (71.8m points)

python - Error when requesting to transfer/send on coinbase api

I am trying to post a transfer to the coinbase api from one crypto account to another, but just cannot seem to make it happen. The error occurs at the bottom of my code when I attempt a transfer 2 times. The first time, it comes back with "{}", and the second it comes back with the traceback error.

Here is my code:

import hmac, hashlib, time, requests, os
from requests.auth import AuthBase
from coinbase.wallet.client import Client

API_KEY = os.environ.get('API_KEY')
API_SECRET = os.environ.get('API_SECRET')
xrp_acct_id = os.environ.get('XRP_ID')
usdc_acct_id = os.environ.get('USDC_ID')
xrp_destination_tag = os.environ.get('xrp_destination_tag')
xtz_acct_id = os.environ.get('XTZ_ID')
user_id = os.environ.get('Coinbase_User_Id')


# Create custom authentication for Coinbase API
class CoinbaseWalletAuth(AuthBase):
    def __init__(self, api_key, secret_key):
        self.api_key = api_key
        self.secret_key = secret_key

    def __call__(self, request):
        timestamp = str(int(time.time()))
        message = timestamp + request.method + request.path_url + (request.body or b'').decode()
        signature = hmac.new(bytes(self.secret_key, 'utf-8'), message.encode('utf-8'), hashlib.sha256).hexdigest()

        request.headers.update({
            'CB-ACCESS-SIGN': signature,
            'CB-ACCESS-TIMESTAMP': timestamp,
            'CB-ACCESS-KEY': self.api_key,
            'CB-VERSION': '2020-01-18'
        })
        return request


api_url = 'https://api.coinbase.com/v2/'
auth = CoinbaseWalletAuth(API_KEY, API_SECRET)
client = Client(API_KEY, API_SECRET)

# Get current user:
#       r_user = requests.get(api_url + 'user', auth=auth)
#       print(r_user.json())

# Get transactions:
# xrp_txs = client.get_transactions(xrp_acct_id)

# Get accounts:
r = requests.get(api_url + 'accounts', auth=auth)

# Get price (XRP-USD):
price = client.get_spot_price(currency_pair='XRP-USD')

# To parse the JSON
accounts_json = r.json()
#
# # Variable to figure out wallet balances
XRP_balance = 0.0

# Dictionary used to store balances and wallet name's
accounts = {}

# Loop to get balances
for i in range(0, len(accounts_json["data"])):
    wallet = accounts_json["data"][i]["name"]
    amount = accounts_json["data"][i]["balance"]["amount"]

    # Switch statement to figure out which index which wallet is
    if wallet == "XRP Wallet":
        XRP_balance = float(amount) * float(price["amount"])
        accounts["XRP_USD"] = XRP_balance
    elif wallet == "USDC Wallet":
        USDC_amount = amount
        accounts["USDC"] = USDC_amount
    else:
        print()

print(accounts)

txs = {
    'type': 'transfer',
    'account_id': usdc_acct_id,
    'to': xrp_acct_id,
    'amount': '10',
    'currency': 'USDC'
}
r = requests.post(api_url + 'accounts/' + usdc_acct_id + '/transactions', json=txs, auth=auth)
print(r.json())
###### OUTPUT FROM THIS IS "{}" ##############

tx = client.transfer_money(account_id=usdc_acct_id,
                           to=xtz_acct_id,
                           amount='10',
                           fee='0.99',
                           currency='USDC')
###### OUTPUT FROM THIS IS "Traceback error" See Below ##############
txs = {
    'type': 'send',
    'to': xrp_address["address"],
    'destination_tag': xrp_destination_tag,
    'amount': '10',
    'currency': 'XRP'
}

r = requests.post(api_url + 'accounts/' + xtz_acct_id + '/transactions', json=txs, auth=auth)
print(r)
print(r.json())

########## THIS OUTPUT IS FROM AFTER TRACEBACK ERROR ################

Here is the entire output:

{'USDC': '100.000000', 'XRP_USD': 571.5256683544001}
{}
Traceback (most recent call last):
  File "/Users/mattaertker/Documents/CryptoExchangeProgram/exchangeMyCurrency.py", line 97, in <module>
    tx = client.transfer_money(account_id=usdc_acct_id,
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/coinbase/wallet/client.py", line 339, in transfer_money
    response = self._post('accounts', account_id, 'transactions', data=params)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/coinbase/wallet/client.py", line 132, in _post
    return self._request('post', *args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/coinbase/wallet/client.py", line 116, in _request
    return self._handle_response(response)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/coinbase/wallet/client.py", line 125, in _handle_response
    raise build_api_error(response)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/coinbase/wallet/error.py", line 49, in build_api_error
    blob = blob or response.json()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/models.py", line 898, in json
    return complexjson.loads(self.text, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

<Response [400]>
{'errors': [{'id': 'validation_error', 'message': 'Please enter a valid email or Tezos address', 'field': 'base'}]}

But hey, at least I can send money from my tezos account to my tezos account:

txs = {
    'type': 'send',
    'to': xtz_address["address"],
    'destination_tag': xrp_destination_tag,
    'amount': '10',
    'currency': 'XRP'
}

r = requests.post(api_url + 'accounts/' + xtz_acct_id + '/transactions', json=txs, auth=auth)
print(r)

OUTPUT:

<Response [201]>

I check my tezos account, and of course because response is 201, it did send it to itself. I recently found out it doesn't do this when you don't have destination_tag specified, but still BUG!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to convert your crypto from one currency to another, you don't have to use transfer_money. Watching Coinbase API from webapp that are the endpoints you need to call:

  1. Have to know base_id of crypto that you want to sell and base_id of crypto want to buy. You can know it by calling GET "https://api.coinbase.com/v2/ /assets/prices?base=USD&filter=holdable&resolution=latest" and get from response the "base_id" of your currencies.

  2. Make an order by calling POST "https://api.coinbase.com/v2/trade" with a request body in json like this: { 'amount': [amount that you want to convert], 'amount_asset': [currency of amount that you want to convert], 'amount_from': 'input', 'source_asset': ["base_id" of crypto that you want to sell], 'target_asset': ["base_id" of crypto that you want to buy] }

  3. If previous POST "/trade" response code is 201, you have to get the "id" value of response's json and do a commit of your order by calling POST "https://api.coinbase.com/v2/trades/[id of json response of previous https://api.coinbase.com/v2/trade POST"]/commit. If the response code of this POST commit is 201, your exchange is started and if there are not error in coinbase, your conversion is done!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...