forked from Lilypad-Tech/lilypad-module-synthetic-data
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate.js
353 lines (295 loc) · 10.3 KB
/
generate.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
const fs = require("fs");
const axios = require("axios");
const seedrandom = require("seedrandom");
const archiver = require("archiver");
const solc = require("solc");
const ethers = require("ethers");
// Function to send logs to the remote logging service
async function sendLog(log) {
try {
await axios.post("https://logging.lilypad.team", { log });
} catch (error) {
console.error("Error sending log:", error);
}
}
// Wrapper to capture console logs and send them
const originalConsoleLog = console.log;
console.log = async function (...args) {
originalConsoleLog.apply(console, args);
await sendLog(args.join(" "));
};
const originalConsoleError = console.error;
console.error = async function (...args) {
originalConsoleError.apply(console, args);
await sendLog(args.join(" "));
};
console.log("Starting the contract generation process...");
function getRandomInt(rng, max) {
return Math.floor(rng() * max);
}
function getRandomAddress(rng) {
const address = `0x${Math.floor(rng() * 16 ** 40)
.toString(16)
.padStart(40, "0")}`;
return ethers.getAddress(address);
}
function generateERC20Contract(rng) {
const tokenName = `Token${getRandomInt(rng, 10000)}`;
const symbol = `TKN${getRandomInt(rng, 100)}`;
const totalSupply = getRandomInt(rng, 1e6) + 1e6;
const decimals = getRandomInt(rng, 18) + 1;
return `
pragma solidity ^0.8.0;
contract ${tokenName} {
string public name = "${tokenName}";
string public symbol = "${symbol}";
uint8 public decimals = ${decimals};
uint256 public totalSupply = ${totalSupply} * (10 ** uint256(decimals));
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
constructor() {
balanceOf[msg.sender] = totalSupply;
}
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= balanceOf[_from]);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
allowance[_from][msg.sender] -= _value;
emit Transfer(_from, _to, _value);
return true;
}
}
`;
}
function generateVotingContract(rng) {
const proposalCount = getRandomInt(rng, 5) + 1;
const proposals = Array.from(
{ length: proposalCount },
(_, i) => `Proposal${i + 1}`
).join(", ");
const duration = getRandomInt(rng, 30) + 1;
return `
pragma solidity ^0.8.0;
contract Voting {
struct Proposal {
string name;
uint256 voteCount;
}
Proposal[] public proposals;
mapping(address => bool) public hasVoted;
uint256 public votingDeadline;
constructor() {
votingDeadline = block.timestamp + ${duration} days;
${proposals
.split(", ")
.map((name) => `proposals.push(Proposal("${name}", 0));`)
.join("\n ")}
}
function vote(uint256 proposal) public {
require(!hasVoted[msg.sender], "Already voted.");
require(block.timestamp < votingDeadline, "Voting has ended.");
require(proposal < proposals.length, "Invalid proposal.");
proposals[proposal].voteCount += 1;
hasVoted[msg.sender] = true;
}
function winningProposal() public view returns (uint256 winningProposal_) {
uint256 winningVoteCount = 0;
for (uint256 p = 0; p < proposals.length; p++) {
if (proposals[p].voteCount > winningVoteCount) {
winningVoteCount = proposals[p].voteCount;
winningProposal_ = p;
}
}
}
}
`;
}
function generateCrowdfundingContract(rng) {
const goalAmount = getRandomInt(rng, 1e5) + 1e4;
const duration = getRandomInt(rng, 30) + 30;
const beneficiary = getRandomAddress(rng);
const minContribution = getRandomInt(rng, 1e3) + 1;
return `
pragma solidity ^0.8.0;
contract Crowdfunding {
address public beneficiary = ${beneficiary};
uint256 public goalAmount = ${goalAmount};
uint256 public deadline = block.timestamp + ${duration} days;
uint256 public amountRaised;
uint256 public minContribution = ${minContribution};
mapping(address => uint256) public balanceOf;
address[] public contributors;
event FundTransfer(address backer, uint256 amount, bool isContribution);
constructor(
address _beneficiary,
uint256 _goalAmount,
uint256 _duration,
uint256 _minContribution
) {
beneficiary = _beneficiary;
goalAmount = _goalAmount;
deadline = block.timestamp + (_duration * 1 days);
minContribution = _minContribution;
}
function contribute() public payable {
require(block.timestamp < deadline);
require(msg.value >= minContribution, "Contribution is below the minimum amount.");
balanceOf[msg.sender] += msg.value;
if (balanceOf[msg.sender] == 0) {
contributors.push(msg.sender);
}
balanceOf[msg.sender] += msg.value;
amountRaised += msg.value;
emit FundTransfer(msg.sender, msg.value, true);
}
function checkGoalReached() public {
require(block.timestamp >= deadline);
if (amountRaised >= goalAmount) {
payable(beneficiary).transfer(amountRaised);
emit FundTransfer(beneficiary, amountRaised, false);
} else {
for (uint256 i = 0; i < contributors.length; i++) {
address backer = contributors[i];
uint256 amount = balanceOf[backer];
if (amount > 0) {
payable(backer).transfer(amount);
balanceOf[backer] = 0;
emit FundTransfer(backer, amount, false);
}
}
}
}
}
`;
}
function generateEscrowContract(rng) {
const agent = getRandomAddress(rng);
const releaseCondition = getRandomInt(rng, 2) === 0 ? "time" : "milestone";
const releaseTime = getRandomInt(rng, 365) + 1;
return `
pragma solidity ^0.8.0;
contract Escrow {
address public agent = ${agent};
mapping(address => uint256) public deposits;
modifier onlyAgent() {
require(msg.sender == agent, "Only agent can call this.");
_;
}
function deposit(address payee) public onlyAgent payable {
uint256 amount = msg.value;
deposits[payee] += amount;
}
function withdraw(address payee) public onlyAgent {
${
releaseCondition === "time"
? `require(block.timestamp >= ${releaseTime} days, "Cannot withdraw before release time.");`
: `// Insert milestone check logic here`
}
uint256 payment = deposits[payee];
deposits[payee] = 0;
payable(payee).transfer(payment);
}
}
`;
}
function generateRandomContract(rng) {
const contractGenerators = [
generateERC20Contract,
generateVotingContract,
generateCrowdfundingContract,
generateEscrowContract,
];
const randomIndex = getRandomInt(rng, contractGenerators.length);
return contractGenerators[randomIndex](rng);
}
function saveContract(contractCode, filename) {
fs.writeFileSync(filename, contractCode, "utf8");
}
function createArchive(output, files) {
const archive = archiver("zip", {
zlib: { level: 9 },
});
const outputZip = fs.createWriteStream(output);
return new Promise((resolve, reject) => {
outputZip.on("close", resolve);
archive.on("error", reject);
archive.pipe(outputZip);
files.forEach((file) => {
archive.file(file, { name: file.split("/").pop() });
});
archive.finalize();
});
}
function validateContract(contractCode) {
const input = {
language: "Solidity",
sources: {
"Contract.sol": {
content: contractCode,
},
},
settings: {
outputSelection: {
"*": {
"*": ["*"],
},
},
},
};
const output = JSON.parse(solc.compile(JSON.stringify(input)));
if (output.errors) {
for (const error of output.errors) {
if (error.severity === "error") {
console.error("Contract validation error:", error);
return false;
}
}
}
return true;
}
const seed = process.env.SEED || "default-seed";
const numberOfContracts = parseInt(process.env.NUM_CONTRACTS, 10) || 10;
const outputZipFile = `./outputs/contracts_${seed}.zip`;
const rng = seedrandom(seed);
console.log(`Using seed: ${seed}`);
console.log(`Generating ${numberOfContracts} contracts`);
if (!fs.existsSync("./contracts")) {
fs.mkdirSync("./contracts");
}
if (!fs.existsSync("./outputs")) {
fs.mkdirSync("./outputs");
}
const contractFiles = [];
let validContractsCount = 0;
while (validContractsCount < numberOfContracts) {
const contractCode = generateRandomContract(rng);
const filename = `./contracts/${
contractCode.match(/contract (\w+)/)[1]
}_${validContractsCount}_seed_${seed}.sol`;
if (validateContract(contractCode)) {
saveContract(contractCode, filename);
contractFiles.push(filename);
validContractsCount++;
console.log(`Generated valid contract: ${filename}`);
} else {
console.error(`Invalid contract generated and skipped: ${filename}`);
}
}
createArchive(outputZipFile, contractFiles)
.then(() => console.log(`Contracts archived in ${outputZipFile}`))
.catch((err) => console.error(`Error creating archive: ${err}`));