|
| 1 | +// scripts/offchain_processing.js |
| 2 | + |
| 3 | +const { create } = require('ipfs-http-client'); |
| 4 | +const { ethers } = require('ethers'); |
| 5 | +require('dotenv').config(); // Load environment variables from .env file |
| 6 | + |
| 7 | +// Initialize IPFS client |
| 8 | +const ipfs = create({ url: 'https://ipfs.infura.io:5001' }); |
| 9 | + |
| 10 | +// Connect to Ethereum network |
| 11 | +const provider = new ethers.providers.JsonRpcProvider(process.env.INFURA_URL); |
| 12 | +const wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider); |
| 13 | +const oracleContractAddress = process.env.ORACLE_CONTRACT_ADDRESS; |
| 14 | +const oracleABI = require('./OracleABI.json'); // Import the ABI of the Oracle contract |
| 15 | +const oracleContract = new ethers.Contract(oracleContractAddress, oracleABI, wallet); |
| 16 | + |
| 17 | +// Function to store data on IPFS |
| 18 | +async function storeDataOnIPFS(data) { |
| 19 | + try { |
| 20 | + const { cid } = await ipfs.add(JSON.stringify(data)); |
| 21 | + console.log(`Data stored on IPFS with CID: ${cid}`); |
| 22 | + return cid.toString(); |
| 23 | + } catch (error) { |
| 24 | + console.error('Error storing data on IPFS:', error); |
| 25 | + throw error; |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +// Function to submit data to the Oracle contract |
| 30 | +async function submitDataToOracle(dataType, data) { |
| 31 | + try { |
| 32 | + const tx = await oracleContract.submitData(dataType, data); |
| 33 | + await tx.wait(); // Wait for the transaction to be mined |
| 34 | + console.log(`Data submitted to Oracle: ${dataType} - ${data}`); |
| 35 | + } catch (error) { |
| 36 | + console.error('Error submitting data to Oracle:', error); |
| 37 | + throw error; |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +// Main function to handle off-chain processing |
| 42 | +async function main() { |
| 43 | + // Example data to process |
| 44 | + const dataToProcess = { |
| 45 | + price: 3000, |
| 46 | + timestamp: new Date().toISOString(), |
| 47 | + source: 'Edge Node', |
| 48 | + }; |
| 49 | + |
| 50 | + // Step 1: Store data on IPFS |
| 51 | + const cid = await storeDataOnIPFS(dataToProcess); |
| 52 | + |
| 53 | + // Step 2: Submit the CID to the Oracle contract |
| 54 | + await submitDataToOracle('ETH/USD', cid); |
| 55 | +} |
| 56 | + |
| 57 | +// Execute the main function |
| 58 | +main() |
| 59 | + .then(() => console.log('Off-chain processing completed successfully.')) |
| 60 | + .catch((error) => console.error('Error in off-chain processing:', error)); |
0 commit comments