# Contract Notifier

This script is useful for monitoring the creation of contracts on the Polygon network and promptly notifying users through Discord when a new contract is detected.

```yaml
from web3 import Web3
from web3.middleware import geth_poa_middleware
import time
import discord

# Set the URL of the Polygon (or Matic) network node
polygon_node_url = "" # INSERT_YOUR_RPC_HERE

# Set the ERC20 contract address for token creation
erc20_contract_address = "0x7d1afa7b718fb893db30a3abc0cfc608aacfebb0"

# Set the Discord bot token
discord_bot_token = "" # INSERT_YOUR_WEBHOOK_HERE

# Set the channel ID where notifications will be sent
discord_channel_id = ""  # INSERT_YOUR_CHANNEL_ID_HERE

# Initialize the Web3 object
web3 = Web3(Web3.HTTPProvider(polygon_node_url))

web3.middleware_onion.inject(geth_poa_middleware, layer=0)

def get_contract_creation_events(contract_address):
    event_signature = web3.keccak(text="Transfer(address,address,uint256)").hex()

    checksum_address = Web3.toChecksumAddress(contract_address)
    filter_params = {
        "address": checksum_address,
        "topics": [event_signature, None, None],
    }
    contract_creation_events = web3.eth.get_logs(filter_params)
    return contract_creation_events

def bytes_to_hex_string(byte_array):
    return byte_array.hex()

def get_latest_block_number():
    # Get the latest block number
    latest_block_number = web3.eth.blockNumber
    return latest_block_number

def send_discord_notification(message):
    # Initialize the Discord 
    client = discord.Client()

    @client.event
    async def on_ready():
        channel = client.get_channel(discord_channel_id)
        await channel.send(message)
        await client.close()

    client.run(discord_bot_token)

def main():
    try:
        # Check the connection to the Polygon network node
        if not web3.isConnected():
            print("Error: Could not connect to the Polygon network node.")
            return

        while True:
            contract_creation_events = get_contract_creation_events(erc20_contract_address)

            if contract_creation_events:
               
                transaction_hashes_bytes = [event["transactionHash"] for event in contract_creation_events]
           
                transaction_hashes_strings = [bytes_to_hex_string(txn_hash) for txn_hash in transaction_hashes_bytes]

                # Send Discord notification
                for txn_hash_string in transaction_hashes_strings:
                    message = f"Contract created in transaction: {txn_hash_string}"
                    print(message)
                    send_discord_notification(message)

            # interval
            time.sleep(1)

    except Exception as e:
        print(f"Error: {str(e)}")

if __name__ == "__main__":
    main()

```

Python and Requests Installation:

Make sure you have Python installed on your system. Open the terminal or command prompt. Execute the following command to install the `requests` library:

```bash
pip install requests
```

Script Execution:

Save the Python script (`Your_script.py`) in the directory of your choice. Place a file named "addresses.txt" in the same directory as the script, containing the addresses of the validators.

Run the Script:

In the terminal or command prompt, navigate to the directory where the script is located. Execute the script using the following command:

```bash
python3 your_script.py
```

Results:

The script will begin monitoring the creation of contracts and send notifications to the configured Discord channel whenever a new contract is detected.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.stakepool.dev.br/polygon/scripts/contract-notifier.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
