Skip to content

Commit

Permalink
Merge pull request #249 from cardanoapi/fix/db-sync
Browse files Browse the repository at this point in the history
Fix/db sync
  • Loading branch information
mesudip authored Nov 6, 2024
2 parents d34a2ca + 20dc219 commit 7b5c8d7
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 13 deletions.
12 changes: 10 additions & 2 deletions agent-manager/src/utils/fuacet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,20 @@ export default async function getFaucetAdaForAddress(address: string) {

export async function fetchWalletBalance(address: string) {
const kuberUrl = environments.kuberBaseUrl
const kuberApiKey = environments.kuberApiKey
if (!kuberUrl) return 0
const url = kuberUrl + '/api/v3/utxo?address=' + address
return fetch(url)
return fetch(url, {
method: 'GET',
headers: {
'api-key': kuberApiKey,
},
})
.then((res) => res.json())
.then((data: any) => {
return data.reduce((totalVal: number, item: any) => totalVal + item.value.lovelace, 0) / 10 ** 6
if (Array.isArray(data)) {
return data.reduce((totalVal: number, item: any) => totalVal + item.value.lovelace, 0) / 10 ** 6
} else return 0
})
.catch((error) => {
throw error
Expand Down
4 changes: 2 additions & 2 deletions api/backend/app/controllers/internal/drep_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ def __init__(self, *args, **kwargs) -> None:
@get("/dreps", response_model=Page)
async def get_all_dreps(self, page: int = 1, pageSize: int = 10, drep_type: str = "all", search: str | None = None):
if drep_type == "internal":
[dreps, total_count] = await self.drep_service.fetch_internal_dreps(page, pageSize, search)
return Page(items=dreps, total=total_count, page=page, size=pageSize, pages=1)
dreps = await self.drep_service.fetch_internal_dreps(page, pageSize, search)
return Page(items=dreps, total=len(dreps), page=page, size=pageSize, pages=1)
else:
drep_data = await self.drep_service.fetch_external_dreps(page, pageSize, search)

Expand Down
11 changes: 6 additions & 5 deletions api/backend/app/services/drep_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ def __init__(self):
self.db = prisma_connection

async def fetch_internal_dreps(self, page: int, page_size: int, search: str | None):
total_count = 0
if search:
try:
internalDrep = await self.db.prisma.agentwalletdetails.find_first(
Expand All @@ -32,21 +31,21 @@ async def fetch_internal_dreps(self, page: int, page_size: int, search: str | No
except:
agents = []
else:
[agents, total_count] = await asyncio.gather(
[agents] = await asyncio.gather(
self.db.prisma.agent.find_many(
include={"wallet_details": True},
where={"deleted_at": None, "is_drep_registered": True},
skip=(page - 1) * page_size,
take=page_size,
order={"last_active": "desc"},
),
self.db.prisma.agent.count(where={"deleted_at": None, "is_drep_registered": True}),
)
async with aiohttp.ClientSession() as session:
async with asyncio.TaskGroup() as tg:
for index, agent in enumerate(agents):
tg.create_task(self.fetch_metadata(agent, index, agents, session))
return [agents, total_count]

return [agent for agent in agents if agent]

async def fetch_metadata(self, agent: Agent, index: int, agents: [Any], session: ClientSession):
drep_dict = {}
Expand All @@ -72,6 +71,8 @@ async def fetch_metadata(self, agent: Agent, index: int, agents: [Any], session:
if drep_dict:
drep_dict = drep_dict | {"agentId": agent.id, "agentName": agent.name}
agents[index] = drep_dict
else:
agents[index] = ""

async def fetch_external_dreps(self, page: int, page_size: int, search: str | None):

Expand All @@ -92,7 +93,7 @@ async def fetch_external_dreps(self, page: int, page_size: int, search: str | No

try:
internalDrep = await self.db.prisma.agentwalletdetails.find_first(
where={"stake_key_hash": convert_hex_to_base64(drep["drepId"])}
where={"stake_key_hash": convert_string_to_base64(drep["drepId"])}
)
except Exception as e:
internalDrep = False
Expand Down
24 changes: 20 additions & 4 deletions dbsync-api/src/repository/drep.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export const fetchDrepList = async (page=1,size=10,drepId='', status?:DrepStatus
'status', CASE
WHEN dr_deposit.deposit > 0 AND (DRepActivity.epoch_no - Max(coalesce(block.epoch_no, block_first_register.epoch_no))) <= DRepActivity.drep_activity THEN 'Active'
WHEN dr_deposit.deposit > 0 AND (DRepActivity.epoch_no - Max(coalesce(block.epoch_no, block_first_register.epoch_no))) > DRepActivity.drep_activity THEN 'Inactive'
WHEN dr_deposit.deposit < 0 THEN 'Retired'
WHEN dr_deposit.deposit < 0 THEN 'Retired'
END,
'latestTxHash', encode(dr_voting_anchor.tx_hash, 'hex'),
'latestRegistrationDate', newestRegister.time,
Expand Down Expand Up @@ -81,7 +81,9 @@ export const fetchDrepList = async (page=1,size=10,drepId='', status?:DrepStatus
tx.hash AS tx_hash
FROM
drep_registration dr
JOIN tx ON tx.id = dr.tx_id) AS dr_voting_anchor ON dr_voting_anchor.drep_hash_id = dh.id
JOIN tx ON tx.id = dr.tx_id
WHERE dr.deposit > 0
) AS dr_voting_anchor ON dr_voting_anchor.drep_hash_id = dh.id
AND dr_voting_anchor.rn = 1
LEFT JOIN (
SELECT
Expand All @@ -108,7 +110,7 @@ export const fetchDrepList = async (page=1,size=10,drepId='', status?:DrepStatus
LEFT JOIN DRepDistr ON DRepDistr.hash_id = dh.id
AND DRepDistr.rn = 1
LEFT JOIN voting_anchor va ON va.id = dr_voting_anchor.voting_anchor_id
LEFT JOIN voting_anchor non_deregister_voting_anchor on non_deregister_voting_anchor.id = dr_non_deregister_voting_anchor.voting_anchor_id
LEFT JOIN voting_anchor non_deregister_voting_anchor on non_deregister_voting_anchor.id = dr_non_deregister_voting_anchor.voting_anchor_id
LEFT JOIN off_chain_vote_fetch_error ON off_chain_vote_fetch_error.voting_anchor_id = va.id
LEFT JOIN off_chain_vote_data ON off_chain_vote_data.voting_anchor_id = va.id
LEFT JOIN off_chain_vote_drep_data on off_chain_vote_drep_data.off_chain_vote_data_id = off_chain_vote_data.id
Expand Down Expand Up @@ -139,7 +141,7 @@ export const fetchDrepList = async (page=1,size=10,drepId='', status?:DrepStatus
LEFT JOIN tx AS tx_first_register ON tx_first_register.id = dr_first_register.tx_id
LEFT JOIN block AS block_first_register ON block_first_register.id = tx_first_register.block_id
${drepId ? Prisma.sql`WHERE dh.raw = decode(${drepId}, 'hex')` : Prisma.sql``}
GROUP BY
GROUP BY
dh.raw,
second_to_newest_drep_registration.voting_anchor_id,
dh.view,
Expand Down Expand Up @@ -344,7 +346,20 @@ export const fetchDrepDetails=async(drepId:string)=>{
LIMIT 1
),
IsScriptHash AS (
SELECT EXISTS(
SELECT
drep_hash.has_script
FROM
drep_hash
CROSS JOIN DRepId
WHERE
drep_hash.raw = DRepId.raw
AND
drep_hash.has_script = true
) AS has_script),
DrepDetails AS (SELECT
IsScriptHash.has_script as "hasScript",
IsRegisteredAsDRep.value as "isRegisteredAsDRep",
WasRegisteredAsDRep.value as "wasRegisteredAsDRep",
IsRegisteredAsSoleVoter.value as "isRegisteredAsSoleVoter",
Expand All @@ -369,6 +384,7 @@ export const fetchDrepDetails=async(drepId:string)=>{
CROSS JOIN DRepRetire
CROSS JOIN SoleVoterRegister
CROSS JOIN SoleVoterRetire
CROSS JOIN IsScriptHash
)
SELECT
Expand Down
3 changes: 3 additions & 0 deletions dbsync-api/swagger.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,9 @@ paths:
schema:
type: object
properties:
hasScript:
type: boolean
description: whether the drep has script or not
isRegisteredAsDRep:
type: boolean
description: Whether the address is currently registered as a DRep.
Expand Down

0 comments on commit 7b5c8d7

Please sign in to comment.