Skip to content

Commit

Permalink
added ai request parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
volkanguneri committed Aug 27, 2024
1 parent 21369fe commit 473e696
Show file tree
Hide file tree
Showing 5 changed files with 181 additions and 87 deletions.
10 changes: 5 additions & 5 deletions packages/foundry/.env.enc
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
ALCHEMY_API_KEY: ENCRYPTED|/HvjPt5PNBnT7mh+K/rk7h71Xo9qdxiWKXGlE74YtD6wH+Jj5vW/8Q6h2xjDwYtWwMT22+4OYmXWyc38H7TFV+e4i4Ml7p8mr+PhiBOrhSk=
DEPLOYER_PRIVATE_KEY: ENCRYPTED|uKo42QPIgEJSevK1QnNoYMRp6+6sVkvg/83Bg/ODqHJN72mDQ2ck9EOB0wkkVMvtCuYE8+vTc9MC9mCaCPOmVn8sf6nOsY0pF1TaJOxUlov7N3d2T7JRXA5xsHl2yD9hSIbSbzTx7cXs6WUvGk3hFeQv
ETHERSCAN_API_KEY: ENCRYPTED|e0hoxM7n/O55KhPtfxLYzgg8RAxDQh6YVvpEVwvbEPbnQvNOVuE4nyY2nXeN4Q1/qND98jiqzW6cYil3PEvgPpmrwoFiD//fRQBrkfxlKBct2g==
OPENAI_API_KEY: ENCRYPTED|t20zMgiqk9PVIETIGH8t8ZnMSL/9rFn14YIlQbGB0rzs3Yr/GAQWt9GysB9r1A/CD+GqJkuLT4UAmumOQIXAPZl3cYqhlB7M4P6Wt99hj4BuHc8ATdeyyc2jRhrmPWa58ps=
ETHEREUM_SEPOLIA_URL: ENCRYPTED|0I7tz794H7l8S5FAfs9n8QSGIHZXgoyuEtxbJaiScu0MGCEFYn8VwRVT6igivpVLoQQqNC1XrRurrw6YX7wzzZh5WBsX+wKSduk6+p9BdMLrmoaPUVPtNWAQ8QvuUuZaHtTrtN9enuhGE3ManA==
ALCHEMY_API_KEY: ENCRYPTED|TERBOvc7yFLCnQSw5PQiou/bg6dYGffA7ACx83RHwrgEiAQuAgaYXOjdmTn+pg3iyHIFLwk0QS5klJzoXOvg/O+a57NvvTB68C1gt4ze8vg=
DEPLOYER_PRIVATE_KEY: ENCRYPTED|czd3Ehf9xMKQ3K032OgkuzD/4J+6nrcI3km2j2RpgYPE9evORmB6wlhS/2bkVcf416qj9N0TSj1aYb607ZwyLeqOeBsBgMV7xAHff37VS2nsGxE9QN1Nu22ZPQUiNCN9iWKQx4lWEI7/uscm4wvm3AeM
ETHERSCAN_API_KEY: ENCRYPTED|RfAFf4NmVU40++0AwwAl+y1BmaVIrcQkQJi7UF2xmLfyT/yMtxIXvyUzVxVlD9L0krUHQSY4VVwAOlp6srxdQ7wf+EATNY8YE1TH1jAm3FsJaQ==
OPENAI_API_KEY: ENCRYPTED|J1RxUY6WYHvuRv+VsWmjoFNJihrRWMVpTB1ml9T02aZ1pxNaPYs8EgUKSPq5oAXLYrneUaGuRDgPlLv7hlAZTRnr1BkfXPcVfVM5x+tr2TBfT8Cu1M/cx8FV+/B+1REm9tz9
ETHEREUM_SEPOLIA_URL: ENCRYPTED|cbyLKT9LiIEVEcJwo2MAwNmKV2/x2rw2TkuQmKg960SoCzSvdyyF6Au0NXSWlgrcXjTLnj6VqhMvNmagh+bjKEDVY7oa5mFLbw8IaXpeeN3L1z9/nE0Ps656HVH+noQtS3BkfNeLSdR6Ftv+tA==
73 changes: 0 additions & 73 deletions packages/foundry/ai-request-suite.js

This file was deleted.

177 changes: 172 additions & 5 deletions packages/foundry/ai-request.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,16 @@ const etherscanResponse = await Functions.makeHttpRequest({
url: `https://api-sepolia.etherscan.io/api?module=contract&action=getsourcecode&address=${contractAddress}&apikey=${secrets.etherscanAPIKey}`,
})

// Verify if the request failed
// console.log(`etherscanResponse: ${etherscanResponse}`)

// Check if the HTTP request was successful
if (etherscanResponse.error) {
throw new Error(`HTTP request failed`);
throw new Error(`HTTP request failed: ${etherscanResponse.error}`);
}

// Check if data and result are defined in the response
if (!etherscanResponse.data || !etherscanResponse.data.result || etherscanResponse.data.result.length === 0) {
throw new Error('Invalid response from Etherscan API or contract not found.');
}

// Retrieve the content of the response
Expand Down Expand Up @@ -40,7 +47,167 @@ if (parsedSourceCode && parsedSourceCode.sources) {
}

// Log the aggregated content (for debugging purposes)
console.log(`🚀 ~ content of contract:`, contractContent);
// console.log(`🚀 ~ content of contract:`, contractContent);


// [3] PROMPT ENGINEERING //
const prompt = `Analyse the smart contract in one sentence tell what is the risk for security if interacted with: ${contractContent}`;
// const prompt = `Analyse the smart contract in one sentence tell what is the risk for security if interacted with: //SPDX-License-Identifier: MIT
// pragma solidity >=0.8.0 <0.9.0;

// contract Basic {
// uint256 numberA = 1;
// uint256 numberB = 2;

// constructor() {}

// function total() external view returns (uint256) {
// return (numberA + numberB);
// }
// }
// `;

// [4] I DATA REQUEST //
let openAIRequest;
try {
// Ensure the API key is available
if (!secrets.openaiAPIKey) {
throw new Error("OpenAI API key is missing. Please ensure it is set correctly.");
}


// Make the OpenAI API request
openAIRequest = await Functions.makeHttpRequest({
url: `https://api.openai.com/v1/chat/completions`,
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${secrets.openaiAPIKey}`,
},
data: {
model: "gpt-3.5-turbo",
messages: [
{
role: "system",
content: "You are a smart contract auditor",
},
{
role: "user",
content: prompt,
},
],
},
timeout: 10000,
responseType: "json",
});
console.log("🚀 ~ openAIRequest:", openAIRequest)

// Log the entire response for debugging purposes
// console.log(`OpenAI API response: ${JSON.stringify(openAIRequest.data, null, 2)}`);

// Check if the data is present and in the expected format
if (!openAIRequest.data || !openAIRequest.data.choices || openAIRequest.data.choices.length === 0) {
throw new Error("Invalid response from OpenAI API: 'choices' array is missing or empty.");
}

// Extract the result from the response
const stringResult = openAIRequest.data.choices[0].message.content.trim();
const result = stringResult.toString();

console.log(`OpenAI security analysis of the contract address ${contractAddress} is: ${result}`);
return Functions.encodeString(result || "Failed");

} catch (error) {
console.error("Error during the OpenAI request process:", error);
return Functions.encodeString("Failed to fetch openAi request response");
}

// // [1] ARGUMENT DECLARATION
// const contractAddress = args[0];

// // [2] REQUEST CONTRACT VIA ETHERSCAN
// const etherscanResponse = await Functions.makeHttpRequest({
// url: `https://api-sepolia.etherscan.io/api?module=contract&action=getsourcecode&address=${contractAddress}&apikey=${secrets.etherscanAPIKey}`,
// });

// if (etherscanResponse.error) {
// throw new Error(`HTTP request failed: ${etherscanResponse.error}`);
// }

// if (!etherscanResponse.data || !etherscanResponse.data.result || etherscanResponse.data.result.length === 0) {
// throw new Error('Invalid response from Etherscan API or contract not found.');
// }

// const sourceCodeJson = etherscanResponse.data.result[0].SourceCode;

// // Parsing the JSON if necessary
// let parsedSourceCode;
// try {
// parsedSourceCode = JSON.parse(sourceCodeJson.replace(/{{/g, '{').replace(/}}/g, '}'));
// } catch (error) {
// console.error("Error parsing the source code JSON:", error);
// }

// // Aggregating the content of all contract files
// let contractContent = "";
// if (parsedSourceCode && parsedSourceCode.sources) {
// for (const [filePath, fileDetails] of Object.entries(parsedSourceCode.sources)) {
// contractContent += fileDetails.content + '\n';
// }
// }

// // [3] SPLITTING THE CONTRACT CONTENT INTO SMALLER CHUNKS
// const chunkSize = 1024; // Adjust the chunk size based on the API's input limit
// const chunks = [];
// for (let i = 0; i < contractContent.length; i += chunkSize) {
// chunks.push(contractContent.slice(i, i + chunkSize));
// }

// // [4] I DATA REQUEST //
// let results = [];

// try {
// if (!secrets.openaiAPIKey) {
// throw new Error("OpenAI API key is missing. Please ensure it is set correctly.");
// }

// for (const chunk of chunks) {
// const openAIRequest = await Functions.makeHttpRequest({
// url: `https://api.openai.com/v1/chat/completions`,
// method: "POST",
// headers: {
// "Content-Type": "application/json",
// Authorization: `Bearer ${secrets.openaiAPIKey}`,
// },
// data: {
// model: "gpt-3.5-turbo",
// messages: [
// {
// role: "system",
// content: "You are a smart contract auditor",
// },
// {
// role: "user",
// content: `Analyze the following smart contract code and report any security threats:\n\n${chunk}`,
// },
// ],
// },
// timeout: 10000,
// responseType: "json",
// });

// if (openAIRequest.data && openAIRequest.data.choices && openAIRequest.data.choices.length > 0) {
// results.push(openAIRequest.data.choices[0].message.content.trim());
// } else {
// throw new Error("Invalid response from OpenAI API: 'choices' array is missing or empty.");
// }
// }

// const finalResult = results.join("\n");
// console.log(`OpenAI security analysis of the contract address ${contractAddress} is:\n${finalResult}`);
// return Functions.encodeString(finalResult || "Failed");

// Return the aggregated content of the contract files
return Functions.encodeString(parsedSourceCode);
// } catch (error) {
// console.error("Error during the OpenAI request process:", error);
// return Functions.encodeString("Failed to fetch openAi request response");
// }
4 changes: 2 additions & 2 deletions packages/foundry/request-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ const requestConfig = {

// (optional) accessed within the source code with `secrets.varName` (ie: secrets.apiKey), must be a string.
secrets: {
apiKey: process.env.OPENAI_API_KEY,
openaiAPIKey: process.env.OPENAI_API_KEY,
etherscanAPIKey: process.env.ETHERSCAN_API_KEY
},

// args (array[""]): source code accesses via `args[index]`.
args: [
"0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512", // contractAddress [0]
"0xCf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9", // contractAddress [0]
],

// code language (JavaScript only)
Expand Down
4 changes: 2 additions & 2 deletions packages/nextjs/contracts/deployedContracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { GenericContractsDeclaration } from "~~/utils/scaffold-eth/contract";
const deployedContracts = {
31337: {
ScamHunterToken: {
address: "0x5fbdb2315678afecb367f032d93f642f64180aa3",
address: "0x9fe46736679d2d9a65f0992f2272de9f3c7fa6e0",
abi: [
{
type: "constructor",
Expand Down Expand Up @@ -463,7 +463,7 @@ const deployedContracts = {
},
},
Basic: {
address: "0xe7f1725e7734ce288f8367e1bb143e90bb3f0512",
address: "0xcf7ed3acca5a467e9e704c703e8d87f634fb0fc9",
abi: [
{
type: "constructor",
Expand Down

0 comments on commit 473e696

Please sign in to comment.