-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
364 lines (291 loc) · 10.7 KB
/
index.js
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-require-imports */
/* eslint-disable prettier/prettier */
const express = require("express");
const { exec } = require("child_process");
const app = express();
const PORT = process.env.PORT || 8000;
const fs = require("fs");
const path = require("path");
const axios = require("axios");
const cors = require("cors");
const { ethers } = require("ethers");
app.use(express.json());
require("dotenv").config();
const { GoogleGenerativeAI, HarmCategory, HarmBlockThreshold } = require("@google/generative-ai");
app.use(cors());
const apiKey = process.env.GEMINI_API_KEY;
const genAI = new GoogleGenerativeAI(apiKey);
const model = genAI.getGenerativeModel({
model: "gemini-1.5-flash",
});
const generationConfig = {
temperature: 1,
topP: 0.95,
topK: 64,
maxOutputTokens: 8192,
responseMimeType: "application/json",
};
const chatSession = model.startChat({
generationConfig,
});
app.post("/deploy", async (req, res) => {
const { contractId, contractName } = req.body;
try {
exec(
`CONTRACT_NAME=${contractName} npx hardhat run contractDeploy/deploy.ts --network virtual_base `,
async (error, stdout, stderr) => {
if (error) {
console.error(`Error: ${error.message}`);
return res.status(500).send(`Error: ${error.message}`);
}
if (stderr) {
console.error(`logs: ${stderr}`);
return res.status(200).send(`logs: ${stderr}`);
}
console.log(`Stdout: ${stdout}`);
// res.send(`Deployment output: ${stdout}`);
const inputString = stdout;
const regex = /0x[a-fA-F0-9]{40}/;
// Extract the contract address
const deployedContractAddress = inputString.match(regex)[0];
const privateKey = process.env.PRIVATE_KEY;
const alchemyUrl = process.env.ALCHEMY_URL;
const provider = new ethers.JsonRpcProvider(alchemyUrl);
const contractAddress = "0xfb3eb41E32CB08965e7FFE95FFD9Bb01D1d631d8";
// Create a wallet instance
const wallet = new ethers.Wallet(privateKey, provider);
// ABI of the AuditMarketplace contract
const abi = [
// Only include the function signature you want to interact with
"function pushDeployedContract(uint256 _contractId, address _deployedAddress) public",
];
// Create a contract instance
const auditMarketplaceContract = new ethers.Contract(contractAddress, abi, wallet);
try {
const tx = await auditMarketplaceContract.pushDeployedContract(contractId, deployedContractAddress);
console.log("Transaction submitted: ", tx.hash);
// Wait for the transaction to be confirmed
const receipt = await tx.wait();
console.log("Transaction confirmed: ", receipt);
res.json(receipt).status(200);
} catch (error) {
console.error("Error performing transaction:", error);
res.json(error).status(500);
}
},
);
} catch (err) {
console.log("error in deploy: ", err);
res.status(500).json({
error: err.message,
});
}
});
app.get("/runscript", (req, res) => {
try {
exec(
`tenderly login --access-key ${process.env.TENDERLY_ACCESS_TOKEN} --authentication-method access-key`,
(error, stdout, stderr) => {
if (error) {
console.error(`Error: ${error.message}`);
return res.status(500).send(`Error: ${error.message}`);
}
if (stderr) {
console.error(`logs: ${stderr}`);
return res.status(500).send(`Stderr: ${stderr}`);
}
console.log(`Stdout: ${stdout}`);
res.send(`Deployment output: ${stdout}`);
},
);
} catch (err) {
console.log("error in runscript: ", err);
res.status(500).json({
error: err.message,
});
}
});
// POST route to create a Solidity file
app.post("/create-contract", async (req, res) => {
const { fileName, repoOwner, repoName, filePath, branch } = req.body;
try {
if (!fileName) {
return res.status(400).send("No fileName mentioned");
}
let solidityCode = await getContractContent(repoOwner, repoName, filePath, branch);
if (!solidityCode) {
return res.status(400).send("Unable to fetch Solidity code");
}
// Define the contracts directory
const contractsDir = path.join(__dirname, "contracts");
// Check if the directory exists, if not, create it
if (!fs.existsSync(contractsDir)) {
fs.mkdirSync(contractsDir, { recursive: true });
}
// Write the Solidity code to the file
const filePath1 = path.join(contractsDir, `${fileName}.sol`);
fs.writeFileSync(filePath1, solidityCode, "utf8");
res.status(201).send(`File ${fileName}.sol has been created in ${contractsDir}`);
} catch (err) {
console.log("error in create contract: ", err);
res.status(500).json({
error: err.message,
});
}
});
// Function to fetch the content of a contract file from a GitHub repository
app.post("/get-contract", async (req, res) => {
const { repoOwner, repoName, filePath, branch } = req.body;
try {
const contractContent = await getContractContent(repoOwner, repoName, filePath, branch);
if (!contractContent) {
return res.status(400).send("Unable to fetch Solidity code");
}
res.status(200).send(contractContent);
} catch (err) {
console.log("error in get contract: ", err);
res.status(500).json({ error: err.message });
}
});
const getContractContent = async (repoOwner, repoName, filePath, branch) => {
const apiUrl = `https://api.github.com/repos/${repoOwner}/${repoName}/contents/${filePath}`;
const token = process.env.GITHUB_ACCESS_TOKEN;
// Define headers with the GitHub token
const headers = {
Authorization: `Bearer ${token}`,
Accept: "application/vnd.github.v3+json",
};
try {
// Fetch file content from GitHub
const response = await axios.get(apiUrl, { headers });
// Decode the base64 content
const currentContent = Buffer.from(response.data.content, "base64").toString("utf-8");
console.log(currentContent, filePath, response.data.sha);
return currentContent;
} catch (error) {
console.error("Error retrieving file content:", error);
}
};
// getContractContent()
// https://github.com/jaydeepdey03/jaydeep-test-alchemy-superhack/blob/main/src/styles/globals.css
// getContractContent(
// "jaydeepdey03",
// "jaydeep-test-alchemy-superhack",
// "src/styles/globals.css",
// "main"
// );
const extractFunctions = solidityCode => {
console.log(solidityCode, "extract functions");
// Split the code by the keyword 'function'
const parts = solidityCode.split("function");
// Filter out and re-add the 'function' keyword to valid function blocks
const functions = parts
.slice(1) // Skip the first part since it will be before the first 'function' keyword
.map(part => "function" + part.split("}")[0] + "}");
// Print the matched functions
functions.forEach((func, index) => {
console.log(`Function ${index + 1}:\n${func}\n`);
});
// const functionRegex = /function\s+[a-zA-Z_][a-zA-Z0-9_]*\s*\([^)]*\)\s*\{[^}]*\}/g;
// const res = solidityCode.match(functionRegex);
// console.log(res, "extract functions");
// return solidityCode.match(functionRegex);
return functions;
};
app.post("/generate-report", async (req, res) => {
const { repoOwner, repoName, filePath, branch } = req.body;
console.log(repoOwner, repoName, filePath, branch);
try {
const contractContent = await getContractContent(repoOwner, repoName, filePath, branch);
console.log(contractContent);
if (!contractContent) {
return res.status(400).send("Unable to fetch Solidity code");
}
const functions = extractFunctions(contractContent);
console.log(functions);
let report = "";
for (let index = 0; index < functions.length; index++) {
const code = functions[index];
const result = await chatSession.sendMessage(` ${code}
In the above code,
If security issues persist, return json (
{
functionName: ....,
result: 'security',
explanation: ....,
})
if improvement are required such as adding Events, etc,
return json
({
functionName: ....,
result: 'improvement',
explanation: ....,
})
if no issues persist, return json
({
functionName: ....,
result: 'good',
explanation: ....})
`);
// console.log(result.response.text());
if (index != 0) report += "," + result.response.text();
else report += result.response.text();
}
report = "[" + report + "]";
console.log(report);
const resReport = JSON.parse(report);
res.json(resReport).status(200);
} catch (err) {
console.log("error: ", err.message);
res.status(500).send(err);
}
// res.send("dsa").status(200);
});
app.post("/get-code", async (req, res) => {
try {
const { code, description } = req;
const result = await chatSession.sendMessage(` ${code}
In the above code,
description of the error or improvement required: ${description}
Send the fixed code as json response
{
"code": ...
}
`);
res.json(result).status(200);
} catch (error) {
res.send(error.message).status(500);
}
});
app.post("/get-abi", async (req, res) => {
const { contractName } = req.body;
try {
// Define the path where the ABI is stored
const filePath = path.join(__dirname, `artifacts/contracts/${contractName}.sol/${contractName}.json`);
// Read the file content synchronously
const data = fs.readFileSync(filePath, "utf8");
// Parse the JSON file content
const contractJson = JSON.parse(data);
const abi = contractJson.abi;
// Send the ABI back to the frontend
res.json({ abi });
} catch (error) {
console.error("An error occurred:", error);
res.status(500).send("An error occurred while retrieving the ABI");
}
});
app.post("/ask", async (req, res) => {
try {
const { simulation } = req.body;
const result = await chatSession.sendMessage(
`explain this transaction simulation ${simulation} and return the response as {result: "..."}`,
);
res.json(result).status(200);
} catch (error) {
res.send(error).status(500);
}
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});