Skip to content

Commit

Permalink
Merge pull request #35 from cowprotocol/fix-key-handling
Browse files Browse the repository at this point in the history
Fix Key Requirement
  • Loading branch information
bram-vdberg authored Aug 20, 2024
2 parents ba1aada + 92bc1c2 commit 37e4fcd
Showing 1 changed file with 16 additions and 11 deletions.
27 changes: 16 additions & 11 deletions src/price_providers/dune_pricing.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
from typing import cast
import dotenv, os
from src.price_providers.pricing_model import AbstractPriceProvider
from dune_client.types import QueryParameter
from dune_client.client import DuneClient
from dune_client.query import QueryBase
from dune_client.models import DuneError
from src.helpers.config import get_web3_instance, get_logger
from src.helpers.helper_functions import extract_params
from src.constants import DUNE_PRICE_QUERY_ID, DUNE_QUERY_BUFFER_TIME

dotenv.load_dotenv()
dune_api_key = os.getenv("DUNE_API_KEY")
dune = DuneClient.from_env()


class DunePriceProvider(AbstractPriceProvider):
Expand All @@ -21,17 +19,30 @@ class DunePriceProvider(AbstractPriceProvider):
def __init__(self) -> None:
self.web3 = get_web3_instance()
self.logger = get_logger()
self.dune = self.initialize_dune_client()

@property
def name(self) -> str:
return "Dune"

def initialize_dune_client(self) -> DuneClient | None:
"""
Initializes the Dune client and returns None if API key is not set.
"""
dune_api_key = os.getenv("DUNE_API_KEY")
if not dune_api_key:
self.logger.warning("DUNE_API_KEY is not set.")
return None
return cast(DuneClient, DuneClient.from_env())

def get_price(self, price_params: dict) -> float | None:
"""
Function returns Dune price for a token address,
closest to and at least as large as the block timestamp for a given tx hash.
"""
try:
if not self.dune:
return None
token_address, block_number = extract_params(price_params, is_block=True)
start_timestamp = getattr(
self.web3.eth.get_block(block_number), "timestamp", None
Expand All @@ -52,14 +63,8 @@ def get_price(self, price_params: dict) -> float | None:
),
],
)
try:
result = dune.run_query(query=query) # type: ignore[attr-defined]
except DuneError as e:
self.logger.warning(
f"Unable to run query, Dune returned with error {e}"
)
return None
if result.result.rows:
result = self.dune.run_query(query=query) # type: ignore[attr-defined]
if result and result.result and result.result.rows:
row = result.result.rows[0]
price = row.get("price")
if price is not None:
Expand Down

0 comments on commit 37e4fcd

Please sign in to comment.