Solidity
我如何計算有多少買家向我的智能合約提出請求並獲得了乙太幣
我正在使用工廠契約來銷售和購買商品。如何檢索有多少買家購買併計算出售商品賺取了多少乙太幣?這是我的原始碼。我是智能合約的新手
contract FactroyContract { address[] public contracts; address public lastContractAddresses; event newPurchaseContract (address contractAddress); function getContractcount() public view returns(uint ContracCount) { return contracts.length; } function newPurchase(uint value, string memory bookName, string memory description, string memory imageHash, string memory privHash, string memory dataHash) public payable returns(address NewContract) { Purchase c = new Purchase(address(msg.sender), value, bookName, description, imageHash, privHash, dataHash); contracts.push(c); lastContractAddresses = address(c); emit newPurchaseContract(c); return c; } function seePurchase(uint pos) public view returns(address contractAddress) { return address(contracts[pos]); } } contract Purchase { uint public price; address public seller; address[] public buyers; address public buyer; string public ipfsHash; string public preview; string public cover; string public name; string public text; constructor(address contractSeller, uint value, string memory bookName, string memory description, string memory imageHash, string memory privHash, string memory dataHash) public payable { seller = contractSeller; name = bookName; text = description; cover = imageHash; preview = privHash; ipfsHash = dataHash; price = value * 1000000000000000000; } modifier condition(bool _condition) { require(_condition); _; } modifier onlyBuyer() { (msg.sender == buyer); _; } modifier onlySeller() { (msg.sender == seller); _; } event ItemReceived(); function confrimReceived() public condition(msg.value == price) payable { emit ItemReceived(); buyer = msg.sender; seller.transfer(address(this).balance); } function getBuyerCount() public view returns(address buyerAddresses) { return buyers.length; } function getEtherCount() public view return(uint earnedEather) { return price+= msg.value; } }
智能合約內部
Purchase
定義了買家總數和總收入的計數器,如下所示:contract Purchase { uint public totalBuyers = 0; uint public totalEarnings = 0; ... }
然後,當確認購買時,適當增加這些計數器:
function confrimReceived() public condition(msg.value == price) payable { totalBuyers += 1; totalEarnings += price; ... }
只要計數器是公開的,您就可以從其他智能合約或鏈下應用程序,甚至從Etherscan.io查詢它們。