Skip to content

Commit

Permalink
chore: refactor functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
stevennevins committed Oct 4, 2024
1 parent c74f591 commit 05a6649
Show file tree
Hide file tree
Showing 7 changed files with 150 additions and 117 deletions.
51 changes: 51 additions & 0 deletions operator/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { createConfig, http } from '@wagmi/core'
import { anvil } from '@wagmi/core/chains'
import { createClient } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import * as dotenv from "dotenv"
import path from 'path'
import fs from 'fs'

dotenv.config()

// Check if the process.env object is empty
if (!Object.keys(process.env).length) {
throw new Error("process.env object is empty")
}

const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`)

const config = createConfig({
chains: [anvil],
client({ chain }) {
return createClient({
chain,
transport: http()
})
},
})

const chainId = 31337

const __dirname = process.cwd()

// Load core deployment data
const avsDeploymentData = JSON.parse(fs.readFileSync(path.resolve(__dirname, `./contracts/deployments/hello-world/${chainId}.json`), 'utf8'))
const coreDeploymentData = JSON.parse(fs.readFileSync(path.resolve(__dirname, `./contracts/deployments/core/${chainId}.json`), 'utf8'))

const delegationManagerAddress = coreDeploymentData.addresses.delegation
const avsDirectoryAddress = coreDeploymentData.addresses.avsDirectory
const helloWorldServiceManagerAddress = avsDeploymentData.addresses.helloWorldServiceManager
const stakeRegistryAddress = avsDeploymentData.addresses.stakeRegistry

export {
account,
config,
chainId,
delegationManagerAddress,
avsDirectoryAddress,
helloWorldServiceManagerAddress,
stakeRegistryAddress
}


120 changes: 3 additions & 117 deletions operator/index.ts
Original file line number Diff line number Diff line change
@@ -1,119 +1,5 @@
import { createConfig, http } from '@wagmi/core'
import { anvil } from '@wagmi/core/chains'
import { createClient, keccak256, toBytes } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { writeDelegationManager, readDelegationManager, readAvsDirectory, watchHelloWorldServiceManagerNewTaskCreatedEvent, writeEcdsaStakeRegistry } from "../dist/generated";
import * as dotenv from "dotenv";
import path from 'path';
import fs from 'fs';
dotenv.config();

// Check if the process.env object is empty
if (!Object.keys(process.env).length) {
throw new Error("process.env object is empty");
}

const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`)

const config = createConfig({
chains: [anvil],
client({ chain }) {
return createClient({
chain, transport: http() })
},
})

const chainId = 31337

// Load core deployment data
const avsDeploymentData = JSON.parse(fs.readFileSync(path.resolve(__dirname, `../contracts/deployments/hello-world/${chainId}.json`), 'utf8'));
const coreDeploymentData = JSON.parse(fs.readFileSync(path.resolve(__dirname, `../contracts/deployments/core/${chainId}.json`), 'utf8'));

const delegationManagerAddress = coreDeploymentData.addresses.delegation;
const avsDirectoryAddress = coreDeploymentData.addresses.avsDirectory;
const helloWorldServiceManagerAddress = avsDeploymentData.addresses.helloWorldServiceManager;
const stakeRegistryAddress = avsDeploymentData.addresses.stakeRegistry;

const registerOperator = async () => {
const registered = await readDelegationManager(
config,
{
address: delegationManagerAddress,
functionName: "isOperator",
args: [account.address]
}
)

console.log(registered);

if (!registered){
await writeDelegationManager(config, {
account: account,
address: delegationManagerAddress,
functionName: "registerAsOperator",
args: [{
__deprecated_earningsReceiver: "0x0000000000000000000000000000000000000000",
delegationApprover: "0x0000000000000000000000000000000000000000",
stakerOptOutWindowBlocks: 0
}, ""],
});
}

const salt = keccak256(toBytes("random_salt_string"));
const expiry = BigInt(Math.floor(Date.now() / 1000) + 3600); // 1 hour from now

// Calculate the registration digest hash
const digestHash = await readAvsDirectory(config, {
address: avsDirectoryAddress,
functionName: "calculateOperatorAVSRegistrationDigestHash",
args: [account.address, helloWorldServiceManagerAddress, salt, expiry]
});


const sig = await account.sign({hash:digestHash});

await writeEcdsaStakeRegistry(
config,{
account: account,
address: stakeRegistryAddress,
functionName: "registerOperatorWithSignature",
args: [{signature: sig, salt: salt, expiry:expiry}, account.address]
})

console.log("Operator registered to AVS");
};

const signAndRespondToTask = async (taskIndex: number, taskCreatedBlock: number, taskName: string) => {
console.log(
`Signing and responding to task ${taskIndex}`
)

console.log(`Responded to task.`);
};

const monitorNewTasks = async () => {
const unwatch = watchHelloWorldServiceManagerNewTaskCreatedEvent(config, {
address: helloWorldServiceManagerAddress,
onLogs: async (logs) => {
for (const log of logs) {
const { args } = log;
if (args && args.taskIndex !== undefined && args.task) {
const { taskIndex, task } = args;
console.log(`New task detected: Hello, ${task.name}`);
await signAndRespondToTask(
taskIndex,
task.taskCreatedBlock,
task.name
);
}else {
console.log("task data not defined")
}
}
},
});

console.log("Monitoring for new tasks...");
};
import { registerOperator } from "./registerAsOperator";
import { monitorNewTasks } from "./monitorTasks";

const main = async () => {
await registerOperator();
Expand All @@ -124,4 +10,4 @@ const main = async () => {

main().catch((error) => {
console.error("Error in main function:", error);
});
});
29 changes: 29 additions & 0 deletions operator/monitorTasks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import {config, helloWorldServiceManagerAddress} from "./config"
import {watchHelloWorldServiceManagerNewTaskCreatedEvent } from "../dist/generated";
import { signAndRespondToTask } from "./signAndRespondToTask";


export const monitorNewTasks = async () => {
const unwatch = watchHelloWorldServiceManagerNewTaskCreatedEvent(config, {
address: helloWorldServiceManagerAddress,
onLogs: async (logs) => {
for (const log of logs) {
const { args } = log;
if (args && args.taskIndex !== undefined && args.task) {
const { taskIndex, task } = args;
console.log(`New task detected: Hello, ${task.name}`);
/// TODO: Clean this up
await signAndRespondToTask(
taskIndex,
task.taskCreatedBlock,
task.name
);
}else {
console.log("task data not defined")
}
}
},
});

console.log("Monitoring for new tasks...");
};
32 changes: 32 additions & 0 deletions operator/registerAsOperator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { writeDelegationManager, readDelegationManager } from "../dist/generated";
import {config, delegationManagerAddress, account } from "./config"

export const registerOperator = async () => {
const registered = await readDelegationManager(
config,
{
address: delegationManagerAddress,
functionName: "isOperator",
args: [account.address]
}
)

console.log(registered);

if (!registered){
await writeDelegationManager(config, {
account: account,
address: delegationManagerAddress,
functionName: "registerAsOperator",
args: [{
__deprecated_earningsReceiver: "0x0000000000000000000000000000000000000000",
delegationApprover: "0x0000000000000000000000000000000000000000",
stakerOptOutWindowBlocks: 0
}, ""],
});
}



console.log("Operator registered to AVS");
};
26 changes: 26 additions & 0 deletions operator/registerToAvs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { keccak256, toBytes } from 'viem'
import { readAvsDirectory, writeEcdsaStakeRegistry } from "../dist/generated";
import {config, account, avsDirectoryAddress, helloWorldServiceManagerAddress, stakeRegistryAddress} from "./config"

export const registerToAvs = async () => {
//// TODO: check if they're already registered to the avs stake registry
const salt = keccak256(toBytes("random_salt_string"));
const expiry = BigInt(Math.floor(Date.now() / 1000) + 3600); // 1 hour from now

const digestHash = await readAvsDirectory(config, {
address: avsDirectoryAddress,
functionName: "calculateOperatorAVSRegistrationDigestHash",
args: [account.address, helloWorldServiceManagerAddress, salt, expiry]
});


const sig = await account.sign({hash:digestHash});

await writeEcdsaStakeRegistry(
config,{
account: account,
address: stakeRegistryAddress,
functionName: "registerOperatorWithSignature",
args: [{signature: sig, salt: salt, expiry:expiry}, account.address]
})
}
Empty file added operator/respondToTask.ts
Empty file.
9 changes: 9 additions & 0 deletions operator/signAndRespondToTask.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@


export const signAndRespondToTask = async (taskIndex: number, taskCreatedBlock: number, taskName: string) => {
console.log(
`Signing and responding to task ${taskIndex}`
)

console.log(`Responded to task.`);
};

0 comments on commit 05a6649

Please sign in to comment.