请求在Coinbase API上传输/发送时出错

如何解决请求在Coinbase API上传输/发送时出错

我正在尝试将从一个加密帐户到coinbase api的转移过帐,但似乎无法实现。当我尝试两次传输时,错误发生在代码的底部。第一次,它返回“ {}”,第二次,它返回回溯错误。

这是我的代码:

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,'currency': 'XRP'
}

r = requests.post(api_url + 'accounts/' + xtz_acct_id + '/transactions',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"],auth=auth)
print(r)

输出:

<Response [201]>

我检查了我的tezos帐户,当然,因为响应为201,所以确实将其发送给自己。我最近发现,当您未指定destination_tag时,它仍然无法执行此操作!

解决方法

如果您想将加密货币从一种货币转换为另一种货币,则不必使用 transfer_money。从 webapp 观看 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. 通过使用 json 中的请求正文调用 POST "https://api.coinbase.com/v2/trade" 来下订单,如下所示:{ '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,你必须得到 响应的 json 的“id”值并通过以下方式提交您的订单 呼叫 POST "https://api.coinbase.com/v2/trades/[id of json response of previous https://api.coinbase.com/v2/trade POST"]/commit。如果 此 POST 提交的响应代码是 201,您的交换是 开始,如果coinbase没有错误,你的转换是 完成!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-