Ethereum mempool transaction pool txpool flow diagram.

Crypto Market Pool: cómo consultar el mempool/txpool de Ethereum con Python

Publicado por
Comparte en redes sociales


En este tutorial, consultaremos el mempool de Ethereum usando Web3.py en Python. El mempool también se conoce como el grupo de transacciones y/o el txpool. Este proceso y el código a continuación funcionarán con todas las cadenas de bloques compatibles con EVM (Ethereum Virtual Machine) (Ethereum, Optimism, BSC, Polygon, Kucoin Chain, Fantom, etc.).

Importancia de Mempool

Cuando se envía una transacción a la cadena de bloques, un nodo Ethereum la recibe. Este nodo Ethereum propaga la transacción a otros nodos pares de Ethereum. Mientras la transacción espera ser agregada al siguiente bloque, reside en un área de preparación llamada mempool/txpool. Esta área de preparación contiene una lista de todas las «transacciones pendientes». Una vez que la transacción se agrega al siguiente bloque, se considera transacción confirmada.

Diagrama de flujo de txpool del grupo de transacciones de mempool de Ethereum.
  1. Las transacciones de diferentes carteras, aplicaciones, etc. se envían a la cadena de bloques para su procesamiento.
  2. Estas transacciones están pendientes y ordenadas en el mempool/txpool.
  3. Las transacciones de Mempool/txpool se incluyen en el siguiente bloque de la cadena de bloques.

Así es como un nodo de blockchain se ocupa de las transacciones que aún no se han incluido en un bloque. Las transacciones pendientes en mempool / txpool son una buena indicación de lo que sucederá a continuación en la cadena de bloques. Examinar las transacciones en el mempool le brindará información adicional que podría necesitar al comerciar, crear aplicaciones, ver direcciones, etc.

Conectarse a la cadena de bloques

Para conectarse a una cadena de bloques, puede usar su propio nodo, Nodo rápido, Chainstack, o cualquier otro servicio. Configurar una cuenta en Chainstack y Quick Node es rápido, fácil y, a veces, gratuito (según el servicio que elija). Intentamos consultar el mempool con Python usando Infura pero el proceso en este tutorial no es compatible. Como se mencionó, este proceso funcionará con cualquier cadena de bloques compatible con EVM, por lo que para este tutorial nos centraremos en Ethereum. Después de configurar su nodo, asegúrese de tomar nota de las credenciales de su nodo Ethereum, ya que deberá incluirlas en el código de Python a continuación.

Configura tu entorno de Python

En este tutorial usaremos un entorno virtual y bibliotecas Web3.py para consultar el mempool de Ethereum con Python. Primero configure un entorno virtual usando su ventana de terminal en su IDE. Luego instale las bibliotecas Web3.py usando la instalación PIP. Para obtener más información sobre cómo descargar Web3.py, lea aquí. Finalmente, prepare sus credenciales de nodo de socket web, ya que deberá incluirlas en el código a continuación.

Consulta el mempool de Ethereum con Python

Parte del código de muestra a continuación fue tomado de Web3.py lea los documentos concurrencia de subproceso único con asyn y await en la sección de filtrado. Luego modificamos el código para adaptarlo a nuestro caso de uso.

Leer también  Wemade y Elympics se embarcan en una alianza estratégica para elevar los juegos blockchain

Copie el código a continuación para consultar el mempool de Ethereum con Python. Lea los comentarios en el código para comprender cómo funciona el código. Asegúrese de ingresar sus credenciales de nodo de socket web.

from web3.auto import Web3
import asyncio
import json

# enter your web socket node credentials here
# this will allow us to stream transactions
wss="wss://EnterYourWSSInformationHere"
web3 = Web3(Web3.WebsocketProvider(wss))


# test to see if you are connected to your node
# this will print out True if you are successfully connected to a node
print(web3.isConnected())


def handle_event(event):
    # print the transaction hash
    # print(Web3.toJSON(event))

    # use a try / except to have the program continue if there is a bad transaction in the list
    try:
        # remove the quotes in the transaction hash
        transaction = Web3.toJSON(event).strip('"')
        # use the transaction hash that we removed the '"' from to get the details of the transaction
        transaction = web3.eth.get_transaction(transaction)
        # print the transaction and its details
        print(transaction)

    except Exception as err:
        # print transactions with errors. Expect to see transactions people submitted with errors 
        print(f'error: {err}')


async def log_loop(event_filter, poll_interval):
    while True:
        for event in event_filter.get_new_entries():
            handle_event(event)
        await asyncio.sleep(poll_interval)


def main():
    # filter for pending transactions
    tx_filter = web3.eth.filter('pending')
    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(
            asyncio.gather(
                log_loop(tx_filter, 2)))
    finally:
        loop.close()


if __name__ == '__main__':
    main()

Filtre mempool para transacciones Uniswap o Pancake Swap con Python

Además, si desea ir un paso más allá y filtrar el mempool/txpool con Python para transacciones que solo vayan a Uniswap o Pancake Swap, pruebe el código a continuación. Se agregó una variable llamada «enrutador» y una condición «si» al bloque de prueba.

from web3.auto import Web3
import asyncio
import json

# enter your node credentials here
wss="wss://EnterYourWSSInformationHere"
web3 = Web3(Web3.WebsocketProvider(wss))


# Check to see if you are connected to your node
print(web3.isConnected())

# add an address you want to filter pending transactions for
# make sure the address is in the correct format
router = web3.toChecksumAddress('EnterUniswapOrPancakeSwapRouterAddressHere')

def handle_event(event):

    try:
        # remove the quotes in the transaction hash
        transaction = Web3.toJSON(event).strip('"')
        # use the transaction hash (that we removed the '"' from to get the details of the transaction
        transaction = web3.eth.get_transaction(transaction)
        # set the variable to the "to" address in the message
        to = transaction['to']
        # if the to address in the message is the router
        if to == router:
            # print the transaction and its details
            print(transaction)
        else:
            print('Not what we are looking for')
    except Exception as err:
        # print transactions with errors. Expect to see transactions people submitted with errors
        print(f'error: {err}')


async def log_loop(event_filter, poll_interval):
    while True:
        for event in event_filter.get_new_entries():
            handle_event(event)
        await asyncio.sleep(poll_interval)


def main():
    # filter for pending transactions
    tx_filter = web3.eth.filter('pending')
    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(
            asyncio.gather(
                log_loop(tx_filter, 2)))
    finally:
        loop.close()


if __name__ == '__main__':
    main()

Filtre mempool para las funciones de transacción Uniswap o Pancake Swap con Python

Finalmente, para la siguiente parte, filtremos por transacciones Uniswap o Pancake Swap y veamos las funciones que los usuarios envían a los contratos. Con el siguiente código, puede filtrar las transacciones enviadas al enrutador, ver las funciones de las transacciones y los detalles incluidos en el mensaje.

from web3.auto import Web3
import asyncio
import json

# enter your node credentials here
wss="wss://EnterYourWSSInformationHere"
web3 = Web3(Web3.WebsocketProvider(wss))


# Check to see if you are connected to your node
print(web3.isConnected())

# add the abi of Uniswap or Pancake Swap
abi = json.loads('[{"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":"amountA","type":"uint256"},{"internalType":"uint256","name":"reserveA","type":"uint256"},{"internalType":"uint256","name":"reserveB","type":"uint256"}],"name":"quote","outputs":[{"internalType":"uint256","name":"amountB","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"tokenA","type":"address"},{"internalType":"address","name":"tokenB","type":"address"},{"internalType":"uint256","name":"liquidity","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":"removeLiquidity","outputs":[{"internalType":"uint256","name":"amountA","type":"uint256"},{"internalType":"uint256","name":"amountB","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"liquidity","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":"removeLiquidityETH","outputs":[{"internalType":"uint256","name":"amountToken","type":"uint256"},{"internalType":"uint256","name":"amountETH","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"liquidity","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":"removeLiquidityETHSupportingFeeOnTransferTokens","outputs":[{"internalType":"uint256","name":"amountETH","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"liquidity","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"},{"internalType":"bool","name":"approveMax","type":"bool"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"removeLiquidityETHWithPermit","outputs":[{"internalType":"uint256","name":"amountToken","type":"uint256"},{"internalType":"uint256","name":"amountETH","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"liquidity","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"},{"internalType":"bool","name":"approveMax","type":"bool"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"removeLiquidityETHWithPermitSupportingFeeOnTransferTokens","outputs":[{"internalType":"uint256","name":"amountETH","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"tokenA","type":"address"},{"internalType":"address","name":"tokenB","type":"address"},{"internalType":"uint256","name":"liquidity","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"},{"internalType":"bool","name":"approveMax","type":"bool"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"removeLiquidityWithPermit","outputs":[{"internalType":"uint256","name":"amountA","type":"uint256"},{"internalType":"uint256","name":"amountB","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountOut","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"}]')

# add an address you want to filter pending transactions for
# make sure the address is in the correct format
router = web3.toChecksumAddress('0x10ed43c718714eb63d5aa57b78b54704e256024e')
Contract = web3.eth.contract(address=router, abi=abi)


def handle_event(event):

    try:
        # remove the quotes in the transaction hash
        transaction = Web3.toJSON(event).strip('"')
        # use the transaction hash (that we removed the '"" from to get the details of the transaction
        transaction = web3.eth.get_transaction(transaction)
        # set the variable to the "to" address in the message
        to = transaction['to']
        # get the input data in the transaction message. This tells us what functions are going to be executed on the router
        input_data = transaction['input']
        # if the to address in the message is the uniswap router
        if to == router:
            # decode the data so you can read it
            decode = Contract.decode_function_input(input_data)
            # print the transaction and its details
            # you will be able to see the functions that are passed to the router
            # try printing the following: for function information use (decode[0]),  or for amount in/out use decode[1], or for the path use decode(['path']), or for amountIn use decode('amountIn')
            print(decode)
        else:
            print('Not what we want')
    except Exception as err:
        # print transactions with errors. Expect to see transactions people submitted with errors
        print(f'error: {err}')


async def log_loop(event_filter, poll_interval):
    while True:
        for event in event_filter.get_new_entries():
            handle_event(event)
        await asyncio.sleep(poll_interval)


def main():
    # filter for pending transactions
    tx_filter = web3.eth.filter('pending')
    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(
            asyncio.gather(
                log_loop(tx_filter, 2)))
    finally:
        loop.close()


if __name__ == '__main__':
    main()

Recursos

Redes de cadena de bloques

A continuación se muestra una lista de redes de cadena de bloques Mainnet y Testnet compatibles con EVM. Cada enlace contiene la configuración de la red, enlaces a varios grifos para probar ETH y tokens, detalles del puente y recursos técnicos para cada cadena de bloques. Básicamente todo lo que necesita para probar e implementar contratos inteligentes o aplicaciones descentralizadas en cada cadena. Para obtener una lista de foros populares de Ethereum y aplicaciones de chat, haga clic aquí.

Leer también  ¿Debería utilizar varias carteras de criptomonedas?
cryptoshitcompra.com/wp-content/uploads/2022/09/Crypto-Market-Pool-como-consultar-el-mempooltxpool-de-Ethereum-con.png» alt=»»/> Ethereum prueba la configuración de la red y prueba la información del grifo ETH
png» alt=»»/> Configuración optimista de Ethereum Mainnet y Testnet, detalles del puente, etc.
Configuración de red de polígono Mainnet y Testnet, grifos para prueba de tokens MATIC, detalles de puente, etc.
Configuración de Binance Smart Chain Mainnet y Testnet, faucets para tokens BNB de prueba, detalles del puente, etc.
Fanton networt Configuración de Mainnet y Testnet, faucets para tokens FTM de prueba, detalles del puente, etc.
Configuración de Kucoin Chain Mainnet y Testnet, faucets para tokens KCS de prueba, detalles del puente, etc.

Bibliotecas de software Web3

Puede usar las siguientes bibliotecas para interactuar con una cadena de bloques compatible con EVM.

Siguiente – Cómo usar Flashbots

Ledger Nano X - La billetera de hardware segura



Source link

Si quiere puede hacernos una donación por el trabajo que hacemos, lo apreciaremos mucho.

Direcciones de Billetera:

- BTC: 14xsuQRtT3Abek4zgDWZxJXs9VRdwxyPUS 

- USDT: TQmV9FyrcpeaZMro3M1yeEHnNjv7xKZDNe 

- BNB: 0x2fdb9034507b6d505d351a6f59d877040d0edb0f

- DOGE: D5SZesmFQGYVkE5trYYLF8hNPBgXgYcmrx 

También puede seguirnos en nuestras Redes sociales para mantenerse al tanto de los últimos post de la web:

-Twitter

- Telegram

Disclaimer: En Cryptoshitcompra.com no nos hacemos responsables de ninguna inversión de ningún visitante, nosotros simplemente damos información sobre Tokens, juegos NFT y criptomonedas, no recomendamos inversiones

Dejar un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *