If you’ve used Ethereum, you’ve paid Gas to execute your transaction on the blockchain. And if you’ve paid Gas, you probably know that it can be very expensive. In fact, the average ethereum transaction fee has been bouncing around $30 USD over the past couple months. With an instant cloud function from Napkin, you can deploy an ETH gas price alert mechanism in few minutes.

This post was originally published in Napkin.

Ideally, we want to execute transactions when the Gas price is reasonably low. But how can we know when that is?

In this tutorial, we’ll be using Napkin to build a Gas Price Monitor to constantly check the price of Gas on the blockchain, and alert us when it’s a good time to buy those precious JPEGs. Specifically we’ll be utilizing the free Etherscan API to check Gas prices and the Discord API to send us an alert on Discord.

Shoutout to Kevin Yang of Anzo Creative, who’s been using this method himself to monitor Gas prices and was kind enough to share his idea for this tutorial.

Creating a Discord Webhook

To create a webhook URL, open your desired Discord server and navigate to Server Settings > Integrations > Webhooks > New Webhook.

Etherscan API Key

To obtain an Etherscan API key, simply create a free profile at etherscan.io and create a key at https://etherscan.io/myapikey.

Coding the Monitor Function

To start off, head on over to napkin.io/dashboard/new and create a new Python function.

We’ll need a few modules: requestsos, and napkin.store. Napkin has hundreds of modules preinstalled in every Napkin runtime, including these three, so nothing more we need to do here other than import them.

from napkin import store
import requests
import os

Napkin lets you create and modify Environment Variables for each of your functions. We can store our Discord webhook URL and Etherscan API Key there via Other > Environment Variables.

Coding time. Let’s split up the main tasks for our monitor into helper functions. We’ll need to look up current Gas price, decide if it’s a good price, and optionally send a message on Discord. We’ll also need a way to cache and retrieve the last price we saw.

Napkin provides a built-in key value store to persist data across function runs, so we can use that to save and look up the previous price.

We’ll simply assume that the current Gas price is “good” if it’s less than 140 GWEI, but feel free to use your own logic.

webhook_url = os.getenv('DISCORD_WEBHOOK_URL')
gas_url = "https://api.etherscan.io/api?" \
  + "module=gastracker" \
  + "&action=gasoracle" \
  + f"&apikey={os.getenv('ETHERSCAN_API_KEY')}"

def send_alert(message):
    requests.post(webhook_url, json={'content': message})

def get_gas_price():
    data = requests.get(gas_url).json()
    return int(data['result'].get('SafeGasPrice'))

def should_alert(current_price, past_price):
    return current_gas_price < THRESHOLD_GWEI < past_price

def save_last_price(price):
    store.put('last_gas_price', price)

With our helper functions written, the final logic is pretty short.

current_gas_price = get_gas_price()
last_gas_price = store.get('last_gas_price')['data'] or THRESHOLD_GWEI+1

if should_alert(current_gas_price, last_gas_price):
    send_alert(f"Gas Price Alert: Current price is {current_gas_price} Gwei.")


Check out our example function here to see the final code.

Lastly, we’ll schedule our function to run automatically. Napkin lets you schedule your functions to run every minute, every hour, or once a day. In this case, we’ll do every minute so that we don’t miss any good Gas deals. Simply navigate to the “Schedule” tab and select “Every Minute”.

Now, just hit the big, blue “Deploy”, and we’re done! From there we can can watch the function running every minute in the “Event Logs” tab.

Once the monitor spots good Gas fees, it will give us a shout on Discord.

Happy coding! 🚀🌚

About the author 

Radiostud.io Staff

Showcasing and curating a knowledge base of tech use cases from across the web.

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
TechForCXO Weekly Newsletter
TechForCXO Weekly Newsletter

TechForCXO - Our Newsletter Delivering Technology Use Case Insights Every Two Weeks