how to listen for buy events of my bsc token? - smartcontracts

I was just trying to create something which will listen to buy(pancakeswap) events of a specific token like SafeMoon & notify me when someone buys it on pancakeswap.
My progress so far.
The Way I Am Doing Now Is Finding Pancakeswap Pair Address Of A Token And Listen For Its Swap Events
pair_address = '0xBc9d0929c5a1D21BbAaB8826c0a6a78e096702A4' #Pair Address Of ORAKLER/WBNB On Pancakeswap
contract = web3.eth.contract(address=web3.toChecksumAddress(pair_address), abi=helper.getTokenAbi(pair_address))
def handle_event(event):
result = Web3.toJSON(event)
main_base = json.loads(result)
txn_hash = main_base['transactionHash']
print(result)
async def log_loop(event_filter, poll_interval):
while True:
for PairCreated in event_filter.get_new_entries():
handle_event(PairCreated)
await asyncio.sleep(poll_interval)
def main():
event_filter = contract.events.Swap.createFilter(fromBlock='latest')
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(
asyncio.gather(
log_loop(event_filter, 2)))
finally:
loop.close()
if __name__ == "__main__":
main()
In the above code, I am listing for Swap Event Of A Smart Contract And The Output I Am Getting Is
{"args": {"sender": "0x10ED43C718714eb63d5aA57B78B54704E256024E", "to": "0x4C7369b0615125481E2D6Fcd39e4d8c70DB2e830", "amount0In": 0, "amount1In": 4957805606627501, "amount0Out": 200000000000000000, "amount1Out": 0}, "event": "Swap", "logIndex": 339, "transactionIndex": 102, "transactionHash": "0x694f61f705d2fa49d6b16f9d56902f6e4b50c88e9d3adb4ab6fbea6632b0eb1b", "address": "0xBc9d0929c5a1D21BbAaB8826c0a6a78e096702A4", "blockHash": "0x6aedadf8d3618a1d21a48890d7bcfd9968df575a1a56323830f5dd242c79cdd3", "blockNumber": 14269884}
It contains Swap Event Parameter And They Look Like That
Swap (
index_topic_1 address sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
index_topic_2 address to
)
I am just confused about how to determine if it's a sold ORAKLER or Just bought & if he did buy how much money In BNB did he spend.
If anyone knows any other solution to do it or anything wrong I am doing here please tell me

I have figured out what I was doing wrong.
First I was using pancake factory address instead of my token lp address.
Second I have to use Swap not PairCreated In The code

Related

I want my telegram bot to send messages at the exact time but when I run my code the message sends immediately and no errors pop up

This is the part of the code where I tried to use scheduler
scheduler = BackgroundScheduler(timezone="Europe/Istanbul")
#bot.message_handler(content_types=\['text', \])
def get_name(message):
keyboard = types.InlineKeyboardMarkup()
cont = types.InlineKeyboardButton(text='re.README', callback_data='yes3')
keyboard.add(cont)
current_user = message.chat.username
res = engine.execute(f"SELECT COUNT(\*) FROM members WHERE username = '{current_user}'").fetchall()\[0\]\[0\]
if res == 0:
engine.execute(f'''INSERT INTO members (username, user_id, name, score) VALUES ('{current_user}', '{message.chat.id}', '{message.text}', '{0}');''')
bot.send_message(message.chat.id, 're.README')
#bot.message_handler(content_types=\['text',\])
def prom(message):
bot.send_message(message.chat.id, 'gyuk')
scheduler.add_job(prom, 'date', run_date=datetime(2023, 1, 20, 14, 30))
if __name__ == '__main__':
try:
scheduler.start()
bot.polling(none_stop=True)
while True:
sleep(1)
except:
pass
I tried different suggestions from here but it still doesn't work
In that case, the bot doesn't know the chat.id parameter where you want to send the message, because no message where sent to him.
If you want to schedule the sending of a message you have to iterate over the database of the people that have activated the bot correctly, and from it, you have to select the chat.id parameter so the bot knows the chat in which sending the message.
Furthermore, the scheduled function does not have to be a handler otherwise the bot will wait for a message to activate that function, instead of the scheduler.

UniswapV2 pairFor gives wrong contract address

When i try to add liquidity function fails because pairFor returns wrong pair address
original code (not working on ganache, hardhat and testnets)
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
found some similar issues on stackoverflow and they suggested changing init code hash
therefore i used bytes32 public constant INIT_CODE_PAIR_HASH = keccak256(abi.encodePacked(type(UniswapV2Pair).creationCode))
and it still doesn't work
My modified code with new init hash
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
'0x932b4f40ffd7547443affda5e84a39f3efc69f2ca17d46f0f9427e015f0fb178' // init code hash
))));
}```

Smart Contract Lottery throws "VirtualMachineError: revert" when ending the lottery

I have been following Solidity, Blockchain, and Smart Contract Course – Beginner to Expert Python Tutorial (https://www.youtube.com/watch?v=M576WGiDBdQ&t=28658s). When I run deploy_lottery.py, it breaks down while ending the lottery. Here is the snippet of code in Lottery.sol
function endLottery() public onlyOwner {
lottery_state = LOTTERY_STATE.CALCULATING_WINNER;
bytes32 requestId = requestRandomness(keyhash, fee);
emit RequestedRandomness(requestId);
}
Here is the code snippet in deploy_lottery.py
def end_lottery():
account = get_account()
lottery = Lottery[-1]
# fund the contract
# then end the lottery
tx = fund_with_link(lottery.address)
tx.wait(1)
print("Here")
ending_transaction = lottery.endLottery({"from": account})
print("ended transaction")
ending_transaction.wait(1)
time.sleep(180)
print(f"{lottery.recentWinner()} is the new winner!")
I have also attached snapshot of error. Thanks in advance.
https://i.stack.imgur.com/yU8jC.png
I have been stuck with the same error. The solution was to fund the contract with sufficient token. For testing I did
amount=5000000000000000000 in fund_with_link()
def fund_with_link(contract_address, account=None, link_token=None, amount=5000000000000000000):
account = account if account else get_account()
link_token = link_token if link_token else get_contract("link_token")
tx = link_token.transfer(contract_address, amount, {"from": account})
tx.wait(1)
print("Contract Funded")
return tx

How can I get all coins in USD parity to the Binance API?

I need binance data to build a mobile app. Only USDT pairs are sufficient. In the link below it takes all trading pairs, but I only want USDT pairs. Which link should I use for this?
https://api.binance.com/api/v3/ticker/price
You can use the Binance Exchange API. There is no need for registering.
The used API call is this: https://api.binance.com/api/v3/exchangeInfo
I recomend you use google colab and python, or any other python resource:
import requests
def get_response(url):
response = requests.get(url)
response.raise_for_status() # raises exception when not a 2xx response
if response.status_code != 204:
return response.json()
def get_exchange_info():
base_url = 'https://api.binance.com'
endpoint = '/api/v3/exchangeInfo'
return get_response(base_url + endpoint)
def create_symbols_list(filter='USDT'):
rows = []
info = get_exchange_info()
pairs_data = info['symbols']
full_data_dic = {s['symbol']: s for s in pairs_data if filter in s['symbol']}
return full_data_dic.keys()
create_symbols_list('USDT')
Result:
['BTCUSDT', 'ETHUSDT', 'BNBUSDT', 'BCCUSDT', 'NEOUSDT', 'LTCUSDT',...
The api call brings you a very large response fill with with interesting data about the exchange. In the function create_symbols_list you get all this data in the full_data_dic dictionary.
There is a python binance client library and you can do check the list of tickers which tickers are quoted in USDT (and status is trading):
from binance.client import Client
client = Client()
info = client.get_exchange_info()
for c in info['symbols']:
if c['quoteAsset']=='USDT' and c['status']=="TRADING":
print(c['symbol'])

In Bloomberg API how do you specify to get FX forwards as a spread rather than absolute values?

How do you explicitly request fx forwards as outrights using the bloomberg API?
In the Bloomberg terminal you can choose whether to get FX Forwards as absolute rates (outrights) or as offsets from Spots (Points) by doing XDF, hitting 7, then the option is about half way down. 0 means outrights, and 1 means offfsets.
With most defaults you can explicitly set them in the API, so your code gives the same result whichever computer you run on. How do you set this one in a V3 API query?
Having had a colleague told by the help desk this is impossible, it turns out they are wrong and it is possible. You override the FWD_CURVE_QUOTE_FORMAT to be RATES for absolute and POINTS as offsets.
Example code (Java):
public static void main(String [] args) throws Exception{
Session session = BlpUtil.connectToReferenceData();
Service refDataService = session.getService("//blp/refdata");
Request request = refDataService.createRequest("HistoricalDataRequest");
Element securities = request.getElement("securities");
securities.appendValue("JPY10Y CMPL Curncy");
Element fields = request.getElement("fields");
fields.appendValue("PX_LAST");
request.set("startDate", "20100527");
request.set("endDate", "20100527");
Element overrides = request.getElement("overrides");
Element override1 = overrides.appendElement();
override1.setElement("fieldId", "FWD_CURVE_QUOTE_FORMAT");
override1.setElement("value", "POINTS");
CorrelationID cid = session.sendRequest(request, null);
while (true) {
Event event = session.nextEvent();
MessageIterator msgIter = event.messageIterator();
while (msgIter.hasNext()) {
Message msg = msgIter.next();
if (msg.correlationID() == cid) {
System.out.println("msg = " + msg);
}
}
}
}