【问题标题】:How can I swap BNB into another crypto currency using web3?如何使用 web3 将 BNB 兑换成另一种加密货币?
【发布时间】:2021-08-24 13:26:22
【问题描述】:

我想使用 web3 通过 Pancakeswap 将 BNB 兑换成其他代币,所以我遇到了这段似乎是正确的代码:

import time
import config as config
from web3 import Web3
 
PancakeABI = open('pancakeABI','r').read().replace('\n','')
 
bsc="https://bsc-dataseed.binance.org/"
web3 = Web3(Web3.HTTPProvider(bsc))
print(web3.isConnected())
 
#My own address to swap from
sender_address = "YOUR OWN WALLET PUBLIC ADDRESS"
 
#This is global Pancake V2 Swap router address
router_address = "0x10ED43C718714eb63d5aA57B78B54704E256024E"
 
#always spend using Wrapped BNB
#I guess you want to use other coins to swap you can do that, but for me I used Wrapped BNB
spend = web3.toChecksumAddress("0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c")
 
#This is your private key info
private="YOUR OWN WALLET PRIVATE KEY"
 
#Print out your balances just for checking
balance = web3.eth.get_balance(sender_address)
print(balance)
 
humanReadable = web3.fromWei(balance,'ether')
print(humanReadable)
 
#Contract id is the new token we are swaping to
contract_id = web3.toChecksumAddress("THE Contract ID of the destination Token")
 
#Setup the PancakeSwap contract
contract = web3.eth.contract(address=router_address, abi=PancakeABI)
 
nonce = web3.eth.get_transaction_count(sender_address)
 
start = time.time()
print(web3.toWei('0.02','ether'))
 
pancakeswap2_txn = contract.functions.swapExactETHForTokens(
  1074184953676691292, # here setup the minimum destination token you want to have, you can do some math, or you can put a 0 if you don't want to care
  [spend,contract_id],
  sender_address,
  (int(time.time()) + 1000000)
).buildTransaction({
  'from': sender_address,
  'value': web3.toWei(0.02,'ether'),#This is the Token(BNB) amount you want to Swap from
  'gas': 250000,
  'gasPrice': web3.toWei('5','gwei'),
  'nonce': nonce,
})
 
signed_txn = web3.eth.account.sign_transaction(pancakeswap2_txn, private_key=private)
tx_token = web3.eth.send_raw_transaction(signed_txn.rawTransaction)
print(web3.toHex(tx_token))

我遇到的问题是我的 BNB 已发送,但没有到达钱包。所以我的BNB就像“迷路”了。

【问题讨论】:

  • 我建议你使用测试网进行测试,pancakeswap 有一个合约发布在测试网你在这里看到:bsc.kiemtienonline360.com

标签: python blockchain web3


【解决方案1】:

首先,您需要创建一个将使用 dex 接口的合约 之后,您需要在 javascript 中调用一个函数。

【讨论】:

  • 不是真的,根本不需要js,python web3完全没问题
猜你喜欢
  • 2020-11-22
  • 1970-01-01
  • 1970-01-01
  • 2014-01-28
  • 1970-01-01
  • 2021-07-20
  • 1970-01-01
  • 1970-01-01
  • 2014-12-08
相关资源
最近更新 更多