Ошибка при запросе передачи / отправки на coinbase api

Я пытаюсь отправить перевод на coinbase api с одной криптографической учетной записи на другую, но не могу этого сделать. Ошибка возникает в нижней части моего кода, когда я пытаюсь выполнить передачу 2 раза. В первый раз он возвращается с {}, а во второй - с ошибкой трассировки.

Вот мой код:

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 ################

Вот весь результат:

{'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'}]}

Но послушайте, по крайней мере, я могу отправить деньги со своего счета tezos на свой счет tezos:

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)

ВЫВОД:

<Response [201]>

Я проверяю свою учетную запись tezos, и, конечно же, поскольку ответ 201, он отправил его самому себе. Недавно я узнал, что он не делает этого, если у вас не указан destination_tag, но все же ОШИБКА !!


person Matt Aertker    schedule 24.09.2020    source источник


Ответы (1)


Если вы хотите конвертировать свою криптовалюту из одной валюты в другую, вам не нужно использовать transfer_money. Наблюдаем за Coinbase API из веб-приложения, которые являются конечными точками, которые вам нужно вызвать:

  1. Необходимо знать base_id криптовалюты, которую вы хотите продать, и base_id криптовалюты, которую хотите купить. Вы можете узнать это, вызвав GET "https://api.coinbase.com/v2/ /assets/prices?base=USD&filter=holdable&resolution=latest" and get из ответа base_id ваших валют.

  2. Сделайте заказ, вызвав POST "https://api.coinbase.com/v2/trade" с телом запроса в json следующим образом: { '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. Если предыдущий код ответа POST / trade - 201, вы должны получить значение id json ответа и выполнить фиксацию своего ордера, вызвав POST "https://api.coinbase.com/v2/trades/[id of json response of previous https://api.coinbase.com/v2/trade POST"]/commit. Если код ответа этой POST-фиксации равен 201, ваш обмен запускается, и если в Coinbase нет ошибок, ваше преобразование выполнено!

person paggio86    schedule 27.03.2021