Skip to content
This repository has been archived by the owner on Sep 19, 2024. It is now read-only.

Refactor/helpers ii #646

Closed
wants to merge 19 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions .cspell.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
{
"useGitignore": true,
"version": "0.2",
"language": "en",
"words": [
"autodetection",
"autopay",
"AUTOPAY",
"bucketid",
"bucketname",
"demilestoned",
"devpool",
"ensname",
"fkey",
"gelato",
"Gelato",
"gollum",
"keccak",
"libsodium",
"logdna",
"LOGDNA",
"mdast",
"Mdast",
"mergeable",
"micromark",
"milestoned",
"Numberish",
"orgname",
"pavlovcik",
"permisson",
"prereleased",
"probot",
"Probot",
"ratelimit",
"rebaseable",
"rerequested",
"scalarmult",
"signoff",
"sortcolumn",
"sortorder",
"supabase",
"Supabase",
"SUPABASE",
"svgs",
"timelabel",
"TURL",
"typebox",
"Ubiqui",
"ubiquibot",
"unarchived",
"Unassigning",
"Upserting",
"URLSAFE",
"vitalik",
"WXDAI"
]
}
7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
"start:serverless": "tsx src/adapters/github/github-actions.ts",
"start:watch": "nodemon --exec 'yarn start'",
"start": "probot run ./lib/src/index.js",
"prepare": "husky install"
"prepare": "husky install",
"utils:cspell": "cspell --config .cspell.json 'src/**/*.{js,ts,json,md,yml}'"
},
"dependencies": {
"@actions/core": "^1.10.0",
Expand All @@ -45,6 +46,7 @@
"ajv-formats": "^2.1.1",
"axios": "^1.3.2",
"copyfiles": "^2.4.1",
"cspell": "^7.0.0",
"ethers": "^5.7.2",
"husky": "^8.0.2",
"jimp": "^0.22.4",
Expand Down Expand Up @@ -86,6 +88,9 @@
"lint-staged": {
"*.{ts,json}": [
"prettier --write"
],
"src/**.{ts,json}": [
"cspell"
]
},
"nodemonConfig": {
Expand Down
20 changes: 10 additions & 10 deletions src/adapters/supabase/helpers/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,13 +169,13 @@ export const upsertWalletAddress = async (username: string, address: string): Pr
});
logger.info(`Upserting a wallet address done, { data: ${data}, error: ${error} }`);
} else {
const { data: _data, error: _error } = await supabase.from("wallets").insert({
const { error } = await supabase.from("wallets").insert({
user_name: username,
wallet_address: address,
created_at: new Date().toUTCString(),
updated_at: new Date().toUTCString(),
});
logger.info(`Creating a new wallet_table record done, { error: ${_error?.message} }`);
logger.info(`Creating a new wallet_table record done, { error: ${error?.message} }`);
}
};

Expand Down Expand Up @@ -309,15 +309,15 @@ export const getWalletInfo = async (username: string, org_id: string): Promise<{
} else return { multiplier: multiplier?.value, address: wallet?.wallet_address };
};

export const addPenalty = async (username: string, repoName: string, tokenAddress: string, networkId: string, penalty: BigNumberish): Promise<void> => {
export const addPenalty = async (username: string, repoName: string, tokenAddress: string, evmNetworkId: string, penalty: BigNumberish): Promise<void> => {
const { supabase } = getAdapters();
const logger = getLogger();

const { error } = await supabase.rpc("add_penalty", {
_username: username,
_repository_name: repoName,
_token_address: tokenAddress,
_network_id: networkId,
_network_id: evmNetworkId,
_penalty_amount: penalty.toString(),
});
logger.debug(`Adding penalty done, { data: ${JSON.stringify(error)}, error: ${JSON.stringify(error)} }`);
Expand All @@ -327,7 +327,7 @@ export const addPenalty = async (username: string, repoName: string, tokenAddres
}
};

export const getPenalty = async (username: string, repoName: string, tokenAddress: string, networkId: string): Promise<BigNumber> => {
export const getPenalty = async (username: string, repoName: string, tokenAddress: string, evmNetworkId: string): Promise<BigNumber> => {
const { supabase } = getAdapters();
const logger = getLogger();

Expand All @@ -336,7 +336,7 @@ export const getPenalty = async (username: string, repoName: string, tokenAddres
.select("amount")
.eq("username", username)
.eq("repository_name", repoName)
.eq("network_id", networkId)
.eq("network_id", evmNetworkId)
.eq("token_address", tokenAddress);
logger.debug(`Getting penalty done, { data: ${JSON.stringify(error)}, error: ${JSON.stringify(error)} }`);

Expand All @@ -350,14 +350,14 @@ export const getPenalty = async (username: string, repoName: string, tokenAddres
return BigNumber.from(data[0].amount);
};

export const removePenalty = async (username: string, repoName: string, tokenAddress: string, networkId: string, penalty: BigNumberish): Promise<void> => {
export const removePenalty = async (username: string, repoName: string, tokenAddress: string, evmNetworkId: string, penalty: BigNumberish): Promise<void> => {
const { supabase } = getAdapters();
const logger = getLogger();

const { error } = await supabase.rpc("remove_penalty", {
_username: username,
_repository_name: repoName,
_network_id: networkId,
_network_id: evmNetworkId,
_token_address: tokenAddress,
_penalty_amount: penalty.toString(),
});
Expand All @@ -373,7 +373,7 @@ const getDbDataFromPermit = (permit: InsertPermit): Record<string, unknown> => {
organization_id: permit.organizationId,
repository_id: permit.repositoryId,
issue_id: permit.issueId,
network_id: permit.networkId,
network_id: permit.evmNetworkId,
bounty_hunter_id: permit.bountyHunterId,
token_address: permit.tokenAddress,
payout_amount: permit.payoutAmount,
Expand All @@ -392,7 +392,7 @@ const getPermitFromDbData = (data: Record<string, unknown>): Permit => {
organizationId: data.organization_id,
repositoryId: data.repository_i,
issueId: data.issue_id,
networkId: data.network_id,
evmNetworkId: data.network_id,
bountyHunterId: data.bounty_hunter_id,
tokenAddress: data.token_address,
payoutAmount: data.payout_amount,
Expand Down
1 change: 1 addition & 0 deletions src/assets/fonts/proxima-nova-regular-b64.ts

Large diffs are not rendered by default.

34 changes: 17 additions & 17 deletions src/bindings/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { DEFAULT_BOT_DELAY, DEFAULT_DISQUALIFY_TIME, DEFAULT_FOLLOWUP_TIME, DEFA
import { getPayoutConfigByNetworkId } from "../helpers";
import { ajv } from "../utils";
import { Context } from "probot";
import { getScalarKey, getWideConfig } from "../utils/private";
import { getScalarKey, getAllConfigs as getConfig } from "../utils/private";

export const loadConfig = async (context: Context): Promise<BotConfig> => {
const {
Expand All @@ -16,19 +16,19 @@ export const loadConfig = async (context: Context): Promise<BotConfig> => {
commentElementPricing,
paymentPermitMaxPrice,
disableAnalytics,
bountyHunterMax,
maxConcurrentAssigns,
incentiveMode,
networkId,
evmNetworkId,
issueCreatorMultiplier,
defaultLabels,
promotionComment,
commandSettings,
assistivePricing,
registerWalletWithVerification,
} = await getWideConfig(context);
} = await getConfig(context);

const publicKey = await getScalarKey(process.env.X25519_PRIVATE_KEY);
const { rpc, paymentToken } = getPayoutConfigByNetworkId(networkId);
const { rpc, paymentToken } = getPayoutConfigByNetworkId(evmNetworkId);

const botConfig: BotConfig = {
log: {
Expand All @@ -38,16 +38,16 @@ export const loadConfig = async (context: Context): Promise<BotConfig> => {
price: {
baseMultiplier,
issueCreatorMultiplier,
timeLabels,
priorityLabels,
commentElementPricing,
defaultLabels,
timeLabels: timeLabels ?? [],
priorityLabels: priorityLabels ?? [],
commentElementPricing: commentElementPricing || {},
defaultLabels: defaultLabels ?? [],
},
comments: {
promotionComment: promotionComment,
promotionComment: promotionComment ?? "",
},
payout: {
networkId: networkId,
evmNetworkId: evmNetworkId,
rpc: rpc,
privateKey: privateKey,
paymentToken: paymentToken,
Expand All @@ -67,20 +67,20 @@ export const loadConfig = async (context: Context): Promise<BotConfig> => {
},
mode: {
paymentPermitMaxPrice: paymentPermitMaxPrice,
disableAnalytics: disableAnalytics,
incentiveMode: incentiveMode,
assistivePricing: assistivePricing,
disableAnalytics: disableAnalytics ?? false,
incentiveMode: incentiveMode ?? false,
assistivePricing: assistivePricing ?? false,
},
command: commandSettings,
command: commandSettings ?? [{ name: "", enabled: false }],
assign: {
bountyHunterMax: bountyHunterMax,
maxConcurrentAssigns: maxConcurrentAssigns,
},
sodium: {
privateKey: process.env.X25519_PRIVATE_KEY ?? "",
publicKey: publicKey ?? "",
},
wallet: {
registerWalletWithVerification: registerWalletWithVerification,
registerWalletWithVerification: registerWalletWithVerification ?? false,
},
};

Expand Down
12 changes: 2 additions & 10 deletions src/bindings/event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,7 @@ export const bindEvents = async (context: Context): Promise<void> => {
return;
}

logger.info(
`Config loaded! config: ${JSON.stringify({
price: botConfig.price,
unassign: botConfig.unassign,
mode: botConfig.mode,
log: botConfig.log,
wallet: botConfig.wallet,
})}`
);
logger.info(`Config loaded! config: ${JSON.stringify(botConfig)}`);
const allowedEvents = Object.values(GithubEvent) as string[];
const eventName = payload.action ? `${name}.${payload.action}` : name; // some events wont have actions as this grows

Expand All @@ -74,7 +66,7 @@ export const bindEvents = async (context: Context): Promise<void> => {
const validate = ajv.compile(PayloadSchema);
const valid = validate(payload);
if (!valid) {
logger.info("Payload schema validation failed!!!", payload);
logger.info("Payload schema validation failed!", payload);
if (validate.errors) logger.warn(validate.errors);
return;
}
Expand Down
2 changes: 2 additions & 0 deletions src/configs/shared.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
// cspell:disable
export const COLORS = {
default: "ededed",
price: "1f883d",
};
// cspell:enable
export const DEFAULT_BOT_DELAY = 100; // 100ms
export const DEFAULT_TIME_RANGE_FOR_MAX_ISSUE = 24;
export const DEFAULT_TIME_RANGE_FOR_MAX_ISSUE_ENABLED = true;
Expand Down
12 changes: 6 additions & 6 deletions src/handlers/assign/action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,13 @@ export const commentWithAssignMessage = async (): Promise<void> => {
return;
}

const curDate = new Date();
const curDateInMillisecs = curDate.getTime();
const endDate = new Date(curDateInMillisecs + duration * 1000);
const commit_msg = `${flattened_assignees} ${deadLinePrefix} ${endDate.toUTCString().replace("GMT", "UTC")}`;
logger.debug(`Creating an issue comment, commit_msg: ${commit_msg}`);
const currentDate = new Date();
const currentDateInMilliseconds = currentDate.getTime();
const endDate = new Date(currentDateInMilliseconds + duration * 1000);
const commitMessage = `${flattened_assignees} ${deadLinePrefix} ${endDate.toUTCString().replace("GMT", "UTC")}`;
logger.debug(`Creating an issue comment, commit_msg: ${commitMessage}`);

await addCommentToIssue(commit_msg, payload.issue?.number);
await addCommentToIssue(commitMessage, payload.issue?.number);
};

export const closePullRequestForAnIssue = async (): Promise<void> => {
Expand Down
6 changes: 3 additions & 3 deletions src/handlers/comment/handlers/assign.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,11 @@ export const assign = async (body: string) => {
logger.info(`Opened Pull Requests with approved reviews or with no reviews but over 24 hours have passed: ${JSON.stringify(openedPullRequests)}`);

const assignedIssues = await getAssignedIssues(payload.sender.login);
logger.info(`Max issue allowed is ${config.assign.bountyHunterMax}`);
logger.info(`Max issue allowed is ${config.assign.maxConcurrentAssigns}`);

// check for max and enforce max
if (assignedIssues.length - openedPullRequests.length >= config.assign.bountyHunterMax) {
return `Too many assigned issues, you have reached your max of ${config.assign.bountyHunterMax}`;
if (assignedIssues.length - openedPullRequests.length >= config.assign.maxConcurrentAssigns) {
return `Too many assigned issues, you have reached your max of ${config.assign.maxConcurrentAssigns}`;
}

if (issue.state == IssueType.CLOSED) {
Expand Down
7 changes: 4 additions & 3 deletions src/handlers/comment/handlers/help.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export const listAvailableCommands = async (body: string) => {
};

export const generateHelpMenu = () => {
let helpMenu = "### Available commands\n```";
let helpMenu = "### Available Commands\n```";
const commands = userCommands();
commands.map((command) => {
// if first command, add a new line
Expand All @@ -42,7 +42,8 @@ export const generateHelpMenu = () => {
helpMenu += `\n`;
}
});

if (!ASSIGN_COMMAND_ENABLED) helpMenu += "```\n***_To assign yourself to an issue, please open a draft pull request that is linked to it._***";
if (!ASSIGN_COMMAND_ENABLED) {
helpMenu += "\n***_To assign yourself to an issue, please open a draft pull request that is linked to it._***";
}
return helpMenu;
};
14 changes: 5 additions & 9 deletions src/handlers/comment/handlers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,18 +203,16 @@ const commandCallback = async (issue_number: number, comment: string, action: st
};

export const userCommands = (): UserCommands[] => {
const config = getBotConfig();

return [
{
id: IssueCommentCommands.START,
description: "Assign the origin sender to the issue automatically.",
description: "Assign yourself to the issue.",
handler: assign,
callback: commandCallback,
},
{
id: IssueCommentCommands.STOP,
description: "Unassign the origin sender from the issue automatically.",
description: "Unassign yourself from the issue.",
handler: unassign,
callback: commandCallback,
},
Expand Down Expand Up @@ -245,21 +243,19 @@ export const userCommands = (): UserCommands[] => {
},
{
id: IssueCommentCommands.MULTIPLIER,
description: `Set the bounty payout multiplier for a specific contributor, and provide the reason for why. \n example usage: "/wallet @user 0.5 'Multiplier reason'"`,
description: `Set the bounty payout multiplier for a specific contributor, and provide a reason for why.\n\te.g. '/wallet @user 0.5 "Multiplier reason"'`,
handler: multiplier,
callback: commandCallback,
},
{
id: IssueCommentCommands.ALLOW,
description: `Set access control. (Admin Only)`,
description: `Set access control. Superuser only.`,
handler: setAccess,
callback: commandCallback,
},
{
id: IssueCommentCommands.WALLET,
description: config.wallet.registerWalletWithVerification
? `<WALLET_ADDRESS | ENS_NAME> <SIGNATURE_HASH>: Register the hunter's wallet address. \n Your message to sign is: DevPool\n You can generate SIGNATURE_HASH at https://etherscan.io/verifiedSignatures\n ex1: /wallet 0x0000000000000000000000000000000000000000 0xe2a3e34a63f3def2c29605de82225b79e1398190b542be917ef88a8e93ff9dc91bdc3ef9b12ed711550f6d2cbbb50671aa3f14a665b709ec391f3e603d0899a41b\n ex2: /wallet vitalik.eth 0x75329f883590507e581cd6dfca62680b6cd12e1f1665db8097f9e642ed70025146b5cf9f777dde90c4a9cbd41500a6bf76bc394fd0b0cae2aab09f7a6f30e3b31b\n`
: `<WALLET_ADDRESS | ENS_NAME>: Register the hunter's wallet address. \n ex1: /wallet 0x0000000000000000000000000000000000000000\n ex2: /wallet vitalik.eth\n`,
description: `<WALLET_ADDRESS | ENS_NAME> <SIGNATURE_HASH>: Register your wallet address for payments.\n\tYour message to sign is: "DevPool"\n\tYou can generate SIGNATURE_HASH at https://etherscan.io/verifiedSignatures\n\te.g. "/wallet 0x16ce4d863eD687455137576da2A0cbaf4f1E8f76 0xe2a3e34a63f3def2c29605de82225b79e1398190b542be917ef88a8e93ff9dc91bdc3ef9b12ed711550f6d2cbbb50671aa3f14a665b709ec391f3e603d0899a41b"`,
handler: registerWallet,
callback: commandCallback,
},
Expand Down
Loading
Loading