Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
theofandrich committed Oct 5, 2023
2 parents 6653efe + f068ace commit 781a1ea
Show file tree
Hide file tree
Showing 6 changed files with 79 additions and 6 deletions.
16 changes: 15 additions & 1 deletion src/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,12 @@ bot.use(async (ctx: BotContext, next: NextFunction): Promise<void> => {
firstResponseTime: 0n,
actualResponseTime: 0n,
sessionState: RequestState.Initial
},
payment: {
paymentTotal: 0,
paymentFreeCredits: 0,
paymentOneCredits: 0,
paymentFiatCredits: 0
}
}
const transaction = Sentry.startTransaction({ name: 'bot-command' })
Expand Down Expand Up @@ -139,6 +145,7 @@ bot.use(async (ctx: BotContext, next: NextFunction): Promise<void> => {
}
await next()
transaction.finish()

if (ctx.transient.analytics.module) {
const userId = Number(ctx.message?.from?.id ?? '0')
const username = ctx.message?.from?.username ?? ''
Expand All @@ -151,6 +158,9 @@ bot.use(async (ctx: BotContext, next: NextFunction): Promise<void> => {
const totalProcessingTime = (now() - startTime).toString()
const firstResponseTime = (ctx.transient.analytics.firstResponseTime - startTime).toString()
const actualResponseTime = (ctx.transient.analytics.actualResponseTime - startTime).toString()

const { paymentTotal, paymentFreeCredits, paymentOneCredits, paymentFiatCredits } = ctx.transient.payment

ES.add({
command,
text: ctx.message?.text ?? '',
Expand All @@ -161,7 +171,11 @@ bot.use(async (ctx: BotContext, next: NextFunction): Promise<void> => {
actualResponseTime,
refunded: ctx.transient.refunded,
sessionState: ctx.transient.analytics.sessionState,
totalProcessingTime
totalProcessingTime,
paymentTotal,
paymentFreeCredits,
paymentOneCredits,
paymentFiatCredits
}).catch((ex: any) => {
logger.error({ errorMsg: ex.message }, 'Failed to add data to ES')
})
Expand Down
28 changes: 26 additions & 2 deletions src/database/chat.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ interface UserCredits {
totalCreditsAmount: bn
}

interface CreditsPayment {
totalCredits: string
freeCredits: string
oneCredits: string
fiatCredits: string
}

export class ChatService {
creditsAssignedCache = new LRUCache<number, boolean>({ max: 1000, ttl: 24 * 60 * 60 * 1000 })

Expand Down Expand Up @@ -109,7 +116,13 @@ export class ChatService {
}
}

public async withdrawCredits (accountId: number, payAmount: bn): Promise<UserCredits> {
public async withdrawCredits (
accountId: number,
payAmount: bn
): Promise<{
userPayment: CreditsPayment
userCredits: UserCredits
}> {
const {
totalCreditsAmount,
creditAmount,
Expand Down Expand Up @@ -139,7 +152,18 @@ export class ChatService {
oneCreditAmount: oneCreditsNext.toFixed(),
fiatCreditAmount: fiatCreditNext.toFixed()
})
return await this.getUserCredits(accountId)

const userCredits = await this.getUserCredits(accountId)

return {
userPayment: {
totalCredits: payAmount.toFixed(),
freeCredits: creditsPayAmount.toFixed(),
oneCredits: oneCreditsPay.toFixed(),
fiatCredits: fiatCreditPay.toFixed()
},
userCredits
}
}

public async initChat ({ tgUserId, accountId, tgUsername = '' }: { tgUserId: number, accountId: number, tgUsername?: string }): Promise<Chat> {
Expand Down
4 changes: 4 additions & 0 deletions src/es/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ export interface BotLogData {
actualResponseTime: string // converted from bigint
refunded: boolean
sessionState: string
paymentTotal: number // float
paymentFreeCredits: number // float
paymentOneCredits: number // float
paymentFiatCredits: number // float
}

const Index = config.es.index ?? 'bot-logs'
Expand Down
12 changes: 12 additions & 0 deletions src/es/schemas/bot-logs.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,18 @@
},
"sessionState": {
"type": "keyword"
},
"paymentTotal": {
"type": "double"
},
"paymentFreeCredits": {
"type": "double"
},
"paymentOneCredits": {
"type": "double"
},
"paymentFiatCredits": {
"type": "double"
}
}
}
Expand Down
18 changes: 15 additions & 3 deletions src/modules/payment/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,12 @@ export class BotPayments {
return +value
}

public async fromONEToUSD (amountWei: string, fractionalDigits = 4): Promise<number> {
const currentRate = await this.getOneRate()
const amountONE = this.web3.utils.fromWei(amountWei, 'ether')
return +(currentRate * +amountONE).toFixed(fractionalDigits)
}

public async getAddressBalance (address: string): Promise<bn> {
const balance = await this.web3.eth.getBalance(address)
return bn(balance.toString())
Expand Down Expand Up @@ -397,13 +403,19 @@ export class BotPayments {
)

if (totalBalanceDelta.gte(0)) {
const balanceAfter = await chatService.withdrawCredits(accountId, totalPayAmount)
const { userPayment, userCredits: userCreditsAfter } = await chatService.withdrawCredits(accountId, totalPayAmount)
this.logger.info(`[${from.id} @${
from.username
}] successfully paid from credits, credits balance after: ${balanceAfter.totalCreditsAmount}`)
}] successfully paid from credits, credits balance after: ${userCreditsAfter.totalCreditsAmount}`)

freeCreditsFeeCounter.inc(this.convertBigNumber(totalPayAmount))
await this.writePaymentLog(ctx, totalPayAmount)

ctx.transient.payment.paymentTotal = await this.fromONEToUSD(userPayment.totalCredits)
ctx.transient.payment.paymentFreeCredits = await this.fromONEToUSD(userPayment.freeCredits)
ctx.transient.payment.paymentOneCredits = await this.fromONEToUSD(userPayment.oneCredits)
ctx.transient.payment.paymentFiatCredits = await this.fromONEToUSD(userPayment.fiatCredits)

freeCreditsFeeCounter.inc(this.convertBigNumber(totalPayAmount))
return true
} else {
const oneBalance = await this.getAddressBalance(userAccount.address)
Expand Down
7 changes: 7 additions & 0 deletions src/modules/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,13 @@ export interface Analytics {
actualResponseTime: bigint
sessionState: RequestState
module: string
}

export interface PaymentAnalytics {
paymentTotal: number
paymentFreeCredits: number
paymentOneCredits: number
paymentFiatCredits: number
}

export interface BotSessionData {
Expand All @@ -123,6 +129,7 @@ export interface TransientStateContext {
transient: {
analytics: Analytics
refunded: boolean
payment: PaymentAnalytics
}
}

Expand Down

0 comments on commit 781a1ea

Please sign in to comment.