Giter Club home page Giter Club logo

selltokenpancakeswap's Introduction

sellTokenPancakeSwap

sell token on pancakeswap in python

selltokenpancakeswap's People

Contributors

codewithjoe2020 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

Watchers

 avatar  avatar  avatar  avatar  avatar

selltokenpancakeswap's Issues

Incorrect Token Value

When you convert the token value from and to wei, you use the built in functions with the parameter 'ether'. However, if the number of decimals of the token that we are selling is different from that of (W)BNB this will give the incorrect value. You want to obtain the decimals from the token contract and then do something like

balance = raw_balance / math.pow(10, decimals)
raw_balance = balance * math.pow(10, decimals)

You didn't set `gas`

I was getting:

web3.exceptions.ContractLogicError: execution reverted: TransferHelper: TRANSFER_FROM_FAILED

on BUNNY -> WETH

Adding gas fixed it:

).buildTransaction({
    'from': config.MY_WALLET_ADDRESS,
    'gas': 250000,
    'gasPrice': web3.toWei('5','gwei'),
    'nonce': web3.eth.get_transaction_count(config.MY_WALLET_ADDRESS),
})

Fail with error 'TransferHelper: TRANSFER_FROM_FAILED'

Hello,

I have problem to swap token for wbnb back from your code. Meybe some tips how to fix this?

i am getting Status: Failed Error Reason: arithmetic underflow or overflow my log
https://dashboard.tenderly.co/tx/bnb/0x18368454753b2f1de9d0d5f1a581ad7c915a5decaaf800705fefaa526d035572
or
https://bscscan.com/tx/0x18368454753b2f1de9d0d5f1a581ad7c915a5decaaf800705fefaa526d035572

Python printed :
Connected to BSC: True
Balance: 20.91228548125376 WYRB
Allowance: 20.91228548125376 WYRB
Updated Allowance: 20.91228548125376 WYRB
Swapping 5 WYRB for BNB
Swapped WYRB: 0x18368454753b2f1de9d0d5f1a581ad7c915a5decaaf800705fefaa526d035572

My edited code from yours:

import json
from web3 import Web3
import time

Define the parameters

user_address = "0xB0e8698c5BdadBf8ADDf772407e5F16e42DBf631"
private_key = "*****************************************"
token_in = "0x683B9F1f6F1c40A10b0Bf992AdB73308d019Ea5F"
token_out = "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"
slippage = 1.0 # Slippage percentage
gas_price = 5 # Gas price in Gwei

bsc = "https://bsc-dataseed.binance.org/"
web3 = Web3(Web3.HTTPProvider(bsc))

print("Connected to BSC:", web3.is_connected())

PancakeSwap router

panRouterContractAddress = '0x10ED43C718714eb63d5aA57B78B54704E256024E'

PancakeSwap router ABI

panabi = '[{"inputs":[{"internalType":"address","name":"_factory","type":"address"},{"internalType":"address","name":"_WETH","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"WETH","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"tokenA","type":"address"},{"internalType":"address","name":"tokenB","type":"address"},{"internalType":"uint256","name":"amountADesired","type":"uint256"},{"internalType":"uint256","name":"amountBDesired","type":"uint256"},{"internalType":"uint256","name":"amountAMin","type":"uint256"},{"internalType":"uint256","name":"amountBMin","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"addLiquidity","outputs":[{"internalType":"uint256","name":"amountA","type":"uint256"},{"internalType":"uint256","name":"amountB","type":"uint256"},{"internalType":"uint256","name":"liquidity","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amountTokenDesired","type":"uint256"},{"internalType":"uint256","name":"amountTokenMin","type":"uint256"},{"internalType":"uint256","name":"amountETHMin","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"addLiquidityETH","outputs":[{"internalType":"uint256","name":"amountToken","type":"uint256"},{"internalType":"uint256","name":"amountETH","type":"uint256"},{"internalType":"uint256","name":"liquidity","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint256","name":"reserveIn","type":"uint256"},{"internalType":"uint256","name":"reserveOut","type":"uint256"}],"name":"getAmountIn","outputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"reserveIn","type":"uint256"},{"internalType":"uint256","name":"reserveOut","type":"uint256"}],"name":"getAmountOut","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"}],"name":"getAmountsIn","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"}],"name":"getAmountsOut","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountOutMin","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapETHForExactTokens","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountOutMin","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapExactETHForTokens","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountOutMin","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapExactETHForTokensSupportingFeeOnTransferTokens","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"amountOutMin","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapExactTokensForETH","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"amountOutMin","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapExactTokensForETHSupportingFeeOnTransferTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"amountOutMin","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapExactTokensForTokens","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"amountOutMin","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapExactTokensForTokensSupportingFeeOnTransferTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint256","name":"amountInMax","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapTokensForExactETH","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint256","name":"amountInMax","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapTokensForExactTokens","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]'

sender_address = '0xB0e8698c5BdadBf8ADDf772407e5F16e42DBf631'
spend = web3.to_checksum_address("0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c") # WBNB Address

Contract id is the new token we are swapping to

contract_id = web3.to_checksum_address(token_in)

Setup the PancakeSwap contract

contract = web3.eth.contract(address=panRouterContractAddress, abi=panabi)

Abi for Token to sell - all we need from here is the balanceOf & approve function can replace with shortABI

sellAbi = '[{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"}]'

Create token Instance for Token

sellTokenContract = web3.eth.contract(contract_id, abi=sellAbi)

Get Token Balance

balance = sellTokenContract.functions.balanceOf(sender_address).call()
decimals = sellTokenContract.functions.decimals().call()
symbol = sellTokenContract.functions.symbol().call()
readable_balance = balance / (10 ** decimals)
print(f"Balance: {readable_balance} {symbol}")

Enter amount of token to sell

import numpy as np

tokenValue = np.uint16(5 * (10 ** decimals))

min_tokenValue = np.uint16(4.8 * (10 ** decimals))

Enter amount of token to sell

tokenValue = int(5 * (10 ** decimals))
min_tokenValue = int(4.5 * (10 ** decimals)) # Set lower to account for slippag

Check allowance

allowance = sellTokenContract.functions.allowance(sender_address, panRouterContractAddress).call()
print(f"Allowance: {allowance / (10 ** decimals)} {symbol}")
if allowance < tokenValue:
print("Approving token...")
approve_tx = sellTokenContract.functions.approve(panRouterContractAddress, tokenValue).build_transaction({
'from': sender_address,
'gasPrice': web3.to_wei(1, 'gwei'),
'nonce': web3.eth.get_transaction_count(sender_address),
})

signed_approve_tx = web3.eth.account.sign_transaction(approve_tx, private_key=private_key)
tx_approve = web3.eth.send_raw_transaction(signed_approve_tx.rawTransaction)
print("Approved: " + web3.to_hex(tx_approve))

# Wait for the approval transaction to be mined
web3.eth.wait_for_transaction_receipt(tx_approve, timeout=120)

Check updated allowance

allowance = sellTokenContract.functions.allowance(sender_address, panRouterContractAddress).call()
print(f"Updated Allowance: {allowance / (10 ** decimals)} {symbol}")

Swap Tokens

print(f"Swapping {5} {symbol} for BNB")
pancakeswap_txn = contract.functions.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenValue,
min_tokenValue,
[contract_id, spend],
sender_address,
(int(time.time()) + 10000)
).build_transaction({
'from': sender_address,
'gasPrice': web3.to_wei(1, 'gwei'),
'gas': 200000, # Adjust gas limit if needed
'nonce': web3.eth.get_transaction_count(sender_address),
})

signed_swap_txn = web3.eth.account.sign_transaction(pancakeswap_txn, private_key=private_key)
tx_swap = web3.eth.send_raw_transaction(signed_swap_txn.rawTransaction)
print(f"Swapped {symbol}: " + web3.to_hex(tx_swap))

Error

Hallo
Run the code and have this error:

PS C:\Users\xxxx\python\VENV\pancakeswapBot> py sell.py True 76443049999999970 0.07644304999999997 Enter the Contract Address of token you want to sell: 0x7a27f05f1f67bd0803e082FcDEF361C562B3851b Traceback (most recent call last): File "C:\Users\xxxxxx\python\VENV\pancakeswapBot\sell.py", line 46, in <module> readable = web3.fromWei(balance) TypeError: from_wei() missing 1 required positional argument: 'unit'

Do you have a solution?
Regards

Token balance display

Lines 47-48
readable = web3.fromWei(balance,'ether')
print("Balance: " + str(web3.fromWei(readable, 'ether')) + " " + symbol)

Aren't we using .fromWei() method twice in this case? - 1st time in "readable" and 2nd time later when we print balance.
Tested it with 0.33 BUSD account - with code above it displays 3.30 BUSD, and if I enter to sell 1 BUSD it will end with error.

If we change 48 line with: print("Balance: " + str(readable) + " " + symbol)
It will display correct balance (0.33 BUSD in my case, with no errors if I sell 0.1 BUSD).

Config.py file missing

Hi, thanks for your nice documentations.

I would like to know where is the config.py file or where can I install the file
or, how to initiliaze config.private at this example?

Error in code

If i try to sell a crypto i see:

996341397394100562
0.996341397394100562
Enter the Contract Address of token you want to sell: 0x4d496efc21754481fe7a9f3f0f758785ade8e1d3

Balance: 9435079356.573655643061248581 SANINU

Enter amount of SANINU you want to sell: 700000

Approved: 0x59a9466c83ab9412cd96614de95937bf8572c3dc6b086c8043eda0e6ab597be9

Swapping 700000 SANINU for BNB

Traceback (most recent call last):
File "sell2.py", line 78, in
pancakeswap2_txn = contract.functions.swapExactTokensForETH(
File "/usr/local/lib/python3.8/dist-packages/web3/contract.py", line 1081, in buildTransaction
return build_transaction_for_function(
File "/usr/local/lib/python3.8/dist-packages/web3/contract.py", line 1650, in build_transaction_for_function
prepared_transaction = fill_transaction_defaults(web3, prepared_transaction)
File "cytoolz/functoolz.pyx", line 250, in cytoolz.functoolz.curry.call
File "/usr/local/lib/python3.8/dist-packages/web3/_utils/transactions.py", line 102, in fill_transaction_defaults
default_val = default_getter(web3, transaction)
File "/usr/local/lib/python3.8/dist-packages/web3/_utils/transactions.py", line 66, in
'gas': lambda web3, tx: web3.eth.estimate_gas(tx),
File "/usr/local/lib/python3.8/dist-packages/web3/eth.py", line 735, in estimate_gas
return self._estimate_gas(transaction, block_identifier)
File "/usr/local/lib/python3.8/dist-packages/web3/module.py", line 57, in caller
result = w3.manager.request_blocking(method_str,
File "/usr/local/lib/python3.8/dist-packages/web3/manager.py", line 187, in request_blocking
return self.formatted_response(response,
File "/usr/local/lib/python3.8/dist-packages/web3/manager.py", line 167, in formatted_response
apply_error_formatters(error_formatters, response)
File "/usr/local/lib/python3.8/dist-packages/web3/manager.py", line 67, in apply_error_formatters
formatted_resp = pipe(response, error_formatters)
File "cytoolz/functoolz.pyx", line 667, in cytoolz.functoolz.pipe
File "cytoolz/functoolz.pyx", line 642, in cytoolz.functoolz.c_pipe
File "/usr/local/lib/python3.8/dist-packages/web3/_utils/method_formatters.py", line 569, in raise_solidity_error_on_revert
raise ContractLogicError(response['error']['message'])
web3.exceptions.ContractLogicError: execution reverted: Pancake: K

Can you help me or fix the code?

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.