Created
August 7, 2023 15:49
-
-
Save OkoliEvans/198bd6090193028dc7c404b06edbb8db to your computer and use it in GitHub Desktop.
Supply chain system: Refactor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
contract SupplyChain { | |
address public owner; | |
uint public productCount; | |
struct Product { | |
uint id; | |
string name; | |
string description; | |
address manufacturer; | |
address[] supplyChainHistory; | |
} | |
mapping(uint => Product) public products; | |
modifier onlyOwner() { | |
require(msg.sender == owner, "Only the owner can perform this action"); | |
_; | |
} | |
constructor() { | |
owner = msg.sender; | |
} | |
function addProduct(string memory _name, string memory _description) external onlyOwner { | |
productCount++; // very gas intensive, pass product id as parameter | |
products[productCount] = Product(productCount, _name, _description, msg.sender, new address[](0)); | |
} | |
// function getProduct(uint _productId) external view returns ( | |
// uint id, | |
// string memory name, | |
// string memory description, | |
// address manufacturer, | |
// address[] memory supplyChainHistory | |
// ) { | |
// require(_productId > 0 && _productId <= productCount, "Invalid product ID"); | |
// Product memory product = products[_productId]; | |
// return ( | |
// product.id, | |
// product.name, | |
// product.description, | |
// product.manufacturer, | |
// product.supplyChainHistory | |
// ); | |
// } | |
/// @notice Function returns struct Product; this is the simplest way to do this. | |
/// Solidity also generates a public function automatically to return the products mapping for you because the mapping is public | |
function products_(uint product_id) external view returns (Product memory) { | |
Product memory product = products[product_id]; | |
return product; | |
} | |
function addToSupplyChain(uint _productId) external { | |
require(_productId > 0 && _productId <= productCount, "Invalid product ID"); | |
Product storage product = products[_productId]; | |
require(msg.sender == product.manufacturer, "Only the manufacturer can add to the supply chain"); | |
// Add the current user to the supply chain history | |
product.supplyChainHistory.push(msg.sender); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment