Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding Infura agent #241

Merged
merged 13 commits into from
Feb 23, 2024
59 changes: 59 additions & 0 deletions integrations/infura-gas-price/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Infura Gas Price

## Description

The Infura Gas Price provides real-time information on suggested gas fees for transactions on blockchain networks. By utilizing the endpoint [https://gas.api.infura.io/networks/{chain_id}/suggestedGasFees](https://gas.api.infura.io/networks/{chain_id}/suggestedGasFees), users can obtain the current recommended gas fees tailored to a specific blockchain network identified by the `{chain_id}` parameter.

## Endpoint

- **API Endpoint:** [https://gas.api.infura.io/networks/{chain_id}/suggestedGasFees](https://gas.api.infura.io/networks/{chain_id}/suggestedGasFees)

## Usage

1. Replace `{chain_id}` in the endpoint with the unique identifier of the desired blockchain network.
2. Send a GET request to the specified endpoint.
3. Retrieve real-time information on the suggested gas fees for transactions on the specified blockchain network.

## Getting an API Key

To access the Infura Gas Fees API, you need to obtain an API key. Follow these steps:

1. Visit the Infura website: [https://infura.io/](https://infura.io/)
2. Sign in to your Infura account or create a new one.
3. Once logged in, navigate to the dashboard.
4. Create a new project by clicking on the "Create New Project" button.
5. Select the blockchain network you are interested in (e.g., Ethereum).
6. After creating the project, you'll find your API key in the project settings.

# Agent Secrets on Agentverse

1. Go to the Agentverse platform.
2. Navigate to the Agent Secrets section.
3. Create an agent and copy the code in it
4. Add a new secret with the key `API_KEY` and the value as your API KEY.

# Steps to Enroll an Agent as a Service on Agentverse

You can integrate into DeltaV your Agents created on your local computer, IoT devices, in the VMs, or agents created on Agentverse. The steps are the same.

Once your agents are run, the agent protocol manifests are uploaded to the Almanac contract in the form of protocol digests. After uploading the manifests, we take the agent addresses and enroll the agents as a service under the "Services" tab in Agentverse.

## Agent Validation on Agentverse Explorer
*Note: You can validate the procedure by searching for your agent's address on Agent Explorer, checking if the protocols have been uploaded successfully. If not, you need to wait for some time (1-2 minutes) until the protocols are uploaded successfully.*

## Create a Service Group

1. Start by creating a new service group on Agentverse.
2. Set up the service group as PRIVATE (you will only be able to see your own agents).
- If you set up your service group as Public, anyone will be able to see your agents.

**Service group has been created.**

## Create a Service

1. To register the agents as a service, input a concise title and description for the agent service.
2. Choose the service group for the agent service that you've created previously.
3. Fill in the agent address in the Agent field.
4. Set the task type to Task.

Now, your agents are enrolled as a service in Agentverse. You can manage and monitor them under the "Services" tab. Ensure that you follow the agent validation steps on Agent Explorer to confirm successful enrollment.
97 changes: 97 additions & 0 deletions integrations/infura-gas-price/agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import requests
from ai_engine import UAgentResponse, UAgentResponseType

class GasPriceRequest(Model):
chain_id: int # Chain ID represented as an integer

gas_price_protocol = Protocol("Infura Gas Price Retrieval")

"""
import base64
api_key =
api_key_secret =
credentials = f"{api_key}:{api_key_secret}"
base64.b64encode(credentials.encode()).decode()
"""

def fetch_gas_prices(chain_id, ctx):
"""Fetch gas prices from Infura API."""
url = f'https://gas.api.infura.io/networks/{str(chain_id)}/suggestedGasFees'
headers = {
"Authorization": f"Basic {API_KEY}"
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
return response.json()
except Exception as exc:
ctx.logger.info(f"Error during Infura gas price retrieval: {exc}")
return None

def format_gas_price_results(results):
formatted_string = "🔥 Gas Price Summary:\n"
for level in ['low', 'medium', 'high']:
gas_info = results[level]
formatted_string += (
f"Level: {level.capitalize()}\n"
f"🚀 Max Priority Fee: {gas_info['suggestedMaxPriorityFeePerGas']} Gwei\n"
f"💸 Max Fee: {gas_info['suggestedMaxFeePerGas']} Gwei\n\n"
)
formatted_string += (
f"🔧 Estimated Base Fee: {results['estimatedBaseFee']} Gwei\n"
f"📊 Network Congestion: {results['networkCongestion']}\n"
f"⬆️ Priority Fee Trend: {results['priorityFeeTrend']}\n"
f"⬇️ Base Fee Trend: {results['baseFeeTrend']}\n"
)
return formatted_string.strip()

@gas_price_protocol.on_message(model=GasPriceRequest, replies=UAgentResponse)
async def on_gas_price_request(ctx: Context, sender: str, msg: GasPriceRequest):
# Log the incoming request
ctx.logger.info(f"Received gas price request for chain ID: {msg.chain_id} from {sender}")

try:
# Fetch gas prices
gas_prices = fetch_gas_prices(msg.chain_id, ctx)
if gas_prices is None:
# Send the error response
await ctx.send(
sender,
UAgentResponse(
message=(
f"⚠️ Error: Unable to fetch gas prices for chain ID: {msg.chain_id}.\n\n"
"Please make sure the chain ID is correct.\n"
"If yes, then there might be something wrong with the API/agent. "
"Please try again later."
),
type=UAgentResponseType.ERROR
)
)

# Format and log the response
formatted_string = format_gas_price_results(gas_prices)
ctx.logger.info(f"Sending gas price information for chain ID: {msg.chain_id} to {sender}\n{formatted_string}")

# Send the response
await ctx.send(
sender,
UAgentResponse(
message=f"{formatted_string}",
type=UAgentResponseType.FINAL
)
)

except Exception as exc:
error_message = f"An error occurred while processing request for chain ID: {msg.chain_id} - {exc}"
ctx.logger.error(error_message)

# Send the error response
await ctx.send(
sender,
UAgentResponse(
message=f"Error: An error occurred while processing request for chain ID: {msg.chain_id}",
type=UAgentResponseType.ERROR
)
)

agent.include(gas_price_protocol)
6 changes: 6 additions & 0 deletions integrations/infura-gas-price/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"title": "Infura Gas price",
"description": "The Infura Gas Fees API provides real-time information on suggested gas fees for transactions on blockchain networks.",
"categories": ["Blockchain", "Cryptocurrency"],
"deltav": true
}
Loading