Transferring and Retrieving Energy Contract Data
I need help sending and reading energy-related data to and from a blockchain using JavaScript and web3.js with a local blockchain. Below are updated Solidity and frontend code examples.
pragma solidity ^0.8.0;
contract EnergyExchange {
struct EnergyData {
uint cost;
uint quantity;
string source;
address creator;
}
EnergyData[] public entries;
mapping(uint => address) public entryCreator;
mapping(address => uint) public creatorCount;
function _addData(uint _cost, uint _quantity, string memory _source) internal {
uint index = entries.length;
entries.push(EnergyData(_cost, _quantity, _source, msg.sender));
entryCreator[index] = msg.sender;
creatorCount[msg.sender]++;
}
function registerData(uint _cost, uint _quantity, string memory _source) public {
require(creatorCount[msg.sender] == 0, "Already registered");
_addData(_cost, _quantity, _source);
}
}
const Web3Lib = require('web3');
const web3Instance = new Web3Lib('http://localhost:8545');
const energyAbi = [/* ABI definition */];
const energyAddress = '0xAbc123...';
const energyContract = new web3Instance.eth.Contract(energyAbi, energyAddress);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Energy Data Interface</title>
</head>
<body>
<input id="cost" type="text" placeholder="Cost">
<input id="quantity" type="text" placeholder="Quantity">
<input id="source" type="text" placeholder="Source">
<button onclick="submitData()">Submit</button>
<script>
async function submitData() {
// Implement transaction with energyContract
}
</script>
</body>
</html>