-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmigrationService.ts
More file actions
185 lines (167 loc) · 7.34 KB
/
migrationService.ts
File metadata and controls
185 lines (167 loc) · 7.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
import { PrivateKeyManager } from './libs/PrivateKeyManager'
const privateKeyManager = new PrivateKeyManager()
import { env } from './env'
import { BlockchainConnectionProvider } from './libs/BlockchainConnectionProvider'
import { Address } from 'viem'
import {
filterAndaddNewFractalityTokenMigrations,
getUnmigratedFractalityTokenMigrations,
finalizeHlMigrations,
setHLMigrationStatus,
TokenMigration
} from './database'
import { HLMigration, MigrationRegisteredEvent, MigrationStatus } from './interfaces'
import { initializeDatabaseConnection } from './database'
import cron from 'node-cron'
import { PreviousBlockManager } from './libs/PreviousBlockManager'
import { HyperliquidManager } from './libs/HyperliquidManager'
import { FatalFinalizationError, MigrationPrepError, RedisError } from './errors'
import { RedisOperations } from './redisOperations/redisOperations'
import { Slack } from './libs/Slack'
export async function main(runWithCron: boolean) {
if (env.SLACK_TOKEN) {
Slack.initialize(env.SLACK_TOKEN!, env.SLACK_CHANNEL_ID!)
}
let blockManager: PreviousBlockManager | null = null
let blockchainConnectionProvider: BlockchainConnectionProvider | null = null
let hlManager: HyperliquidManager | null = null
let redisOperations: RedisOperations | null = null
try{
await privateKeyManager.init()
await initializeDatabaseConnection()
redisOperations = new RedisOperations()
await redisOperations.initialize()
hlManager = new HyperliquidManager(false, env.TESTNET, privateKeyManager.getPrivateKey())
blockchainConnectionProvider = new BlockchainConnectionProvider({
providerUrl: env.PROVIDER_URL,
y2kTokenMigrationAddress: env.Y2K_TOKEN_MIGRATION_ADDRESS as Address,
frctRTokenMigrationAddress: env.FRCT_R_MIGRATION_ADDRESS as Address
})
await hlManager.init(await blockchainConnectionProvider.getArbitrumTokenDecimals())
blockManager = new PreviousBlockManager(
redisOperations,
BigInt(env.SAFETY_CUSHION_NUMBER_OF_BLOCKS),
() => blockchainConnectionProvider!.getCurrentBlockNumber()
)
} catch (error) {
console.error("Error initializing migration service due to the following error, skipping this run", error);
throw error;
}
console.info('migration service initialized')
if (runWithCron) {
console.info('starting cron job for migrations, running every 5 minutes')
const scheduledTask = cron.schedule('* * * * *', async () => {
try {
await coreMigrationService(blockManager, blockchainConnectionProvider, hlManager)
} catch (error) {
if (error instanceof FatalFinalizationError) {
scheduledTask.stop()
} else {
console.info('Error in core migration service, this run will be skipped', error)
}
}
})
} else {
try {
if (await redisOperations.shouldRunAccordingToStopRunningFlag()) {
await coreMigrationService(blockManager, blockchainConnectionProvider, hlManager)
} else {
console.info('stopRunning flag is set, not running core migration service')
return
}
} catch (error) {
if (error instanceof FatalFinalizationError) {
await redisOperations.setStopRunningFlag()
} else {
console.info('Error in core migration service, this run will be skipped', error)
}
throw error
}
}
}
export async function coreMigrationService(
blockManager: PreviousBlockManager,
blockchainConnectionProvider: BlockchainConnectionProvider,
hlManager: HyperliquidManager
) {
//This, if fails will do a scan from the start block, not a big dea.
const fromBlock = await blockManager.getFromBlockForScan()
//This gets the current block and sets it in redis. If fails, will bubble up and this run will be skipped.
const toBlock = await blockManager.setFromBlockForScanToCurrentBlock()
console.info(`looking for migrations from block ${fromBlock} to block ${toBlock}`)
//Gets logs from the blockchain. If fails, will bubble up and this run will be skipped.
const y2kMigrations = await blockchainConnectionProvider.scanMigrations(
env.Y2K_TOKEN_MIGRATION_ADDRESS as Address,
fromBlock,
toBlock
)
const frctRMigrations = await blockchainConnectionProvider.scanMigrations(
env.FRCT_R_MIGRATION_ADDRESS as Address,
fromBlock,
toBlock
)
//This is atomic, if it fails, nothing was written and we can try again next time.
await addMigrationsToDatabase([...y2kMigrations, ...frctRMigrations])
//get migrations that still have not been sent to hyperliquid
//This includes the ones we added above... as well as those that were not migrated for some reason.
//If this fails, we will skip this run and try again next time.
const unmigratedMigrations: TokenMigration[] = await getUnmigratedFractalityTokenMigrations()
//calcualate the amount of tokens to send to hyperliquid
//If all the migrations are not able to be prepped, we will skip this run and try again next time.
//However, I don't see this failing as it's just doing some math.
const hlMigrations = await prepForHLMigration(hlManager, unmigratedMigrations)
console.info('hlMigrations', hlMigrations)
//This fails gracefully, the ones we could not send are in the faulures array.
const { successes, failures } = await hlManager.sendHLMigrations(hlMigrations)
console.info('successes', successes)
console.info('failures', failures)
let finalizationMaxRetries = 3
let migrationsToFinalize = successes
for (const attemptNumber of Array(finalizationMaxRetries).keys()) {
const finalizationResults = await finalizeHlMigrations(migrationsToFinalize)
if (finalizationResults.failures.length === 0) {
break
}
migrationsToFinalize = finalizationResults.failures
if (attemptNumber === finalizationMaxRetries - 1) {
throw new FatalFinalizationError(
'FATAL ERROR: Error finalizing HL migrations. The following migration need to manually be marked as sent to HL',
finalizationResults.failures
)
}
}
}
//Maybe I can add some in success and failure buckets.
async function prepForHLMigration(
hlManager: HyperliquidManager,
unmigratedMigrations: TokenMigration[]
): Promise<HLMigration[]> {
try {
const hlMigrations: HLMigration[] = []
for (const unmigratedMigration of unmigratedMigrations) {
if (unmigratedMigration.amount && unmigratedMigration.migrationAddress) {
const arbitrumAmount = BigInt(unmigratedMigration.amount)
const hlAmount = hlManager.decimalConversion!.convertToHlToken(arbitrumAmount)
hlMigrations.push({
originalTransactionHash: unmigratedMigration.transactionHash,
hlTokenAmount: hlAmount,
sendToAddress: unmigratedMigration.migrationAddress
})
} else {
console.error(
`migration with hash ${unmigratedMigration.transactionHash} has no amount or no migration address`
)
}
}
return hlMigrations
} catch (error) {
throw new MigrationPrepError('Error preparing for HL migration: ' + error)
}
}
async function addMigrationsToDatabase(migrations: MigrationRegisteredEvent[]) {
const result = await filterAndaddNewFractalityTokenMigrations(migrations) //TODO: make this batch
console.info(
`Inserted ${result.newMigrations.length} new migrations and found ${result.existingTxs.length} existing migrations`
)
console.info(`existing migrations that already exist in the database`, result.existingTxs)
}