-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkeepalive-hermes.ts
302 lines (264 loc) · 8.12 KB
/
keepalive-hermes.ts
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
import { Command } from 'commander'
import { spawn } from 'child_process'
import { DirectSecp256k1HdWallet } from '@cosmjs/proto-signing'
import toml from 'toml'
import fs from 'fs'
import chainRegistry from 'chain-registry'
import { StargateClient } from '@cosmjs/stargate'
import { EmbedBuilder, WebhookClient } from 'discord.js'
type Config = {
mnemonic: string
discord: {
webhook_url: string
notify_user_ids: string[]
}
chains?: {
// Name in chain-registry
name: string
// Notify if balance drops below this threshold
notify_balance_threshold: number
// Override chain-registry RPC
rpc?: string
}[]
// Polytone connections to keep alive
connections: {
// Name in chain-registry
chain_a: string
// IBC client id
client_a: string
// Name in chain-registry
chain_b: string
// IBC client id
client_b: string
}[]
}
const spawnPromise = (cmd: string, args: string[]) =>
new Promise<string>((resolve, reject) => {
try {
const runCommand = spawn(cmd, args)
let output = ''
runCommand.stdout.on('data', (data) => (output += data.toString()))
runCommand.stderr.on('data', (data) => (output += data.toString()))
runCommand.on('error', (err) => {
reject(new Error(err.message))
})
runCommand.on('exit', (code) => {
if (code === 0) {
resolve(output)
} else {
reject(new Error(`[${code}] ${output}`))
}
})
} catch (e) {
reject(e)
}
})
const main = async () => {
const program = new Command()
program.option('-c, --config <config>', 'config file', 'config.toml')
program.parse()
const { config: configFile } = program.opts()
const config: Config = toml.parse(fs.readFileSync(configFile, 'utf-8'))
const webhookClient = new WebhookClient({
url: config.discord.webhook_url,
})
const sendDiscordNotification = async (
type: 'success' | 'error',
title: string,
description: string | null = null
) => {
const embed = new EmbedBuilder()
.setColor(type === 'success' ? '#00ff00' : '#ff0000')
.setTitle(title)
.setDescription(description)
.setTimestamp()
await webhookClient.send({
content:
type === 'error' && config.discord.notify_user_ids.length > 0
? `<@!${config.discord.notify_user_ids.join('>, <@!')}>`
: undefined,
embeds: [embed],
})
}
const connections = await Promise.all(
config.connections.map(async ({ chain_a, client_a, chain_b, client_b }) => {
//! CHAIN A
const chainA = chainRegistry.chains.find((c) => c.chain_name === chain_a)
if (!chainA) {
throw new Error(`chain A ${chain_a} not found`)
}
const chainAConfig = config.chains?.find((c) => c.name === chain_a)
// Get chain A RPC
const rpcA = chainAConfig?.rpc || chainA.apis?.rpc?.[0]?.address
if (!rpcA) {
throw new Error(`rpc not found for chain A ${chain_a}`)
}
const notifyBalanceThresholdA =
chainAConfig?.notify_balance_threshold ?? 0
// Get chain A wallet
const walletA = await DirectSecp256k1HdWallet.fromMnemonic(
config.mnemonic,
{
prefix: chainA.bech32_prefix,
}
)
const [{ address: addressA }] = await walletA.getAccounts()
const stargateA = await StargateClient.connect(rpcA)
//! CHAIN B
const chainB = chainRegistry.chains.find((c) => c.chain_name === chain_b)
if (!chainB) {
throw new Error(`chain B ${chain_b} not found`)
}
const chainBConfig = config.chains?.find((c) => c.name === chain_b)
// Get chain B RPC
const rpcB =
config.chains?.find((c) => c.name === chain_b)?.rpc ||
chainB.apis?.rpc?.[0]?.address
if (!rpcB) {
throw new Error(`rpc not found for chain B ${chain_b}`)
}
const notifyBalanceThresholdB =
chainBConfig?.notify_balance_threshold ?? 0
// Get chain B wallet
const walletB = await DirectSecp256k1HdWallet.fromMnemonic(
config.mnemonic,
{
prefix: chainB.bech32_prefix,
}
)
const [{ address: addressB }] = await walletB.getAccounts()
const stargateB = await StargateClient.connect(rpcB)
return {
a: {
chain: chainA,
denom: chainA.fees?.fee_tokens?.[0]?.denom ?? '',
wallet: walletA,
address: addressA,
client: client_a,
stargate: stargateA,
notifyBalanceThreshold: notifyBalanceThresholdA,
},
b: {
chain: chainB,
denom: chainB.fees?.fee_tokens?.[0]?.denom ?? '',
wallet: walletB,
address: addressB,
client: client_b,
stargate: stargateB,
notifyBalanceThreshold: notifyBalanceThresholdB,
},
}
})
)
const uniqueChains = Object.values(
connections.reduce(
(prev, { a, b }) => ({
...prev,
[a.chain.chain_name]: a,
[b.chain.chain_name]: b,
}),
{} as Record<string, (typeof connections)[number]['a']>
)
)
// Check balances...
await uniqueChains.reduce(
async (
prev,
{ chain, stargate, address, denom, notifyBalanceThreshold }
) => {
await prev
const balance = Number((await stargate.getBalance(address, denom)).amount)
console.log(`----- ${chain.chain_name} (${address})\n${balance}${denom}`)
if (balance < notifyBalanceThreshold) {
console.log(
`--- WARNING: balance is below ${notifyBalanceThreshold}${denom}`
)
// Notify via Discord
await sendDiscordNotification(
'error',
'Low Balance',
`Chain: \`${
chain.pretty_name
}\`\nAddress: \`${address}\`\nBalance: \`${balance.toLocaleString()}${denom}\``
)
}
console.log()
},
Promise.resolve()
)
// Update clients...
let updatedSuccessfully = 0
await connections.reduce(async (prev, { a, b }) => {
await prev
// Update client A
try {
console.log(
`----- updating ${a.chain.chain_name}=>${b.chain.chain_name} client ${a.client}...`
)
const outputA = await spawnPromise('hermes', [
'update',
'client',
'--host-chain',
a.chain.chain_id,
'--client',
a.client,
])
// If unsuccessful, throw output as error.
if (!outputA.includes('SUCCESS')) {
throw new Error(outputA)
}
console.log(outputA)
updatedSuccessfully++
} catch (err) {
console.error('ERROR:', err instanceof Error ? err.message : err)
// Notify via Discord
await sendDiscordNotification(
'error',
`${a.chain.pretty_name} :arrow_right: ${b.chain.pretty_name} update failure`,
`Chain ID: \`${a.chain.chain_id}\`\nIBC Client ID: \`${
a.client
}\`\n\`\`\`${err instanceof Error ? err.message : err}\`\`\``
)
}
// Update client B
try {
console.log(
`----- updating ${b.chain.chain_name} => ${a.chain.chain_name} client ${b.client}...`
)
const outputB = await spawnPromise('hermes', [
'update',
'client',
'--host-chain',
b.chain.chain_id,
'--client',
b.client,
])
// If unsuccessful, throw output as error.
if (!outputB.includes('SUCCESS')) {
throw new Error(outputB)
}
console.log(outputB)
updatedSuccessfully++
} catch (err) {
console.error('ERROR:', err instanceof Error ? err.message : err)
// Notify via Discord
await sendDiscordNotification(
'error',
`${b.chain.pretty_name} :arrow_right: ${a.chain.pretty_name} update failure`,
`Chain ID: \`${b.chain.chain_id}\`\nIBC Client ID: \`${
b.client
}\`\n\`\`\`${err instanceof Error ? err.message : err}\`\`\``
)
}
}, Promise.resolve())
// Notify via Discord
if (updatedSuccessfully > 0) {
await sendDiscordNotification(
'success',
`${updatedSuccessfully}/${
connections.length * 2
} clients updated successfully`
)
}
}
main().catch(console.error)