import { ChainId , getRedPacketConstants } from '@masknet/web3-shared-evm' ; import type { RedPacketRecord , RedPacketJSONPayload , RedPacketJSONPayloadFromChain } from '../types' ; import * as subgraph from './apis/subgraph' ; import * as chain from './apis/chain' ; import * as database from './database' ; import * as nftDb from './databaseForNft' ; export { addRedPacketNft , getRedPacketNft , updateRedPacketNft } from './databaseForNft' ; export async function discoverRedPacket ( record ) { if ( record . contract_version === 1 ) { const txid = await subgraph . getRedPacketTxid ( record . id ) ; if ( ! txid ) return ; record . id = txid ; } database . addRedPacket ( record ) ; } export async function getRedPacketHistory ( address , chainId , endBlock ) { const { HAPPY_RED_PACKET_ADDRESS_V4_BLOCK_HEIGHT } = getRedPacketConstants ( chainId ) ; const redpacketsFromSubgraph = await subgraph . getRedPacketHistory ( address , chainId ) ; const latestPoolFromSubgraph = redpacketsFromSubgraph [ 0 ] ; const startBlockNumberFromChain = getLatestBlockNumberFromSubgraph ( latestPoolFromSubgraph , HAPPY_RED_PACKET_ADDRESS_V4_BLOCK_HEIGHT ) ; const redpacketsFromChain = await chain . getRedPacketHistory ( chainId , startBlockNumberFromChain , endBlock , address ) ; const redpacketsFromNetwork = ( redpacketsFromChain as ( RedPacketJSONPayloadFromChain | RedPacketJSONPayload ) [ ] ) . concat ( redpacketsFromSubgraph ) ; const redpacketsFromDatabase = await database . getAllRedpackets ( redpacketsFromNetwork . map ( ( x ) => x . txid ) ) ; return redpacketsFromNetwork . map ( ( x ) => { const record = redpacketsFromDatabase . find ( ( y ) => y . id === x . txid ) ; if ( ! record ) return x ; return { ... x , password : record . password , } ; } ) ; } export async function getNftRedPacketHistory ( address , chainId , page ) { const histories = await subgraph . getNftRedPacketHistory ( address , page ) ; const historiesWithPassword = [ ] ; for ( const history of histories ) { const record = await nftDb . getRedPacketNft ( history . txid ) ; if ( history . chain_id === chainId && record ) { history . password = record . password ; history . payload . password = record . password ; } else { history . password = '' ; history . payload . password = '' ; } historiesWithPassword . push ( history ) ; } return historiesWithPassword ; } function getLatestBlockNumberFromSubgraph ( redpacketFromSubgraph , creationBlockNumber ) { return redpacketFromSubgraph ? redpacketFromSubgraph . block_number ! + 1 : creationBlockNumber ; }