diff --git a/common/utils/garage.py b/common/utils/garage.py deleted file mode 100644 index 86ac6fc..0000000 --- a/common/utils/garage.py +++ /dev/null @@ -1,74 +0,0 @@ -import os -from typing import List - -from gql.dsl import dsl_gql, DSLQuery -from sqlalchemy import select, distinct - -from common import logger -from common._crypto import Account -from common._graphql import GQL -from common.models.garage import GarageItemStatus -from common.models.product import FungibleItemProduct -from common.utils.aws import fetch_kms_key_id - - -def update_iap_garage(sess, url: str): - client = GQL(url) - account = Account(fetch_kms_key_id(os.environ.get("STAGE", "development"), os.environ.get("REGION_NAME"))) - fungible_id_list = sess.scalars(select(distinct(FungibleItemProduct.fungible_item_id))).fetchall() - query = dsl_gql( - DSLQuery( - client.ds.StandaloneQuery.stateQuery.select( - client.ds.StateQuery.garages.args( - agentAddr=account.address, - fungibleItemIds=fungible_id_list, - ).select( - client.ds.GaragesType.agentAddr, - client.ds.GaragesType.fungibleItemGarages.select( - client.ds.FungibleItemGarageWithAddressType.fungibleItemId, - client.ds.FungibleItemGarageWithAddressType.count, - ) - ) - ) - ) - ) - resp = client.execute(query) - if "errors" in resp: - msg = f"GQL failed to get IAP garage: {resp['errors']}" - logger.error(msg) - # TODO: Send message to recognize - # raise Exception(msg) - return {} - - data = {x["fungibleItemId"]: x["count"] for x in resp["stateQuery"]["garages"]["fungibleItemGarages"]} - target_garages = sess.scalars( - select(GarageItemStatus).where(GarageItemStatus.address == account.address) - ).all() - for garage_status in target_garages: - amount = data.pop(garage_status.fungible_id, 0) - garage_status.amount = amount or 0 - sess.add_all(target_garages) - logger.info(f"{len(target_garages)} garages are updated") - - for fungible_id, amount in data.items(): - sess.add(GarageItemStatus(address=account.address, fungible_id=fungible_id, amount=amount or 0)) - logger.info(f"{len(data)} garages are added") - return data - - -def get_iap_garage(sess) -> List[GarageItemStatus]: - """ - Get NCG balance and fungible item count of IAP address. - :return: - """ - stage = os.environ.get("STAGE", "development") - region_name = os.environ.get("REGION_NAME", "us-east-2") - account = Account(fetch_kms_key_id(stage, region_name)) - - fungible_id_list = sess.scalars(select(distinct(FungibleItemProduct.fungible_item_id))).fetchall() - return sess.scalars( - select(GarageItemStatus).where( - GarageItemStatus.address == account.address, - GarageItemStatus.fungible_id.in_(fungible_id_list) - ) - ) diff --git a/iap/api/admin.py b/iap/api/admin.py index f4f1157..b65faf8 100644 --- a/iap/api/admin.py +++ b/iap/api/admin.py @@ -7,7 +7,6 @@ from common.enums import Store, ReceiptStatus from common.models.receipt import Receipt -from common.utils.garage import update_iap_garage from common.utils.google import update_google_price from iap import settings from iap.dependencies import session @@ -37,11 +36,6 @@ def update_price(store: Store, sess=Depends(session)): return f"{updated_price_count} prices in {updated_product_count} products are updated." -@router.get("/update-garage") -def update_garage(sess=Depends(session)): - return update_iap_garage(sess) - - @router.get("/refunded", response_model=List[RefundedReceiptSchema]) def fetch_refunded( start: Annotated[ diff --git a/iap/api/history.py b/iap/api/history.py index 063ef3d..3aaa468 100644 --- a/iap/api/history.py +++ b/iap/api/history.py @@ -5,16 +5,11 @@ from typing import Dict import requests -from fastapi import APIRouter, Depends, HTTPException -from sqlalchemy import desc, select -from sqlalchemy.exc import NoResultFound -from sqlalchemy.orm import Session +from fastapi import APIRouter, HTTPException from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR from common import logger from common.consts import HOST_LIST -from common.models.garage import GarageActionHistory -from iap.dependencies import session router = APIRouter( prefix="/history", @@ -101,48 +96,3 @@ def sync_block(block_data): logger.info("=" * 32) logger.info(f"{cnt} actions are processed") - - -@router.get("/sync") -def sync_block_history(start: int = None, end: int = None, limit: int = 100, sess: Session = Depends(session)): - tip_query = """query { blockQuery { blocks(desc: true limit: 1) { index } } }""" - resp = request(EXPLORER_URL, {"query": tip_query}) - tip = resp["data"]["blockQuery"]["blocks"][0]["index"] - - if end is None: - end = tip - - if start is None: - # Start from last block on DB - try: - last_block = sess.execute( - select(GarageActionHistory).order_by(desc(GarageActionHistory.block_index)) - ).scalars().one() - except NoResultFound: - last_block = None - - if not last_block: - start = end - limit - - logger.info(f"{start} ~ {end}, limit {limit}") - - query = f""" - query {{ blockQuery {{ blocks(desc: true offset: {tip - start} limit: {limit}) {{ - hash index timestamp transactions {{ id signer timestamp actions {{ json }} }} - }} }} }} - """ - resp = request(EXPLORER_URL, {"query": query}) - - block_list = resp["data"]["blockQuery"]["blocks"] - logger.info(f"{len(block_list)} blocks are fetched") - if len(block_list) == 0: - msg = f"No block containing transactions found between {start} and {end}" - logger.warning(msg) - return msg - - for block in block_list: - sync_block(block) - - result = f"{len(block_list)} blocks synced: from {block_list[-1]['index']} to {block_list[0]['index']}" - logger.info(result) - return result diff --git a/iap/utils.py b/iap/utils.py index 7f883f7..b5de80a 100644 --- a/iap/utils.py +++ b/iap/utils.py @@ -8,11 +8,11 @@ from common import logger from common.enums import ReceiptStatus +from common.models.mileage import Mileage from common.models.product import Product from common.models.receipt import Receipt from common.utils.receipt import PlanetID from iap import settings -from models.mileage import Mileage def get_purchase_history(sess, planet_id: PlanetID, address: str, product: Optional[Product] = None,