CreateBridgeTaskJob.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { CronJob } from './CronJob'
  2. import { DBClient } from '../singletons'
  3. import { Account, TaskStatus } from '@prisma/client'
  4. import { ChainId } from '../config/chain'
  5. export class CreateBridgeTaskJob extends CronJob {
  6. constructor() {
  7. super('CreateTask')
  8. }
  9. protected async run(): Promise<void> {
  10. // find all eligible accounts that is not in the middle of a task and not at ZKSync
  11. const eligibleAccounts = await DBClient.instance.account.findMany({
  12. where: {
  13. currentChainId: {
  14. not: ChainId.ZKSYNC,
  15. },
  16. Task: {
  17. none: {
  18. status: {
  19. in: [TaskStatus.AWAITING, TaskStatus.IN_PROGRESS],
  20. },
  21. },
  22. },
  23. },
  24. })
  25. // create a task for each eligible account
  26. for (const account of eligibleAccounts) {
  27. await DBClient.instance.account.update({
  28. where: {
  29. address: account.address,
  30. },
  31. data: {
  32. Task: {
  33. create: {
  34. scheduleTime: this.getRandomTime(30),
  35. fromChain: account.currentChainId,
  36. toChain: this.getRandomDestination(account),
  37. status: TaskStatus.AWAITING,
  38. },
  39. },
  40. },
  41. })
  42. }
  43. }
  44. private getRandomTime(hours: number) {
  45. const timespan = hours * 60 * 60 * 1000
  46. const randomMilliseconds = Math.floor(Math.random() * timespan)
  47. return new Date(Date.now() + randomMilliseconds)
  48. }
  49. private getRandomDestination(account: Account) {
  50. let toZkSync = false
  51. if (account.bridgeCount > 7 && account.bridgeCount < 10) {
  52. toZkSync = Math.random() > 0.5
  53. } else if (account.bridgeCount >= 10) {
  54. toZkSync = true
  55. }
  56. if (toZkSync) return ChainId.ZKSYNC
  57. const chainIds = Object.values(ChainId).filter(
  58. (value): value is number =>
  59. typeof value === 'number' && value !== account.currentChainId && value !== ChainId.ZKSYNC,
  60. )
  61. return chainIds[Math.floor(Math.random() * chainIds.length)]
  62. }
  63. }