-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
✨ feat(multi-asset): add daily price multi-asset support
- Loading branch information
1 parent
2719c40
commit 95ab70f
Showing
15 changed files
with
218 additions
and
56 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
import os | ||
import requests | ||
import logging | ||
|
||
CMC_API_KEY = os.environ["CMC_API_KEY"] | ||
CMC_API_URL = os.environ.get( | ||
"CMC_API_URL", | ||
"https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest", | ||
) | ||
|
||
logger = logging.getLogger() | ||
logger.setLevel(logging.INFO) | ||
|
||
|
||
def fetch_token_price_from_cmc(token_ticker): | ||
headers = {"X-CMC_PRO_API_KEY": CMC_API_KEY} | ||
params = {"symbol": token_ticker, "convert": "USD"} | ||
|
||
logger.info(f"Fetching price for {token_ticker} from CoinMarketCap") | ||
|
||
response = requests.get(CMC_API_URL, headers=headers, params=params) | ||
data = response.json() | ||
|
||
if response.status_code != 200 or "data" not in data: | ||
logger.error( | ||
f"Failed to fetch price for {token_ticker} from CoinMarketCap: {data}" | ||
) | ||
return None | ||
|
||
price = data["data"][token_ticker]["quote"]["USD"]["price"] | ||
logger.info(f"Fetched price for {token_ticker}: {price}") | ||
return price |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
import os | ||
from datetime import datetime, timezone | ||
from s3_cache import get_token_price_from_s3, save_token_price_to_s3 | ||
from api import fetch_token_price_from_cmc | ||
from utils import create_response | ||
import logging | ||
|
||
BUCKET_NAME = os.environ["S3_BUCKET_NAME"] | ||
|
||
logger = logging.getLogger() | ||
logger.setLevel(logging.INFO) | ||
|
||
|
||
def lambda_handler(event, context): | ||
query_params = event.get("queryStringParameters", {}) | ||
ticker = query_params.get("ticker") | ||
if not ticker: | ||
logger.error("Missing ticker in the request") | ||
return create_response(400, "Missing ticker in the request") | ||
|
||
today = datetime.now(timezone.utc).strftime("%Y-%m-%d") | ||
s3_key = f"tokens/{ticker}/{today}.txt" | ||
|
||
logger.info(f"Checking S3 for cached price of {ticker} on {today}") | ||
|
||
token_price = get_token_price_from_s3(BUCKET_NAME, s3_key) | ||
if token_price is not None: | ||
logger.info(f"Found cached price for {ticker}: {token_price}") | ||
return create_response(200, {"price": token_price}) | ||
|
||
logger.info(f"Cached price for {ticker} not found, fetching from CoinMarketCap") | ||
|
||
token_price = fetch_token_price_from_cmc(ticker) | ||
if token_price is None: | ||
logger.error(f"Failed to fetch price for {ticker} from CoinMarketCap") | ||
return create_response(500, "Failed to fetch price from CoinMarketCap") | ||
|
||
save_token_price_to_s3(BUCKET_NAME, s3_key, token_price) | ||
logger.info(f"Saved price for {ticker} to S3: {token_price}") | ||
|
||
return create_response(200, {"price": token_price}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
import os | ||
import boto3 | ||
import logging | ||
|
||
aws_access_key_id = os.getenv("ACCESS_KEY_ID") | ||
aws_secret_access_key = os.getenv("SECRET_ACCESS_KEY") | ||
s3_region = os.getenv("S3_REGION", "eu-central-1") | ||
|
||
s3_client = boto3.client( | ||
"s3", | ||
aws_access_key_id=aws_access_key_id, | ||
aws_secret_access_key=aws_secret_access_key, | ||
region_name=s3_region, | ||
) | ||
|
||
logger = logging.getLogger() | ||
logger.setLevel(logging.INFO) | ||
|
||
|
||
def get_token_price_from_s3(bucket_name, key): | ||
try: | ||
logger.info(f"Fetching {key} from bucket {bucket_name}") | ||
response = s3_client.get_object(Bucket=bucket_name, Key=key) | ||
token_price = response["Body"].read().decode("utf-8") | ||
logger.info(f"Fetched price from S3: {token_price}") | ||
return token_price | ||
except s3_client.exceptions.NoSuchKey: | ||
logger.warning(f"{key} not found in bucket {bucket_name}") | ||
return None | ||
except Exception as e: | ||
logger.error(f"Error fetching {key} from bucket {bucket_name}: {str(e)}") | ||
return None | ||
|
||
|
||
def save_token_price_to_s3(bucket_name, key, token_price): | ||
try: | ||
logger.info(f"Saving {key} to bucket {bucket_name} with price {token_price}") | ||
s3_client.put_object(Bucket=bucket_name, Key=key, Body=str(token_price)) | ||
logger.info(f"Saved price {token_price} to S3 at {key}") | ||
except Exception as e: | ||
logger.error(f"Error saving {key} to bucket {bucket_name}: {str(e)}") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
import json | ||
|
||
|
||
def create_response(status_code, body): | ||
return { | ||
"statusCode": status_code, | ||
"headers": { | ||
"Access-Control-Allow-Origin": "*", | ||
"Access-Control-Allow-Methods": "GET", | ||
}, | ||
"body": json.dumps(body), | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
import dotenv from 'dotenv'; | ||
import { toast } from 'sonner'; | ||
|
||
dotenv.config(); | ||
|
||
const API_GATEWAY_ENDPOINT = process.env.API_GATEWAY_ENDPOINT; | ||
|
||
export const getTokenPrice = async (tokenTicker: string): Promise<number> => { | ||
if (['DAI', 'USDC', 'USDT'].includes(tokenTicker)) { | ||
return 1; | ||
} | ||
|
||
try { | ||
const response = await fetch(`${API_GATEWAY_ENDPOINT}/token/price?ticker=${tokenTicker}`, { | ||
method: 'GET', | ||
headers: { | ||
'Content-Type': 'application/json', | ||
}, | ||
}); | ||
|
||
if (!response.ok) { | ||
throw new Error(`Failed to fetch price for ${tokenTicker}: ${response.statusText}`); | ||
} | ||
|
||
const data: { price: number | string } = await response.json(); | ||
return Number(data.price); | ||
} catch (error) { | ||
toast.error( | ||
"Uh oh! 😞 We couldn't get price data for all of your tokens right now. Please try refreshing the page or check back later. 🔄", | ||
); | ||
throw new Error('Failed to fetch token price'); | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.