├── discord-bot ├── .gitignore ├── package.json ├── commands │ └── vote.js ├── index.js ├── deploy-commands.js └── .eslintrc.json ├── .gitmodules ├── src ├── services │ ├── database │ │ ├── instantiator.ts │ │ └── services │ │ │ └── hasura.ts │ ├── watcher.ts │ ├── distribution.ts │ ├── proposals.ts │ ├── status.ts │ └── rewards.ts ├── helpers │ ├── reprefix.ts │ ├── interval.factory.ts │ ├── global.types.ts │ ├── class.report.ts │ ├── balances.ts │ ├── socket.factory.ts │ ├── rpc_query │ │ ├── block.ts │ │ ├── delegate.ts │ │ └── send.ts │ ├── notify.ts │ ├── queryOnChainProposals.ts │ └── utils.ts ├── commands │ ├── help.ts │ ├── config.ts │ └── vote │ │ ├── handler.ts │ │ └── tx.ts ├── server.ts └── index.ts ├── nodemon.json ├── nodemon.prod.json ├── changelog.md ├── templates ├── authz-sending.json ├── authz-sending-v47.json ├── authz-voting.json ├── fee-grant.json ├── authz-managing.json ├── authz-restaking.json └── authz-all.json ├── package.json ├── .gitignore ├── configs └── default.json ├── tsconfig.json ├── README.md └── LICENSE /discord-bot/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .env 3 | config.json -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "proto/cosmos-sdk"] 2 | path = proto/cosmos-sdk 3 | url = git@github.com:cosmos/cosmos-sdk.git 4 | -------------------------------------------------------------------------------- /src/services/database/instantiator.ts: -------------------------------------------------------------------------------- 1 | //simple instatiator to allow for multiple database adaptors 2 | 3 | import { dbMethods as hasura } from './services/hasura' 4 | 5 | const services = { 6 | hasura, 7 | } 8 | 9 | export const instantiator = { 10 | init(service) { 11 | return services[service] || null 12 | } 13 | } -------------------------------------------------------------------------------- /nodemon.json: -------------------------------------------------------------------------------- 1 | { 2 | "restartable": "rs", 3 | "ignore": [ 4 | ".git", 5 | "node_modules/", 6 | "dist/", 7 | "coverage/" 8 | ], 9 | "watch": [ 10 | "src" 11 | ], 12 | "execMap": { 13 | "ts": "node -r tsconfig-paths/register -r ts-node/register" 14 | }, 15 | "env": { 16 | "NODE_ENV": "development" 17 | }, 18 | "ext": "json,ts" 19 | } -------------------------------------------------------------------------------- /src/helpers/reprefix.ts: -------------------------------------------------------------------------------- 1 | 2 | import { bech32 } from "bech32" 3 | 4 | export const reprefix = (oldAddress, newPrefix) => { 5 | // Decode the bech32 address to get the public key hash 6 | const decoded = bech32.decode(oldAddress); 7 | 8 | // Encode the address with a new prefix 9 | const newAddress = bech32.encode(newPrefix, decoded.words); 10 | 11 | return newAddress 12 | } -------------------------------------------------------------------------------- /nodemon.prod.json: -------------------------------------------------------------------------------- 1 | { 2 | "restartable": "rs", 3 | "ignore": [ 4 | ".git", 5 | "node_modules/", 6 | "dist/", 7 | "coverage/" 8 | ], 9 | "watch": [ 10 | "src" 11 | ], 12 | "execMap": { 13 | "ts": "node -r ts-node/register" 14 | }, 15 | "env": { 16 | "NODE_ENV": "production" 17 | }, 18 | "ext": "json,ts" 19 | } -------------------------------------------------------------------------------- /discord-bot/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "discord-bot", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "devDependencies": { 13 | "eslint": "^8.26.0" 14 | }, 15 | "dependencies": { 16 | "axios": "^1.1.3", 17 | "discord.js": "^14.6.0", 18 | "dotenv": "^16.0.3" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/commands/help.ts: -------------------------------------------------------------------------------- 1 | import { Router, Request, Response } from "express"; 2 | const express = require('express') 3 | const router: Router = express.Router(); 4 | 5 | const handler = async (req: Request, res: Response) => { 6 | try { 7 | res.status(200).send(JSON.stringify(res.locals.CONFIGS)); 8 | } catch (e) { 9 | console.log("VOTE ERROR",e) 10 | res.status(400).send(e.message || e); 11 | } 12 | } 13 | 14 | router.post('/',handler) 15 | 16 | export default router; -------------------------------------------------------------------------------- /src/commands/config.ts: -------------------------------------------------------------------------------- 1 | import { Router, Request, Response } from "express"; 2 | const express = require('express') 3 | const router: Router = express.Router(); 4 | 5 | const handler = async (req: Request, res: Response) => { 6 | try { 7 | let cmd = req.body.text.split(" ") 8 | let propString = cmd[0] 9 | let value = cmd[1] 10 | let nestedProperties = propString.split(".") 11 | let result = nestedProperties.reduce((acc,prop)=>acc[prop],res.locals.CONFIGS) 12 | if (value.trim().length > 0) { 13 | let lastKey = nestedProperties.pop() 14 | let property = nestedProperties.reduce((acc, prop) => acc[prop], res.locals.CONFIGS) 15 | property[lastKey] = value 16 | } 17 | res.status(200).send(result); 18 | 19 | } catch (e) { 20 | console.log("VOTE ERROR",e) 21 | res.status(400).send(e.message || e); 22 | } 23 | } 24 | router.post('/',handler) 25 | 26 | export default router; -------------------------------------------------------------------------------- /changelog.md: -------------------------------------------------------------------------------- 1 | 2 | # Change Log 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](http://keepachangelog.com/) 6 | and this project adheres to [Semantic Versioning](http://semver.org/). 7 | 8 | ## [0.3.1] - 2023-04-17 9 | 10 | - Improvements in frequency of block checking 11 | - Improved config files with gas settings 12 | - Improved logging 13 | - Reduce Coingecko dependency as price oracle 14 | 15 | ### Added 16 | - [Issue #1](https://github.com/LOA-Labs/loa-node-toolkit/issues/2) 17 | Cache Coingecko prices per chain per every 6 hours 18 | - [Issue #2](https://github.com/LOA-Labs/loa-node-toolkit/issues/2) 19 | New Block Event Subscriptions 20 | - Add `appendRow` method to report class 21 | 22 | ### Changed 23 | - signature of `getSignerObject` changed, handles mnemonic in function now 24 | 25 | ### Fixed 26 | - fix report icon formatting 27 | - allow 0 fees for chains without fees specified, set in network config 28 | -------------------------------------------------------------------------------- /templates/authz-sending.json: -------------------------------------------------------------------------------- 1 | { 2 | "body": { 3 | "messages": [ 4 | { 5 | "@type": "/cosmos.authz.v1beta1.MsgGrant", 6 | "granter": "cosmos...", 7 | "grantee": "cosmos...", 8 | "grant": { 9 | "authorization": { 10 | "@type": "/cosmos.bank.v1beta1.SendAuthorization", 11 | "spend_limit": [ 12 | { 13 | "denom": "uatom", 14 | "amount": "100000" 15 | } 16 | ] 17 | }, 18 | "expiration": null 19 | } 20 | } 21 | ], 22 | "memo": "", 23 | "timeout_height": "0", 24 | "extension_options": [], 25 | "non_critical_extension_options": [] 26 | }, 27 | "auth_info": { 28 | "signer_infos": [], 29 | "fee": { 30 | "amount": [ 31 | { 32 | "denom": "uatom", 33 | "amount": "5000" 34 | } 35 | ], 36 | "gas_limit": "200000", 37 | "payer": "", 38 | "granter": "" 39 | } 40 | }, 41 | "signatures": [] 42 | } -------------------------------------------------------------------------------- /src/helpers/interval.factory.ts: -------------------------------------------------------------------------------- 1 | const counts = [] 2 | export const Interval = { 3 | init(uuid: string, period: number = 1): void { 4 | if (counts[uuid] == undefined) { 5 | counts[uuid] = { period, count: 0 } 6 | } 7 | }, 8 | inc(uuid: string): void { 9 | counts[uuid].count++ 10 | }, 11 | reset(uuid: string): void { 12 | counts[uuid].count = 0 13 | }, 14 | count(uuid: string): number { 15 | return counts[uuid].count 16 | }, 17 | status({ info, uuid }: { info: string, uuid: string }): void { 18 | const now = new Date().toISOString() 19 | console.log(`\n===============\n\t${info}\n\t${uuid} 20 | \n\tTime: ${now} 21 | \n\tInterval ${counts[uuid].count} / ${counts[uuid].period}`) 22 | }, 23 | complete(uuid: string, run_on_start: boolean): boolean { 24 | if (run_on_start === true && counts[uuid].ran_on_start === undefined) { 25 | return counts[uuid].ran_on_start = true 26 | } 27 | console.log(`\ncounts[${uuid}].count ${counts[uuid].count} >= counts[${uuid}].period ${counts[uuid].period}: ${counts[uuid].count >= counts[uuid].period}`) 28 | return counts[uuid].count >= counts[uuid].period 29 | } 30 | } -------------------------------------------------------------------------------- /templates/authz-sending-v47.json: -------------------------------------------------------------------------------- 1 | { 2 | "body": { 3 | "messages": [ 4 | { 5 | "@type": "/cosmos.authz.v1beta1.MsgGrant", 6 | "granter": "cosmos...", 7 | "grantee": "cosmos...", 8 | "grant": { 9 | "authorization": { 10 | "@type": "/cosmos.bank.v1beta1.SendAuthorization", 11 | "spend_limit": [ 12 | { 13 | "denom": "uatom", 14 | "amount": "100000" 15 | } 16 | ], 17 | "allow_list": [ 18 | "cosmos...", 19 | "cosmos..." 20 | ] 21 | }, 22 | "expiration": null 23 | } 24 | } 25 | ], 26 | "memo": "", 27 | "timeout_height": "0", 28 | "extension_options": [], 29 | "non_critical_extension_options": [] 30 | }, 31 | "auth_info": { 32 | "signer_infos": [], 33 | "fee": { 34 | "amount": [ 35 | { 36 | "denom": "uatom", 37 | "amount": "5000" 38 | } 39 | ], 40 | "gas_limit": "200000", 41 | "payer": "", 42 | "granter": "" 43 | } 44 | }, 45 | "signatures": [] 46 | } -------------------------------------------------------------------------------- /discord-bot/commands/vote.js: -------------------------------------------------------------------------------- 1 | const { SlashCommandBuilder } = require('discord.js'); 2 | const axios = require('axios') 3 | 4 | module.exports = { 5 | data: new SlashCommandBuilder() 6 | .setName('vote') 7 | .setDescription('Executes vote. Usage: /vote chain prop# option').addStringOption(option => 8 | option.setName('input') 9 | .setDescription('chain prop# option')), 10 | async execute(interaction) { 11 | 12 | const { options, applicationId, channelId, commandGuildId, commandName, commandId, user } = interaction 13 | await interaction.reply({ content: 'Processing vote now...', ephemeral: true }); 14 | try { 15 | const params = new URLSearchParams(); 16 | params.append('text', options.getString('input')); 17 | params.append('channel_id', channelId); 18 | let res = await axios.post("http://localhost:4040/vote", params) 19 | await interaction.followUp(`Processed ${res}`); 20 | } catch (e) { 21 | console.log(e) 22 | await interaction.reply({ content: `Err: ${e.message}`, ephemeral: true }); 23 | } 24 | 25 | }, 26 | }; -------------------------------------------------------------------------------- /src/commands/vote/handler.ts: -------------------------------------------------------------------------------- 1 | import { Router, Request, Response } from "express"; 2 | const express = require('express') 3 | const router: Router = express.Router(); 4 | 5 | import { getCommandConfigBy } from "../../helpers/utils" 6 | import tx_vote from "./tx"; 7 | 8 | const handler = async (req: Request, res: Response) => { 9 | try { 10 | let config: any = null 11 | 12 | if (req?.body?.channel_id) { 13 | //channel id should defined to increase security, check channel id in request 14 | const [filename, configData] = getCommandConfigBy(res.locals.CONFIGS, { 15 | credentialsKey: "channel_id", 16 | value: req?.body?.channel_id, 17 | command: "vote" 18 | }) 19 | config = configData 20 | } else { 21 | config = res.locals.CONFIGS[req.query.config] 22 | } 23 | 24 | if (config) { 25 | res.status(200).send(`Processing request... \n\`${req.body.text}\``); 26 | return await tx_vote({ req, config }) 27 | } else throw new Error("No config found. Could not process vote request.") 28 | 29 | } catch (e) { 30 | console.log("VOTE ERROR", e) 31 | res.status(400).send(e.message || e); 32 | } 33 | } 34 | 35 | router.post('/', handler) 36 | 37 | export default router; -------------------------------------------------------------------------------- /templates/authz-voting.json: -------------------------------------------------------------------------------- 1 | { 2 | "body": { 3 | "messages": [ 4 | { 5 | "@type": "/cosmos.authz.v1beta1.MsgGrant", 6 | "granter": "cosmos1...", 7 | "grantee": "cosmos1...", 8 | "grant": { 9 | "authorization": { 10 | "@type": "/cosmos.authz.v1beta1.GenericAuthorization", 11 | "msg": "/cosmos.gov.v1beta1.MsgVote" 12 | } 13 | } 14 | }, 15 | { 16 | "@type": "/cosmos.authz.v1beta1.MsgGrant", 17 | "granter": "cosmos1...", 18 | "grantee": "cosmos1...", 19 | "grant": { 20 | "authorization": { 21 | "@type": "/cosmos.authz.v1beta1.GenericAuthorization", 22 | "msg": "/cosmos.gov.v1beta1.MsgSubmitProposal" 23 | } 24 | } 25 | } 26 | ], 27 | "memo": "", 28 | "timeout_height": "0", 29 | "extension_options": [], 30 | "non_critical_extension_options": [] 31 | }, 32 | "auth_info": { 33 | "signer_infos": [], 34 | "fee": { 35 | "amount": [ 36 | { 37 | "denom": "uatom", 38 | "amount": "5000" 39 | } 40 | ], 41 | "gas_limit": "200000", 42 | "payer": "", 43 | "granter": "" 44 | } 45 | }, 46 | "signatures": [] 47 | } -------------------------------------------------------------------------------- /discord-bot/index.js: -------------------------------------------------------------------------------- 1 | const fs = require('node:fs'); 2 | const path = require('node:path'); 3 | const { Client, Collection, Events, GatewayIntentBits } = require('discord.js'); 4 | const { token } = require('./config.json'); 5 | 6 | const client = new Client({ intents: [GatewayIntentBits.Guilds] }); 7 | 8 | client.commands = new Collection(); 9 | const commandsPath = path.join(__dirname, 'commands'); 10 | const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js')); 11 | 12 | for (const file of commandFiles) { 13 | const filePath = path.join(commandsPath, file); 14 | const command = require(filePath); 15 | client.commands.set(command.data.name, command); 16 | } 17 | 18 | client.once(Events.ClientReady, () => { 19 | console.log('Ready!'); 20 | }); 21 | 22 | client.on(Events.InteractionCreate, async interaction => { 23 | if (!interaction.isChatInputCommand()) return; 24 | 25 | const command = client.commands.get(interaction.commandName); 26 | 27 | if (!command) return; 28 | 29 | try { 30 | await command.execute(interaction); 31 | } catch (error) { 32 | console.error(error); 33 | await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true }); 34 | } 35 | }); 36 | 37 | client.login(token); -------------------------------------------------------------------------------- /templates/fee-grant.json: -------------------------------------------------------------------------------- 1 | { 2 | "body": { 3 | "messages": [ 4 | { 5 | "@type": "/cosmos.feegrant.v1beta1.MsgGrantAllowance", 6 | "granter": "cosmos1...", 7 | "grantee": "cosmos1...", 8 | "allowance": { 9 | "@type": "/cosmos.feegrant.v1beta1.PeriodicAllowance", 10 | "basic": { 11 | "spend_limit": [], 12 | "expiration": "" 13 | }, 14 | "period": "86400s", 15 | "period_spend_limit": [ 16 | { 17 | "denom": "uatom", 18 | "amount": "1000000" 19 | } 20 | ], 21 | "period_can_spend": [ 22 | { 23 | "denom": "uatom", 24 | "amount": "1000000" 25 | } 26 | ], 27 | "period_reset": "" 28 | } 29 | } 30 | ], 31 | "memo": "", 32 | "timeout_height": "0", 33 | "extension_options": [], 34 | "non_critical_extension_options": [] 35 | }, 36 | "auth_info": { 37 | "signer_infos": [], 38 | "fee": { 39 | "amount": [ 40 | { 41 | "denom": "uatom", 42 | "amount": "5000" 43 | } 44 | ], 45 | "gas_limit": "200000", 46 | "payer": "", 47 | "granter": "" 48 | } 49 | }, 50 | "signatures": [] 51 | } -------------------------------------------------------------------------------- /templates/authz-managing.json: -------------------------------------------------------------------------------- 1 | { 2 | "body": { 3 | "messages": [ 4 | { 5 | "@type": "/cosmos.authz.v1beta1.MsgGrant", 6 | "granter": "cosmos...", 7 | "grantee": "cosmos...", 8 | "grant": { 9 | "authorization": { 10 | "@type": "/cosmos.authz.v1beta1.GenericAuthorization", 11 | "msg": "/cosmos.slashing.v1beta1.MsgUnjail" 12 | }, 13 | "expiration": null 14 | } 15 | }, 16 | { 17 | "@type": "/cosmos.authz.v1beta1.MsgGrant", 18 | "granter": "cosmos...", 19 | "grantee": "cosmos...", 20 | "grant": { 21 | "authorization": { 22 | "@type": "/cosmos.authz.v1beta1.GenericAuthorization", 23 | "msg": "/cosmos.staking.v1beta1.MsgEditValidator" 24 | }, 25 | "expiration": null 26 | } 27 | } 28 | ], 29 | "memo": "", 30 | "timeout_height": "0", 31 | "extension_options": [], 32 | "non_critical_extension_options": [] 33 | }, 34 | "auth_info": { 35 | "signer_infos": [], 36 | "fee": { 37 | "amount": [ 38 | { 39 | "denom": "uatom", 40 | "amount": "5000" 41 | } 42 | ], 43 | "gas_limit": "200000", 44 | "payer": "", 45 | "granter": "" 46 | } 47 | }, 48 | "signatures": [] 49 | } -------------------------------------------------------------------------------- /discord-bot/deploy-commands.js: -------------------------------------------------------------------------------- 1 | const { REST, Routes } = require('discord.js'); 2 | const { clientId, guildId, token } = require('./config.json'); 3 | const fs = require('node:fs'); 4 | 5 | const commands = []; 6 | // Grab all the command files from the commands directory you created earlier 7 | const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js')); 8 | 9 | // Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment 10 | for (const file of commandFiles) { 11 | const command = require(`./commands/${file}`); 12 | commands.push(command.data.toJSON()); 13 | } 14 | 15 | // Construct and prepare an instance of the REST module 16 | const rest = new REST({ version: '10' }).setToken(token); 17 | 18 | // and deploy your commands! 19 | (async() => { 20 | try { 21 | console.log(`Started refreshing ${commands.length} application (/) commands.`); 22 | 23 | // The put method is used to fully refresh all commands in the guild with the current set 24 | const data = await rest.put( 25 | Routes.applicationGuildCommands(clientId, guildId), { body: commands }, 26 | ); 27 | 28 | console.log(`Successfully reloaded ${data.length} application (/) commands.`); 29 | } catch (error) { 30 | // And of course, make sure you catch and log any errors! 31 | console.error(error); 32 | } 33 | })(); -------------------------------------------------------------------------------- /src/server.ts: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | import { Request, Response, Next } from "express"; 3 | import Report from "./helpers/class.report"; 4 | const report = new Report(); 5 | 6 | //on demand commands 7 | import vote from './commands/vote/handler'; 8 | import { LntConfig } from "./helpers/global.types"; 9 | 10 | export default (CONFIGS: LntConfig[]) => { 11 | const app = express() 12 | const port = 4040 13 | 14 | app.use(express.urlencoded({ 15 | extended: true 16 | })) 17 | 18 | app.use((req: Request, res: Response, next: Next) => { 19 | res.locals.CONFIGS = CONFIGS 20 | next(); 21 | }); 22 | 23 | app.use('/vote', vote); 24 | app.use('/api', async (req: Request, res: Response) => { 25 | try { 26 | res.status(200).send({ 27 | "message": "Verification successful" 28 | }); 29 | 30 | } catch (e) { 31 | console.log("caught error", e) 32 | } 33 | }); 34 | 35 | app.listen(port, () => { 36 | 37 | report.header(`SERVER Listening for commands on port ${port}`) 38 | Object.entries(CONFIGS).map(([key, object]: any) => { 39 | report.addRow(`\n\t ${key} ${object.enabled ? 'ENABLED' : 'NOT ENABLED'}`) 40 | if (object.enabled) { 41 | Object.entries(object.commands).map(([cmdKey, cmdObj]: any) => { 42 | report.addRow(`\n\t\t- ${cmdKey} command ${cmdObj.enabled ? 'ENABLED' : 'NOT ENABLED'}`) 43 | }) 44 | } 45 | 46 | }) 47 | report.log() 48 | }); 49 | 50 | } -------------------------------------------------------------------------------- /src/helpers/global.types.ts: -------------------------------------------------------------------------------- 1 | import { HttpEndpoint } from "@cosmjs/tendermint-rpc"; 2 | 3 | export type Service = { 4 | enabled?: boolean 5 | run_on_start?: boolean 6 | title: string 7 | cron: string 8 | force_notify_count: number 9 | active_notify_count?: number 10 | query?: any 11 | notify?: object 12 | uuid: string | undefined 13 | } 14 | 15 | export type Command = { 16 | enabled?: boolean 17 | title: string 18 | use_mnemonic: string 19 | force_notify_count: number 20 | credentials?: object 21 | notify?: object 22 | } 23 | 24 | export type LntConfig = { 25 | enabled?: boolean 26 | title: string 27 | services?: { 28 | status?: Service 29 | rewards?: Service 30 | proposals?: Service 31 | distribution?: Service 32 | } 33 | commands?: { 34 | vote?: Command, 35 | } 36 | grantee_mnemonics?: object 37 | notifications?: object 38 | explorer?: string 39 | networks: NetworkConfig[] 40 | debug: { 41 | TEST_CRON_ONLY: boolean 42 | SCHEDULE_CRON: boolean 43 | } 44 | } 45 | 46 | export type NetworkConfig = { 47 | enabled?: boolean 48 | name: string 49 | chain_id: string 50 | coingecko_id?: string 51 | denom: string 52 | gas_prices?: number 53 | gas?: number 54 | rpc: string 55 | disk_check_endpoint?: string 56 | granter: string 57 | valoper: string 58 | restake: number 59 | network_handles?: object 60 | filter_services?: string[] 61 | explorer?: string 62 | exponent?: number 63 | feegrant_enabled: undefined | boolean 64 | } -------------------------------------------------------------------------------- /templates/authz-restaking.json: -------------------------------------------------------------------------------- 1 | { 2 | "body": { 3 | "messages": [ 4 | { 5 | "@type": "/cosmos.authz.v1beta1.MsgGrant", 6 | "granter": "cosmos1...", 7 | "grantee": "cosmos1...", 8 | "grant": { 9 | "authorization": { 10 | "@type": "/cosmos.authz.v1beta1.GenericAuthorization", 11 | "msg": "/cosmos.staking.v1beta1.MsgDelegate" 12 | } 13 | } 14 | }, 15 | { 16 | "@type": "/cosmos.authz.v1beta1.MsgGrant", 17 | "granter": "cosmos1...", 18 | "grantee": "cosmos1...", 19 | "grant": { 20 | "authorization": { 21 | "@type": "/cosmos.authz.v1beta1.GenericAuthorization", 22 | "msg": "/cosmos.distribution.v1beta1.MsgWithdrawDelegatorReward" 23 | } 24 | } 25 | }, 26 | { 27 | "@type": "/cosmos.authz.v1beta1.MsgGrant", 28 | "granter": "cosmos1...", 29 | "grantee": "cosmos1...", 30 | "grant": { 31 | "authorization": { 32 | "@type": "/cosmos.authz.v1beta1.GenericAuthorization", 33 | "msg": "/cosmos.distribution.v1beta1.MsgWithdrawValidatorCommission" 34 | } 35 | } 36 | } 37 | ], 38 | "memo": "", 39 | "timeout_height": "0", 40 | "extension_options": [], 41 | "non_critical_extension_options": [] 42 | }, 43 | "auth_info": { 44 | "signer_infos": [], 45 | "fee": { 46 | "amount": [ 47 | { 48 | "denom": "uatom", 49 | "amount": "5000" 50 | } 51 | ], 52 | "gas_limit": "200000", 53 | "payer": "", 54 | "granter": "" 55 | } 56 | }, 57 | "signatures": [] 58 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "loa-node-toolkit", 3 | "version": "0.3.1", 4 | "main": "src/index.ts", 5 | "license": "MIT", 6 | "scripts": { 7 | "clean": "rimraf dist/", 8 | "copy-files": "copyfiles -u 1 src/configs/*.json dist/", 9 | "start": "NODE_ENV=production node ./dist/index.js", 10 | "start-ts-old": "NODE_ENV=production node -r ts-node/register ./src/index.ts", 11 | "build": "npm run clean && tsc --allowSyntheticDefaultImports src/*.ts --outDir ./dist", 12 | "devprod": "nodemon --config nodemon.prod.json src/index.ts", 13 | "dev": "NODE_ENV=development nodemon --config nodemon.json src/index.ts", 14 | "start-ts": "nodemon --config nodemon-prod.json src/index.ts", 15 | "dev:debug": "nodemon --config nodemon.json --inspect-brk src/index.ts", 16 | "deploy": "gpl; nrb; apprestart;" 17 | }, 18 | "devDependencies": { 19 | "@types/node": "^14.11.2", 20 | "nodemon": "^2.0.4", 21 | "ts-node": "^9.1.1", 22 | "typescript": "^4.0.3" 23 | }, 24 | "dependencies": { 25 | "@cosmjs/proto-signing": "^0.29.5", 26 | "@cosmjs/stargate": "^0.29.5", 27 | "@cosmjs/tendermint-rpc": "^0.29.5", 28 | "@slack/webhook": "^6.1.0", 29 | "@types/bech32": "^1.1.4", 30 | "axios": "^0.27.2", 31 | "bech32": "^2.0.0", 32 | "bip32": "^3.1.0", 33 | "check-disk-space": "^3.3.1", 34 | "copyfiles": "^2.4.1", 35 | "cosmjs-types": "^0.5.1", 36 | "croner": "^4.3.16", 37 | "discord-interactions": "^3.2.0", 38 | "dotenv": "^16.0.3", 39 | "express": "^4.18.2", 40 | "human-date": "^1.4.0", 41 | "node-fetch": "^3.2.10", 42 | "rimraf": "^3.0.2", 43 | "tsconfig-paths": "^4.1.2", 44 | "twitter-api-v2": "^1.12.8", 45 | "uuid": "^8.3.2" 46 | } 47 | } -------------------------------------------------------------------------------- /src/helpers/class.report.ts: -------------------------------------------------------------------------------- 1 | export default class Report { 2 | private rows: any = []; 3 | private cols: any = ""; 4 | private colWidths: number[] = []; 5 | private colIndex: number = 0; 6 | constructor() { } 7 | 8 | private div: string = `\n\n============================` 9 | private break: string = `\n----------------------------` 10 | 11 | public header(data: string): Report { 12 | this.rows.push('') 13 | this.rows.push(this.div) 14 | this.rows.push(`# ${data}`) 15 | return this 16 | } 17 | 18 | public section(data?: string): Report { 19 | this.rows.push(this.break) 20 | this.rows.push(data) 21 | return this 22 | } 23 | public addRow(data: string): Report { 24 | this.rows.push(data) 25 | return this 26 | } 27 | public appendRow(data: string): Report { 28 | this.rows[this.rows.length - 1] += data 29 | return this 30 | } 31 | public addCol(data: any, align: string = "left", pad?: number): Report { 32 | data = data.toString() 33 | pad = this.colWidths[this.colIndex] !== undefined ? this.colWidths[this.colIndex] : pad != undefined ? pad : 0 34 | this.cols += align == "left" ? data.padEnd(pad) : data.padStart(pad) 35 | this.colIndex++ 36 | return this 37 | } 38 | public startCol(colWidths: number[]): Report { 39 | this.colWidths = colWidths 40 | this.colIndex = 0 41 | return this 42 | } 43 | public endCol(): string { 44 | let res = this.cols 45 | this.cols = "" 46 | this.colIndex = 0 47 | return res 48 | } 49 | public addHeader(data: string): Report { 50 | this.rows.unshift(data) 51 | return this 52 | } 53 | public backticks(): Report { 54 | this.rows.push("```") 55 | return this 56 | } 57 | public print(): string { 58 | let res = this.rows.join(`\n`) 59 | this.rows.length = 0 60 | return res 61 | } 62 | public log(): void { 63 | console.log(this.print()) 64 | } 65 | } -------------------------------------------------------------------------------- /src/helpers/balances.ts: -------------------------------------------------------------------------------- 1 | import { createProtobufRpcClient, QueryClient } from "@cosmjs/stargate"; 2 | import { QueryClientImpl as QueryClientImplBankQuery } from "cosmjs-types/cosmos/bank/v1beta1/query"; 3 | import { QueryClientImpl as QueryClientImplStakingDelegation } from "cosmjs-types/cosmos/staking/v1beta1/query"; 4 | import { Tendermint34Client } from "@cosmjs/tendermint-rpc"; 5 | import { NetworkConfig } from "./global.types"; 6 | 7 | export type queryBalanceResult = { 8 | amount: number 9 | error?:Error 10 | } 11 | 12 | 13 | export const queryBalance = async (network: NetworkConfig):Promise => { 14 | try { 15 | if (!network.rpc) throw new Error(`Network ${network.name}: RPC is undefined`); 16 | const tendermint = await Tendermint34Client.connect(network.rpc); 17 | const queryClient = new QueryClient(tendermint); 18 | const rpcClient = createProtobufRpcClient(queryClient); 19 | const bankQueryService = new QueryClientImplBankQuery(rpcClient); 20 | let res = await bankQueryService.Balance({ 21 | address: network.granter, 22 | denom: network.denom, 23 | }); 24 | let resultObject = {amount:Number(res.balance.amount)}; 25 | return resultObject; 26 | } catch (error) { 27 | console.log(error); 28 | return { amount:0, error }; 29 | } 30 | }; 31 | 32 | export const queryStaked = async (network: NetworkConfig):Promise => { 33 | try { 34 | if (!network.rpc) throw new Error(`Network ${network.name}: RPC is undefined`); 35 | const tendermint = await Tendermint34Client.connect(network.rpc); 36 | const queryClient = new QueryClient(tendermint); 37 | const rpcClient = createProtobufRpcClient(queryClient); 38 | const stakingQueryService = new QueryClientImplStakingDelegation(rpcClient); 39 | let res = await stakingQueryService.Delegation({ 40 | delegatorAddr: network.granter, 41 | validatorAddr: network.valoper, 42 | }); 43 | let resultObject = { 44 | amount:Number(res.delegationResponse.balance.amount), 45 | }; 46 | return resultObject; 47 | } catch (error) { 48 | console.log(error); 49 | return { amount:0, error }; 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | 3 | # lnm needs these specifically ignored 4 | configs 5 | dist 6 | .env 7 | 8 | # Logs 9 | logs 10 | *.log 11 | npm-debug.log* 12 | yarn-debug.log* 13 | yarn-error.log* 14 | lerna-debug.log* 15 | 16 | # Diagnostic reports (https://nodejs.org/api/report.html) 17 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 18 | 19 | # Runtime data 20 | pids 21 | *.pid 22 | *.seed 23 | *.pid.lock 24 | 25 | # Directory for instrumented libs generated by jscoverage/JSCover 26 | lib-cov 27 | 28 | # Coverage directory used by tools like istanbul 29 | coverage 30 | *.lcov 31 | 32 | # nyc test coverage 33 | .nyc_output 34 | 35 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 36 | .grunt 37 | 38 | # Bower dependency directory (https://bower.io/) 39 | bower_components 40 | 41 | # node-waf configuration 42 | .lock-wscript 43 | 44 | # Compiled binary addons (https://nodejs.org/api/addons.html) 45 | build/Release 46 | 47 | # Dependency directories 48 | node_modules/ 49 | jspm_packages/ 50 | 51 | # TypeScript v1 declaration files 52 | typings/ 53 | 54 | # TypeScript cache 55 | *.tsbuildinfo 56 | 57 | # Optional npm cache directory 58 | .npm 59 | 60 | # Optional eslint cache 61 | .eslintcache 62 | 63 | # Microbundle cache 64 | .rpt2_cache/ 65 | .rts2_cache_cjs/ 66 | .rts2_cache_es/ 67 | .rts2_cache_umd/ 68 | 69 | # Optional REPL history 70 | .node_repl_history 71 | 72 | # Output of 'npm pack' 73 | *.tgz 74 | 75 | # Yarn Integrity file 76 | .yarn-integrity 77 | 78 | # dotenv environment variables file 79 | .env 80 | .env.test 81 | 82 | # parcel-bundler cache (https://parceljs.org/) 83 | .cache 84 | 85 | # Next.js build output 86 | .next 87 | 88 | # Nuxt.js build / generate output 89 | .nuxt 90 | dist 91 | 92 | # Gatsby files 93 | .cache/ 94 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 95 | # https://nextjs.org/blog/next-9-1#public-directory-support 96 | # public 97 | 98 | # vuepress build output 99 | .vuepress/dist 100 | 101 | # Serverless directories 102 | .serverless/ 103 | 104 | # FuseBox cache 105 | .fusebox/ 106 | 107 | # DynamoDB Local files 108 | .dynamodb/ 109 | 110 | # TernJS port file 111 | .tern-port 112 | -------------------------------------------------------------------------------- /discord-bot/.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "eslint:recommended", 3 | "env": { 4 | "node": true, 5 | "es6": true 6 | }, 7 | "parserOptions": { 8 | "ecmaVersion": 2021 9 | }, 10 | "rules": { 11 | "arrow-spacing": [ 12 | "warn", 13 | { 14 | "before": true, 15 | "after": true 16 | } 17 | ], 18 | "brace-style": [ 19 | "error", 20 | "stroustrup", 21 | { 22 | "allowSingleLine": true 23 | } 24 | ], 25 | "comma-dangle": [ 26 | "error", 27 | "always-multiline" 28 | ], 29 | "comma-spacing": "error", 30 | "comma-style": "error", 31 | "curly": [ 32 | "error", 33 | "multi-line", 34 | "consistent" 35 | ], 36 | "dot-location": [ 37 | "error", 38 | "property" 39 | ], 40 | "handle-callback-err": "off", 41 | "indent": [ 42 | "error", 43 | "tab" 44 | ], 45 | "keyword-spacing": "error", 46 | "max-nested-callbacks": [ 47 | "error", 48 | { 49 | "max": 4 50 | } 51 | ], 52 | "max-statements-per-line": [ 53 | "error", 54 | { 55 | "max": 2 56 | } 57 | ], 58 | "no-console": "off", 59 | "no-empty-function": "error", 60 | "no-floating-decimal": "error", 61 | "no-inline-comments": "error", 62 | "no-lonely-if": "error", 63 | "no-multi-spaces": "error", 64 | "no-multiple-empty-lines": [ 65 | "error", 66 | { 67 | "max": 2, 68 | "maxEOF": 1, 69 | "maxBOF": 0 70 | } 71 | ], 72 | "no-shadow": [ 73 | "error", 74 | { 75 | "allow": [ 76 | "err", 77 | "resolve", 78 | "reject" 79 | ] 80 | } 81 | ], 82 | "no-trailing-spaces": [ 83 | "error" 84 | ], 85 | "no-var": "error", 86 | "object-curly-spacing": [ 87 | "error", 88 | "always" 89 | ], 90 | "prefer-const": "error", 91 | "quotes": [ 92 | "error", 93 | "single" 94 | ], 95 | "semi": [ 96 | "error", 97 | "always" 98 | ], 99 | "space-before-blocks": "error", 100 | "space-before-function-paren": [ 101 | "error", 102 | { 103 | "anonymous": "never", 104 | "named": "never", 105 | "asyncArrow": "always" 106 | } 107 | ], 108 | "space-in-parens": "error", 109 | "space-infix-ops": "error", 110 | "space-unary-ops": "error", 111 | "spaced-comment": "error", 112 | "yoda": "error" 113 | } 114 | } -------------------------------------------------------------------------------- /src/helpers/socket.factory.ts: -------------------------------------------------------------------------------- 1 | 2 | import { WebsocketClient } from '@cosmjs/tendermint-rpc'; 3 | import { LntConfig, NetworkConfig, Service } from "./global.types"; 4 | import { notify } from "../helpers/notify"; 5 | 6 | type addSubscriptionParams = { 7 | key: string 8 | config: LntConfig 9 | network: NetworkConfig 10 | service: Service 11 | notify: Function 12 | requestFunction: Function 13 | eventHandler: Function 14 | } 15 | export type WebsocketClientObject = { 16 | client: WebsocketClient 17 | subscriptions: [] 18 | addSubscription: Function 19 | } 20 | export type RequestFunctionProps = { 21 | network: NetworkConfig 22 | id: number 23 | service: Service 24 | } 25 | 26 | let subId = 100; 27 | const websocketClients = []; 28 | export const socketFactory = async (rpc: string): Promise => { 29 | 30 | try { 31 | if (websocketClients[rpc] === null || websocketClients[rpc] === undefined) { 32 | 33 | websocketClients[rpc] = {} 34 | websocketClients[rpc].client = new WebsocketClient(rpc.split("http").join("ws"), (e) => { 35 | console.log("WebsocketClient onError caught:", e) 36 | }) 37 | 38 | websocketClients[rpc].subscriptions = {} 39 | 40 | websocketClients[rpc].addSubscription = async ({ key, config, network, service, requestFunction, eventHandler }: addSubscriptionParams) => { 41 | if (websocketClients[rpc][key] !== undefined) return 42 | let reqDef = requestFunction({ network, service, id: subId }) 43 | subId++ 44 | console.log(`\nSubscribing to event id ${subId}: ${network.chain_id}, ${key}`) 45 | console.log(` ${reqDef?.params?.query}`) 46 | let stream = await websocketClients[rpc].client.listen(reqDef) 47 | stream.subscribe({ 48 | next: (event: any) => { 49 | try { 50 | // console.log(event) 51 | eventHandler(event, { key, config, network, service, notify }) 52 | } catch (e) { 53 | console.log("Subscription error caught:", e, event) 54 | } 55 | }, 56 | error: (error: any) => { 57 | console.log("Subscription error:", key, error) 58 | notify({ text: `Subscription error: ${network.chain_id} ${key} ${JSON.stringify(error)}`, config, service }) 59 | }, 60 | complete: () => { 61 | console.log(key, "STREAM COMPLETE") 62 | } 63 | }) 64 | websocketClients[rpc][key] = true; 65 | } 66 | } 67 | 68 | return websocketClients[rpc] 69 | } catch (e) { 70 | console.log("Caught error", e) 71 | return null 72 | } 73 | } -------------------------------------------------------------------------------- /configs/default.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "DEFAULT CONFIG", 3 | "enabled": true, 4 | "networks": [ 5 | { 6 | "name": "regen", 7 | "chain_id": "regen-1", 8 | "rpc": "http://127.0.0.1:26657", 9 | "coingecko_id": "regen", 10 | "denom": "uregen", 11 | "gas_prices": "0.025", 12 | "gas_auto": true, 13 | "granter": "regen1...", 14 | "valoper": "regenvaloper1...", 15 | "restake": 0.5 16 | } 17 | ], 18 | "services": { 19 | "status": { 20 | "enabled": true, 21 | "run_on_start": true, 22 | "title": "Status Service", 23 | "cron": "*/5 * * * *", 24 | "force_notify_count": 72, 25 | "notify": { 26 | "discord": "#node-monitor", 27 | "slack": "#node-monitor" 28 | } 29 | }, 30 | "proposals": { 31 | "enabled": false, 32 | "run_on_start": false, 33 | "title": "Proposal Check", 34 | "cron": "*/15 * * * *", 35 | "force_notify_count": 12, 36 | "active_notify_count": 6, 37 | "notify": { 38 | "slack": "#gov-monitor", 39 | "discord": "#gov-monitor" 40 | } 41 | }, 42 | "rewards": { 43 | "enabled": false, 44 | "run_on_start": false, 45 | "title": "Daily Rewards Report", 46 | "cron": "0 12 * * *", 47 | "use_mnemonic": "asset_manager", 48 | "notify": { 49 | "slack": "#node-monitor", 50 | "discord": "#node-monitor" 51 | } 52 | } 53 | }, 54 | "notifications": { 55 | "discord": { 56 | "#node-monitor": { 57 | "enabled": true, 58 | "endpoint": "https://discord.com/api/webhooks/<12345678>/<12345678>" 59 | } 60 | }, 61 | "slack": { 62 | "#node-monitor": { 63 | "enabled": true, 64 | "endpoint": "https://hooks.slack.com/services/<12345678>/<12345678>/<12345678>" 65 | } 66 | } 67 | }, 68 | "commands": { 69 | "vote": { 70 | "enabled": false, 71 | "title": "Voting", 72 | "use_mnemonic": "voter", 73 | "credentials": { 74 | "channel_id": [ 75 | "12345678", 76 | "12345678" 77 | ] 78 | }, 79 | "notify": { 80 | "slack": "#node-monitor", 81 | "discord": "#node-monitor" 82 | } 83 | } 84 | }, 85 | "grantee_mnemonics": { 86 | "asset_manager": "", 87 | "voter": "" 88 | }, 89 | "explorer": "https://www.mintscan.io", 90 | "debug": { 91 | "TEST_CRON_ONLY": false, 92 | "SCHEDULE_CRON": true 93 | } 94 | } -------------------------------------------------------------------------------- /src/helpers/rpc_query/block.ts: -------------------------------------------------------------------------------- 1 | import { JsonRpcRequest } from "@cosmjs/json-rpc"; 2 | import { RequestFunctionProps } from "../socket.factory"; 3 | 4 | import { Service, LntConfig, NetworkConfig } from "../global.types"; 5 | 6 | export const getNewBlock = ({ network, id, service }: RequestFunctionProps): JsonRpcRequest => { 7 | return { 8 | jsonrpc: "2.0", 9 | id, 10 | method: "subscribe", 11 | params: { 12 | query: `tm.event = 'NewBlock'` 13 | } 14 | } 15 | } 16 | 17 | 18 | // For each chain keep an interval running, alert 19 | // if latest block exceeds a certain time 20 | class IntervalChecker { 21 | latest_block_time_tolerance: number = 20000 22 | key: string 23 | config: LntConfig 24 | network: NetworkConfig 25 | service: Service 26 | notify: Function 27 | interval: any 28 | latest_block_time: number 29 | 30 | constructor({ key, config, network, service, notify }) { 31 | this.key = key 32 | this.config = config 33 | this.network = network 34 | this.service = service 35 | this.notify = notify 36 | 37 | this.latest_block_time_tolerance = network.latest_block_time_tolerance || this.latest_block_time_tolerance 38 | this.interval = setInterval(() => { 39 | let dif = new Date().getTime() - this.latest_block_time 40 | if (dif > this.latest_block_time_tolerance) { 41 | notify({ text: `🔴 [${this.network.chain_id}] Latest Block Exceeds ${this.latest_block_time_tolerance / 1000}s (${Math.ceil(dif / 1000)}s)`, config: this.config, service: this.service }) 42 | } 43 | }, this.latest_block_time_tolerance) 44 | } 45 | reset() { 46 | this.latest_block_time = new Date().getTime() 47 | } 48 | } 49 | const blockTimeouts = {} 50 | 51 | 52 | 53 | export const getNewBlockEventHandler = (event, { key, config, network, service, notify }): void => { 54 | // keep store of last block time by chain_id 55 | if (blockTimeouts[network.chain_id] == undefined) { 56 | blockTimeouts[network.chain_id] = new IntervalChecker({ key, config, network, service, notify }) 57 | } 58 | blockTimeouts[network.chain_id].reset() 59 | 60 | console.log(`\n============================\nBLOCK ${key} ${network.chain_id} ${event.data.value.block.header.height}`) 61 | // console.log(event.data.value.block.header.time) 62 | // console.log(event.events['proposer_reward.validator']) 63 | // console.log(event.events['liveness.missed_blocks']) 64 | 65 | } 66 | 67 | 68 | export const getVoteEvent = ({ network, id, service }: RequestFunctionProps): JsonRpcRequest => { 69 | return { 70 | jsonrpc: "2.0", 71 | id, 72 | method: "subscribe", 73 | params: { 74 | query: `tm.event = 'Vote'` 75 | } 76 | } 77 | } 78 | 79 | export const getVoteEventHandler = (event, { key, config, network, service, notify }): void => { 80 | // console.log(`\n\n\n============================\nVOTE ${key}`) 81 | // console.log(event.data) 82 | 83 | } 84 | 85 | 86 | -------------------------------------------------------------------------------- /src/helpers/notify.ts: -------------------------------------------------------------------------------- 1 | import { IncomingWebhook } from "@slack/webhook"; 2 | import axios from "axios"; 3 | import { Command, LntConfig, Service } from "./global.types"; 4 | 5 | export type NotifyParams = { 6 | text: string 7 | config: LntConfig 8 | service: Service | Command 9 | response_url?: string | null 10 | } 11 | 12 | const getMsgServices = (): object => { 13 | return { 14 | discord: { 15 | method: async ({ notificationConfig, text, broadcast }) => { 16 | if (broadcast) 17 | return await axios.post(notificationConfig.endpoint, { 18 | content: text, 19 | }); 20 | else return null; 21 | }, 22 | }, 23 | slack: { 24 | method: async ({ notificationConfig, text, response_url, broadcast }) => { 25 | const webhook = new IncomingWebhook( 26 | notificationConfig.endpoint || response_url 27 | ); 28 | if (broadcast) return await webhook.send({ text }); 29 | else return null; 30 | }, 31 | }, 32 | }; 33 | }; 34 | 35 | export const notify = async ({ text, config, service, response_url = null }: NotifyParams): Promise => { 36 | 37 | try { 38 | if (typeof service.notify != "object") throw new Error(`Service notify object not configured.`) 39 | const msgServices: object = getMsgServices(); 40 | const serviceKeys: string[] = Object.keys(service.notify); 41 | const sendToChannels: boolean = false; 42 | let res = []; 43 | 44 | for (let index = 0; index < serviceKeys.length; index++) { 45 | let serviceKey: any = serviceKeys[index]; 46 | 47 | const msgService = msgServices[serviceKey]; 48 | 49 | let broadcast = process.env.NODE_ENV === "production" || sendToChannels; 50 | 51 | try { 52 | const notificationConfig = checkNotificationConfig({ 53 | config, 54 | service, 55 | serviceKey, 56 | }); 57 | res.push( 58 | await msgService.method({ 59 | notificationConfig, 60 | text, 61 | serviceKey, 62 | response_url, 63 | broadcast, 64 | }) 65 | ); 66 | console.log( 67 | `>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>`, 68 | `START ${serviceKey} NOTIFICATION\n${text}\n`, 69 | `\nEND ${serviceKey} NOTIFICATION\n`, 70 | `<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n` 71 | ); 72 | } catch (e) { 73 | console.log(e.message || e); 74 | res.push(e.message); 75 | } 76 | } 77 | 78 | return res; 79 | } catch (e) { 80 | console.log(`Notify Error: ${e.message}`) 81 | return [] 82 | } 83 | }; 84 | 85 | const checkNotificationConfig = ({ config, service, serviceKey }) => { 86 | const serviceChannel = service.notify?.[serviceKey]; 87 | const notificationConfig = 88 | config.notifications?.[serviceKey]?.[serviceChannel]; 89 | if (notificationConfig?.enabled !== true) 90 | throw new Error(`Notification enabled must be set to true: ${service.name} ${serviceKey}`); 91 | else return notificationConfig; 92 | }; 93 | -------------------------------------------------------------------------------- /src/services/watcher.ts: -------------------------------------------------------------------------------- 1 | 2 | import { serviceFiltered } from "../helpers/utils"; 3 | import { LntConfig, NetworkConfig, Service } from "../helpers/global.types"; 4 | import { socketFactory, WebsocketClientObject } from "../helpers/socket.factory"; 5 | import { delegationsEventHandler, delegationsEventHandlerWhale, getReqMsgDelegate, getReqMsgDelegateWhale, getReqMsgUndelegate, getReqMsgUndelegateWhale } from "../helpers/rpc_query/delegate"; 6 | import { getReqMsgSendByReceiver, getReqMsgSendBySpender, getReqMsgSendWhale, sendEventHandler, sendEventHandlerWhale } from "../helpers/rpc_query/send"; 7 | import { notify } from "../helpers/notify"; 8 | 9 | const localWatcherTesting = true; 10 | 11 | export default async (service: Service, config: LntConfig): Promise => { 12 | 13 | for (let index = 0; index < config.networks.length; index++) { 14 | 15 | const network: NetworkConfig = config.networks[index]; 16 | if (serviceFiltered("watcher", network) || network?.enabled === false) continue; 17 | 18 | console.log(`\nWatcher services ${network.chain_id}:`) 19 | if (process.env.NODE_ENV == "production" || localWatcherTesting) { 20 | try { 21 | const WS: WebsocketClientObject = await socketFactory(network.rpc) 22 | //////////////////////////////////////////////////// 23 | //add delegate subscriptions 24 | if (service.query?.delegate?.enabled === true) { 25 | WS.addSubscription({ key: "_getReqMsgDelegate", config, network, service, requestFunction: getReqMsgDelegate, eventHandler: delegationsEventHandler }) 26 | WS.addSubscription({ key: "_getReqMsgUnDelegate", config, network, service, requestFunction: getReqMsgUndelegate, eventHandler: delegationsEventHandler }) 27 | } 28 | if (service.query?.delegate_whale?.enabled === true) { 29 | WS.addSubscription({ key: "_getReqMsgDelegateWhale", config, network, service, requestFunction: getReqMsgDelegateWhale, eventHandler: delegationsEventHandlerWhale }) 30 | WS.addSubscription({ key: "_getReqMsgUndelegateWhale", config, network, service, requestFunction: getReqMsgUndelegateWhale, eventHandler: delegationsEventHandlerWhale }) 31 | } 32 | //////////////////////////////////////////////////// 33 | //add send/receive subscriptions 34 | if (service.query?.send?.enabled === true) { 35 | WS.addSubscription({ key: "_getReqMsgSendBySpender", config, network, service, requestFunction: getReqMsgSendBySpender, eventHandler: sendEventHandler }) 36 | WS.addSubscription({ key: "_getReqMsgSendByReceiver", config, network, service, requestFunction: getReqMsgSendByReceiver, eventHandler: sendEventHandler }) 37 | } 38 | if (service.query?.send_whale?.enabled === true) { 39 | WS.addSubscription({ key: "_getReqMsgSendWhale", config, network, service, requestFunction: getReqMsgSendWhale, eventHandler: sendEventHandlerWhale }) 40 | } 41 | 42 | } catch (e) { 43 | console.log("Caught watcher error", e) 44 | } 45 | } 46 | } 47 | 48 | 49 | await notify({ text: `👀 ${service.title} Running\n${JSON.stringify(service.query)}`, config, service }); 50 | return true 51 | } 52 | -------------------------------------------------------------------------------- /src/helpers/rpc_query/delegate.ts: -------------------------------------------------------------------------------- 1 | 2 | import { JsonRpcRequest } from "@cosmjs/json-rpc"; 3 | import { icons, macroToMicro, microToMacro } from "../utils"; 4 | import Report from "../class.report"; 5 | import { RequestFunctionProps } from "../socket.factory"; 6 | 7 | export const goodActions = ['/cosmos.staking.v1beta1.MsgDelegate'] 8 | 9 | export const getReqMsgDelegate = ({ network, id, service }: RequestFunctionProps): JsonRpcRequest => { 10 | let microAmount = `${macroToMicro(service.query?.delegate?.min_amount || 25)}` 11 | const query = `tm.event = 'Tx' AND message.action='/cosmos.staking.v1beta1.MsgDelegate' AND delegate.validator='${network.valoper}' AND delegate.amount >= ${microAmount}` 12 | return { 13 | jsonrpc: "2.0", 14 | id, 15 | method: "subscribe", 16 | params: { 17 | query 18 | } 19 | } 20 | } 21 | export const getReqMsgUndelegate = ({ network, id, service }: RequestFunctionProps): JsonRpcRequest => { 22 | let microAmount = `${macroToMicro(service.query?.delegate?.min_amount || 25)}` 23 | const query = `tm.event = 'Tx' AND message.action='/cosmos.staking.v1beta1.MsgUndelegate' AND unbond.validator='${network.valoper}' AND unbond.amount >= ${microAmount}` 24 | return { 25 | jsonrpc: "2.0", 26 | id, 27 | method: "subscribe", 28 | params: { 29 | query 30 | } 31 | } 32 | } 33 | 34 | export const delegationsEventHandler = (event, { key, config, network, service, notify }): void => { 35 | let amount = event.events['delegate.amount']?.[0] || event.events['unbond.amount']?.[0] || "" 36 | let tx = event.events['tx.hash']?.[0] 37 | let action = event.events['message.action']?.[0] 38 | let macroAmount = microToMacro(amount) 39 | let macroDenom = network.denom.replace(/^\w/, '') //remove first char from denom 40 | let icon = goodActions.indexOf(action) === -1 ? icons.bad : icons.good 41 | const report = new Report() 42 | report.addRow("*New Delegation Event*") 43 | .addRow(`\`====== ${network.name} ======\``).backticks() 44 | .addRow(`${icon} ${action}`) 45 | .addRow(`${macroAmount} ${macroDenom}`) 46 | .addRow(`Tx: ${config.explorer}/${network.name}/txs/${tx}`).backticks() 47 | notify({ text: report.print(), config, service }); 48 | } 49 | 50 | export const getReqMsgDelegateWhale = ({ network, id, service }: RequestFunctionProps): JsonRpcRequest => { 51 | let microAmount = `${macroToMicro(service.query?.delegate_whale?.min_amount || 10000)}` 52 | const query = `tm.event = 'Tx' AND message.action='/cosmos.staking.v1beta1.MsgDelegate' AND delegate.amount >= ${microAmount}` 53 | return { 54 | jsonrpc: "2.0", 55 | id, 56 | method: "subscribe", 57 | params: { 58 | query 59 | } 60 | } 61 | } 62 | export const getReqMsgUndelegateWhale = ({ network, id, service }: RequestFunctionProps): JsonRpcRequest => { 63 | let microAmount = `${macroToMicro(service.query?.delegate_whale?.min_amount || 10000)}` 64 | const query = `tm.event = 'Tx' AND message.action='/cosmos.staking.v1beta1.MsgUndelegate' AND unbond.amount >= ${microAmount}` 65 | return { 66 | jsonrpc: "2.0", 67 | id, 68 | method: "subscribe", 69 | params: { 70 | query 71 | } 72 | } 73 | } 74 | 75 | export const delegationsEventHandlerWhale = (event, { key, config, network, service, notify }): void => { 76 | let amount = event.events['delegate.amount']?.[0] || event.events['unbond.amount']?.[0] || "" 77 | let tx = event.events['tx.hash']?.[0] 78 | let action = event.events['message.action']?.[0] 79 | let macroAmount = microToMacro(amount) 80 | let macroDenom = network.denom.replace(/^\w/, '') //remove first char from denom 81 | let icon = goodActions.indexOf(action) === -1 ? icons.bad : icons.good 82 | const report = new Report() 83 | report.addRow("*New 🐳 Delegation*") 84 | .addRow(`\`====== ${network.name} ======\``).backticks() 85 | .addRow(`${icon} ${action}`) 86 | .addRow(`${macroAmount} ${macroDenom}`) 87 | .addRow(`Tx: ${config.explorer}/${network.name}/txs/${tx}`).backticks() 88 | notify({ text: report.print(), config, service }); 89 | } -------------------------------------------------------------------------------- /src/helpers/rpc_query/send.ts: -------------------------------------------------------------------------------- 1 | import { JsonRpcRequest } from "@cosmjs/json-rpc"; 2 | import { icons, macroToMicro, microToMacro } from "../utils"; 3 | import Report from "../class.report"; 4 | import { RequestFunctionProps } from "../socket.factory"; 5 | 6 | export const getReqMsgSendBySpender = ({ network, id, service }: RequestFunctionProps): JsonRpcRequest => { 7 | let min_amount = '' 8 | if (service.query?.send?.min_amount) { 9 | let microAmount = `${macroToMicro(service.query?.send?.min_amount)}` 10 | min_amount = service.query?.send?.min_amount ? ` AND coin_spent.amount >= ${microAmount}` : '' 11 | } 12 | return { 13 | jsonrpc: "2.0", 14 | id, 15 | method: "subscribe", 16 | params: { 17 | query: `tm.event = 'Tx' AND message.action='/cosmos.bank.v1beta1.MsgSend' AND coin_spent.spender='${network.granter}'${min_amount}` 18 | } 19 | } 20 | } 21 | 22 | export const getReqMsgSendByReceiver = ({ network, id, service }: RequestFunctionProps): JsonRpcRequest => { 23 | let min_amount = '' 24 | if (service.query?.send?.min_amount) { 25 | let microAmount = `${macroToMicro(service.query?.send?.min_amount)}` 26 | min_amount = service.query?.send?.min_amount ? ` AND coin_received.amount >= ${microAmount}` : '' 27 | } 28 | return { 29 | jsonrpc: "2.0", 30 | id, 31 | method: "subscribe", 32 | params: { 33 | query: `tm.event = 'Tx' AND message.action='/cosmos.bank.v1beta1.MsgSend' AND coin_received.spender='${network.granter}'${min_amount}` 34 | } 35 | } 36 | } 37 | export const sendEventHandler = (event, { key, config, network, service, notify }): void => { 38 | 39 | let amount = event.events['coin_received.amount']?.[0] || event.events['coin_spent.amount']?.[0] || "" 40 | 41 | let tx = event.events['tx.hash']?.[0] 42 | let action = event.events['message.action']?.[0] 43 | let macroAmount = microToMacro(amount) 44 | let macroDenom = network.denom.replace(/^\w/, '') //remove first char from denom 45 | let icon = icons.bad 46 | const report = new Report() 47 | report.addRow("*New Send Event*") 48 | .addRow(`\`====== ${network.name} ======\``).backticks() 49 | .addRow(`${icon} ${action}`) 50 | .addRow(`${macroAmount} ${macroDenom}`) 51 | .addRow(`Tx: ${config.explorer}/${network.name}/txs/${tx}`).backticks() 52 | notify({ text: report.print(), config, service }); 53 | } 54 | 55 | 56 | export const getReqMsgSendWhale = ({ network, id, service }: RequestFunctionProps): JsonRpcRequest => { 57 | 58 | let min_whale_amount = service.query?.send_whale?.min_amount || 10000 59 | let microAmount = `${macroToMicro(min_whale_amount)}` 60 | const query = `tm.event = 'Tx' AND message.action='/cosmos.bank.v1beta1.MsgSend' AND coin_received.amount >= ${microAmount}` 61 | return { 62 | jsonrpc: "2.0", 63 | id, 64 | method: "subscribe", 65 | params: { 66 | query 67 | } 68 | } 69 | } 70 | 71 | export const sendEventHandlerWhale = (event, { key, config, network, service, notify }): void => { 72 | 73 | try { 74 | let amount = "" 75 | //all transfer amounts returned, such as gas and fees, find the largest 76 | if (Array.isArray(event.events['transfer.amount'])) { 77 | amount = event.events['transfer.amount'].reduce((a, b) => { 78 | let aMacro = microToMacro(a) 79 | let bMacro = microToMacro(b) 80 | return Math.max(aMacro, bMacro) 81 | }) 82 | 83 | } 84 | console.log("amount", amount) 85 | //smart contracts with other denom swaps trigger this query 86 | if (amount <= service.queries.send_whale.min_amount) return 87 | 88 | // console.log(event.events) 89 | let tx = event.events['tx.hash']?.[0] 90 | let action = event.events['message.action']?.[0] 91 | let macroDenom = network.denom.replace(/^\w/, '') //remove first char from denom 92 | let icon = icons.bad 93 | const report = new Report() 94 | report.addRow("*🐳 New Whale Event!*") 95 | .addRow(`\`====== ${network.name} ======\``).backticks() 96 | .addRow(`${icon} ${action}`) 97 | .addRow(`${amount} ${macroDenom}`) 98 | .addRow(`Tx: ${config.explorer}/${network.name}/txs/${tx}`).backticks() 99 | notify({ text: report.print(), config, service }); 100 | } catch (e) { 101 | console.log("Caught error sendEventHandlerWhale", e) 102 | } 103 | } -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | /* 2 | LOA LABS Nodejs Toolkit {ia} 3 | index.ts entrypoint 4 | */ 5 | 6 | 7 | //load env variables defined in .env file 8 | require('dotenv').config() 9 | const package_json = require('../package.json'); 10 | 11 | import { readdirSync, readFileSync } from 'fs'; 12 | import { Cron } from "croner"; 13 | import { v4 } from "uuid" 14 | import Report from "./helpers/class.report"; 15 | const report = new Report(); 16 | 17 | //server 18 | import runServer from './server' 19 | 20 | //cron services 21 | import status from './services/status' 22 | import rewards from './services/rewards' 23 | import proposals from './services/proposals' 24 | import distribution from './services/distribution' 25 | 26 | //ws services 27 | import watcher from './services/watcher' 28 | 29 | //types 30 | import { LntConfig, Service } from './helpers/global.types'; 31 | import { icons } from './helpers/utils'; 32 | 33 | try { 34 | const startTime = new Date().toISOString() 35 | 36 | report.header(`LOA Node Toolkit v${package_json.version}\nStart: \t${startTime} \nENV: \t${process.env.NODE_ENV}`) 37 | 38 | const jobs: Cron[] = []; 39 | const CONFIGS: LntConfig[] = []; 40 | 41 | 42 | 43 | (async () => { 44 | 45 | const SERVICES = { status, watcher, rewards, proposals, distribution } 46 | const configDir: string = __dirname + `/../configs/` 47 | const configFiles: string[] = await readdirSync(configDir) 48 | 49 | //start services 50 | //implement each json config found in configs folder 51 | for (let i = 0; i < configFiles.length; i++) { 52 | 53 | const filePath: string = configDir + configFiles[i] 54 | 55 | let config: LntConfig 56 | 57 | try { 58 | config = JSON.parse(await readFileSync(filePath, 'utf-8')) 59 | } catch (e) { 60 | console.log(`ERROR: Could not read config: ${filePath}`) 61 | continue 62 | } 63 | 64 | try { 65 | 66 | CONFIGS[configFiles[i].split(".").shift()] = config //index and store in memory 67 | 68 | if (config.enabled === false) { 69 | report.section(`${icons.bad} Config Not Enabled: ${filePath}\n`) 70 | continue 71 | } 72 | 73 | report.section(`${icons.good} Config Enabled: ${filePath}\n`) 74 | 75 | const serviceKeys: string[] = Object.keys(config.services) 76 | 77 | //schedule each service enabled in config 78 | //no large queries, n^2 should be ok here 79 | let taskCount = 0 80 | for (let j = 0; j < serviceKeys.length; j++) { 81 | 82 | const serviceKey = serviceKeys[j] 83 | const service: Service = config.services[serviceKey]; 84 | if (service.enabled === false) { 85 | report.addRow(`${icons.bad} [${serviceKey}] Service Not Enabled.`) 86 | continue 87 | } 88 | 89 | report.addRow(`${icons.good} [${serviceKey}] Service Enabled.`) 90 | 91 | service.uuid = v4() //assign each service unique id 92 | 93 | try { 94 | if (process.env.NODE_ENV === "production" || config.debug.SCHEDULE_CRON) { 95 | 96 | if (service.cron) { 97 | jobs[j] = new Cron( 98 | service.cron, 99 | { catch: true }, 100 | () => { 101 | 102 | if (config.debug.TEST_CRON_ONLY) { 103 | report.addRow(`debug.TEST_CRON_ONLY is true. ${serviceKey}`) 104 | return 105 | } 106 | 107 | SERVICES[serviceKey]({ ...service }, config) 108 | } 109 | ) 110 | 111 | report.addRow(` * Task ${taskCount} - Cron started: ${config.title} ${service.title}`) 112 | taskCount++ 113 | } 114 | 115 | if (service.run_on_start === true) { 116 | report.appendRow(` (Running on start)`) 117 | SERVICES[serviceKey]({ ...service }, config) 118 | } 119 | 120 | } 121 | 122 | } catch (e) { 123 | console.log(`ERROR: Could not run service: ${serviceKey}`, e) 124 | } 125 | } 126 | } catch (e) { 127 | console.log(`Caught error:`, e) 128 | } 129 | } 130 | 131 | console.log(report.print()) 132 | 133 | //start server to recieve commands 134 | runServer(CONFIGS) 135 | })() 136 | 137 | } catch (e) { 138 | console.log("Caught top level error.", e) 139 | } -------------------------------------------------------------------------------- /src/helpers/queryOnChainProposals.ts: -------------------------------------------------------------------------------- 1 | import { createProtobufRpcClient, QueryClient } from "@cosmjs/stargate"; import { 2 | QueryClientImpl, 3 | QueryProposalsRequest, 4 | QueryProposalsResponse, 5 | QueryVoteRequest 6 | } from "cosmjs-types/cosmos/gov/v1beta1/query"; 7 | import { Tendermint34Client } from "@cosmjs/tendermint-rpc"; 8 | 9 | import { unicodeToChar } from "./utils"; 10 | import { ProposalStatus, VoteOption } from "cosmjs-types/cosmos/gov/v1beta1/gov"; 11 | 12 | export type OnChainProposalResult = { 13 | proposal_id: number 14 | chain_id: string 15 | type: string 16 | voting_end_time: string 17 | title: string 18 | description: string 19 | option: number 20 | status: ProposalStatus 21 | } 22 | 23 | export const VoteOptions = [ 24 | { chain: VoteOption.VOTE_OPTION_UNSPECIFIED, human: "n/a" }, 25 | { chain: VoteOption.VOTE_OPTION_YES, human: "yes" }, 26 | { chain: VoteOption.VOTE_OPTION_ABSTAIN, human: "abstain" }, 27 | { chain: VoteOption.VOTE_OPTION_NO, human: "no" }, 28 | { chain: VoteOption.VOTE_OPTION_NO_WITH_VETO, human: "nowithveto" }, 29 | ] 30 | export const chainReadibleVoteOption = (option: number): VoteOption => { 31 | return VoteOptions[option].chain 32 | } 33 | export const humanReadibleVoteOption = (option: number): string => { 34 | return VoteOptions[option].human 35 | } 36 | export const humanVoteOptionToNumber = (text: string): VoteOption => { 37 | text = text.toLowerCase().trim() 38 | let option = VoteOptions.find(item => item.human == text) 39 | return option ? option.chain : 0 40 | } 41 | 42 | export const ProposalStatuses = [ 43 | { chain: ProposalStatus.PROPOSAL_STATUS_UNSPECIFIED, human: "N/A" }, 44 | { chain: ProposalStatus.PROPOSAL_STATUS_DEPOSIT_PERIOD, human: "Deposit Period" }, 45 | { chain: ProposalStatus.PROPOSAL_STATUS_VOTING_PERIOD, human: "Voting Period" }, 46 | { chain: ProposalStatus.PROPOSAL_STATUS_PASSED, human: "PASSED" }, 47 | { chain: ProposalStatus.PROPOSAL_STATUS_REJECTED, human: "REJECTED" }, 48 | { chain: ProposalStatus.PROPOSAL_STATUS_FAILED, human: "FAILED" } 49 | ] 50 | export const chainReadibleProposalStatus = (status: number): ProposalStatus => { 51 | return ProposalStatuses[status].chain 52 | } 53 | export const humanReadibleProposalStatus = (status: number): string => { 54 | return ProposalStatuses[status].human 55 | } 56 | 57 | export const queryOnChainProposals = async ({ network, status }): Promise => { 58 | if (!network.rpc) return [] 59 | try { 60 | const tendermint = await Tendermint34Client.connect(network.rpc); 61 | const queryClient = new QueryClient(tendermint); 62 | const rpcClient = createProtobufRpcClient(queryClient); 63 | const QueryService = new QueryClientImpl(rpcClient); 64 | const request: QueryProposalsRequest = { proposalStatus: chainReadibleProposalStatus(status), voter: "", depositor: "" } 65 | let res: QueryProposalsResponse = await QueryService.Proposals(request); 66 | //network has enabled propsals 67 | if (res.proposals?.length) { 68 | const proposalsParsed: OnChainProposalResult[] = [] 69 | for (let index = 0; index < res.proposals.length; index++) { 70 | 71 | const prop = res.proposals[index]; 72 | let resVote = null 73 | try { 74 | const request: QueryVoteRequest = { proposalId: prop.proposalId, voter: network.granter } 75 | resVote = await QueryService.Vote(request); 76 | } catch (e) { 77 | console.log(`\tPROP ${network.name} ${prop.proposalId} NO VOTE FOUND`) 78 | } 79 | let description = unicodeToChar(new TextDecoder().decode(prop.content.value)) 80 | let title = description.replace(/[a-z][^�#\n]*/, "") 81 | proposalsParsed.push({ 82 | proposal_id: prop.proposalId.low, 83 | chain_id: network.chain_id, 84 | type: prop.content.typeUrl.split(".").pop(), 85 | voting_end_time: new Date(prop.votingEndTime.seconds.low * 1000).toISOString(), 86 | title, 87 | description, 88 | option: resVote?.vote?.options?.[0].option ? Number(resVote?.vote?.options?.[0].option) : 0, 89 | status: prop.status 90 | }) 91 | 92 | } 93 | return proposalsParsed 94 | } else { 95 | console.log(`\n\tNo ${network.chain_id} proposals found`) 96 | return [] 97 | } 98 | 99 | } catch (e) { 100 | console.log(`queryOnChainProposals caught error for ${network.name}`, e) 101 | return [] 102 | } 103 | }; -------------------------------------------------------------------------------- /templates/authz-all.json: -------------------------------------------------------------------------------- 1 | { 2 | "body": { 3 | "messages": [ 4 | { 5 | "@type": "/cosmos.authz.v1beta1.MsgGrant", 6 | "granter": "cosmos1...", 7 | "grantee": "cosmos1...", 8 | "grant": { 9 | "authorization": { 10 | "@type": "/cosmos.authz.v1beta1.GenericAuthorization", 11 | "msg": "/cosmos.staking.v1beta1.MsgDelegate" 12 | } 13 | } 14 | }, 15 | { 16 | "@type": "/cosmos.authz.v1beta1.MsgGrant", 17 | "granter": "cosmos1...", 18 | "grantee": "cosmos1...", 19 | "grant": { 20 | "authorization": { 21 | "@type": "/cosmos.authz.v1beta1.GenericAuthorization", 22 | "msg": "/cosmos.distribution.v1beta1.MsgWithdrawDelegatorReward" 23 | } 24 | } 25 | }, 26 | { 27 | "@type": "/cosmos.authz.v1beta1.MsgGrant", 28 | "granter": "cosmos1...", 29 | "grantee": "cosmos1...", 30 | "grant": { 31 | "authorization": { 32 | "@type": "/cosmos.authz.v1beta1.GenericAuthorization", 33 | "msg": "/cosmos.distribution.v1beta1.MsgWithdrawValidatorCommission" 34 | } 35 | } 36 | }, 37 | { 38 | "@type": "/cosmos.authz.v1beta1.MsgGrant", 39 | "granter": "cosmos1...", 40 | "grantee": "cosmos1...", 41 | "grant": { 42 | "authorization": { 43 | "@type": "/cosmos.authz.v1beta1.GenericAuthorization", 44 | "msg": "/cosmos.gov.v1beta1.MsgVote" 45 | } 46 | } 47 | }, 48 | { 49 | "@type": "/cosmos.authz.v1beta1.MsgGrant", 50 | "granter": "cosmos1...", 51 | "grantee": "cosmos1...", 52 | "grant": { 53 | "authorization": { 54 | "@type": "/cosmos.authz.v1beta1.GenericAuthorization", 55 | "msg": "/cosmos.gov.v1beta1.MsgSubmitProposal" 56 | } 57 | } 58 | }, 59 | { 60 | "@type": "/cosmos.authz.v1beta1.MsgGrant", 61 | "granter": "cosmos...", 62 | "grantee": "cosmos...", 63 | "grant": { 64 | "authorization": { 65 | "@type": "/cosmos.bank.v1beta1.SendAuthorization", 66 | "spend_limit": [ 67 | { 68 | "denom": "uatom", 69 | "amount": "100000" 70 | } 71 | ] 72 | }, 73 | "expiration": null 74 | } 75 | }, 76 | { 77 | "@type": "/cosmos.authz.v1beta1.MsgGrant", 78 | "granter": "cosmos...", 79 | "grantee": "cosmos...", 80 | "grant": { 81 | "authorization": { 82 | "@type": "/cosmos.authz.v1beta1.GenericAuthorization", 83 | "msg": "/cosmos.slashing.v1beta1.MsgUnjail" 84 | }, 85 | "expiration": null 86 | } 87 | }, 88 | { 89 | "@type": "/cosmos.authz.v1beta1.MsgGrant", 90 | "granter": "cosmos...", 91 | "grantee": "cosmos...", 92 | "grant": { 93 | "authorization": { 94 | "@type": "/cosmos.authz.v1beta1.GenericAuthorization", 95 | "msg": "/cosmos.staking.v1beta1.MsgEditValidator" 96 | }, 97 | "expiration": null 98 | } 99 | }, 100 | { 101 | "@type": "/cosmos.feegrant.v1beta1.MsgGrantAllowance", 102 | "granter": "cosmos1...", 103 | "grantee": "cosmos1...", 104 | "allowance": { 105 | "@type": "/cosmos.feegrant.v1beta1.PeriodicAllowance", 106 | "basic": { 107 | "spend_limit": [], 108 | "expiration": "" 109 | }, 110 | "period": "86400s", 111 | "period_spend_limit": [ 112 | { 113 | "denom": "uatom", 114 | "amount": "1000000" 115 | } 116 | ], 117 | "period_can_spend": [ 118 | { 119 | "denom": "uatom", 120 | "amount": "1000000" 121 | } 122 | ], 123 | "period_reset": "" 124 | } 125 | } 126 | ], 127 | "memo": "", 128 | "timeout_height": "0", 129 | "extension_options": [], 130 | "non_critical_extension_options": [] 131 | }, 132 | "auth_info": { 133 | "signer_infos": [], 134 | "fee": { 135 | "amount": [ 136 | { 137 | "denom": "uatom", 138 | "amount": "5000" 139 | } 140 | ], 141 | "gas_limit": "200000", 142 | "payer": "", 143 | "granter": "" 144 | } 145 | }, 146 | "signatures": [] 147 | } -------------------------------------------------------------------------------- /src/services/database/services/hasura.ts: -------------------------------------------------------------------------------- 1 | //hasura db service 2 | import axios from "axios" 3 | 4 | const headers: any = { 5 | "Content-Type": "application/json", 6 | "X-Hasura-Admin-Secret": process.env.HASURA_ADMIN_SECRET 7 | } 8 | 9 | //define graphql table schema 10 | const props = [ 11 | { name: "uuid", type: "uuid" }, 12 | { name: "chain_id", type: "String" }, 13 | { name: "proposal_id", type: "Int" }, 14 | { name: "type", type: "String" }, 15 | { name: "notes", type: "String" }, 16 | { name: "option", type: "Int" }, 17 | { name: "status", type: "Int" }, 18 | { name: "voting_end_time", type: "timestamptz" } 19 | ] 20 | 21 | //@todo needs interface 22 | export const dbMethods = { 23 | 24 | exec: async (cmd, payload) => { 25 | return await dbMethods[cmd](payload) 26 | }, 27 | dbExec: async (body) => { 28 | console.log("process.env.HASURA_ENDPOINT", process.env.HASURA_ENDPOINT) 29 | const gqlResponse = await axios.post(process.env.HASURA_ENDPOINT, body, { headers }) 30 | return gqlResponse.data 31 | }, 32 | getPropsList: (props) => { 33 | return props.map((item: any) => item.name).join('\n') 34 | }, 35 | getPropsObject: (props, variables, filterAr = []) => { 36 | return dbMethods.filterProps(props, variables, filterAr).map((item: any) => 37 | `${item.name}: \$${item.name}`).join(',\n') 38 | }, 39 | getTypeValues: (props, variables, filterAr = []) => { 40 | return dbMethods.filterProps(props, variables, filterAr).map((item: any) => 41 | `\$${item.name}: ${item.type} = "${variables[item.name]}"`).join(',\n') 42 | }, 43 | filterProps: (props, variables, filterAr) => { 44 | return props.filter((item: any) => !filterAr.includes(item.name) && variables[item.name] !== undefined) 45 | }, 46 | getWhereQuery: (whereObject) => { 47 | let whereValuePairs = Object.keys(whereObject) 48 | .map(key => `${key}:{${whereObject[key]}: \$${key}}`) 49 | return `where: {${whereValuePairs.join(',')}}` 50 | }, 51 | getSetQuery: (setArray) => { 52 | let setKeyValuePairs = setArray.map(name => `${name}:\$${name}`) 53 | return `_set: {${setKeyValuePairs.join(',')}}` 54 | }, 55 | 56 | updateProposal: async ({ variables, whereObject, setArray }) => { 57 | 58 | const propsList = dbMethods.getPropsList(props) 59 | const propsTypeValues = dbMethods.getTypeValues(props, variables, ['uuid']) 60 | const whereQuery = dbMethods.getWhereQuery(whereObject) 61 | const setQuery = dbMethods.getSetQuery(setArray) 62 | 63 | let body = JSON.stringify({ 64 | query: ` 65 | mutation updateProposal(${propsTypeValues}) { 66 | update_proposals(${whereQuery}, ${setQuery}) { 67 | returning { 68 | ${propsList} 69 | } 70 | } 71 | } 72 | ` 73 | }) 74 | 75 | let res = await dbMethods.dbExec(body) 76 | console.log(res) 77 | return res 78 | 79 | }, 80 | 81 | getProposal: async ({ variables, whereObject, setArray }: any) => { 82 | console.log(variables, whereObject) 83 | const propsList = dbMethods.getPropsList(props) 84 | const propsTypeValues = dbMethods.getTypeValues(props, variables, ['uuid']) 85 | const whereQuery = dbMethods.getWhereQuery(whereObject) 86 | 87 | let body = JSON.stringify({ 88 | query: ` 89 | query getProposal(${propsTypeValues}) { 90 | proposals(${whereQuery}) { 91 | ${propsList} 92 | } 93 | } 94 | ` 95 | }) 96 | // console.log(body) 97 | let res = await dbMethods.dbExec(body) 98 | return res 99 | }, 100 | 101 | getActiveProposals: async ({ timestamp }) => { 102 | 103 | const propsList = dbMethods.getPropsList(props) 104 | let body = JSON.stringify({ 105 | query: ` 106 | query getActiveProposals($_gte: timestamptz = "${timestamp}") { 107 | proposals(where: {voting_end_time: {_gte: $_gte}}) { 108 | ${propsList} 109 | } 110 | } 111 | ` 112 | }) 113 | let res = await dbMethods.dbExec(body) 114 | return res 115 | }, 116 | 117 | insertProposal: async ({ variables }) => { 118 | 119 | const propsList = dbMethods.getPropsList(props) 120 | const propsObject = dbMethods.getPropsObject(props, variables, ['uuid']) 121 | const propsTypeValues = dbMethods.getTypeValues(props, variables, ['uuid']) 122 | let body = JSON.stringify({ 123 | query: ` 124 | mutation insertProposal(${propsTypeValues}) { 125 | insert_proposals(objects: {${propsObject}}) { 126 | returning { 127 | ${propsList} 128 | } 129 | } 130 | } 131 | ` 132 | }) 133 | 134 | let res = await dbMethods.dbExec(body) 135 | return res 136 | 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /src/services/distribution.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Warning: Use caution when activating this module. Ensure that appropriate limits and authorized wallets are set in Authz grants. 3 | */ 4 | 5 | import { queryBalance, queryBalanceResult } from "../helpers/balances"; 6 | import { MsgSend } from "cosmjs-types/cosmos/bank/v1beta1/tx"; 7 | import { notify } from "../helpers/notify"; 8 | import { 9 | $fmt, 10 | microToMacro, 11 | serviceFiltered, 12 | extractBech32Prefix, 13 | getCoinGeckoPrice, 14 | SignerObject, 15 | getSignerObject, 16 | execSignAndBroadcast, 17 | } from "../helpers/utils"; 18 | import Report from "../helpers/class.report"; 19 | import { LntConfig, NetworkConfig, Service } from "../helpers/global.types"; 20 | 21 | const testProduction = true; 22 | 23 | export default async (service: Service, config: LntConfig): Promise => { 24 | 25 | try { 26 | //////////////////////////////////////////////////// 27 | //init reporting 28 | const report = new Report(); 29 | report.addRow(`${config.title} ${service.title}`).backticks(); 30 | 31 | //set defaults 32 | let titlePad = 18; 33 | let $pad = 16; 34 | let coinPad = 10; 35 | let curPrice = 0; 36 | let resDistribution: any; 37 | 38 | for (let index = 0; index < config.networks.length; index++) { 39 | const network: NetworkConfig = config.networks[index]; 40 | 41 | if (serviceFiltered("status", network) || network?.enabled === false) continue; 42 | 43 | if (process.env.NODE_ENV == "production" || testProduction) { 44 | 45 | console.log(`\nTrying distribution for ${network.denom}...\n`); 46 | let pre_balance: queryBalanceResult = await queryBalance(network); 47 | report.section(`Pre Balance: ${pre_balance.amount}${network.denom}`); 48 | try { 49 | curPrice = await getCoinGeckoPrice({ 50 | id: network.coingecko_id, 51 | currency: "usd", 52 | }); 53 | console.log(`Current price is ${curPrice}`); 54 | 55 | //////////////////////////////////////////////////// 56 | //execute distrubtions 57 | resDistribution = await txDistribution({ config, network, service }); 58 | console.log("resDistribution", resDistribution); 59 | 60 | } catch (e) { 61 | console.log("ERROR", e); 62 | } 63 | } 64 | 65 | //////////////////////////////////////////////////// 66 | //prepare report 67 | report.addRow(`${network.chain_id}\nPrice:\t${$fmt(curPrice, 20)}`); 68 | for (let index = 0; index < resDistribution.sendReport.length; index++) { 69 | let sendReport: any = resDistribution.sendReport[index]; 70 | let $value = microToMacro(sendReport.amount) * curPrice; 71 | let macroAmountDisplay = `${sendReport.amount}${network.denom}`.padStart( 72 | coinPad 73 | ); 74 | report.addRow( 75 | `\n${"To:".padEnd(titlePad)}${sendReport.toAddress}` + 76 | `\n${"Amount:".padEnd(titlePad)}${macroAmountDisplay}${$fmt( 77 | $value, 78 | $pad 79 | )}` 80 | ); 81 | } 82 | 83 | let new_balance: queryBalanceResult = await queryBalance(network); 84 | report.addRow(`\nNew Balance: ${new_balance.amount}${network.denom}`).section(); 85 | 86 | 87 | } 88 | 89 | await notify({ text: report.backticks().print(), config, service }); 90 | return true 91 | 92 | } catch (e) { 93 | await notify({ text: `Caught Error ${e.message}`, config, service }); 94 | return false 95 | } 96 | }; 97 | 98 | 99 | //////////////////////////////////////////////////// 100 | //MsgSend transaction, abstract into separate function 101 | const txDistribution = async ({ config, network, service }): Promise => { 102 | let balance: queryBalanceResult = await queryBalance(network); 103 | 104 | //////////////////////////////////////////////////// 105 | //get signer address 106 | const signerObject: SignerObject = await getSignerObject({ config, network, service }) 107 | 108 | const distributionMsgsAr = []; 109 | const sendReport = []; 110 | 111 | for (let index = 0; index < network.distribution.length; index++) { 112 | let dist = network.distribution[index]; 113 | let amount: any = Math.floor(Number(balance.amount) * dist.allocation); 114 | 115 | let distValues = { 116 | fromAddress: network.granter, 117 | toAddress: dist.addr, 118 | amount: [ 119 | { 120 | denom: network.denom, 121 | amount: `${amount}`, 122 | }, 123 | ], 124 | }; 125 | 126 | distributionMsgsAr.push({ 127 | typeUrl: "/cosmos.bank.v1beta1.MsgSend", 128 | value: MsgSend.encode(MsgSend.fromPartial(distValues)).finish(), 129 | }); 130 | 131 | sendReport.push({ 132 | toAddress: dist.addr, 133 | amount, 134 | }); 135 | } 136 | 137 | const MsgExec = { 138 | typeUrl: "/cosmos.authz.v1beta1.MsgExec", 139 | value: { 140 | grantee: signerObject.senderAddress, 141 | msgs: distributionMsgsAr, 142 | }, 143 | }; 144 | 145 | let res: any = await execSignAndBroadcast({ signerObject, msg: [MsgExec], network }); 146 | res.sendReport = sendReport; 147 | return res; 148 | }; 149 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 4 | 5 | /* Basic Options */ 6 | // "incremental": true, /* Enable incremental compilation */ 7 | "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ 8 | "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ 9 | // "lib": [], /* Specify library files to be included in the compilation. */ 10 | // "allowJs": true, /* Allow javascript files to be compiled. */ 11 | // "checkJs": true, /* Report errors in .js files. */ 12 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 13 | // "declaration": true, /* Generates corresponding '.d.ts' file. */ 14 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 15 | "sourceMap": true, /* Generates corresponding '.map' file. */ 16 | // "outFile": "./", /* Concatenate and emit output to single file. */ 17 | // "outDir": "./", /* Redirect output structure to the directory. */ 18 | "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 19 | // "composite": true, /* Enable project compilation */ 20 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 21 | "removeComments": true, /* Do not emit comments to output. */ 22 | // "noEmit": true, /* Do not emit outputs. */ 23 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 24 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 25 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 26 | 27 | /* Strict Type-Checking Options */ 28 | "strict": false, /* Enable all strict type-checking options. */ 29 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 30 | // "strictNullChecks": true, /* Enable strict null checks. */ 31 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 32 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 33 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 34 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 35 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 36 | 37 | /* Additional Checks */ 38 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 39 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 40 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 41 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 42 | 43 | /* Module Resolution Options */ 44 | "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 45 | "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 46 | "typeRoots": ["./node_modules/@types"], /* List of folders to include type definitions from. */ 47 | // "types": [], /* Type declaration files to be included in compilation. */ 48 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 49 | "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 50 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 51 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 52 | 53 | /* Source Map Options */ 54 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 55 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 56 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 57 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 58 | 59 | /* Experimental Options */ 60 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 61 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 62 | 63 | /* Advanced Options */ 64 | "skipLibCheck": true, /* Skip type checking of declaration files. */ 65 | "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */ 66 | "baseUrl": ".", 67 | 68 | },"include": ["src","src/**/*.ts","@types/**/*.d.ts"], 69 | "exclude": ["node_modules"] 70 | } 71 | -------------------------------------------------------------------------------- /src/services/proposals.ts: -------------------------------------------------------------------------------- 1 | import { humanRelativeDate, serviceFiltered, icons } from "../helpers/utils"; 2 | import { 3 | queryOnChainProposals, 4 | humanReadibleProposalStatus, 5 | humanReadibleVoteOption, 6 | OnChainProposalResult, 7 | } from "../helpers/queryOnChainProposals"; 8 | import { notify } from "../helpers/notify"; 9 | import Report from "../helpers/class.report"; 10 | import { Interval } from "../helpers/interval.factory"; 11 | import { ProposalStatus } from "cosmjs-types/cosmos/gov/v1beta1/gov"; 12 | import { LntConfig, NetworkConfig, Service } from "../helpers/global.types"; 13 | 14 | const localTesting = true 15 | 16 | //////////////////////////////////////////////////// 17 | //keep in memory new proposals that have already triggered notification 18 | const newProposalNotifications = []; 19 | 20 | export default async (service: Service, config: LntConfig): Promise => { 21 | 22 | try { 23 | //////////////////////////////////////////////////// 24 | //start two interval counts, one regular, one more frequent 25 | const uuid_regular: string = service.uuid + "-regular"; 26 | const uuid_active: string = service.uuid + "-active"; 27 | Interval.init(uuid_regular, service.force_notify_count); 28 | Interval.init(uuid_active, service.active_notify_count); 29 | Interval.inc(uuid_regular); 30 | Interval.inc(uuid_active); 31 | Interval.status({ 32 | info: `${config.title} ${service.title}`, 33 | uuid: uuid_regular, 34 | }); 35 | Interval.status({ 36 | info: `${config.title} ${service.title}`, 37 | uuid: uuid_active, 38 | }); 39 | 40 | //////////////////////////////////////////////////// 41 | //init reporting 42 | const report = new Report(); 43 | report.addRow(`*${config.title} ${service.title}*`); 44 | 45 | let proposalNotVoted = false; 46 | let newProposal = false; 47 | 48 | if (process.env.NODE_ENV == "production" || localTesting) { 49 | 50 | //////////////////////////////////////////////////// 51 | //get on-chain proposals open for voting for each network 52 | const openProposalsOnChain = []; 53 | for (let index = 0; index < config.networks.length; index++) { 54 | const network: NetworkConfig = config.networks[index]; 55 | if (serviceFiltered("proposals", network) || network?.enabled === false) continue; 56 | 57 | let proposalsArray: OnChainProposalResult[] = await queryOnChainProposals({ 58 | network, 59 | status: ProposalStatus.PROPOSAL_STATUS_VOTING_PERIOD, 60 | }); 61 | if (proposalsArray.length > 0) 62 | openProposalsOnChain.push(...proposalsArray); 63 | else { 64 | report.addRow(`\n\`====== ${network.name} ======\``); 65 | report.addRow(`No proposals in Voting Period.`); 66 | } 67 | } 68 | 69 | console.log( 70 | "\n========= openProposalsOnChain.length ", 71 | openProposalsOnChain.length 72 | ); 73 | 74 | if (openProposalsOnChain.length > 0) { 75 | let curChainId = ""; 76 | let curNetworkConfig: any = {}; 77 | 78 | //////////////////////////////////////////////////// 79 | //check each on-chain proposal 80 | for (let index = 0; index < openProposalsOnChain.length; index++) { 81 | 82 | const chainProposal = openProposalsOnChain[index]; 83 | 84 | //////////////////////////////////////////////////// 85 | //add network heading for reporting 86 | if (chainProposal.chain_id !== curChainId) { 87 | curChainId = chainProposal.chain_id; 88 | curNetworkConfig = config.networks.find( 89 | (item: any) => item.chain_id == curChainId 90 | ); 91 | report.addRow( 92 | `\n\`====== ${curNetworkConfig.name || curChainId} ======\`` 93 | ); 94 | } 95 | 96 | let uniqueProposalId = `${curNetworkConfig.name}_${chainProposal.id}`; 97 | let voteIcon = icons.good; 98 | 99 | //////////////////////////////////////////////////// 100 | //if proposal has not been voted on yet, set notifications 101 | if (parseInt(chainProposal.option) === 0) { 102 | 103 | proposalNotVoted = true; 104 | voteIcon = icons.bad; 105 | 106 | //if not in newProposalNotifications array, forceNotification no matter the inverval state 107 | if (newProposalNotifications.indexOf(uniqueProposalId) === -1) { 108 | newProposal = true; 109 | newProposalNotifications.push(uniqueProposalId); 110 | } 111 | 112 | } 113 | 114 | //////////////////////////////////////////////////// 115 | //add proposal info to report 116 | report.addRow(`${voteIcon} *Prop ${chainProposal.proposal_id}*`); 117 | report.addRow( 118 | `${config.explorer}/${curNetworkConfig.name}/proposals/${chainProposal.proposal_id}` 119 | ); 120 | report.backticks().addRow(`Type: ${chainProposal.type}`); 121 | report.addRow( 122 | `Vote: *${humanReadibleVoteOption( 123 | chainProposal.option 124 | ).toUpperCase()}*` 125 | ); 126 | report.addRow( 127 | `Status: ${humanReadibleProposalStatus(chainProposal.status)}` 128 | ); 129 | report 130 | .addRow(`Ends: ${humanRelativeDate(chainProposal.voting_end_time)}`) 131 | .backticks(); 132 | } 133 | } 134 | } 135 | 136 | //////////////////////////////////////////////////// 137 | //regualr notification confirmation false, only triggered at intervals 138 | let confirmNotify = false; 139 | 140 | //////////////////////////////////////////////////// 141 | //regular proposal checkin interval, always send at specified interval regardless of voted 142 | if (Interval.complete(uuid_regular, service.run_on_start)) { 143 | confirmNotify = true; 144 | Interval.reset(uuid_regular); 145 | newProposalNotifications.length = 0; //flush from memory when notifying 146 | } 147 | 148 | //////////////////////////////////////////////////// 149 | //if the shorter uuid_active interval is reached 150 | if (Interval.complete(uuid_active, false)) { 151 | //and active proposal not voted on 152 | if (proposalNotVoted === true) confirmNotify = true; 153 | Interval.reset(uuid_active); 154 | } 155 | 156 | //////////////////////////////////////////////////// 157 | //confirmNotify triggered at regular intervals, force notify triggered on new proposals only 158 | if (confirmNotify || newProposal) { 159 | await notify({ text: report.print(), config, service }); 160 | } 161 | 162 | return true 163 | 164 | } catch (e) { 165 | await notify({ text: `Caught Error ${e.message}`, config, service }); 166 | return false 167 | } 168 | }; 169 | -------------------------------------------------------------------------------- /src/services/status.ts: -------------------------------------------------------------------------------- 1 | import axios from "axios"; 2 | import { notify } from "../helpers/notify"; 3 | import Report from "../helpers/class.report"; 4 | import { Interval } from "../helpers/interval.factory"; 5 | import { serviceFiltered, icons, microToMacro } from "../helpers/utils"; 6 | import { LntConfig, NetworkConfig, Service } from "../helpers/global.types"; 7 | import { socketFactory, WebsocketClientObject } from "../helpers/socket.factory"; 8 | import { JsonRpcRequest } from "@cosmjs/json-rpc"; 9 | import { getNewBlock, getNewBlockEventHandler } from "../helpers/rpc_query/block"; 10 | 11 | const localStatusTesting = true; 12 | 13 | //not currently used but 14 | //keeping JsonRpcRequest notes here for next time 15 | const statusRequest: JsonRpcRequest = { 16 | jsonrpc: "2.0", 17 | id: 1, 18 | method: "status", 19 | params: [] 20 | } 21 | const consensusParams: JsonRpcRequest = { 22 | jsonrpc: "2.0", 23 | id: 2, 24 | method: "consensus_params", 25 | params: [] 26 | } 27 | const accQuery: JsonRpcRequest = { 28 | jsonrpc: "2.0", 29 | id: 3, 30 | method: "abci_query", 31 | params: { 32 | path: "custom/auth/account", 33 | data: Buffer.from("{\"address\":\"regen1...\"}", "utf8").toString("hex") 34 | } 35 | }; 36 | const validatorQuery: JsonRpcRequest = { 37 | jsonrpc: "2.0", 38 | id: 3, 39 | method: "staking/validator", 40 | params: { 41 | validator_addr: "" 42 | } 43 | } 44 | ////////////////// 45 | 46 | 47 | export default async (service: Service, config: LntConfig): Promise => { 48 | 49 | //////////////////////////////////////////////////// 50 | //start interval service 51 | Interval.init(service.uuid, service.force_notify_count); 52 | Interval.inc(service.uuid); 53 | Interval.status({ 54 | info: `${config.title} ${service.title}`, 55 | uuid: service.uuid, 56 | }); 57 | 58 | //////////////////////////////////////////////////// 59 | //set report defaults 60 | let notifyFlag = false; 61 | let messageType = "Checkin"; 62 | let latest_block_time_dif_seconds = -1 63 | let latest_block_time_maxdif_seconds = 60; 64 | let disk_alert_threshold = 96; 65 | 66 | const report = new Report(); 67 | 68 | const colWidths = [5, 20, 5, 10, 10, 15] 69 | report.backticks().addRow( 70 | report.startCol(colWidths) 71 | .addCol("/// ", "left") 72 | .addCol("Network", "left") 73 | .addCol("Disk", "right") 74 | .addCol("Height", "right") 75 | .addCol("Elapsed", "right") 76 | .addCol("Voting Power", "right") 77 | .endCol() 78 | ) 79 | 80 | for (let index = 0; index < config.networks.length; index++) { 81 | 82 | const network: NetworkConfig = config.networks[index]; 83 | if (serviceFiltered("status", network) || network?.enabled === false) continue; 84 | 85 | //////////////////////////////////////////////////// 86 | //reset defaults for individual networks 87 | let icon = icons.good; 88 | let unix_time_now = 0; 89 | let unix_time_block = 0; 90 | let latest_block_time = 0; 91 | let latest_block_height = 0; 92 | let catching_up = true; 93 | let voting_power = 0; 94 | 95 | if (process.env.NODE_ENV == "production" || localStatusTesting) { 96 | try { 97 | //////////////////////////////////////////////////// 98 | //get client object and query status 99 | const WS: WebsocketClientObject = await socketFactory(network.rpc) 100 | const res_status = await WS.client.execute(statusRequest) 101 | // const res_consensus = await WS.client.execute(consensusParams) 102 | const res_acc = await WS.client.execute(accQuery) 103 | // console.log(res_acc.result.response.value) 104 | // console.log(atob(res_acc.result.response.value)) 105 | 106 | WS.addSubscription({ key: "_getNewBlock", config, network, service, requestFunction: getNewBlock, eventHandler: getNewBlockEventHandler }) 107 | // WS.addSubscription({ key: "_getVote", config, network, service, requestFunction: getVoteEvent, eventHandler: getVoteEventHandler }) 108 | // WS.addSubscription({ key: "_valQuery", config, network, service, requestFunction: validatorQuery, eventHandler: getVoteEventHandler }) 109 | 110 | //collect data of interest 111 | voting_power = res_status.result.validator_info.voting_power; 112 | latest_block_height = res_status.result.sync_info.latest_block_height; 113 | catching_up = res_status.result.sync_info.catching_up; 114 | latest_block_time = res_status.result.sync_info.latest_block_time; 115 | //compute time since last block 116 | unix_time_now = new Date().getTime() / 1000; 117 | unix_time_block = new Date(latest_block_time).getTime() / 1000; 118 | latest_block_time_dif_seconds = Math.abs(unix_time_block - unix_time_now) 119 | 120 | //check elapsed time since last block 121 | if ( 122 | catching_up == true || 123 | latest_block_time_dif_seconds > latest_block_time_maxdif_seconds || 124 | latest_block_height <= 0 125 | ) { 126 | notifyFlag = true; 127 | messageType = "BLOCK ALERT!"; 128 | icon = icons.bad; 129 | } 130 | 131 | } catch (e) { 132 | if (e.config?.url && e.message) e.message += `: ${e.config?.url}`; notifyFlag = true; 133 | messageType = "RPC ERROR"; 134 | icon = icons.bad; 135 | report.addRow(e.message) 136 | } 137 | 138 | } 139 | 140 | //////////////////////////////////////////////////// 141 | //check disk usage 142 | let diskReport = "N/A"; 143 | if (network.disk_check_endpoint && process.env.NODE_ENV == "production" || localStatusTesting) { 144 | try { 145 | const diskData: any = await axios.get(`${network.disk_check_endpoint}`, { 146 | timeout: 5000, 147 | }); 148 | 149 | let diskPercent = diskData?.data?.percent 150 | ? parseInt(diskData?.data?.percent) 151 | : 0; 152 | if (diskPercent >= disk_alert_threshold) { 153 | notifyFlag = true; 154 | messageType = "DISK ALERT!"; 155 | icon = icons.bad; 156 | } 157 | diskReport = `${diskData.data.percent}%`; 158 | } catch (e) { 159 | console.log("Caught disk check error", network.chain_id, e.config || e); 160 | } 161 | } 162 | 163 | //////////////////////////////////////////////////// 164 | //add report row with data results 165 | report.addRow( 166 | report.startCol(colWidths) 167 | .addCol(icon, "left") 168 | .addCol(network.chain_id, "left") 169 | .addCol(diskReport, "right") 170 | .addCol(latest_block_height, "right") 171 | .addCol(`${latest_block_time_dif_seconds.toFixed(1)}s`, "right") 172 | .addCol(`${Number(microToMacro(voting_power) / 1000).toFixed(3)}`, "right") 173 | .endCol() 174 | ) 175 | 176 | } 177 | 178 | if (Interval.complete(service.uuid, service.run_on_start)) { 179 | notifyFlag = true; 180 | Interval.reset(service.uuid); 181 | } 182 | 183 | report.addHeader(`\n*Monitoring ${messageType}*`) 184 | 185 | let text = report.backticks().print(); 186 | 187 | if (notifyFlag) { 188 | await notify({ text, config, service }); 189 | } else console.log(text); 190 | 191 | return true 192 | }; 193 | -------------------------------------------------------------------------------- /src/commands/vote/tx.ts: -------------------------------------------------------------------------------- 1 | import { EncodeObject } from "@cosmjs/proto-signing" 2 | import { VoteOption } from "cosmjs-types/cosmos/gov/v1beta1/gov" 3 | import { MsgVote } from "cosmjs-types/cosmos/gov/v1beta1/tx" 4 | import Report from "../../helpers/class.report" 5 | import { notify } from "../../helpers/notify" 6 | import { humanReadibleVoteOption, humanVoteOptionToNumber } from "../../helpers/queryOnChainProposals" 7 | import { extractBech32Prefix, getSignerObject, execSignAndBroadcast, SignerObject, icons } from "../../helpers/utils" 8 | import { LntConfig } from "../../helpers/global.types" 9 | import Request from "express" 10 | import { instantiator } from "../../services/database/instantiator" 11 | 12 | //optional storing of votes in db 13 | const dbInstance = instantiator.init("hasura") || null 14 | 15 | const testVoteTx = true 16 | 17 | export default async ({ req, config }: { req: Request, config: LntConfig }): Promise => { 18 | 19 | console.log("\nVOTE QUERY:", req.query) 20 | console.log("VOTE QUERY BODY TEXT:", req.body.text) 21 | const command = config?.commands?.vote 22 | const report = new Report() 23 | 24 | //crude auth 25 | try { 26 | let authed = false 27 | if (command.enabled !== true) { 28 | report.addRow("Service not enabled.") 29 | } else if (typeof command.credentials === "object" && command.credentials !== null) { 30 | //////////////////////////////////////////////////// 31 | //authenticate source of command 32 | let credKeys = Object.keys(command.credentials) 33 | for (let index = 0; index < credKeys.length; index++) { 34 | let cred_value = command.credentials[credKeys[index]]; 35 | cred_value = Array.isArray(cred_value) ? cred_value : [cred_value] 36 | if (cred_value && cred_value.indexOf(req.body[credKeys[index]]) !== -1) { 37 | authed = true 38 | } 39 | } 40 | } 41 | 42 | //////////////////////////////////////////////////// 43 | //exit with error if not authorized 44 | if (!authed) { 45 | report.addRow("Unauthorized vote.") 46 | await notify({ 47 | text: report.print(), 48 | config, 49 | service: command, 50 | response_url: req.body.response_url 51 | }) 52 | return false 53 | } 54 | } catch (e) { 55 | console.log("Caught Error:", e) 56 | } 57 | 58 | try { 59 | //////////////////////////////////////////////////// 60 | //parse command 61 | let commandParts = req.body.text.split("|") 62 | let [chain, proposal_id, option] = commandParts[0].replace(/\s+/, " ").split(" ") 63 | let notes: string = commandParts?.[1] ? commandParts[1].trim() : "" 64 | proposal_id = parseInt(proposal_id) 65 | let optionNumber: VoteOption = humanVoteOptionToNumber(option) 66 | 67 | //////////////////////////////////////////////////// 68 | //determine which network config 69 | let network = config.networks.find(item => { 70 | return item.name.toLowerCase() == chain.toLowerCase() 71 | }) 72 | 73 | //////////////////////////////////////////////////// 74 | //get signer address 75 | const signerObject: SignerObject = await getSignerObject({ config, network, service: command }) 76 | 77 | //////////////////////////////////////////////////// 78 | //create msg vote 79 | const txMsgVote = { 80 | typeUrl: "/cosmos.gov.v1beta1.MsgVote", 81 | value: MsgVote.encode( 82 | MsgVote.fromPartial({ 83 | proposalId: proposal_id, 84 | voter: network.granter, 85 | option: optionNumber 86 | })).finish() 87 | }; 88 | 89 | //////////////////////////////////////////////////// 90 | //create msg exec 91 | const MsgExec: EncodeObject = { 92 | typeUrl: "/cosmos.authz.v1beta1.MsgExec", 93 | value: { 94 | grantee: signerObject.senderAddress, 95 | msgs: [txMsgVote], 96 | }, 97 | }; 98 | 99 | try { 100 | //////////////////////////////////////////////////// 101 | //sign and broadcast tx 102 | let res_tx: any = "" 103 | if (process.env.NODE_ENV === "production" || testVoteTx) { 104 | //broadcast vote 105 | res_tx = await execSignAndBroadcast({ signerObject, msg: [MsgExec], network }); 106 | console.log(`\n\n\n=========== signAndBroadcast \n\n\n`, res_tx, `res_tx?.transactionHash?.length ${res_tx?.res?.transactionHash?.length}`) 107 | } else { 108 | console.log("No broadcast", [MsgExec]) 109 | } 110 | 111 | res_tx.res 112 | //////////////////////////////////////////////////// 113 | //successful tx, notify 114 | if (res_tx?.res?.transactionHash?.length) { 115 | 116 | console.log("Notify...") 117 | //////////////////////////////////////////////////// 118 | //prep report 119 | if (res_tx.res.code !== 0) { 120 | //was not successful 121 | report.addRow(`${icons.bad} *Vote Failed on \`${network.name}\` Prop ${proposal_id}*`) 122 | report.addRow(`TX: ${config.explorer}/${network.name}/txs/${res_tx.res.transactionHash}`) 123 | report.addRow(`Code: ${res_tx.res.code}\n${res_tx.res.rawLog}`) 124 | 125 | } else { 126 | report.addRow(`${icons.good} *Completed Vote on \`${network.name}\` Prop ${proposal_id}*`) 127 | report.backticks().addRow(`Vote: *${humanReadibleVoteOption(optionNumber).toUpperCase()}*`) 128 | report.addRow(`TX: ${config.explorer}/${network.name}/txs/${res_tx.res.transactionHash}`) 129 | report.addRow(`Note: ${notes}`) 130 | report.backticks() 131 | } 132 | 133 | await notify({ 134 | text: report.print(), config, service: command, 135 | response_url: req.body.response_url 136 | }) 137 | 138 | //////////////////////////////////////////////////// 139 | //if storing in database 140 | if (dbInstance) { 141 | await storeVoteInDB({ 142 | chain_id: network.chain_id, 143 | proposal_id, 144 | option: optionNumber, 145 | notes, 146 | }) 147 | } 148 | 149 | } else { 150 | report.addRow(`🚨 *Error Executing Vote on Prop*: ${chain} ${proposal_id}`) 151 | await notify({ 152 | text: report.print(), config, service: command, 153 | response_url: req.body.response_url 154 | }) 155 | } 156 | 157 | } catch (e) { 158 | console.log("Caught Error:", e) 159 | report.addRow(`🚨 *Error Signing & Broadcasting Vote*: ${chain} ${proposal_id}: ${e.message}`) 160 | await notify({ 161 | text: report.print(), config, service: command, 162 | response_url: req.body.response_url 163 | }) 164 | } 165 | 166 | } catch (e) { 167 | console.log("Caught Error:", e) 168 | report.addRow(`🚨 *Error Forumlating Vote*: ${req.body["text"]}`) 169 | await notify({ 170 | text: report.print(), config, service: command, 171 | response_url: req.body.response_url 172 | }) 173 | } 174 | 175 | return true 176 | } 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | const storeVoteInDB = async (variables: any): Promise => { 187 | 188 | try { 189 | //////////////////////////////////////////////////// 190 | //check if already voted 191 | let res = await dbInstance.exec("getProposal", { 192 | variables: { 193 | chain_id: variables.chain_id, 194 | proposal_id: variables.proposal_id 195 | }, 196 | whereObject: { 197 | chain_id: "_eq", 198 | proposal_id: "_eq", 199 | }, 200 | }); 201 | 202 | //if proposal found, update with new vote info 203 | if (res.data?.proposals?.length) { 204 | await dbInstance.exec("updateProposal", 205 | { 206 | variables, 207 | whereObject: { 208 | chain_id: "_eq", 209 | proposal_id: "_eq", 210 | }, 211 | setArray: ["option", "notes"] 212 | }) 213 | 214 | } else { 215 | //else proposal not found, insert 216 | await dbInstance.exec("insertProposal", { 217 | variables 218 | }); 219 | } 220 | 221 | } catch (e) { 222 | console.log("Caught Error:", e) 223 | } 224 | 225 | return true 226 | } -------------------------------------------------------------------------------- /src/helpers/utils.ts: -------------------------------------------------------------------------------- 1 | import { createProtobufRpcClient, DeliverTxResponse, GasPrice, QueryClient, SigningStargateClient, StdFee } from "@cosmjs/stargate"; 2 | import { 3 | Coin, 4 | DirectSecp256k1HdWallet, 5 | EncodeObject, 6 | OfflineDirectSigner, 7 | } from "@cosmjs/proto-signing"; 8 | import axios from "axios"; 9 | import { relativeTime } from "human-date"; 10 | import { LntConfig, NetworkConfig } from "./global.types"; 11 | import { Tendermint34Client } from "@cosmjs/tendermint-rpc"; 12 | 13 | 14 | 15 | 16 | //iterate through the CONFIGS and find the one that matches the credential key/val pair provided in request 17 | //since multiple sets of configs can run simultaneously we need to find the correct one without having to specify it in the command line 18 | export const getCommandConfigBy = (CONFIGS: LntConfig[], { credentialsKey, value, command }): [string, LntConfig] => { 19 | return Object.entries(CONFIGS).find(([_, config]: any) => { 20 | 21 | let credentials = config?.commands?.[command]?.credentials?.[credentialsKey] 22 | 23 | let credentialsAr = Array.isArray(credentials) ? credentials : [credentials] 24 | 25 | return credentialsAr.indexOf(value) !== -1 && config.enabled 26 | 27 | }) || [null, null] 28 | } 29 | 30 | // Add cache to getCoinGeckoPrice so that we don't ping coinGecko every time we need a price 31 | const coinGeckoCache: { [key: string]: { lastChecked: number, price: number } } = {}; 32 | const coinGeckoCacheStale = 1000 * 60 * 60 * 6 //6 hours 33 | 34 | export const getCoinGeckoPrice = async ({ 35 | id, 36 | currency, 37 | }: { id: string, currency: string }): Promise => { 38 | try { 39 | 40 | if (coinGeckoCache[id] && coinGeckoCache[id].lastChecked < new Date().getTime() - coinGeckoCacheStale) { 41 | console.log(`\ngetCoinGeckoPrice: (CACHED) ${id} price: ${coinGeckoCache[id].price}${currency}\n`); 42 | return coinGeckoCache[id].price 43 | } 44 | let res: any = await axios.get( 45 | `https://api.coingecko.com/api/v3/coins/${id}` 46 | ); 47 | let price = res.data.market_data.current_price[currency]; 48 | coinGeckoCache[id] = { lastChecked: new Date().getTime(), price } 49 | 50 | console.log(`\ngetCoinGeckoPrice: ${id} price: ${price}${currency}\n`); 51 | return price; 52 | } catch (e) { 53 | console.log(`Caught getCoinGeckoPrice ERROR`, e); 54 | return 0; 55 | } 56 | }; 57 | 58 | import { QueryClientImpl, QueryAllowanceRequest } from "cosmjs-types/cosmos/feegrant/v1beta1/query"; 59 | const checkFeeGrant = async (network: NetworkConfig, senderAddress): Promise => { 60 | 61 | try { 62 | //@todo need Tendermint34Client factory to go with webSocket factor! 63 | const tendermint = await Tendermint34Client.connect(network.rpc); 64 | const queryClient = new QueryClient(tendermint); 65 | const rpcClient = createProtobufRpcClient(queryClient); 66 | const feeGrantQueryService = new QueryClientImpl(rpcClient); 67 | 68 | const query: QueryAllowanceRequest = { 69 | granter: network.granter, 70 | grantee: senderAddress 71 | } 72 | let res = await feeGrantQueryService.Allowance(query); 73 | console.log("\n========== checkFeeGrant", res) 74 | 75 | if (res.allowance?.allowance?.value) return true 76 | } catch (e) { 77 | console.log("\n========== Caught checkFeeGrant error:", e) 78 | } 79 | return false 80 | } 81 | 82 | export type SignerObject = { 83 | Signer: OfflineDirectSigner 84 | senderAddress: string 85 | mnemonic: string 86 | prefix: string 87 | } 88 | 89 | export const getSignerObject = async ({ 90 | config, 91 | network, 92 | service 93 | }): Promise => { 94 | 95 | let mnemonic = "" 96 | if (network.grantee_mnemonic) { //name of mnemonic in networks config 97 | mnemonic = config.grantee_mnemonics[network.grantee_mnemonic] 98 | } else { //use default mnemonic of service 99 | mnemonic = config.grantee_mnemonics[service.use_mnemonic] 100 | } 101 | 102 | let prefix = extractBech32Prefix(network.granter) 103 | const getSignerFromMnemonic = async (): Promise => { 104 | return await DirectSecp256k1HdWallet.fromMnemonic(mnemonic, { 105 | prefix 106 | }); 107 | }; 108 | const Signer: OfflineDirectSigner = await getSignerFromMnemonic(); 109 | const senderAddress = (await Signer.getAccounts())[0].address 110 | return { Signer, senderAddress, mnemonic, prefix }; 111 | }; 112 | 113 | export const granterStdFee = async (network: NetworkConfig, senderAddress: string, gas_required: number): Promise => { 114 | 115 | if (network.feegrant_enabled === undefined) { 116 | network.feegrant_enabled = await checkFeeGrant(network, senderAddress) 117 | } 118 | 119 | gas_required = Math.ceil(gas_required * 1.5) //gas adjustment 120 | let gas_prices = network.gas_prices == undefined || null ? 0.03 : network.gas_prices 121 | let denom: string = network.denom 122 | let amount = `${Math.ceil(gas_required * gas_prices)}` 123 | let coinAmount: Coin = { amount, denom } 124 | 125 | let res = { 126 | amount: [coinAmount], 127 | gas: `${gas_required}`, 128 | granter: network.feegrant_enabled ? network.granter : '' 129 | } 130 | 131 | console.log("\n========== granterStdFee", res) 132 | return res 133 | }; 134 | 135 | export const execSignAndBroadcast = async (props: 136 | { 137 | signerObject: SignerObject, 138 | msg: EncodeObject[] 139 | network: NetworkConfig, 140 | }) => { 141 | const { signerObject, msg, network } = props; 142 | 143 | try { 144 | const signingClient: SigningStargateClient = await SigningStargateClient.connectWithSigner( 145 | network.rpc, 146 | signerObject.Signer 147 | ); 148 | 149 | let gas_required = network.gas || 350000 //default gas required, increased to 350k 150 | // simulations are not working, estimates are too low 151 | // try { 152 | // gas_required = await signingClient.simulate(signerObject.senderAddress, msg, "simulate tx") 153 | // console.log("\nsigningClient.simulate gas_required:", gas_required) 154 | // } catch (e) { 155 | // console.log("Caught simulate error:", e); 156 | // } 157 | 158 | let fee = await granterStdFee(network, signerObject.senderAddress, gas_required) 159 | console.log("\ngranterStdFee:", fee) 160 | 161 | let res: DeliverTxResponse = await signingClient.signAndBroadcast(signerObject.senderAddress, msg, fee) 162 | console.log("\nsignAndBroadcast res:", res.code, res.transactionHash) 163 | let returning: any = { code: res.code, transactionHash: res.transactionHash } 164 | if (res.code !== 0) { 165 | console.log(res.rawLog) 166 | returning.rawLog = res.rawLog 167 | } 168 | 169 | return { chain_id: network.chain_id, res: returning }; 170 | 171 | } catch (e) { 172 | console.log("\nCaught execSignAndBroadcast error:", e); 173 | return { chain_id: network.chain_id, error: e }; 174 | } 175 | } 176 | 177 | 178 | export const extractBech32Prefix = (addr: string): string => { 179 | return addr.split("1").shift(); 180 | }; 181 | 182 | export const humanReadibleDateFromISO = (isoDate: string): string => { 183 | let options: any = { 184 | weekday: "short", 185 | year: "numeric", 186 | month: "short", 187 | day: "2-digit", 188 | hour: "2-digit", 189 | minute: "2-digit", 190 | timeZone: "UTC", 191 | timeZoneName: "short", 192 | }; 193 | return new Date(isoDate).toLocaleString("en-US", options); 194 | }; 195 | 196 | export const humanRelativeDate = (dateRepresentation: string): string => { 197 | return relativeTime(dateRepresentation); 198 | }; 199 | 200 | export const unicodeToChar = (text: string): string => { 201 | return text.replace(/\\u[\dA-F]{4}/gi, function (match) { 202 | return String.fromCharCode(parseInt(match.replace(/\\u/g, ""), 16)); 203 | }); 204 | }; 205 | 206 | export const serviceFiltered = ( 207 | service_name: string, 208 | network: NetworkConfig 209 | ): Boolean => { 210 | if (Array.isArray(network.filter_services)) { 211 | return network.filter_services.indexOf(service_name) !== -1 ? true : false; 212 | } 213 | return false; 214 | }; 215 | 216 | export const $fmt = (value: any, pad = 0): string => { 217 | value = isNaN(value) ? 0 : value //ensure number 218 | return value 219 | .toLocaleString("en-US", { style: "currency", currency: "USD" }) 220 | .padStart(pad); 221 | }; 222 | 223 | export const microToMacro = (value: any, network?: NetworkConfig): number => { 224 | let exponent = network?.exponent || 6 225 | let denomenator = parseInt("1".padEnd(exponent + 1, "0")) 226 | // console.log("value", value, "denomenator", denomenator) 227 | return parseInt(value) / denomenator; 228 | }; 229 | 230 | export const macroToMicro = (value: any, network?: NetworkConfig): number => { 231 | let exponent = network?.exponent || 6 232 | return parseFloat(value) * parseInt("1".padEnd(exponent + 1, "0")); 233 | }; 234 | 235 | export const icons = { 236 | good: "✅", 237 | bad: "🔴 ", 238 | } 239 | -------------------------------------------------------------------------------- /src/services/rewards.ts: -------------------------------------------------------------------------------- 1 | import { queryBalance, queryStaked, queryBalanceResult } from "../helpers/balances"; 2 | import { 3 | MsgWithdrawDelegatorReward, 4 | MsgWithdrawValidatorCommission, 5 | } from "cosmjs-types/cosmos/distribution/v1beta1/tx"; 6 | import { MsgDelegate } from "cosmjs-types/cosmos/staking/v1beta1/tx"; 7 | import { notify } from "../helpers/notify"; 8 | import { 9 | $fmt, 10 | extractBech32Prefix, 11 | microToMacro, 12 | serviceFiltered, 13 | getCoinGeckoPrice, 14 | SignerObject, 15 | getSignerObject, 16 | execSignAndBroadcast, 17 | } from "../helpers/utils"; 18 | import Report from "../helpers/class.report"; 19 | import { LntConfig, NetworkConfig, Service } from "../helpers/global.types"; 20 | 21 | 22 | const testAsProduction = true; 23 | const debug = new Report(); 24 | 25 | export default async (service: Service, config: LntConfig): Promise => { 26 | debug.header("REWARDS") 27 | try { 28 | 29 | const nowTime = new Date().toISOString(); 30 | debug.addRow(`\t${config.title} ${service.title} \n\tTime: ${nowTime}`); 31 | 32 | const report = new Report(); 33 | report.addRow(`${config.title} ${service.title}`).backticks(); 34 | 35 | 36 | let titlePad = 18; 37 | let $pad = 16; 38 | let $EarningsTotal: number = 0; 39 | let $BalanceTotal: number = 0; 40 | let $StakedTotal: number = 0; 41 | 42 | for (let index = 0; index < config.networks.length; index++) { 43 | 44 | const network: NetworkConfig = config.networks[index]; 45 | 46 | if (serviceFiltered("rewards", network) || network.enabled === false) 47 | continue; 48 | 49 | //defaults 50 | let macroDenom = network.denom.substring(1); 51 | let macroEarnings = 0; 52 | let macroBalance = 0; 53 | let macroStaked = 0; 54 | let macroRestaked = 0; 55 | let price = 0; 56 | 57 | if (process.env.NODE_ENV === "production" || testAsProduction) { 58 | try { 59 | //////////////////////////////////////////////////// 60 | //get price 61 | // price = 0.18 62 | price = await getCoinGeckoPrice({ 63 | id: network.coingecko_id, 64 | currency: "usd", 65 | }); 66 | 67 | const preBalance: queryBalanceResult = await queryBalance(network); 68 | 69 | //////////////////////////////////////////////////// 70 | //withdraw rewards and commissions 71 | let resRewards: any = await txRewards({ config, network, service }); 72 | debug.addRow(`DEBUG REWARDS === ${network.chain_id}`) 73 | .addRow(JSON.stringify(resRewards.res)) 74 | 75 | //////////////////////////////////////////////////// 76 | //resRewards.res.rawLog is array with object types "type": "withdraw_rewards", "type": "withdraw_commission" but need to be iterated to find, easier to compare postBalance to get the earnings 77 | const postBalance: queryBalanceResult = await queryBalance(network); 78 | let earnings = Math.abs(postBalance.amount - preBalance.amount); 79 | debug.addRow(`Earnings: ${earnings}`); 80 | 81 | //////////////////////////////////////////////////// 82 | //if restake amount set in network config, execute restaking tx 83 | let amountToRestake = Math.floor(earnings * Number(network.restake || 0)); 84 | if (Math.abs(amountToRestake / 100000) > 0) { 85 | debug.addRow("Restaking") 86 | let resRestake: any = await txRestake({ 87 | amountToRestake, 88 | config, 89 | network, 90 | service, 91 | }); 92 | } 93 | const stakedBalance: queryBalanceResult = await queryStaked(network); 94 | 95 | //////////////////////////////////////////////////// 96 | //prepare human readable amounts 97 | macroEarnings = microToMacro(earnings, network); 98 | macroBalance = microToMacro(postBalance.amount, network); 99 | macroRestaked = microToMacro(amountToRestake, network); 100 | macroStaked = microToMacro(stakedBalance.amount, network); 101 | 102 | } catch (e) { 103 | debug.addRow(`Caught ERROR: `).addRow(e); 104 | } 105 | } 106 | 107 | 108 | //////////////////////////////////////////////////// 109 | //get values in fiat 110 | let $Earnings: any = macroEarnings * price; 111 | let $Balance: any = macroBalance * price; 112 | let $Restaked: any = macroRestaked * price; 113 | let $Staked: any = macroStaked * price; 114 | 115 | //////////////////////////////////////////////////// 116 | //add to report total 117 | $EarningsTotal += !isNaN($Earnings) ? $Earnings : 0; 118 | $BalanceTotal += !isNaN($Balance) ? $Balance : 0; 119 | $StakedTotal += !isNaN($Staked) ? $Staked : 0; 120 | 121 | //////////////////////////////////////////////////// 122 | //prep report display 123 | let denomPad = 21; 124 | let macroEarningsDisplay = (macroEarnings.toFixed(3) + macroDenom).padStart(denomPad); 125 | let macroBalanceDisplay = (macroBalance.toFixed(3) + macroDenom).padStart(denomPad); 126 | let macroRestakedDisplay = (macroRestaked.toFixed(3) + macroDenom).padStart(denomPad); 127 | let macroStakedDisplay = (macroStaked.toFixed(3) + macroDenom).padStart(denomPad); 128 | 129 | //////////////////////////////////////////////////// 130 | //add row to report 131 | report.addRow( 132 | `---\n${network.chain_id}` + 133 | `\n${"Price:".padEnd(titlePad)}${$fmt(price)}` + 134 | `\n${"Earnings:".padEnd(titlePad)}${macroEarningsDisplay}${$fmt( 135 | $Earnings, 136 | $pad 137 | )}` + 138 | `\n${"Liquid Balance:".padEnd(titlePad)}${macroBalanceDisplay}${$fmt( 139 | $Balance, 140 | $pad 141 | )}` + 142 | `\n${`${network.restake * 100}% Restaked:`.padEnd( 143 | titlePad 144 | )}${macroRestakedDisplay}${$fmt($Restaked, $pad)}` + 145 | `\n${"Total Staked:".padEnd(titlePad)}${macroStakedDisplay}${$fmt( 146 | $Staked, 147 | $pad 148 | )}` 149 | ); 150 | } 151 | 152 | let totalPad = 25; 153 | let total$Pad = 30; 154 | 155 | //////////////////////////////////////////////////// 156 | //add totals to report 157 | report 158 | .addRow( 159 | `\n---------` + 160 | `\n${"Total Earnings:".padEnd(totalPad)}${$fmt( 161 | $EarningsTotal, 162 | total$Pad 163 | )}` + 164 | `\n${"Total Liquid Balance:".padEnd(totalPad)}${$fmt( 165 | $BalanceTotal, 166 | total$Pad 167 | )}` + 168 | `\n${"Total Staked:".padEnd(totalPad)}${$fmt($StakedTotal, total$Pad)}` 169 | ) 170 | .backticks(); 171 | 172 | await notify({ text: report.print(), config, service }); 173 | 174 | } catch (e) { 175 | await notify({ text: `Caught Error ${e.message}`, config, service }); 176 | } 177 | 178 | debug.log() 179 | 180 | } 181 | 182 | 183 | //////////////////////////////////////////////////// 184 | //validator distributions transaction, abstract into separate function 185 | const txRewards = async ({ config, network, service }): Promise => { 186 | //////////////////////////////////////////////////// 187 | //get signer address 188 | const signerObject: SignerObject = await getSignerObject({ config, network, service }) 189 | 190 | const txMsgWithdrawDelegatorReward = { 191 | typeUrl: "/cosmos.distribution.v1beta1.MsgWithdrawDelegatorReward", 192 | value: MsgWithdrawDelegatorReward.encode( 193 | MsgWithdrawDelegatorReward.fromPartial({ 194 | delegatorAddress: network.granter, 195 | validatorAddress: network.valoper, 196 | }) 197 | ).finish(), 198 | }; 199 | 200 | const txMsgWithdrawValidatorCommission = { 201 | typeUrl: "/cosmos.distribution.v1beta1.MsgWithdrawValidatorCommission", 202 | value: MsgWithdrawValidatorCommission.encode( 203 | MsgWithdrawValidatorCommission.fromPartial({ 204 | validatorAddress: network.valoper, 205 | }) 206 | ).finish(), 207 | }; 208 | 209 | const MsgExec = { 210 | typeUrl: "/cosmos.authz.v1beta1.MsgExec", 211 | value: { 212 | grantee: signerObject.senderAddress, 213 | msgs: [txMsgWithdrawDelegatorReward, txMsgWithdrawValidatorCommission], 214 | }, 215 | }; 216 | 217 | try { 218 | let res = await execSignAndBroadcast({ signerObject, msg: [MsgExec], network }); 219 | return { chain_id: network.chain_id, res }; 220 | } catch (e) { 221 | return { chain_id: network.chain_id, error: e }; 222 | } 223 | }; 224 | 225 | //////////////////////////////////////////////////// 226 | //validator restaking transaction, abstract into separate function 227 | const txRestake = async ({ amountToRestake, config, network, service }): Promise => { 228 | debug.section().addRow(`Restaking ${amountToRestake}${network.denom}`); 229 | 230 | //////////////////////////////////////////////////// 231 | //get signer address 232 | const signerObject: SignerObject = await getSignerObject({ config, network, service }) 233 | 234 | const txMsgDelegate = { 235 | typeUrl: "/cosmos.staking.v1beta1.MsgDelegate", 236 | value: MsgDelegate.encode( 237 | MsgDelegate.fromPartial({ 238 | delegatorAddress: network.granter, 239 | validatorAddress: network.valoper, 240 | amount: { 241 | denom: network.denom, 242 | amount: `${amountToRestake}`, 243 | }, 244 | }) 245 | ).finish(), 246 | }; 247 | 248 | const MsgExec = { 249 | typeUrl: "/cosmos.authz.v1beta1.MsgExec", 250 | value: { 251 | grantee: signerObject.senderAddress, 252 | msgs: [txMsgDelegate], 253 | }, 254 | }; 255 | 256 | try { 257 | let res = await execSignAndBroadcast({ signerObject, msg: [MsgExec], network }); 258 | return { chain_id: network.chain_id, res }; 259 | } catch (e) { 260 | return { chain_id: network.chain_id, error: e }; 261 | } 262 | }; 263 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![LNT](https://user-images.githubusercontent.com/9093152/215165214-b69a09cf-10a1-42bc-b3ce-04c997f9c152.png) 2 | 3 | Highly configurable and lightweight Nodejs toolkit for monitoring, governing, and financing validator nodes on Cosmos. 4 | 5 | [Installation](#installation) 6 | 7 | * Nodejs toolset to monitor validator uptime and diskspace, automate rewards and restaking, monitor and vote on governance proposals, websocket watch wallet or validator for transactions. 8 | 9 | * Takes a lightweight approach to node monitoring and automation. Nodejs instance(s) can run on its own node, or on validator node. 10 | 11 | * Single instance can monitor multiple chains and connect to multiple notification channels such as Slack, Discord, Telegram, and Twitter. 12 | 13 | * Leverages authz to delegate a sub-set of needed authorizations to perform automated tasks. 14 | ​ 15 | * Each service runs on its own cron schedule, frequency of check-ins and notifications can be customized. 16 | 17 | ### Monitoring Checks fed into Slack Channel 18 | ![Monitoring Checks](https://user-images.githubusercontent.com/9093152/215628279-bafd4c8d-3b3c-49cd-b634-c365fbc13796.png) 19 | 20 | ### WS Watchers for events that meet notification thresholds 21 | ![image](https://user-images.githubusercontent.com/9093152/215513855-1490feb7-a0d2-466b-9833-36191f9e8b76.png) 22 | 23 | ### Automatic Rewards Withdrawals and Restaking Daily Compounding Report 24 | ![Auto Rewards and Auto Restaking](https://user-images.githubusercontent.com/9093152/214908668-5fd3bd06-9bd2-4736-bffb-f4f36f954b57.png) 25 | ​ 26 | ### Gov Proposal Checks fed into private Slack Channel, also Monitoring alert shown with comment thread and Governance Votes Execution with Slack (or Discord) Command from private channel, also gov disccussion in comment thread 27 | ![Proposal Checks](https://user-images.githubusercontent.com/9093152/214908831-1e3acc9a-43fe-4d2d-9c98-8b6c4c06c2a5.png) 28 | 29 | ## Installation 30 | ​ 31 | System requirements 32 | ``` 33 | node ^18.7.0 34 | npm ^8.18.0 35 | ``` 36 | ​ 37 | Checkout and install 38 | ``` 39 | git clone https://github.com/LOA-Labs/loa-node-toolkit.git 40 | ​ 41 | cd loa-node-toolkit 42 | 43 | npm install 44 | ``` 45 | 46 | Configure (use your favorite editor) 47 | ``` 48 | vim configs/default.json 49 | ``` 50 | 51 | ### 1. Status Service 52 | 53 | The most basic service is Status, so let's begin with it. It pings node to check status using a cron interval, default is set to check every 5 minutes. 54 | 55 | Under "networks" section, update "name", "chain_id", and "rpc" with your chain/node's information. 56 | 57 | This are the only three settings required for Status service: 58 | ``` 59 | { 60 | "name": "regen", 61 | "chain_id": "regen-1", 62 | "rpc": "http://127.0.0.1:26657" 63 | } 64 | ``` 65 | 66 | If not enabled already, you'll need to open your node's RPC port: 67 | 68 | Edit your node's `./config/config.toml` 69 | 70 | The default is 127.0.0.1, you may wish to change to your node's IP address or to 0.0.0.0 71 | ``` 72 | # TCP or UNIX socket address for the RPC server to listen on 73 | laddr = "tcp://127.0.0.1:26657" 74 | ``` 75 | 76 | After restarting your node, http://:26657 should now show the default list of available RPC queries. 77 | 78 | If you do not wish your RPC server to be public, you can use UFW firewall to allow access to only your known IP addresses. 79 | 80 | **Status service configs:** 81 | ``` 82 | "status": { 83 | "enabled": true, 84 | "run_on_start": true, 85 | "title": "Status Service", 86 | //check status every 5 minutes 87 | "cron": "*/5 * * * *", 88 | //notify every 72 checks (every 6 hours) 89 | "force_notify_count": 72, 90 | //channel configs status notifications 91 | "notify": { 92 | "discord": "#node-monitor", 93 | "slack": "#node-monitor" 94 | } 95 | } 96 | ``` 97 | 98 | **Notification configs:** 99 | Setting up [Discord webhook](https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks) 100 | Setting up [Slack webhook](https://api.slack.com/messaging/webhooks) 101 | ``` 102 | "notifications": { 103 | "discord": { 104 | "#node-monitor": { 105 | "enabled": true, 106 | "endpoint": "https://discord.com/api/webhooks/<12345678>/<12345678>" 107 | } 108 | }, 109 | "slack": { 110 | "#node-monitor": { 111 | "enabled": true, 112 | "endpoint": "https://hooks.slack.com/services/<12345678>/<12345678>/<12345678>" 113 | } 114 | } 115 | } 116 | ``` 117 | 118 | Once networks, services, and notifications are configured, run: 119 | 120 | ``` 121 | npm run build 122 | ​ 123 | npm run start 124 | ``` 125 | 126 | ### 2. Proposals Service 127 | 128 | This service sends notifications to a Sla ck or Discord channel when there are new governance proposals. Its purpose is not let you forget to cast a vote; it sends repeated notifications until the vote has been cast. 129 | 130 | Edit `configs/default.json` 131 | 132 | Set `enabled` to true. Set `run_on_start` to true also for testing. 133 | 134 | Default cron is set to check for new government proposals every 15 minutes. 135 | 136 | `force_notify_count` is set to send proposal status every 64 checks, which will send every 12 hours regardless of any new proposals. A peace of mind. 137 | 138 | `active_notify_count` is set to send proposal status every 16 checks, which will send every 3 hours if there are open proposals of which the validator has not voted. Using the Vote Command to vote already! 139 | 140 | Notify is set here to same `#node-monitor` channel configuration, but sending proposal notices to a different channel is also possible. 141 | 142 | ``` 143 | "proposals": { 144 | "enabled": true, 145 | "run_on_start": true, 146 | "title": "Proposal Check", 147 | "cron": "*/15 * * * *", 148 | "force_notify_count": 64, 149 | "active_notify_count": 16, 150 | "notify": { 151 | "slack": "#node-monitor", 152 | "discord": "#node-monitor" 153 | } 154 | } 155 | ``` 156 | 157 | 158 | ### 3. Vote Command 159 | 160 | This command allows you to easily submit a vote transaction from within Slack or Discord messaging app. 161 | 162 | **Note: [Requires Authz](#authz)** 163 | 164 | 1. Create a grantee bot account with voting authorization to vote on behalf of the grantor validator account. You can use the [Governance Messages Template](https://github.com/LOA-Labs/loa-node-toolkit/blob/main/templates/authz-governance.json). You can follow the [Authz](#authz) instructions below. 165 | 166 | 2. Enable the vote command in the `commands` section. You can set the command to use the specific 'voter' mnemonic, or a general bot account that has been granted many types of permissions. If you wish to add more security on who can vote from Slack or Discord channel, you may add allowed `channel_id` strings as an array, and/or allowed `user_id` strings. 167 | 168 | We allow voting from within the same channel that the proposal notices are sent. 169 | 170 | 3. Set the `notify` channels where voting result should be sent. 171 | 172 | ``` 173 | "vote": { 174 | "enabled": false, 175 | "title": "Voting", 176 | "use_mnemonic": "voter", 177 | "credentials": { 178 | "channel_id": [ 179 | "12345678", 180 | "12345678" 181 | ] 182 | }, 183 | "notify": { 184 | "slack": "#node-monitor", 185 | "discord": "#node-monitor" 186 | } 187 | } 188 | ``` 189 | 190 | 4. When LNT is built with this configuration enabled, it will log the port that the expressjs server is listening on for receiving commands from Slack or Discord. 191 | 192 | Slash Command format from Slack is `/vote [| Note about vote decision]` 193 | 194 | See this resource to set up [Slack Slash Commands](https://api.slack.com/interactivity/slash-commands) 195 | 196 | ### 4. Rewards Service 197 | 198 | This service is used to withdraw staking and commission rewards, and restake a percentage of those rewards all on an automatic schedule. 199 | 200 | **Note: [Requires Authz](#authz)** 201 | 202 | 1. Enable the rewards feature by setting to `true`. The default cron is set on to run at the 12th UTC hour every day. 203 | 204 | 2. The [Restaking Template](https://github.com/LOA-Labs/loa-node-toolkit/blob/main/templates/authz-restaking.json). After granting the necessary permissions, or by using a general bot, set the label of bot mnemonic that should be used. 205 | 206 | ``` 207 | "rewards": { 208 | "enabled": true, 209 | "run_on_start": false, 210 | "title": "Daily Rewards Report", 211 | "cron": "0 12 * * *", 212 | "use_mnemonic": "asset_manager", 213 | "notify": { 214 | "slack": "#node-monitor", 215 | "discord": "#node-monitor" 216 | } 217 | } 218 | ``` 219 | 220 | 3. By default, restaking will not happen during the withdraw rewards process. Restaking must be set individually on each network. 221 | 222 | In the `networks` section, the `restake` parameter must be set. It takes a float representation of a percentage. 0.5 = 50% restake. The restaking amount is based on the amount of rewards withdrawn and not the full wallet balance; this is to ensure that the wallet balance is never drained unintentionally. 223 | 224 | ``` 225 | "networks": [ 226 | { 227 | "name": "regen", 228 | "chain_id": "regen-1", 229 | "rpc": "http://127.0.0.1:26657", 230 | "coingecko_id": "regen", 231 | "denom": "uregen", 232 | "gas_prices": "0.025", 233 | "gas_auto": true, 234 | "granter": "regen1...", 235 | "valoper": "regenvaloper1...", 236 | "restake": 0.5 237 | } 238 | ] 239 | ``` 240 | 241 | 4. Rebuild and restart LNT. 242 | 243 | ### 5. Distribution Service 244 | 245 | This service automatically sends funds broken down by percentages to various wallet addresses. 246 | 247 | **Be very careful with this one!** Granting bank send permissions adds risk to validator funds if the seed phrase for the bot account is exposed. 248 | 249 | To help mitigate this risk: 250 | * Be sure to correctly set a limit for the amount of funds that can be send per day, and/or: 251 | * Wait until Cosmos SDK v0.47 is available on your chain, which allows you to add an `allow_list` of wallets that the bot account may send funds to. 252 | 253 | **Note: [Requires Authz](#authz)** 254 | 255 | 1. The templates for sending are [Sending Template](https://github.com/LOA-Labs/loa-node-toolkit/blob/main/templates/authz-sending.json) and [Sending Template v0.47](https://github.com/LOA-Labs/loa-node-toolkit/blob/main/templates/authz-sending-v47.json) 256 | 257 | 2. Set distribution enabled to true. By default, the cron is set to run 10 minutes after the rewards have been withdrawn/restaking. Distribution should run after rewards withdrawn/restaking has completed. 258 | 259 | ``` 260 | "distribution": { 261 | "enabled": true, 262 | "run_on_start": false, 263 | "title": "Daily Distribution", 264 | "cron": "10 12 * * *", 265 | "use_mnemonic": "asset_manager", 266 | "notify": { 267 | "slack": "#node-monitor" 268 | } 269 | } 270 | ``` 271 | 272 | 3. Distribution amounts must be set individually on each network. Distribution is based on the current account balance. Thus, percentage total of distributions must be less than 100% or the account will be emptied of funds. 273 | 274 | ``` 275 | "networks": [ 276 | { 277 | "enabled": true, 278 | "name": "regen", 279 | ... 280 | "restake": 0.5, 281 | "distribution": [ 282 | { 283 | "addr": "regen1a...", 284 | "allocation": 0.48 285 | }, 286 | { 287 | "addr": "regen1b...", 288 | "allocation": 0.48 289 | } 290 | ] 291 | } 292 | ] 293 | ``` 294 | 295 | 296 | ## Authz 297 | 298 | Using authz to give restricted permissions to a bot wallet, many validator tasks can run automatically using the LNT cron service configurations. It is important to set up Authz correctly to maintain asset security even if the bot seed phrase is accidentally leaked. The bot seed phrase is used to generate the offline signer which has permissions to execute certain tasks on behalf of the validator. 299 | 300 | Authz grant message [templates are located here](https://github.com/LOA-Labs/loa-node-toolkit/tree/main/templates). 301 | 302 | You may choose the [authz-all.json](https://github.com/LOA-Labs/loa-node-toolkit/tree/main/templates/authz-all.json) template and grant everything the bot account might utilize, or you may wish to break up permissions granularly: 303 | 304 | * [Voting (authz-voting.json)](https://github.com/LOA-Labs/loa-node-toolkit/tree/main/templates/authz-voting.json) - gives permission to create proposals and vote on behalf of granter. This feature can be used to vote from within a private Slack or Discord channel. 305 | 306 | * [Managing Validator (authz-managing.json)](https://github.com/LOA-Labs/loa-node-toolkit/tree/main/templates/authz-managing.json) - edit validator info, unjail. 307 | 308 | * [Restaking (authz-restaking.json)](https://github.com/LOA-Labs/loa-node-toolkit/tree/main/templates/authz-restaking.json) - withdraw rewards, withdraw commissions, restake. 309 | 310 | * [Sending (authz-sending.json)](https://github.com/LOA-Labs/loa-node-toolkit/tree/main/templates/authz-sending.json) - Important to set sending limits, and even better use with Cosmos SDK v47 [Sending (authz-sending-v47.json)](https://github.com/LOA-Labs/loa-node-toolkit/tree/main/templates/authz-sending-v47.json) with allow_list option. Sending feature can automated distributions of funds to specified wallets. 311 | 312 | * [Fee Grant (fee-grant.json)](https://github.com/LOA-Labs/loa-node-toolkit/tree/main/templates/fee-grant.json) - not a part of Authz but an important piece to the automation stack. Fee Grant message is included in all of the authz templates. If Fee Grant is not granted, the bot wallet needs to have funds periodically added to pay for gas to execute transactions on behalf of validator. 313 | 314 | **Authz steps:** 315 | 316 | 1. Create a new wallet for the bot account and send a tiny amount to it to establish its presence on chain 317 | 2. Add the bot account seed phrase to the config file 318 | 3. Using one of the Authz json templates: 319 | - replace the grantee fields with the bot account's bech32 address 320 | - replace the grater fields with the validator's bech32 address 321 | - replace the denoms with target chain's denom 322 | - adjust any other configurations 323 | 4. Using the CLI execute ` tx sign --from > signed-authz-template.json` 324 | 5. Then broadcast ` tx broadcast signed-authz-template.json --from ` 325 | 6. You can check which authz permissions have been granted with ` q authz grants-by-grantee ` 326 | 7. You can fee grant with ` q feegrant grants-by-grantee ` 327 | 328 | Also see: [https://docs.cosmos.network/v0.47/modules/authz](https://docs.cosmos.network/v0.47/modules/authz) 329 | 330 | 331 | ## NOTICE PER [GPL-3.0 license](https://github.com/LOA-Labs/loa-node-toolkit/blob/main/LICENSE) 332 | 333 | Software provided "As Is". The entire risk of using this software is with you. 334 | 335 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 336 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 337 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 338 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 339 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 340 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 341 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 342 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 343 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------