File size: 9,272 Bytes
86deab0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// scripts/deploy-all-testnets.js
// Deploy QuantumRandomnessOracle to all testnets

const { ethers } = require("hardhat");
const fs = require("fs");
const path = require("path");

// Deployment configuration
const DEPLOYMENT_CONFIG = {
  fee: ethers.utils.parseEther("0.01"), // 0.01 native token per request
  oracleNodeAddress: null, // Will be set to deployer address
};

// Testnet configurations
const TESTNETS = [
  {
    name: "sepolia",
    displayName: "Ethereum Sepolia",
    chainId: 11155111,
    explorer: "https://sepolia.etherscan.io",
    explorerApi: "https://api-sepolia.etherscan.io/api"
  },
  {
    name: "polygonAmoy",
    displayName: "Polygon Amoy",
    chainId: 80002,
    explorer: "https://amoy.polygonscan.com",
    explorerApi: "https://api-amoy.polygonscan.com/api"
  },
  {
    name: "bscTestnet",
    displayName: "BSC Testnet",
    chainId: 97,
    explorer: "https://testnet.bscscan.com",
    explorerApi: "https://api-testnet.bscscan.com/api"
  },
  {
    name: "avalancheFuji",
    displayName: "Avalanche Fuji",
    chainId: 43113,
    explorer: "https://testnet.snowtrace.io",
    explorerApi: "https://api-testnet.snowtrace.io/api"
  },
  {
    name: "fantomTestnet",
    displayName: "Fantom Testnet",
    chainId: 4002,
    explorer: "https://testnet.ftmscan.com",
    explorerApi: "https://api-testnet.ftmscan.com/api"
  }
];

async function deployToNetwork(networkName) {
  const networkConfig = TESTNETS.find(n => n.name === networkName);
  if (!networkConfig) {
    throw new Error(`Unknown network: ${networkName}`);
  }

  console.log(`\n========================================`);
  console.log(`Deploying to ${networkConfig.displayName}...`);
  console.log(`========================================`);

  // Get deployer
  const [deployer] = await ethers.getSigners();
  console.log("Deploying contracts with the account:", deployer.address);
  
  const balance = await deployer.getBalance();
  console.log("Account balance:", ethers.utils.formatEther(balance), "ETH");

  // Set oracle node address to deployer
  DEPLOYMENT_CONFIG.oracleNodeAddress = deployer.address;

  // Deploy contract
  console.log("\nDeploying QuantumRandomnessOracle...");
  console.log("Fee:", ethers.utils.formatEther(DEPLOYMENT_CONFIG.fee), "ETH");
  console.log("Oracle Node:", DEPLOYMENT_CONFIG.oracleNodeAddress);

  const QuantumRandomnessOracle = await ethers.getContractFactory("QuantumRandomnessOracle");
  const oracleContract = await QuantumRandomnessOracle.deploy(
    DEPLOYMENT_CONFIG.fee,
    DEPLOYMENT_CONFIG.oracleNodeAddress
  );

  console.log("Waiting for deployment...");
  await oracleContract.deployed();

  console.log("βœ“ QuantumRandomnessOracle deployed to:", oracleContract.address);
  console.log("Explorer URL:", `${networkConfig.explorer}/tx/${oracleContract.deployTransaction.hash}`);

  // Wait for additional confirmations
  console.log("Waiting for 5 confirmations...");
  await oracleContract.deployTransaction.wait(5);
  console.log("βœ“ Deployment confirmed");

  return {
    network: networkName,
    displayName: networkConfig.displayName,
    chainId: networkConfig.chainId,
    contractAddress: oracleContract.address,
    deployerAddress: deployer.address,
    fee: DEPLOYMENT_CONFIG.fee.toString(),
    deploymentTxHash: oracleContract.deployTransaction.hash,
    explorerUrl: `${networkConfig.explorer}/address/${oracleContract.address}`,
    deploymentTimestamp: new Date().toISOString()
  };
}

async function verifyContract(networkName, contractAddress) {
  console.log(`\nVerifying contract on ${networkName}...`);
  
  try {
    await hre.run("verify:verify", {
      address: contractAddress,
      constructorArguments: [
        DEPLOYMENT_CONFIG.fee,
        DEPLOYMENT_CONFIG.oracleNodeAddress
      ]
    });
    console.log("βœ“ Contract verified successfully");
    return true;
  } catch (error) {
    console.log("βœ— Contract verification failed:", error.message);
    return false;
  }
}

async function saveDeploymentResults(results) {
  const deploymentsDir = path.join(__dirname, "../deployments");
  
  // Create deployments directory if it doesn't exist
  if (!fs.existsSync(deploymentsDir)) {
    fs.mkdirSync(deploymentsDir, { recursive: true });
  }

  // Save individual network deployments
  results.forEach(result => {
    const filename = `deployment-${result.network}.json`;
    const filepath = path.join(deploymentsDir, filename);
    fs.writeFileSync(filepath, JSON.stringify(result, null, 2));
    console.log(`βœ“ Saved deployment info: ${filename}`);
  });

  // Save combined deployment summary
  const summary = {
    deploymentDate: new Date().toISOString(),
    totalNetworks: results.length,
    deployments: results,
    summary: results.map(r => ({
      network: r.network,
      displayName: r.displayName,
      contractAddress: r.contractAddress,
      explorerUrl: r.explorerUrl
    }))
  };

  const summaryPath = path.join(deploymentsDir, "deployment-summary.json");
  fs.writeFileSync(summaryPath, JSON.stringify(summary, null, 2));
  console.log(`βœ“ Saved deployment summary: deployment-summary.json`);

  // Save as Markdown report
  const mdReport = generateMarkdownReport(summary);
  const mdPath = path.join(deploymentsDir, "DEPLOYMENT_REPORT.md");
  fs.writeFileSync(mdPath, mdReport);
  console.log(`βœ“ Saved deployment report: DEPLOYMENT_REPORT.md`);
}

function generateMarkdownReport(summary) {
  let md = `# QuantumRandomnessOracle Deployment Report\n\n`;
  md += `**Deployment Date:** ${summary.deploymentDate}\n\n`;
  md += `**Total Networks:** ${summary.totalNetworks}\n\n`;
  md += `---\n\n`;
  md += `## Contract Addresses\n\n`;
  md += `| Network | Contract Address | Explorer |\n`;
  md += `|---------|-----------------|----------|\n`;
  
  summary.deployments.forEach(dep => {
    md += `| ${dep.displayName} | \`${dep.contractAddress}\` | [View](${dep.explorerUrl}) |\n`;
  });
  
  md += `\n---\n\n`;
  md += `## Deployment Details\n\n`;
  
  summary.deployments.forEach(dep => {
    md += `### ${dep.displayName}\n\n`;
    md += `- **Contract Address:** \`${dep.contractAddress}\`\n`;
    md += `- **Chain ID:** ${dep.chainId}\n`;
    md += `- **Deployer:** \`${dep.deployerAddress}\`\n`;
    md += `- **Fee:** ${ethers.utils.formatEther(dep.fee)} ETH\n`;
    md += `- **Deployment TX:** [${dep.deploymentTxHash.slice(0, 10)}...${dep.deploymentTxHash.slice(-8)}](${dep.explorerUrl})\n`;
    md += `- **Timestamp:** ${dep.deploymentTimestamp}\n\n`;
  });
  
  md += `---\n\n`;
  md += `## Usage\n\n`;
  md += `### Add to Configuration\n\n`;
  md += `\`\`\`bash\n`;
  md += `# Add these to your .env file or app/config.py\n`;
  summary.deployments.forEach(dep => {
    const envName = dep.network.toUpperCase().replace('TESTNET', '').replace('FUJI', 'AVALANCHE');
    md += `${envName}_ORACLE_CONTRACT="${dep.contractAddress}"\n`;
  });
  md += `\`\`\`\n\n`;
  
  md += `### API Configuration\n\n`;
  md += `\`\`\`python\n`;
  md += `# app/config.py or environment variables\n`;
  summary.deployments.forEach(dep => {
    const envName = dep.network.toUpperCase().replace('TESTNET', '').replace('FUJI', 'AVALANCHE');
    md += `ORACLE_CONTRACT_${envName} = "${dep.contractAddress}"\n`;
  });
  md += `\`\`\`\n\n`;
  
  return md;
}

async function main() {
  console.log("==============================================");
  console.log("QuantumRandomnessOracle Multi-Network Deploy");
  console.log("==============================================\n");

  const results = [];
  const failed = [];

  // Get deployment targets from command line or deploy to all testnets
  const targetNetworks = process.argv.length > 2 
    ? process.argv.slice(2)
    : TESTNETS.map(n => n.name);

  console.log("Target networks:", targetNetworks.join(", "));

  // Deploy to each network
  for (const networkName of targetNetworks) {
    try {
      // Switch network
      await hre.network.change(networkName);
      
      const result = await deployToNetwork(networkName);
      results.push(result);

      // Verify contract (optional, requires API key)
      if (process.env.SKIP_VERIFICATION !== "true") {
        await verifyContract(networkName, result.contractAddress);
      }
    } catch (error) {
      console.error(`\nβœ— Deployment to ${networkName} failed:`, error.message);
      failed.push({ network: networkName, error: error.message });
    }
  }

  // Save results
  if (results.length > 0) {
    await saveDeploymentResults(results);
  }

  // Summary
  console.log("\n==============================================");
  console.log("Deployment Summary");
  console.log("==============================================");
  console.log(`Successful: ${results.length}/${targetNetworks.length}`);
  console.log(`Failed: ${failed.length}/${targetNetworks.length}`);

  if (failed.length > 0) {
    console.log("\nFailed deployments:");
    failed.forEach(f => {
      console.log(`  - ${f.network}: ${f.error}`);
    });
  }

  if (results.length > 0) {
    console.log("\nβœ“ Deployments complete!");
    console.log("Check deployments/ folder for contract addresses and details.");
  }
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error("Fatal error:", error);
    process.exit(1);
  });