Skip to content

Commit

Permalink
Merge pull request #78 from initia-labs/feat/tx-search
Browse files Browse the repository at this point in the history
Feat/tx-search
  • Loading branch information
joon9823 authored Sep 10, 2024
2 parents a87190d + 973686d commit 51e0590
Showing 1 changed file with 60 additions and 6 deletions.
66 changes: 60 additions & 6 deletions src/client/lcd/api/TxAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ export namespace TxResult {

export interface TxSearchResult {
pagination: Pagination
total: number
txs: TxInfo[]
}

Expand All @@ -148,6 +149,7 @@ export namespace TxSearchResult {
txs: Tx.Data[]
tx_responses: TxInfo.Data[]
pagination: Pagination
total: string
}
}

Expand Down Expand Up @@ -187,13 +189,14 @@ export namespace SimulateResponse {
}

export type TxSearchOp = '=' | '<' | '<=' | '>' | '>=' | 'CONTAINS' | 'EXISTS'

export interface TxSearchQuery {
key: string
value: string
op?: TxSearchOp
}
export interface TxSearchOptions extends PaginationOptions {
query: {
key: string
value: string
op?: TxSearchOp
}[]
page: number
query: TxSearchQuery[]
}

export class TxAPI extends BaseAPI {
Expand Down Expand Up @@ -545,7 +548,58 @@ export class TxAPI extends BaseAPI {
TxInfo.fromData(tx_response)
),
pagination: d.pagination,
total: Number(d.total),
}
})
}

public async searchEvents(
moduleAddr: string,
moduleName: string,
startHeight: number,
endHeight: number
): Promise<Event[]> {
if (endHeight < startHeight) {
throw new Error(`Start height cannot be greater than end height`)
}

if (endHeight - startHeight > 100) {
throw new Error(`Query height range cannot be greater than 100`)
}

const targetEvents: Event[] = []
const targetTag = `${moduleAddr}::${moduleName}`
const query: TxSearchQuery[] = [
{ key: 'tx.height', value: startHeight.toString(), op: '>=' },
{ key: 'tx.height', value: endHeight.toString(), op: '<=' },
{ key: 'move.type_tag', value: targetTag, op: 'CONTAINS' },
]
const filterEvents = (tx: TxInfo) => {
return tx.events.filter((event) => {
if (event.type !== 'move') return false
const typeTag = event.attributes.find((attr) => attr.key === 'type_tag')
return typeTag && typeTag.value.startsWith(targetTag)
})
}

const { txs, total } = await this.search({ query })
const events = txs.flatMap((tx) => filterEvents(tx))
targetEvents.push(...events)

if (total > 100) {
const lastPage = Math.ceil(total / 100)
// if last page = 10, pages = [2, 3, 4, 5, ..., 10]
const pages = [...Array(lastPage - 1).keys()].map((page) => page + 2)
const eventsList: Event[][] = await Promise.all(
pages.map(async (page) => {
return this.search({ query, page }).then((res) =>
res.txs.flatMap((tx) => filterEvents(tx))
)
})
)
targetEvents.push(...eventsList.flat())
}

return targetEvents
}
}

0 comments on commit 51e0590

Please sign in to comment.