Skip to content

Commit

Permalink
Refactoring init event (#125)
Browse files Browse the repository at this point in the history
  • Loading branch information
sleyter93 authored Dec 22, 2023
1 parent 9b3f09f commit 17fff9c
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 104 deletions.
2 changes: 1 addition & 1 deletion packages/rifWalletServices/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@rsksmart/rif-wallet-services",
"version": "1.2.0",
"version": "1.2.1",
"description": "RIF Wallet Services library",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand Down
10 changes: 5 additions & 5 deletions packages/rifWalletServices/src/RifWalletServicesFetcher.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {
FetchBalancesTransactionsPricesByAddressFunction,
FetchBalancesTransactionsPricesByAddressFunctionResult,
SearchAddressDetailsFunction,
AddressDetailsResponse,
IRegisteredDappsGroup,
ITokenWithBalance, IXPubBalanceData,
RifWalletFetcherDependencies, RIFWalletServicesFetcherInterface,
Expand Down Expand Up @@ -85,10 +85,10 @@ export class RifWalletServicesFetcher implements RIFWalletServicesFetcherInterfa
return response.data
}

fetchBalancesTransactionsPricesByAddress = async ({ address, prev, next, blockNumber = '0', limit }: FetchBalancesTransactionsPricesByAddressFunction) => {
fetchBalancesTransactionsPricesByAddress = async ({ address, prev, next, blockNumber = '0', limit }: SearchAddressDetailsFunction) => {
const addressLowerCase = address.toLowerCase()
const url = `/address/${addressLowerCase}/all`
const promise = this.axiosInstance.get<FetchBalancesTransactionsPricesByAddressFunctionResult>(url, { params: { prev, next, blockNumber, limit } })
const url = `/address/${addressLowerCase}`
const promise = this.axiosInstance.get<AddressDetailsResponse>(url, { params: { prev, next, blockNumber, limit } })
const response = await this.retryPromise(promise, 2)
return response.data
}
Expand Down
102 changes: 9 additions & 93 deletions packages/rifWalletServices/src/RifWalletServicesSocket.ts
Original file line number Diff line number Diff line change
@@ -1,109 +1,25 @@
import EventEmitter from 'events'
import { io, Socket } from 'socket.io-client'

import { IAbiEnhancer } from '@rsksmart/rif-wallet-abi-enhancer'
import { RifWalletServicesFetcher } from './RifWalletServicesFetcher'

import {
CacheInterface, EnhanceTransactionFunction,
FilterOutRepeatedTransactionsFunction,
AddressDetailsResponse,
Header,
IApiTransaction,
IRifWalletServicesSocket, IServiceChangeEvent, OnBeforeInitFunction,
RifWalletSocketDependencies
IRifWalletServicesSocket, IServiceChangeEvent,
} from './types'

export class RifWalletServicesSocket
extends EventEmitter
implements IRifWalletServicesSocket {
private rifWalletServicesUrl: string
private abiEnhancer: IAbiEnhancer
private socket: Socket | undefined
onFilterOutRepeatedTransactions: FilterOutRepeatedTransactionsFunction
onEnhanceTransaction: EnhanceTransactionFunction
cache: CacheInterface
cacheTexts = {
cacheBlockNumberText: 'blockNumber',
cacheTxsText: 'cachedTxs'
}

onBeforeInit: OnBeforeInitFunction
constructor(rifWalletServicesUrl: string, abiEnhancer: IAbiEnhancer, dependencies: RifWalletSocketDependencies, cacheTextOptions?: {
cacheBlockNumberText: string
cacheTxsText: string
}
) {
constructor(rifWalletServicesUrl: string) {
super()

this.abiEnhancer = abiEnhancer
this.rifWalletServicesUrl = rifWalletServicesUrl
this.onFilterOutRepeatedTransactions = dependencies.onFilterOutRepeatedTransactions
this.cache = dependencies.cache
this.onBeforeInit = dependencies.onBeforeInit
this.onEnhanceTransaction = dependencies.onEnhanceTransaction
this.cacheTexts.cacheTxsText = cacheTextOptions?.cacheTxsText || this.cacheTexts.cacheTxsText
this.cacheTexts.cacheBlockNumberText = cacheTextOptions?.cacheBlockNumberText || this.cacheTexts.cacheBlockNumberText
}

private async init(
address: string,
chainId: number,
fetcher: RifWalletServicesFetcher,
) {
this.onBeforeInit(this)
const { cacheBlockNumberText, cacheTxsText } = this.cacheTexts

const blockNumber = this.cache.get(cacheBlockNumberText) || '0'
const catchedTxs = this.cache.get(cacheTxsText) || []

const { prices, tokens: fetchedTokens, transactions: fetchedTransactions } = await fetcher.fetchBalancesTransactionsPricesByAddress({ address, blockNumber })

let lastBlockNumber = blockNumber
const activityTransactions = await Promise.all(
fetchedTransactions.data.map(async (tx: IApiTransaction) => {
if (parseInt(blockNumber, 10) < tx.blockNumber) {
lastBlockNumber = tx.blockNumber
}
if (this.cache.has(tx.hash)) {
return {
originTransaction: tx,
enhancedTransaction: this.cache.get(tx.hash),
}
}
const enhancedTransaction = await this.onEnhanceTransaction(tx, chainId)
if (enhancedTransaction) {
this.cache.set(tx.hash, enhancedTransaction)
return {
originTransaction: tx,
enhancedTransaction,
}
} else {
return {
originTransaction: tx,
enhancedTransaction: undefined,
}
}
}),
)
const transactions = catchedTxs
.concat(activityTransactions)
.filter(this.onFilterOutRepeatedTransactions)

this.cache.set(cacheTxsText, transactions)
this.cache.set(cacheBlockNumberText, lastBlockNumber.toString())

this.emit('init', {
transactions: transactions,
balances: fetchedTokens,
prices,
})
}

async connect(address: string, chainId: number,
fetcher: RifWalletServicesFetcher, headers: Header) {
connect(address: string, chainId: number, headers: Header) {
try {
await this.init(address, chainId, fetcher)

const socket = io(this.rifWalletServicesUrl, {
path: '/ws',
forceNew: true,
Expand All @@ -119,8 +35,13 @@ export class RifWalletServicesSocket
this.emit('change', event)
})

socket.on('init', (event: AddressDetailsResponse) => {
this.emit('init', event)
})

socket.emit('subscribe', {
address,
chainId
})
})

Expand All @@ -146,9 +67,4 @@ export class RifWalletServicesSocket

return this.socket.connected
}

setCache(cache: CacheInterface) {
this.cache = cache
return cache
}
}
8 changes: 3 additions & 5 deletions packages/rifWalletServices/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { ContractReceipt } from '@ethersproject/contracts'
import EventEmitter from 'events'
import { RifWalletServicesFetcher } from './RifWalletServicesFetcher'
import { EnhancedResult } from '@rsksmart/rif-wallet-abi-enhancer'
import { RifWalletServicesSocket } from './RifWalletServicesSocket'

Expand Down Expand Up @@ -170,9 +169,8 @@ export interface IRifWalletServicesSocket extends EventEmitter {
connect: (
address: string,
chainId: number,
fetcher: RifWalletServicesFetcher,
headers: Header
) => Promise<void>
) => void

disconnect(): void
isConnected(): boolean
Expand Down Expand Up @@ -203,15 +201,15 @@ export type RifWalletSocketDependencies = {
onEnhanceTransaction: EnhanceTransactionFunction
}

export interface FetchBalancesTransactionsPricesByAddressFunction {
export interface SearchAddressDetailsFunction {
address: string
blockNumber?: string
prev?: string
next?: string
limit?: string
}

export interface FetchBalancesTransactionsPricesByAddressFunctionResult {
export interface AddressDetailsResponse {
tokens: ITokenWithBalance[]
prices: Record<string, { price: number, lastUpdated: string }>
transactions: TransactionsServerResponse
Expand Down

0 comments on commit 17fff9c

Please sign in to comment.