-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathbot-handle-comment.ts
222 lines (199 loc) · 8.57 KB
/
bot-handle-comment.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import { github } from "@eng-automation/integrations";
import { GitHubInstance } from "@eng-automation/integrations/dist/github/types";
import { envVar } from "@eng-automation/js";
import { IssueCommentCreatedEvent } from "@octokit/webhooks-types";
import { ss58Address } from "@polkadot-labs/hdkd-helpers";
import { updateBalance } from "./balance";
import { matrixNotifyOnFailure, matrixNotifyOnNewTip } from "./matrix";
import { recordTip } from "./metrics";
import { tipUser, tipUserLink } from "./tip";
import { updatePolkassemblyPost } from "./tip-opengov";
import { GithubReactionType, State, TipRequest, TipResult } from "./types";
import { formatTipSize, getTipSize, parseContributorAccount } from "./util";
type OnIssueCommentResult =
| { success: true; message: string }
| { success: true; message: string; tipRequest: TipRequest; tipResult: Extract<TipResult, { success: true }> }
| { success: false; errorMessage: string };
export const handleIssueCommentCreated = async (state: State, event: IssueCommentCreatedEvent): Promise<void> => {
const [botMention] = event.comment.body.split(" ") as (string | undefined)[];
// The bot only triggers on creation of a new comment on a pull request.
if (!event.issue.pull_request || event.action !== "created" || !botMention?.startsWith("/tip")) {
return;
}
// The "Unsafe assignment of an error typed value" error here goes deep into octokit types, that are full of `any`s
// I wasn't able to get around it
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const appOctokitInstance: GitHubInstance = await github.getInstance({
authType: "app",
appId: envVar("GITHUB_APP_ID"),
privateKey: envVar("GITHUB_PRIVATE_KEY"),
...(process.env.GITHUB_BASE_URL && { apiEndpoint: envVar("GITHUB_BASE_URL") }),
});
const tipRequester = event.comment.user.login;
const installationId = (
await github.getRepoInstallation(
{
owner: event.repository.owner.login,
repo: event.repository.name,
},
{ octokitInstance: appOctokitInstance },
)
).id;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const octokitInstance: GitHubInstance = await github.getInstance({
authType: "installation",
appId: envVar("GITHUB_APP_ID"),
installationId: String(installationId),
privateKey: envVar("GITHUB_PRIVATE_KEY"),
...(process.env.GITHUB_BASE_URL && { apiEndpoint: envVar("GITHUB_BASE_URL") }),
});
const respondParams = {
owner: event.repository.owner.login,
repo: event.repository.name,
issue_number: event.issue.number,
};
const githubComment = async (body: string) =>
await github.createComment({ ...respondParams, body }, { octokitInstance });
const githubEmojiReaction = async (reaction: GithubReactionType) =>
await github.createReactionForIssueComment(
{ ...respondParams, comment_id: event.comment.id, content: reaction },
{ octokitInstance },
);
await githubEmojiReaction("eyes");
await matrixNotifyOnNewTip(state.matrix, event);
let result: OnIssueCommentResult;
try {
result = await handleTipRequest(state, event, tipRequester, octokitInstance);
if (result.success) {
await githubComment(result.message);
await githubEmojiReaction("rocket");
} else {
await githubComment(result.errorMessage);
await githubEmojiReaction("confused");
await matrixNotifyOnFailure(state.matrix, event, { tagMaintainers: false });
}
} catch (e) {
state.bot.log.error(e.message);
await githubComment(
`@${tipRequester} Could not submit tip :( The team has been notified. Alternatively open an issue [here](https://github.com/paritytech/substrate-tip-bot/issues/new).`,
);
await githubEmojiReaction("confused");
await matrixNotifyOnFailure(state.matrix, event, { tagMaintainers: true });
return;
}
if (result.success && state.polkassembly && "tipResult" in result && result.tipResult.referendumNumber) {
try {
const { url } = await updatePolkassemblyPost({
polkassembly: state.polkassembly,
referendumId: result.tipResult.referendumNumber,
tipRequest: result.tipRequest,
track: result.tipResult.track,
log: state.bot.log,
});
await githubComment(`The referendum has appeared on [Polkassembly](${url}).`);
} catch (e) {
state.bot.log.error(
`Failed to update the Polkasssembly metadata; referendumId: ${result.tipResult.referendumNumber}`,
result.tipRequest,
);
state.bot.log.error(e.message);
await matrixNotifyOnFailure(state.matrix, event, {
tagMaintainers: true,
failedItem: "Polkassembly post update",
});
}
}
};
export const handleTipRequest = async (
state: State,
event: IssueCommentCreatedEvent,
tipRequester: string,
octokitInstance: github.GitHubInstance,
): Promise<OnIssueCommentResult> => {
const { allowedGitHubOrg, allowedGitHubTeam, bot } = state;
const [_, tipSizeInput] = event.comment.body.split(" ") as (string | undefined)[];
const pullRequestBody = event.issue.body;
const pullRequestUrl = event.issue.html_url;
const contributorLogin = event.issue.user.login;
const pullRequestNumber = event.issue.number;
const pullRequestRepo = event.repository.name;
if (tipRequester === contributorLogin) {
return { success: false, errorMessage: `@${tipRequester} Contributor and tipper cannot be the same person!` };
}
const userBio = (await octokitInstance.rest.users.getByUsername({ username: contributorLogin })).data.bio;
const contributorAccount = parseContributorAccount([pullRequestBody, userBio]);
if ("error" in contributorAccount) {
// Contributor is tagged because it is up to him to properly prepare his address.
return { success: false, errorMessage: `@${contributorLogin} ${contributorAccount.error}` };
}
const tipSize = getTipSize(tipSizeInput?.trim());
if (typeof tipSize == "object" && "error" in tipSize) {
return { success: false, errorMessage: `@${tipRequester} ${tipSize.error}` };
}
const tipRequest: TipRequest = {
contributor: { githubUsername: contributorLogin, account: contributorAccount },
pullRequestNumber,
pullRequestRepo,
tip: { size: tipSize },
};
bot.log(
`Valid command!\n${tipRequester} wants to tip ${contributorLogin} (${contributorAccount.address} on ${
contributorAccount.network
}) a ${formatTipSize(tipRequest)} tip for pull request ${pullRequestUrl}.`,
);
if (
!(await github.isGithubTeamMember(
{ org: allowedGitHubOrg, team: allowedGitHubTeam, username: tipRequester },
{ octokitInstance },
))
) {
let createReferendumLink: string | undefined;
try {
const tipLink = await tipUserLink(state, tipRequest);
if (!tipLink.success) {
throw new Error(tipLink.errorMessage);
}
createReferendumLink = tipLink.extrinsicCreationLink;
} catch (e) {
bot.log.error("Failed to encode and create a link to tip referendum creation.");
bot.log.error(e.message);
}
let message =
`Only members of \`${allowedGitHubOrg}/${allowedGitHubTeam}\` ` +
`have permission to request the creation of the tip referendum from the bot.\n\n`;
message += `However, you can create the tip referendum yourself using [Polkassembly](https://wiki.polkadot.network/docs/learn-polkadot-opengov-treasury#submit-treasury-proposal-via-polkassembly)`;
return {
success: true,
message: createReferendumLink ? message + ` or [PolkadotJS Apps](${createReferendumLink}).` : message + ".",
};
}
const tipResult = await tipUser(state, tipRequest);
// The user doesn't need to wait until we update metrics and balances, so launching it separately.
void (async () => {
try {
recordTip({ tipRequest, tipResult });
await updateBalance({
network: tipRequest.contributor.account.network,
tipBotAddress: ss58Address(state.botTipAccount.publicKey),
});
} catch (e) {
bot.log.error(e.message);
}
})();
if (tipResult.success) {
const numberInfo =
tipResult.referendumNumber !== null ? `Referendum number: **${tipResult.referendumNumber}**.` : "";
return {
success: true,
tipRequest,
tipResult,
message: `@${tipRequester} A referendum for a ${formatTipSize(
tipRequest,
)} tip was successfully submitted for @${contributorLogin} (${contributorAccount.address} on ${
contributorAccount.network
}).\n\n${numberInfo}\n`,
};
} else {
return { success: false, errorMessage: tipResult.errorMessage };
}
};