From d560ea33e4d998d10a474fd760367d2296af655c Mon Sep 17 00:00:00 2001 From: 0xGorilla <0xGorilla@protonmail.com> Date: Wed, 19 Jan 2022 12:45:14 -0300 Subject: [PATCH] feat: added strategies and vaults --- LICENSE | 2 +- README.md | 110 ++++++------------------ eth-sdk/config.ts | 15 ++-- package.json | 13 +-- src/goerli/job-a-stealth/README.md | 17 ---- src/goerli/job-a-stealth/job.ts | 73 ---------------- src/goerli/job-a-stealth/metadata.json | 3 - src/goerli/job-a/README.md | 16 ---- src/goerli/job-a/job.ts | 64 -------------- src/goerli/job-a/metadata.json | 3 - src/goerli/job-strategies/README.md | 16 ---- src/goerli/job-strategies/job.ts | 109 ----------------------- src/goerli/job-strategies/metadata.json | 3 - src/strategies/job.ts | 70 +++++++++++++++ src/strategies/metadata.json | 3 + src/vaults/job.ts | 70 +++++++++++++++ src/vaults/metadata.json | 3 + 17 files changed, 187 insertions(+), 403 deletions(-) delete mode 100644 src/goerli/job-a-stealth/README.md delete mode 100644 src/goerli/job-a-stealth/job.ts delete mode 100644 src/goerli/job-a-stealth/metadata.json delete mode 100644 src/goerli/job-a/README.md delete mode 100644 src/goerli/job-a/job.ts delete mode 100644 src/goerli/job-a/metadata.json delete mode 100644 src/goerli/job-strategies/README.md delete mode 100644 src/goerli/job-strategies/job.ts delete mode 100644 src/goerli/job-strategies/metadata.json create mode 100644 src/strategies/job.ts create mode 100644 src/strategies/metadata.json create mode 100644 src/vaults/job.ts create mode 100644 src/vaults/metadata.json diff --git a/LICENSE b/LICENSE index 496a7b6..48a1e7e 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ (The MIT License) -Copyright 2022 DeFi Wonderland +Copyright 2022 Mushrooms Finance Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/README.md b/README.md index 2863e66..51a0225 100644 --- a/README.md +++ b/README.md @@ -1,91 +1,35 @@ -[![image](https://img.shields.io/npm/v/@defi-wonderland/keep3r-cli-job-boilerplate.svg?style=flat-square)](https://www.npmjs.org/package/@defi-wonderland/keep3r-cli-job-boilerplate) +[![image](https://img.shields.io/npm/v/@mushroomsfi/keep3r-cli-job.svg?style=flat-square)](https://www.npmjs.org/package/@mushroomsfi/keep3r-cli-job) -# Keep3r CLI Job Boilerplate +# Mushrooms Finance CLI Job -`@defi-wonderland/keep3r-cli-job-boilerplate` aims to provide protocols an easy way of creating a CLI compatible job, just start by forking this repo. +This job enables The Keep3r Network keepers on Ethereum to execute tasks for Mushrooms yield-farming vaults (`earn`) and underlying strategies (`harvest`). -As well, this repository includes testnet jobs that can be installed and tested without any real costs. +## How to install +1. Open a terminal inside your [CLI](https://github.com/keep3r-network/cli) setup +2. Run `yarn add @mushroomsfi/keep3r-cli-job` +3. Add job inside your CLI config file. It should look something like this: +``` +{ + ... + "jobs": [ + ..., + { + "path": "node_modules/@mushroomsfi/keep3r-cli-job/dist/src/mainnet/strategies" + }, + { + "path": "node_modules/@mushroomsfi/keep3r-cli-job/dist/src/mainnet/vaults" + } + ] +} +``` -## Using testnet jobs +## Keeper Requirements -This repository comes with some jobs deployed to goerli that serve as a safe and easy way to test whether users running Keep3r CLI have setup their keepers correctly. These jobs are: +* Must be a valid Keeper on Keep3r V1 -- [Job A](https://github.com/defi-wonderland/keep3r-cli-job-boilerplate/blob/main/src/goerli/job-a/README.md) -- [Job A Stealth](https://github.com/defi-wonderland/keep3r-cli-job-boilerplate/blob/main/src/goerli/job-a-stealth/README.md) -- [Job Strategies](https://github.com/defi-wonderland/keep3r-cli-job-boilerplate/blob/main/src/goerli/job-strategies/README.md) +## Useful Links - -## Creating a new job - -1. Fork this repository -2. Update organization and package name inside: -* `package.json` -* `README.md` -* `LICENSE` -3. Create a github repository and add a secret named `NPM_TOKEN` - - This token can be generated in [npmjs.com](https://www.npmjs.com) -> account -> access tokens -> generate new token -> add name and select the publish type -4. Update `eth-sdk/config.ts` with your relevant contracts and chain -5. Adapt `src` to fit your job while maintaining the same structure -6. As soon as you merge into a branch called `main`, a deployment to npm will occur - - - -## Job specifics - -- `metadata.json`: Super simple `.json` file containing the name of the job. This is an example of how it would look like if your job was called `My First Job`. - - ```bash - { - "name": "My First Job" - } - ``` - - Right now this file seems unimportant, but in future versions it will be used to add extra information about each specific job. An example of this, would be the tokens the job uses to pay the keepers—right now we assume they pay in KP3R or ETH—which will help the Keep3r-CLI properly calculate the profitability of the transaction. In the current version, the name is used to create an id for each job, which will help the Keep3r-CLI know which job is currently in progress to avoid rerunning it unnecessarily. - -- `job.ts`: This file will contain the logic of the job script, and therefore it will be the file the Keep3r-CLI runs when it intends to work your job. Writing the logic in this file can sound like a daunting task at first, but we have built everything so that there's a lot of shared logic between scripts, which makes creating a script for your job a simple task. -After going through the examples you will find that all the jobs follow a similar pattern to this one: - - Declare a variable that contains the address of your job. - - Create an async function called `getWorkableTxs` which will take `args` as arguments. This function will contain all the important logic to create what we call **workable groups** and send them along with an id to the Keep3r-CLI. - A workable group is an array that contains objects that have: - - The target block at which to perform a transaction. - - An array containing the populated transactions to be performed - - An id to identify each array in the workable group, so it's easier for keepers to read the logs. - - For example, let's say `ExampleJob` needs a keeper to call the `work` function and let's say the keeper establishes `100` as the target block. When a keeper executes `getWorkableTxs`, this function will output the following working group: - - ```bash - workableGroup = [{ - targetBlock: 100, - txs: [populated tx data to call work], - logId: some randomly generated id - }] - ``` - - This working group will then be passed to the Keep3r-CLI `job-wrapper.ts` file, for additional checks before sending the transactions to flashbots. - **All of the following points will be different points of logic inside `getWorkableTxs`** - - - Create a `correlationId`, which will be used to track if the current job being executed to avoid rerunning it unnecessarily. - - Create an if check that checks, using the `correlationId`, whether that job should be rerun in a block or not. For example: the keeper runs your job at block `100`, but specifies `105` as its target block. The `correlationId` and this additional check will prevent all the logic to check whether the job is workable or not from being rerun in the blocks `101, 102, 103, 104`, where it's not necessary. - - Create a variable `logMetadata` containing all the relevant information you would like the keeper to see in their logs. We recommend creating an object containing the name of your job, the current block, and a logId to help identify each job. - - Create a `logConsole` variable that calls the `prelog` utility function passing in the `logMetadata` as an argument. This is simply used to log better logs. It appends all the information established in `logMetadata` to each log that uses `logConsole` instead of `console.log` - - Create a variable containing your job's contract. This will be used to populate the transactions the keeper will end up running. - - Create a try catch finally statement. - - The try statement will call the `work` function to check if, in the current block, that job can be worked or if it's on cooldown. If it is workable, it adds a log and then creates a `workableGroup` variable initialized to an empty array. - Things get interesting after this. Because we know the job is workable, we can now populate the transactions we will need to send to flashbots in order to execute this job, and then push an object containing those transactions along with the target block and id of each one to our `workableGroup`. - To populate transactions for consequent blocks we use a for loop that will push as many objects to `workableGroups` as the keeper has passed as the `bundleBurst` parameter. In these objects, the array of populated transactions will always be the same, but the target block and the id will change. - If everything went well, `getWorkableTxs` sends an object containing the workable groups and the current job `correlationId` to the Keep3r-CLI, which will be received by `job-wrapper.ts`. - - The catch statement will catch any error and log out a message for the keeper to read. The most common error that will occur is that the job is currently in cooldown, therefore it can't be worked. - - The finally statement will kill the process once it has concluded. - - Lastly, and outside the `getWorkableTxs` function, we export `getWorkableTxs`. - - This is the shared structure among jobs and it's exactly the structure that can be found in the `JobA` example we provide. However, some jobs will have protocol-specific logic that will modify this structure ever-so-slightly. - - For example: some jobs will have multiple strategies that need to be run. Others will require the keeper to call a function before calling the `work` function. For these two cases we have provided examples that show how to modify the basic structure to add protocol-specific features: - - - Strategies are covered in `harvest-v2`, `tend-v2`, `tend-v2-2`. - - Jobs that require a previous function to be called is covered in `dca` - - Jobs that use relayers are covered in `harvest-v2`, `jobAStealth` - -If you still have doubts as to how to implement a script for your job, reach out to us! +* [Job](https://etherscan.io/address/0x0bd1d668d8e83d14252f2e01d5873df77a6511f0) +* [Documentation](https://github.com/keep3r-network/keep3r.network/pull/52) +* [Keep3r V1](https://etherscan.io/address/0x1ceb5cb57c4d4e2b2433641b95dd330a33185a44) \ No newline at end of file diff --git a/eth-sdk/config.ts b/eth-sdk/config.ts index a3cdbe1..6e3ba82 100644 --- a/eth-sdk/config.ts +++ b/eth-sdk/config.ts @@ -1,13 +1,10 @@ import { defineConfig } from '@dethcrypto/eth-sdk'; export default defineConfig({ - outputPath: 'src/eth-sdk-build', - contracts: { - goerli: { - jobA: '0xd50345ca88e0B2cF9a6f5eD29C1F1f9d76A16C3c', - jobAStealth: '0x9DC52d978290f13b73692C5AeA21B4C8954e909A', - stealthRelayer: '0xD44A48001A4BAd6f23aD8750eaD0036765A35d4b', - jobStrategies: '0x8CeA64dc82515D56c22d072167Da44Abd3211B6f', - }, - }, + outputPath: 'src/eth-sdk-build', + contracts: { + mainnet: { + job: '0x0bD1d668d8E83d14252F2e01D5873df77A6511f0', + }, + }, }); diff --git a/package.json b/package.json index 3853f12..46f3696 100644 --- a/package.json +++ b/package.json @@ -1,20 +1,21 @@ { - "name": "@defi-wonderland/keep3r-cli-job-boilerplate", - "version": "1.0.2", - "description": "Keep3r CLI Job Boilerplate", + "name": "@mushroomsfi/keep3r-cli-job", + "version": "1.0.0", + "description": "Mushrooms Finance CLI Job for The Keep3r Network", "keywords": [ + "mushroom", "keep3r", "cli", + "sample", "job", - "boilerplate", "ethereum" ], "repository": { "type": "git", - "url": "git+https://github.com/defi-wonderland/keep3r-cli-job-boilerplate.git" + "url": "git+https://github.com/mushroomsforest/keep3r-cli-jobs.git" }, "license": "MIT", - "author": "DeFi Wonderland", + "author": "Mushrooms Finance", "contributors": [ "0xGorilla (https://github.com/0xGorilla)", "0xng (https://github.com/0xng)", diff --git a/src/goerli/job-a-stealth/README.md b/src/goerli/job-a-stealth/README.md deleted file mode 100644 index b0adae1..0000000 --- a/src/goerli/job-a-stealth/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# Job A Stealth - -This is a slightly more complicated job than `JobA` as it uses a stealth mechanism to avoid frontrunning. For this reason, `JobAStealth`'s only purpose it's to add an extra job keepers can run to test their setup, and to see how to add upon `JobA`'s foundation to write a slightly complex job script. - -## Config path - -`node_modules/@defi-wonderland/keep3r-cli-job-boilerplate/dist/src/goerli/job-a-stealth` - -## Keeper Requirements - -* Must be a valid Keeper on Keep3r V1 - -## Useful Links - -* [Job](https://goerli.etherscan.io/address/0x9DC52d978290f13b73692C5AeA21B4C8954e909A) -* [Stealth Relayer](https://goerli.etherscan.io/address/0xD44A48001A4BAd6f23aD8750eaD0036765A35d4b) -* [Keep3r V1](https://goerli.etherscan.io/address/0x3364bf0a8dcb15e463e6659175c90a57ee3d4288) \ No newline at end of file diff --git a/src/goerli/job-a-stealth/job.ts b/src/goerli/job-a-stealth/job.ts deleted file mode 100644 index 1f01f78..0000000 --- a/src/goerli/job-a-stealth/job.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { getStealthHash, Job, JobWorkableGroup, makeid, prelog, toKebabCase } from '@keep3r-network/cli-utils'; -import { getGoerliSdk } from '../../eth-sdk-build'; -import metadata from './metadata.json'; - -const getWorkableTxs: Job['getWorkableTxs'] = async (args) => { - // setup logs - const correlationId = toKebabCase(metadata.name); - const logMetadata = { - job: metadata.name, - block: args.advancedBlock, - logId: makeid(5), - }; - const logConsole = prelog(logMetadata); - - // skip job if already in progress - if (args.skipIds.includes(correlationId)) { - logConsole.log(`Skipping job`); - return args.subject.complete(); - } - - logConsole.log(`Trying to work`); - - // setup job - const signer = args.fork.ethersProvider.getSigner(args.keeperAddress); - const { jobAStealth: job, stealthRelayer } = getGoerliSdk(signer); - - const workData: string = job.interface.encodeFunctionData('work'); - const stealthHash: string = getStealthHash(); - - try { - // check if job is workable - await stealthRelayer.callStatic.execute(job.address, workData, stealthHash, args.advancedBlock, { - blockTag: args.advancedBlock, - }); - - logConsole.log(`Found workable block`); - - const workableGroups: JobWorkableGroup[] = []; - - // create a workable group every bundle burst - for (let index = 0; index < args.bundleBurst; index++) { - - // create work tx - const tx = await stealthRelayer - .populateTransaction.execute(job.address, workData, stealthHash, args.targetBlock + index, { - nonce: args.keeperNonce, - gasLimit: args.block.gasLimit, - type: 2, - }); - - workableGroups.push({ - targetBlock: args.targetBlock + index, - txs: [tx], - logId: `${logMetadata.logId}-${makeid(5)}`, - }); - } - - // submit all bundles - args.subject.next({ - workableGroups, - correlationId, - }); - } catch (err: unknown) { - logConsole.warn('Simulation failed, probably in cooldown'); - } - - // finish job process - args.subject.complete(); -}; - -module.exports = { - getWorkableTxs, -} as Job; diff --git a/src/goerli/job-a-stealth/metadata.json b/src/goerli/job-a-stealth/metadata.json deleted file mode 100644 index c7da91f..0000000 --- a/src/goerli/job-a-stealth/metadata.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "name": "Job A Stealth" -} diff --git a/src/goerli/job-a/README.md b/src/goerli/job-a/README.md deleted file mode 100644 index ee4955a..0000000 --- a/src/goerli/job-a/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# Job A - -This is the simplest job we can find as well as the simplest script to write. It doesn't have any strategies nor complex mechanisms. It's simply a job with a single function that must be called. For this reason, the script we have provided for `JobA` serves as the perfect foundation for users to use at the time of writing scripts for more complex jobs. - -## Config path - -`node_modules/@defi-wonderland/keep3r-cli-job-boilerplate/dist/src/goerli/job-a` - -## Keeper Requirements - -* Must be a valid Keeper on Keep3r V1 - -## Useful Links - -* [Job](https://goerli.etherscan.io/address/0xd50345ca88e0B2cF9a6f5eD29C1F1f9d76A16C3c) -* [Keep3r V1](https://goerli.etherscan.io/address/0x3364bf0a8dcb15e463e6659175c90a57ee3d4288) \ No newline at end of file diff --git a/src/goerli/job-a/job.ts b/src/goerli/job-a/job.ts deleted file mode 100644 index 1c06409..0000000 --- a/src/goerli/job-a/job.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { Job, JobWorkableGroup, makeid, prelog, toKebabCase } from '@keep3r-network/cli-utils'; -import { getGoerliSdk } from '../../eth-sdk-build'; -import metadata from './metadata.json'; - -const getWorkableTxs: Job['getWorkableTxs'] = async (args) => { - // setup logs - const correlationId = toKebabCase(metadata.name); - const logMetadata = { - job: metadata.name, - block: args.advancedBlock, - logId: makeid(5), - }; - const logConsole = prelog(logMetadata); - - // skip job if already in progress - if (args.skipIds.includes(correlationId)) { - logConsole.log(`Skipping job`); - return args.subject.complete(); - } - - logConsole.log(`Trying to work`); - - // setup job - const signer = args.fork.ethersProvider.getSigner(args.keeperAddress); - const { jobA: job } = getGoerliSdk(signer); - - try { - // check if job is workable - await job.callStatic.work({ - blockTag: args.advancedBlock, - }); - - logConsole.log(`Job is workable`); - - // create work tx - const tx = await job.populateTransaction.work({ - nonce: args.keeperNonce, - gasLimit: 2_000_000, - type: 2, - }); - - // create a workable group every bundle burst - const workableGroups: JobWorkableGroup[] = new Array(args.bundleBurst).fill(null).map((_, index) => ({ - targetBlock: args.targetBlock + index, - txs: [tx], - logId: `${logMetadata.logId}-${makeid(5)}`, - })); - - // submit all bundles - args.subject.next({ - workableGroups, - correlationId, - }); - } catch (err: unknown) { - logConsole.warn('Simulation failed, probably in cooldown'); - } - - // finish job process - args.subject.complete(); -}; - -module.exports = { - getWorkableTxs, -} as Job; diff --git a/src/goerli/job-a/metadata.json b/src/goerli/job-a/metadata.json deleted file mode 100644 index 8bec5cd..0000000 --- a/src/goerli/job-a/metadata.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "name": "Job A" -} diff --git a/src/goerli/job-strategies/README.md b/src/goerli/job-strategies/README.md deleted file mode 100644 index 8419056..0000000 --- a/src/goerli/job-strategies/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# Job A Stealth - -This is the most complex of the test jobs despite not using a stealth relayer. The complexity comes due to the fact that this job contains strategies, each which is a job of their own. This job works as a sort of relayer containing the different strategies and providing functions to execute each one of them. - -## Config path - -`node_modules/@defi-wonderland/keep3r-cli-job-boilerplate/dist/src/goerli/job-strategies` - -## Keeper Requirements - -- Must be a valid Keeper on Keep3r V1 - -## Useful Links - -- [Job](https://goerli.etherscan.io/address/0x8CeA64dc82515D56c22d072167Da44Abd3211B6f) -- [Keep3r V1](https://goerli.etherscan.io/address/0x3364bf0a8dcb15e463e6659175c90a57ee3d4288) \ No newline at end of file diff --git a/src/goerli/job-strategies/job.ts b/src/goerli/job-strategies/job.ts deleted file mode 100644 index 0f78ad1..0000000 --- a/src/goerli/job-strategies/job.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { createForks, GanacheFork, Job, JobWorkableGroup, makeid, prelog, TransactionError } from '@keep3r-network/cli-utils'; -import { getGoerliSdk } from '../../eth-sdk-build'; -import metadata from './metadata.json'; - -const expectedErrors: string[] = ['V2Keep3rJob::work:not-workable', '!authorized', '!healthcheck']; -const maxStrategiesPerFork = 5; - -const getWorkableTxs: Job['getWorkableTxs'] = async (args) => { - // setup logs - const logMetadata = { - job: metadata.name, - block: args.advancedBlock, - logId: makeid(5), - }; - const logConsole = prelog(logMetadata); - - logConsole.log(`Trying to work`); - - // setup job with default fork provider - const signer = args.fork.ethersProvider.getSigner(args.keeperAddress); - const { jobStrategies: defaultJob } = getGoerliSdk(signer); - - // get strategies to work - const strategies: string[] = args.retryId ? [args.retryId] : await defaultJob.jobs(); - logConsole.log(args.retryId ? `Retrying strategy` : `Simulating ${strategies.length} strategies`); - - // create needed forks in order to work in parallel - const forksToCreate = Math.ceil(strategies.length / maxStrategiesPerFork) - 1; - const forks: GanacheFork[] = [args.fork, ...(await createForks(forksToCreate, args))]; - logConsole.debug(`Created ${forks.length} forks in order to work in parellel`); - - // for each fork - const workPromises = forks.map(async (fork, forkIndex) => { - - // setup job using fork provider - const signer = fork.ethersProvider.getSigner(args.keeperAddress); - const { jobStrategies: forkJob } = getGoerliSdk(signer); - - const forkStrategies = strategies.slice(forkIndex * maxStrategiesPerFork, forkIndex * maxStrategiesPerFork + maxStrategiesPerFork); - - // for each strategy - for (const [index, strategy] of forkStrategies.entries()) { - - // setup logs for strategy - const strategyIndex = forkIndex * maxStrategiesPerFork + index; - const strategyLogId = `${logMetadata.logId}-${makeid(5)}`; - const strategyConsole = prelog({ ...logMetadata, logId: strategyLogId }); - - // skip strategy if already in progress - if (args.skipIds.includes(strategy)) { - strategyConsole.info('Skipping strategy', { strategy }); - continue; - } - - try { - // check if strategy is workable - await forkJob.callStatic.execute(strategy, { - blockTag: args.advancedBlock, - }); - strategyConsole.log(`Strategy #${strategyIndex} is workable`, { strategy }); - - // create work tx - const tx = await forkJob.populateTransaction.execute(strategy, { - nonce: args.keeperNonce, - gasLimit: 5_000_000, - type: 2, - }); - - // create a workable group every bundle burst - const workableGroups: JobWorkableGroup[] = new Array(args.bundleBurst).fill(null).map((_, index) => ({ - targetBlock: args.targetBlock + index, - txs: [tx], - logId: `${strategyLogId}-${makeid(5)}`, - })); - - // submit all bundles - args.subject.next({ - workableGroups, - correlationId: strategy, - }); - - } catch (err: any) { - // handle error logs - const isExpectedError = expectedErrors.find((expectedError) => { - return (err as TransactionError).message?.includes(expectedError); - }); - - if (!isExpectedError) { - strategyConsole.warn(`Strategy #${strategyIndex} failed with unknown error`, { - strategy, - message: err.message, - }); - } else { - strategyConsole.log(`Strategy #${strategyIndex} is not workable`, { strategy }); - } - } - } - }); - - // wait for all parallel forks to finish - await Promise.all(workPromises); - - // finish job process - args.subject.complete(); -}; - -module.exports = { - getWorkableTxs, -} as Job; diff --git a/src/goerli/job-strategies/metadata.json b/src/goerli/job-strategies/metadata.json deleted file mode 100644 index d74d13d..0000000 --- a/src/goerli/job-strategies/metadata.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "name": "Job Strategies" -} diff --git a/src/strategies/job.ts b/src/strategies/job.ts new file mode 100644 index 0000000..0780216 --- /dev/null +++ b/src/strategies/job.ts @@ -0,0 +1,70 @@ +import { Job, JobWorkableGroup, makeid, prelog } from '@keep3r-network/cli-utils'; +import { getMainnetSdk } from '../eth-sdk-build'; +import metadata from './metadata.json'; + +const getWorkableTxs: Job['getWorkableTxs'] = async (args) => { + // setup logs + const logMetadata = { + job: metadata.name, + block: args.advancedBlock, + logId: makeid(5), + }; + const logConsole = prelog(logMetadata); + + logConsole.log(`Trying to work`); + + // setup job + const signer = args.fork.ethersProvider.getSigner(args.keeperAddress); + const { job } = getMainnetSdk(signer); + + // get strategies + const strategies: string[] = args.retryId ? [args.retryId] : await job.getStrategies(); + logConsole.log(args.retryId ? `Retrying strategy` : `Simulating ${strategies.length} strategies`); + + try { + for (const [index, strategy] of strategies.entries()) { + const strategyLogId = `${logMetadata.logId}-${makeid(5)}`; + const strategyConsole = prelog({ ...logMetadata, logId: strategyLogId, strategy }); + + // skip strategy if already in progress + if (args.skipIds.includes(strategy)) { + strategyConsole.info('Skipping strategy'); + continue; + } + + // check if strategy is workable + const workable = await job.callStatic.harvestable(strategy, { blockTag: args.advancedBlock }); + strategyConsole.log(`Strategy #${index} ${workable ? 'is' : 'is not'} workable`, { strategy }); + if (!workable) continue; + + // create work tx + const tx = await job.connect(args.keeperAddress).populateTransaction.harvest(strategy, { + nonce: args.keeperNonce, + gasLimit: 2_500_000, + type: 2, + }); + + // create a workable group every bundle burst + const workableGroups: JobWorkableGroup[] = new Array(args.bundleBurst).fill(null).map((_, index) => ({ + targetBlock: args.targetBlock + index, + txs: [tx], + logId: `${strategyLogId}-${makeid(5)}`, + })); + + // submit all bundles + args.subject.next({ + workableGroups, + correlationId: strategy, + }); + } + } catch (err: unknown) { + logConsole.warn('Unexpected error', { message: (err as Error).message }); + } + + // finish job process + args.subject.complete(); +}; + +module.exports = { + getWorkableTxs, +} as Job; diff --git a/src/strategies/metadata.json b/src/strategies/metadata.json new file mode 100644 index 0000000..9160c70 --- /dev/null +++ b/src/strategies/metadata.json @@ -0,0 +1,3 @@ +{ + "name": "MF Strategies" +} diff --git a/src/vaults/job.ts b/src/vaults/job.ts new file mode 100644 index 0000000..cbc11d8 --- /dev/null +++ b/src/vaults/job.ts @@ -0,0 +1,70 @@ +import { Job, JobWorkableGroup, makeid, prelog } from '@keep3r-network/cli-utils'; +import { getMainnetSdk } from '../eth-sdk-build'; +import metadata from './metadata.json'; + +const getWorkableTxs: Job['getWorkableTxs'] = async (args) => { + // setup logs + const logMetadata = { + job: metadata.name, + block: args.advancedBlock, + logId: makeid(5), + }; + const logConsole = prelog(logMetadata); + + logConsole.log(`Trying to work`); + + // setup job + const signer = args.fork.ethersProvider.getSigner(args.keeperAddress); + const { job } = getMainnetSdk(signer); + + // get vaults + const vaults: string[] = args.retryId ? [args.retryId] : await job.getVaults(); + logConsole.log(args.retryId ? `Retrying vault` : `Simulating ${vaults.length} vaults`); + + try { + for (const [index, vault] of vaults.entries()) { + const vaultLogId = `${logMetadata.logId}-${makeid(5)}`; + const vaultConsole = prelog({ ...logMetadata, logId: vaultLogId, vault }); + + // skip vault if already in progress + if (args.skipIds.includes(vault)) { + vaultConsole.info('Skipping vault'); + continue; + } + + // check if vault is workable + const earnable = await job.callStatic.earnable(vault, { blockTag: args.advancedBlock }); + vaultConsole.log(`Vault #${index} ${earnable ? 'is' : 'is not'} earnable`, { vault }); + if (!earnable) continue; + + // create work tx + const tx = await job.connect(args.keeperAddress).populateTransaction.earn(vault, { + nonce: args.keeperNonce, + gasLimit: 2_500_000, + type: 2, + }); + + // create a workable group every bundle burst + const workableGroups: JobWorkableGroup[] = new Array(args.bundleBurst).fill(null).map((_, index) => ({ + targetBlock: args.targetBlock + index, + txs: [tx], + logId: `${vaultLogId}-${makeid(5)}`, + })); + + // submit all bundles + args.subject.next({ + workableGroups, + correlationId: vault, + }); + } + } catch (err: unknown) { + logConsole.warn('Unexpected error', { message: (err as Error).message }); + } + + // finish job process + args.subject.complete(); +}; + +module.exports = { + getWorkableTxs, +} as Job; diff --git a/src/vaults/metadata.json b/src/vaults/metadata.json new file mode 100644 index 0000000..eccf099 --- /dev/null +++ b/src/vaults/metadata.json @@ -0,0 +1,3 @@ +{ + "name": "MF Vaults" +}