chore: apply prettier
This commit is contained in:
@ -21,7 +21,6 @@ export async function task(roundNumber: number): Promise<void> {
|
||||
// FORCE TO PAUSE 30 SECONDS
|
||||
// No submission on Round 0 so no need to trigger fetch audit result before round 3
|
||||
// Changed from 3 to 4 to have more time
|
||||
|
||||
// if (roundNumber >= 4) {
|
||||
// const auditRound = roundNumber - 4;
|
||||
// const response = await fetch(`${middleServerUrl}/summarizer/worker/update-audit-result`, {
|
||||
@ -32,4 +31,4 @@ export async function task(roundNumber: number): Promise<void> {
|
||||
// console.log(`[TASK] Fetched audit result for round ${auditRound}. Status: ${response.status}`);
|
||||
// }
|
||||
// console.log(`[TASK] EXECUTE TASK FOR ROUND ${roundNumber}`);
|
||||
}
|
||||
}
|
||||
|
@ -24,7 +24,7 @@ export async function submission(roundNumber: number): Promise<string | void> {
|
||||
* The default implementation handles uploading the proofs to IPFS
|
||||
* and returning the CID
|
||||
*/
|
||||
if(!await preRunCheck(roundNumber.toString())){
|
||||
if (!(await preRunCheck(roundNumber.toString()))) {
|
||||
return;
|
||||
}
|
||||
const stakingKeypair = await namespaceWrapper.getSubmitterAccount();
|
||||
@ -34,14 +34,14 @@ export async function submission(roundNumber: number): Promise<string | void> {
|
||||
throw new Error("No staking keypair or public key found");
|
||||
}
|
||||
const stakingKey = stakingKeypair.publicKey.toBase58();
|
||||
|
||||
|
||||
const secretKey = stakingKeypair.secretKey;
|
||||
console.log(`[SUBMISSION] Starting submission process for round ${roundNumber}`);
|
||||
|
||||
try {
|
||||
const orcaClient = await initializeOrcaClient();
|
||||
const shouldMakeSubmission = await namespaceWrapper.storeGet(`shouldMakeSubmission`);
|
||||
|
||||
|
||||
if (!shouldMakeSubmission || shouldMakeSubmission !== "true") {
|
||||
return;
|
||||
}
|
||||
@ -51,7 +51,7 @@ export async function submission(roundNumber: number): Promise<string | void> {
|
||||
roundNumber,
|
||||
stakingKey,
|
||||
publicKey: pubKey,
|
||||
secretKey
|
||||
secretKey,
|
||||
});
|
||||
|
||||
return cid || void 0;
|
||||
@ -64,19 +64,19 @@ export async function submission(roundNumber: number): Promise<string | void> {
|
||||
async function initializeOrcaClient() {
|
||||
console.log("[SUBMISSION] Initializing Orca client...");
|
||||
const orcaClient = await getOrcaClient();
|
||||
|
||||
|
||||
if (!orcaClient) {
|
||||
console.error("[SUBMISSION] Failed to initialize Orca client");
|
||||
throw new Error("Failed to initialize Orca client");
|
||||
}
|
||||
|
||||
|
||||
console.log("[SUBMISSION] Orca client initialized successfully");
|
||||
return orcaClient;
|
||||
}
|
||||
|
||||
async function makeSubmission(params: SubmissionParams): Promise<string | void> {
|
||||
const { orcaClient, roundNumber, stakingKey, publicKey, secretKey } = params;
|
||||
|
||||
|
||||
const swarmBountyId = await namespaceWrapper.storeGet(`swarmBountyId`);
|
||||
if (!swarmBountyId) {
|
||||
console.log("[SUBMISSION] No swarm bounty id found for this round");
|
||||
@ -94,35 +94,36 @@ async function makeSubmission(params: SubmissionParams): Promise<string | void>
|
||||
prUrl: submissionData.prUrl,
|
||||
stakingKey,
|
||||
publicKey,
|
||||
secretKey
|
||||
secretKey,
|
||||
});
|
||||
|
||||
const signature = await signSubmissionPayload({
|
||||
taskId: TASK_ID,
|
||||
roundNumber,
|
||||
stakingKey,
|
||||
pubKey: publicKey,
|
||||
...submissionData
|
||||
}, secretKey);
|
||||
const signature = await signSubmissionPayload(
|
||||
{
|
||||
taskId: TASK_ID,
|
||||
roundNumber,
|
||||
stakingKey,
|
||||
pubKey: publicKey,
|
||||
...submissionData,
|
||||
},
|
||||
secretKey,
|
||||
);
|
||||
|
||||
const cid = await storeSubmissionOnIPFS(signature);
|
||||
await cleanupSubmissionState();
|
||||
|
||||
|
||||
return cid;
|
||||
}
|
||||
|
||||
async function fetchSubmissionData(orcaClient: any, swarmBountyId: string): Promise<SubmissionData | null> {
|
||||
console.log(`[SUBMISSION] Fetching submission data for swarm bounty ${swarmBountyId}`);
|
||||
const result = await orcaClient.podCall(`submission/${swarmBountyId}`);
|
||||
|
||||
|
||||
if (!result || result.data === "No submission") {
|
||||
console.log("[SUBMISSION] No existing submission found");
|
||||
return null;
|
||||
}
|
||||
|
||||
const submission = typeof result.data === 'object' && 'data' in result.data
|
||||
? result.data.data
|
||||
: result.data;
|
||||
const submission = typeof result.data === "object" && "data" in result.data ? result.data.data : result.data;
|
||||
|
||||
if (!submission?.prUrl) {
|
||||
throw new Error("Submission is missing PR URL");
|
||||
@ -140,7 +141,7 @@ async function notifyMiddleServer(params: {
|
||||
secretKey: Uint8Array<ArrayBufferLike>;
|
||||
}) {
|
||||
const { taskId, swarmBountyId, prUrl, stakingKey, publicKey, secretKey } = params;
|
||||
|
||||
|
||||
const payload = {
|
||||
taskId,
|
||||
swarmBountyId,
|
||||
@ -184,4 +185,4 @@ async function storeSubmissionOnIPFS(signature: string): Promise<string> {
|
||||
async function cleanupSubmissionState(): Promise<void> {
|
||||
await namespaceWrapper.storeSet(`shouldMakeSubmission`, "false");
|
||||
await namespaceWrapper.storeSet(`swarmBountyId`, "");
|
||||
}
|
||||
}
|
||||
|
@ -82,4 +82,4 @@ export async function audit(cid: string, roundNumber: number, submitterKey: stri
|
||||
// When Error---NO RETURN;
|
||||
// return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -14,7 +14,6 @@ import { middleServerUrl, status } from "../utils/constant";
|
||||
|
||||
//Example route
|
||||
export async function routes() {
|
||||
|
||||
app.get("/value", async (_req, res) => {
|
||||
const value = await namespaceWrapper.storeGet("value");
|
||||
console.log("value", value);
|
||||
@ -64,7 +63,7 @@ export async function routes() {
|
||||
const message = req.body.message;
|
||||
console.log("[TASK] req.body", req.body);
|
||||
try {
|
||||
if (!success){
|
||||
if (!success) {
|
||||
console.error("[TASK] Error summarizing repository:", message);
|
||||
return;
|
||||
}
|
||||
@ -128,7 +127,6 @@ export async function routes() {
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// TODO: To be completed
|
||||
app.post("/failed-task", async (req, res) => {
|
||||
res.status(200).json({ result: "Successfully saved task result" });
|
||||
|
@ -1,36 +1,35 @@
|
||||
export function isValidAnthropicApiKey(key: string) {
|
||||
const regex = /^sk-ant-[a-zA-Z0-9_-]{32,}$/;
|
||||
return regex.test(key);
|
||||
const regex = /^sk-ant-[a-zA-Z0-9_-]{32,}$/;
|
||||
return regex.test(key);
|
||||
}
|
||||
|
||||
export async function checkAnthropicAPIKey(apiKey: string) {
|
||||
const response = await fetch('https://api.anthropic.com/v1/messages', {
|
||||
method: 'POST',
|
||||
const response = await fetch("https://api.anthropic.com/v1/messages", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
'x-api-key': apiKey,
|
||||
'anthropic-version': '2023-06-01',
|
||||
'content-type': 'application/json',
|
||||
"x-api-key": apiKey,
|
||||
"anthropic-version": "2023-06-01",
|
||||
"content-type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: 'claude-3-opus-20240229', // or a cheaper model
|
||||
model: "claude-3-opus-20240229", // or a cheaper model
|
||||
max_tokens: 1, // minimal usage
|
||||
messages: [{ role: 'user', content: 'Hi' }],
|
||||
messages: [{ role: "user", content: "Hi" }],
|
||||
}),
|
||||
});
|
||||
|
||||
if (response.status === 200) {
|
||||
console.log('✅ API key is valid and has credit.');
|
||||
console.log("✅ API key is valid and has credit.");
|
||||
return true;
|
||||
} else {
|
||||
const data = await response.json().catch(() => ({}));
|
||||
if (response.status === 401) {
|
||||
console.log('❌ Invalid API key.');
|
||||
} else if (response.status === 403 && data.error?.message?.includes('billing')) {
|
||||
console.log('❌ API key has no credit or is not authorized.');
|
||||
console.log("❌ Invalid API key.");
|
||||
} else if (response.status === 403 && data.error?.message?.includes("billing")) {
|
||||
console.log("❌ API key has no credit or is not authorized.");
|
||||
} else {
|
||||
console.log('⚠️ Unexpected error:', data);
|
||||
console.log("⚠️ Unexpected error:", data);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -5,8 +5,8 @@ import { LogLevel } from "@_koii/namespace-wrapper/dist/types";
|
||||
import { errorMessage, actionMessage, status } from "../constant";
|
||||
import { checkAnthropicAPIKey } from "./anthropicCheck";
|
||||
import { checkGitHub } from "./githubCheck";
|
||||
export async function preRunCheck(roundNumber:string){
|
||||
if (!process.env.ANTHROPIC_API_KEY) {
|
||||
export async function preRunCheck(roundNumber: string) {
|
||||
if (!process.env.ANTHROPIC_API_KEY) {
|
||||
await namespaceWrapper.logMessage(
|
||||
LogLevel.Error,
|
||||
errorMessage.ANTHROPIC_API_KEY_INVALID,
|
||||
@ -54,4 +54,4 @@ if (!process.env.ANTHROPIC_API_KEY) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
@ -1,36 +1,36 @@
|
||||
export async function checkGitHub(username: string, token: string) {
|
||||
// 1. Check username
|
||||
const userRes = await fetch(`https://api.github.com/users/${username}`);
|
||||
const isUsernameValid = userRes.status === 200;
|
||||
|
||||
// 2. Check token
|
||||
const tokenRes = await fetch('https://api.github.com/user', {
|
||||
headers: {
|
||||
Authorization: `token ${token}`,
|
||||
},
|
||||
});
|
||||
const isTokenValid = tokenRes.status === 200;
|
||||
const isIdentityValid = await checkGitHubIdentity(username, token);
|
||||
return isIdentityValid&&isUsernameValid&&isTokenValid
|
||||
// 1. Check username
|
||||
const userRes = await fetch(`https://api.github.com/users/${username}`);
|
||||
const isUsernameValid = userRes.status === 200;
|
||||
|
||||
// 2. Check token
|
||||
const tokenRes = await fetch("https://api.github.com/user", {
|
||||
headers: {
|
||||
Authorization: `token ${token}`,
|
||||
},
|
||||
});
|
||||
const isTokenValid = tokenRes.status === 200;
|
||||
const isIdentityValid = await checkGitHubIdentity(username, token);
|
||||
return isIdentityValid && isUsernameValid && isTokenValid;
|
||||
}
|
||||
|
||||
async function checkGitHubIdentity(username: string, token: string) {
|
||||
const res = await fetch('https://api.github.com/user', {
|
||||
headers: {
|
||||
Authorization: `token ${token}`,
|
||||
Accept: 'application/vnd.github.v3+json',
|
||||
},
|
||||
});
|
||||
|
||||
if (res.status !== 200) {
|
||||
return false
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
if (data.login.toLowerCase() !== username.toLowerCase()) {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
const res = await fetch("https://api.github.com/user", {
|
||||
headers: {
|
||||
Authorization: `token ${token}`,
|
||||
Accept: "application/vnd.github.v3+json",
|
||||
},
|
||||
});
|
||||
|
||||
if (res.status !== 200) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
if (data.login.toLowerCase() !== username.toLowerCase()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
@ -59,4 +59,4 @@ export const defaultBountyMarkdownFile =
|
||||
|
||||
export const customReward = 400 * 10 ** 9; // This should be in ROE!
|
||||
|
||||
export const middleServerUrl = "https://builder247-prod.dev.koii.network";
|
||||
export const middleServerUrl = "https://builder247-prod.dev.koii.network";
|
||||
|
@ -12,90 +12,90 @@ interface BountyIssue {
|
||||
}
|
||||
|
||||
export async function getExistingIssues(): Promise<BountyIssue[]> {
|
||||
try {
|
||||
// read from the bounty markdown file
|
||||
try {
|
||||
// read from the bounty markdown file
|
||||
// console.log('Fetching markdown file from:', defaultBountyMarkdownFile);
|
||||
const bountyMarkdownFile = await fetch(defaultBountyMarkdownFile);
|
||||
const bountyMarkdownFileText = await bountyMarkdownFile.text();
|
||||
|
||||
// console.log('Raw markdown content:', bountyMarkdownFileText);
|
||||
|
||||
const bountyMarkdownFileLines = bountyMarkdownFileText.split("\n");
|
||||
// console.log('Number of lines:', bountyMarkdownFileLines.length);
|
||||
|
||||
const issues: BountyIssue[] = [];
|
||||
let isTableStarted = false;
|
||||
|
||||
for (const line of bountyMarkdownFileLines) {
|
||||
// Skip empty lines
|
||||
if (line.trim() === '') {
|
||||
// console.log('Skipping empty line');
|
||||
continue;
|
||||
}
|
||||
|
||||
// console.log('Processing line:', line);
|
||||
|
||||
// Skip the title line starting with #
|
||||
if (line.startsWith('#')) {
|
||||
// console.log('Found title line:', line);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip the header and separator lines
|
||||
if (line.startsWith('|') && line.includes('GitHub URL')) {
|
||||
//console.log('Found header line');
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith('|') && line.includes('-----')) {
|
||||
// console.log('Found separator line');
|
||||
continue;
|
||||
}
|
||||
|
||||
// Process table rows
|
||||
if (line.startsWith('|')) {
|
||||
isTableStarted = true;
|
||||
// Remove first and last | and split by |
|
||||
const cells = line.slice(1, -1).split('|').map(cell => cell.trim());
|
||||
// console.log('Parsed cells:', cells);
|
||||
|
||||
// Extract GitHub URL and name from markdown link format [name](url)
|
||||
const githubUrlMatch = cells[0].match(/\[(.*?)\]\((.*?)\)/);
|
||||
// console.log('GitHub URL match:', githubUrlMatch);
|
||||
|
||||
const projectName = githubUrlMatch ? githubUrlMatch[1] : '';
|
||||
const githubUrl = githubUrlMatch ? githubUrlMatch[2] : '';
|
||||
|
||||
const issue: BountyIssue = {
|
||||
githubUrl,
|
||||
projectName,
|
||||
bountyTask: cells[1],
|
||||
description: cells[3],
|
||||
bountyAmount: cells[4],
|
||||
bountyType: cells[5],
|
||||
transactionHash: cells[6],
|
||||
status: cells[7]
|
||||
};
|
||||
|
||||
// console.log('Created issue object:', issue);
|
||||
issues.push(issue);
|
||||
}
|
||||
}
|
||||
// Filter all issues with status "Initialized" && Bounty Task is Document & Summarize
|
||||
console.log('Final parsed issues number:', issues.length);
|
||||
return issues
|
||||
} catch (error) {
|
||||
// console.error('Error processing markdown:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
const bountyMarkdownFile = await fetch(defaultBountyMarkdownFile);
|
||||
const bountyMarkdownFileText = await bountyMarkdownFile.text();
|
||||
|
||||
// console.log('Raw markdown content:', bountyMarkdownFileText);
|
||||
|
||||
const bountyMarkdownFileLines = bountyMarkdownFileText.split("\n");
|
||||
// console.log('Number of lines:', bountyMarkdownFileLines.length);
|
||||
|
||||
const issues: BountyIssue[] = [];
|
||||
let isTableStarted = false;
|
||||
|
||||
for (const line of bountyMarkdownFileLines) {
|
||||
// Skip empty lines
|
||||
if (line.trim() === "") {
|
||||
// console.log('Skipping empty line');
|
||||
continue;
|
||||
}
|
||||
|
||||
// console.log('Processing line:', line);
|
||||
|
||||
// Skip the title line starting with #
|
||||
if (line.startsWith("#")) {
|
||||
// console.log('Found title line:', line);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip the header and separator lines
|
||||
if (line.startsWith("|") && line.includes("GitHub URL")) {
|
||||
//console.log('Found header line');
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith("|") && line.includes("-----")) {
|
||||
// console.log('Found separator line');
|
||||
continue;
|
||||
}
|
||||
|
||||
// Process table rows
|
||||
if (line.startsWith("|")) {
|
||||
isTableStarted = true;
|
||||
// Remove first and last | and split by |
|
||||
const cells = line
|
||||
.slice(1, -1)
|
||||
.split("|")
|
||||
.map((cell) => cell.trim());
|
||||
// console.log('Parsed cells:', cells);
|
||||
|
||||
// Extract GitHub URL and name from markdown link format [name](url)
|
||||
const githubUrlMatch = cells[0].match(/\[(.*?)\]\((.*?)\)/);
|
||||
// console.log('GitHub URL match:', githubUrlMatch);
|
||||
|
||||
const projectName = githubUrlMatch ? githubUrlMatch[1] : "";
|
||||
const githubUrl = githubUrlMatch ? githubUrlMatch[2] : "";
|
||||
|
||||
const issue: BountyIssue = {
|
||||
githubUrl,
|
||||
projectName,
|
||||
bountyTask: cells[1],
|
||||
description: cells[3],
|
||||
bountyAmount: cells[4],
|
||||
bountyType: cells[5],
|
||||
transactionHash: cells[6],
|
||||
status: cells[7],
|
||||
};
|
||||
|
||||
// console.log('Created issue object:', issue);
|
||||
issues.push(issue);
|
||||
}
|
||||
}
|
||||
// Filter all issues with status "Initialized" && Bounty Task is Document & Summarize
|
||||
console.log("Final parsed issues number:", issues.length);
|
||||
return issues;
|
||||
} catch (error) {
|
||||
// console.error('Error processing markdown:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getInitializedDocumentSummarizeIssues(issues: BountyIssue[]) {
|
||||
|
||||
return issues.filter(issue => issue.status === "Initialized" && issue.bountyTask === "Document & Summarize");
|
||||
return issues.filter((issue) => issue.status === "Initialized" && issue.bountyTask === "Document & Summarize");
|
||||
}
|
||||
|
||||
|
||||
// async function main(){
|
||||
// const existingIssues = await getExistingIssues();
|
||||
// const transactionHashs = [
|
||||
@ -146,7 +146,7 @@ export async function getInitializedDocumentSummarizeIssues(issues: BountyIssue[
|
||||
// if (initializedDocumentSummarizeIssues.length == 0) {
|
||||
// console.log("No issues pending to be summarized");
|
||||
// return;
|
||||
// }
|
||||
// }
|
||||
// console.log("Initialized Document & Summarize issues number:", initializedDocumentSummarizeIssues.length);
|
||||
// }
|
||||
// async function main() {
|
||||
@ -158,4 +158,4 @@ export async function getInitializedDocumentSummarizeIssues(issues: BountyIssue[
|
||||
// }
|
||||
// }
|
||||
|
||||
// main();
|
||||
// main();
|
||||
|
@ -140,13 +140,13 @@ export async function getRandomNodes(roundNumber: number, numberOfNodes: number)
|
||||
|
||||
const lastRoundSubmissions = lastRoundSubmission.submissions;
|
||||
console.log("Last round submissions:", lastRoundSubmissions);
|
||||
|
||||
|
||||
// Get the last round number
|
||||
const lastRound = Object.keys(lastRoundSubmissions).pop();
|
||||
if (!lastRound) {
|
||||
return [];
|
||||
}
|
||||
|
||||
|
||||
// Get the submissions for that round
|
||||
const submissions = lastRoundSubmissions[lastRound];
|
||||
console.log("Submissions:", submissions);
|
||||
@ -156,12 +156,12 @@ export async function getRandomNodes(roundNumber: number, numberOfNodes: number)
|
||||
if (availableKeys.length <= numberOfNodes) {
|
||||
return availableKeys;
|
||||
}
|
||||
|
||||
|
||||
const seed = TASK_ID + roundNumber.toString() || "default" + roundNumber;
|
||||
const rng = seedrandom(seed);
|
||||
// Use the keys from the submissions object
|
||||
const randomKeys = availableKeys.sort(() => rng() - 0.5).slice(0, numberOfNodes);
|
||||
|
||||
|
||||
console.log("Random keys:", randomKeys);
|
||||
return randomKeys;
|
||||
}
|
||||
|
@ -3,38 +3,45 @@ import { getFile } from "./ipfs";
|
||||
import { Submission } from "@_koii/namespace-wrapper/dist/types";
|
||||
import { Submitter } from "@_koii/task-manager/dist/types/global";
|
||||
import { namespaceWrapper } from "@_koii/namespace-wrapper";
|
||||
export async function submissionJSONSignatureDecode({submission_value, submitterPublicKey, roundNumber}: {submission_value: string, submitterPublicKey: string, roundNumber: number}) {
|
||||
let submissionString;
|
||||
try {
|
||||
console.log("Getting file from IPFS", submission_value);
|
||||
submissionString = await getFile(submission_value);
|
||||
console.log("submissionString", submissionString);
|
||||
} catch (error) {
|
||||
|
||||
console.log("error", error);
|
||||
console.error("INVALID SIGNATURE DATA");
|
||||
return null;
|
||||
}
|
||||
// verify the signature of the submission
|
||||
const submission = JSON.parse(submissionString);
|
||||
console.log("submission", submission);
|
||||
const signaturePayload = await namespaceWrapper.verifySignature(submission.signature, submitterPublicKey);
|
||||
if (!signaturePayload.data) {
|
||||
console.error("INVALID SIGNATURE");
|
||||
return null;
|
||||
}
|
||||
const data = JSON.parse(signaturePayload.data);
|
||||
console.log("signaturePayload", signaturePayload);
|
||||
console.log("data", data);
|
||||
if (
|
||||
data.taskId !== TASK_ID ||
|
||||
data.roundNumber !== roundNumber ||
|
||||
data.stakingKey !== submitterPublicKey ||
|
||||
!data.pubKey ||
|
||||
!data.prUrl
|
||||
) {
|
||||
console.error("INVALID SIGNATURE DATA");
|
||||
return null;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
export async function submissionJSONSignatureDecode({
|
||||
submission_value,
|
||||
submitterPublicKey,
|
||||
roundNumber,
|
||||
}: {
|
||||
submission_value: string;
|
||||
submitterPublicKey: string;
|
||||
roundNumber: number;
|
||||
}) {
|
||||
let submissionString;
|
||||
try {
|
||||
console.log("Getting file from IPFS", submission_value);
|
||||
submissionString = await getFile(submission_value);
|
||||
console.log("submissionString", submissionString);
|
||||
} catch (error) {
|
||||
console.log("error", error);
|
||||
console.error("INVALID SIGNATURE DATA");
|
||||
return null;
|
||||
}
|
||||
// verify the signature of the submission
|
||||
const submission = JSON.parse(submissionString);
|
||||
console.log("submission", submission);
|
||||
const signaturePayload = await namespaceWrapper.verifySignature(submission.signature, submitterPublicKey);
|
||||
if (!signaturePayload.data) {
|
||||
console.error("INVALID SIGNATURE");
|
||||
return null;
|
||||
}
|
||||
const data = JSON.parse(signaturePayload.data);
|
||||
console.log("signaturePayload", signaturePayload);
|
||||
console.log("data", data);
|
||||
if (
|
||||
data.taskId !== TASK_ID ||
|
||||
data.roundNumber !== roundNumber ||
|
||||
data.stakingKey !== submitterPublicKey ||
|
||||
!data.pubKey ||
|
||||
!data.prUrl
|
||||
) {
|
||||
console.error("INVALID SIGNATURE DATA");
|
||||
return null;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
@ -5,105 +5,107 @@ import { actionMessage, errorMessage, middleServerUrl } from "../constant";
|
||||
|
||||
import { TASK_ID, namespaceWrapper } from "@_koii/namespace-wrapper";
|
||||
import { LogLevel } from "@_koii/namespace-wrapper/dist/types";
|
||||
export async function task(){
|
||||
while (true) {
|
||||
try {
|
||||
let requiredWorkResponse;
|
||||
const orcaClient = await getOrcaClient();
|
||||
// check if the env variable is valid
|
||||
const stakingKeypair = await namespaceWrapper.getSubmitterAccount()!;
|
||||
const pubKey = await namespaceWrapper.getMainAccountPubkey();
|
||||
if (!orcaClient || !stakingKeypair || !pubKey) {
|
||||
await namespaceWrapper.logMessage(LogLevel.Error, errorMessage.NO_ORCA_CLIENT, actionMessage.NO_ORCA_CLIENT);
|
||||
// Wait for 1 minute before retrying
|
||||
await new Promise(resolve => setTimeout(resolve, 60000));
|
||||
continue;
|
||||
}
|
||||
const stakingKey = stakingKeypair.publicKey.toBase58();
|
||||
export async function task() {
|
||||
while (true) {
|
||||
try {
|
||||
let requiredWorkResponse;
|
||||
const orcaClient = await getOrcaClient();
|
||||
// check if the env variable is valid
|
||||
const stakingKeypair = await namespaceWrapper.getSubmitterAccount()!;
|
||||
const pubKey = await namespaceWrapper.getMainAccountPubkey();
|
||||
if (!orcaClient || !stakingKeypair || !pubKey) {
|
||||
await namespaceWrapper.logMessage(LogLevel.Error, errorMessage.NO_ORCA_CLIENT, actionMessage.NO_ORCA_CLIENT);
|
||||
// Wait for 1 minute before retrying
|
||||
await new Promise((resolve) => setTimeout(resolve, 60000));
|
||||
continue;
|
||||
}
|
||||
const stakingKey = stakingKeypair.publicKey.toBase58();
|
||||
|
||||
/****************** All these issues need to be generate a markdown file ******************/
|
||||
/****************** All these issues need to be generate a markdown file ******************/
|
||||
|
||||
const signature = await namespaceWrapper.payloadSigning(
|
||||
{
|
||||
taskId: TASK_ID,
|
||||
// roundNumber: roundNumber,
|
||||
action: "fetch-todo",
|
||||
githubUsername: stakingKey,
|
||||
stakingKey: stakingKey,
|
||||
},
|
||||
stakingKeypair.secretKey,
|
||||
);
|
||||
|
||||
const retryDelay = 10000; // 10 seconds in milliseconds
|
||||
const signature = await namespaceWrapper.payloadSigning(
|
||||
{
|
||||
taskId: TASK_ID,
|
||||
// roundNumber: roundNumber,
|
||||
action: "fetch-todo",
|
||||
githubUsername: stakingKey,
|
||||
stakingKey: stakingKey,
|
||||
},
|
||||
stakingKeypair.secretKey,
|
||||
);
|
||||
|
||||
while (true) {
|
||||
requiredWorkResponse = await fetch(`${middleServerUrl}/summarizer/worker/fetch-todo`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ signature: signature, stakingKey: stakingKey }),
|
||||
});
|
||||
const retryDelay = 10000; // 10 seconds in milliseconds
|
||||
|
||||
if (requiredWorkResponse.status === 200) {
|
||||
break;
|
||||
}
|
||||
while (true) {
|
||||
requiredWorkResponse = await fetch(`${middleServerUrl}/summarizer/worker/fetch-todo`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ signature: signature, stakingKey: stakingKey }),
|
||||
});
|
||||
|
||||
console.log(`[TASK] Server returned status ${requiredWorkResponse.status}, retrying in ${retryDelay/1000} seconds...`);
|
||||
await new Promise(resolve => setTimeout(resolve, retryDelay));
|
||||
}
|
||||
|
||||
// check if the response is 200 after all retries
|
||||
if (!requiredWorkResponse || requiredWorkResponse.status !== 200) {
|
||||
// await namespaceWrapper.storeSet(`result-${roundNumber}`, status.NO_ISSUES_PENDING_TO_BE_SUMMARIZED);
|
||||
return;
|
||||
}
|
||||
const requiredWorkResponseData = await requiredWorkResponse.json();
|
||||
console.log("[TASK] requiredWorkResponseData: ", requiredWorkResponseData);
|
||||
// const uuid = uuidv4();
|
||||
const alreadyAssigned = await namespaceWrapper.storeGet(JSON.stringify(requiredWorkResponseData.data.id));
|
||||
if (alreadyAssigned) {
|
||||
return;
|
||||
}else{
|
||||
await namespaceWrapper.storeSet(JSON.stringify(requiredWorkResponseData.data.id), "initialized");
|
||||
}
|
||||
|
||||
const podcallPayload = {
|
||||
taskId: TASK_ID,
|
||||
};
|
||||
|
||||
const podCallSignature = await namespaceWrapper.payloadSigning(podcallPayload, stakingKeypair.secretKey);
|
||||
|
||||
const jsonBody = {
|
||||
task_id: TASK_ID,
|
||||
swarmBountyId: requiredWorkResponseData.data.id,
|
||||
repo_url: `https://github.com/${requiredWorkResponseData.data.repo_owner}/${requiredWorkResponseData.data.repo_name}`,
|
||||
podcall_signature: podCallSignature,
|
||||
};
|
||||
console.log("[TASK] jsonBody: ", jsonBody);
|
||||
try {
|
||||
const repoSummaryResponse = await orcaClient.podCall(`worker-task`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(jsonBody),
|
||||
});
|
||||
console.log("[TASK] repoSummaryResponse: ", repoSummaryResponse);
|
||||
if (repoSummaryResponse.status !== 200) {
|
||||
// await namespaceWrapper.storeSet(`result-${roundNumber}`, status.ISSUE_SUMMARIZATION_FAILED);
|
||||
}
|
||||
} catch (error) {
|
||||
// await namespaceWrapper.storeSet(`result-${roundNumber}`, status.ISSUE_SUMMARIZATION_FAILED);
|
||||
console.error("[TASK] EXECUTE TASK ERROR:", error);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("[TASK] EXECUTE TASK ERROR:", error);
|
||||
// Wait for 1 minute before retrying on error
|
||||
await new Promise(resolve => setTimeout(resolve, 60000));
|
||||
if (requiredWorkResponse.status === 200) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Wait for 1 minute before starting the next iteration
|
||||
await new Promise(resolve => setTimeout(resolve, 60000));
|
||||
|
||||
console.log(
|
||||
`[TASK] Server returned status ${requiredWorkResponse.status}, retrying in ${retryDelay / 1000} seconds...`,
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, retryDelay));
|
||||
}
|
||||
|
||||
// check if the response is 200 after all retries
|
||||
if (!requiredWorkResponse || requiredWorkResponse.status !== 200) {
|
||||
// await namespaceWrapper.storeSet(`result-${roundNumber}`, status.NO_ISSUES_PENDING_TO_BE_SUMMARIZED);
|
||||
return;
|
||||
}
|
||||
const requiredWorkResponseData = await requiredWorkResponse.json();
|
||||
console.log("[TASK] requiredWorkResponseData: ", requiredWorkResponseData);
|
||||
// const uuid = uuidv4();
|
||||
const alreadyAssigned = await namespaceWrapper.storeGet(JSON.stringify(requiredWorkResponseData.data.id));
|
||||
if (alreadyAssigned) {
|
||||
return;
|
||||
} else {
|
||||
await namespaceWrapper.storeSet(JSON.stringify(requiredWorkResponseData.data.id), "initialized");
|
||||
}
|
||||
|
||||
const podcallPayload = {
|
||||
taskId: TASK_ID,
|
||||
};
|
||||
|
||||
const podCallSignature = await namespaceWrapper.payloadSigning(podcallPayload, stakingKeypair.secretKey);
|
||||
|
||||
const jsonBody = {
|
||||
task_id: TASK_ID,
|
||||
swarmBountyId: requiredWorkResponseData.data.id,
|
||||
repo_url: `https://github.com/${requiredWorkResponseData.data.repo_owner}/${requiredWorkResponseData.data.repo_name}`,
|
||||
podcall_signature: podCallSignature,
|
||||
};
|
||||
console.log("[TASK] jsonBody: ", jsonBody);
|
||||
try {
|
||||
const repoSummaryResponse = await orcaClient.podCall(`worker-task`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(jsonBody),
|
||||
});
|
||||
console.log("[TASK] repoSummaryResponse: ", repoSummaryResponse);
|
||||
if (repoSummaryResponse.status !== 200) {
|
||||
// await namespaceWrapper.storeSet(`result-${roundNumber}`, status.ISSUE_SUMMARIZATION_FAILED);
|
||||
}
|
||||
} catch (error) {
|
||||
// await namespaceWrapper.storeSet(`result-${roundNumber}`, status.ISSUE_SUMMARIZATION_FAILED);
|
||||
console.error("[TASK] EXECUTE TASK ERROR:", error);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("[TASK] EXECUTE TASK ERROR:", error);
|
||||
// Wait for 1 minute before retrying on error
|
||||
await new Promise((resolve) => setTimeout(resolve, 60000));
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for 1 minute before starting the next iteration
|
||||
await new Promise((resolve) => setTimeout(resolve, 60000));
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user