import type { JSON_PayloadInMask , PoolRecord , PoolFromNetwork } from '../types' ; import * as subgraph from './apis/subgraph' ; import * as chain from './apis/chain' ; import * as database from './database' ; import { getChainDetailed , ChainId , getITOConstants } from '@masknet/web3-shared-evm' ; export async function getTradeInfo ( pid , trader ) { const tradeInfo = await subgraph . getTradeInfo ( pid , trader ) ; return tradeInfo ; } export async function getPool ( pid ) { const poolFromChain = await subgraph . getPool ( pid ) ; const poolFromDB = await database . getPoolFromDB ( pid ) ; if ( poolFromDB ?. payload . password ) poolFromChain . password = poolFromDB . payload . password ; return poolFromChain ; } export async function getAllPoolsAsSeller ( address , page , endBlock , chainId ) { const { ITO2_CONTRACT_CREATION_BLOCK_HEIGHT } = getITOConstants ( chainId ) ; const poolsFromSubgraph = await subgraph . getAllPoolsAsSeller ( address , page , chainId ) ; const latestPoolFromSubgraph = poolsFromSubgraph [ 0 ] ; const startBlockNumberFromChain = getLatestBlockNumberFromSubgraph ( latestPoolFromSubgraph , page , ITO2_CONTRACT_CREATION_BLOCK_HEIGHT ) ; const poolsFromChain = await chain . getAllPoolsAsSeller ( chainId , startBlockNumberFromChain , endBlock , address ) ; const poolsFromNetwork = poolsFromChain . concat ( poolsFromSubgraph ) ; const poolsFromDB = await database . getAllPoolsAsSeller ( poolsFromNetwork . map ( ( x ) => x . pool . pid ) ) ; return poolsFromNetwork . map ( ( x ) => { const pool = poolsFromDB . find ( ( y ) => y . payload . pid === x . pool . pid ) ; if ( ! pool ) return x ; return { ... x , pool : { ... x . pool , password : pool . payload . password , } , } ; } ) . filter ( ( x ) => x . pool . chain_id === chainId ) ; } export async function getAllPoolsAsBuyer ( address , chainId ) { const chainDetailed = getChainDetailed ( chainId ) ; if ( ! chainDetailed ) return [ ] ; const pools = await subgraph . getAllPoolsAsBuyer ( address , chainId ) ; return pools . filter ( ( x ) => x . pool . chain_id === chainId ) ; } export async function discoverPool ( from , payload ) { if ( ! payload . pid ) return ; if ( ! payload . password ) return ; const record_ = await database . getPoolFromDB ( payload . pid ) ; const record = { id : payload . pid , from : record_ ?. from || from , payload : { ... record_ ?. payload , ... payload , password : payload . password || ( record_ ?. payload . password ?? '' ) , } , } ; await database . addPoolIntoDB ( record ) ; } function getLatestBlockNumberFromSubgraph ( poolFromSubgraph , page , creationBlockNumber ) { return page === 0 ? poolFromSubgraph ?. pool ? poolFromSubgraph . pool . block_number ! + 1 : creationBlockNumber : undefined ; }