-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBookBorrowing.sol
60 lines (49 loc) · 2.22 KB
/
BookBorrowing.sol
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
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "./BookLibrary.sol";
contract BookBorrowing is BookLibrary {
// borrowed books by address
mapping (address => mapping (uint => BorrowedBook)) public borrowings;
mapping (uint => address[]) borrowersByBook;
function listAvailableBooks() external view returns (Book[] memory) {
uint counter = 0;
for (uint i = 0; i < isbns.length; i++) {
uint bookId = uint(keccak256(abi.encodePacked(isbns[i])));
if (availability[bookId] > 0) {
counter++;
}
}
Book[] memory availableBooks = new Book[](counter);
counter = 0;
for (uint i = 0; i < isbns.length; i++) {
uint bookId = uint(keccak256(abi.encodePacked(isbns[i])));
if (availability[bookId] > 0) {
availableBooks[counter] = Book(books[bookId].name, books[bookId].author, books[bookId].isbn, availability[bookId]);
counter++;
}
}
return availableBooks;
}
function listBorrowersByBook(string memory _isbn) external view returns (address[] memory) {
uint bookId = uint(keccak256(abi.encodePacked(_isbn)));
return borrowersByBook[bookId];
}
function borrowBook(string memory _isbn) external {
uint bookId = uint(keccak256(abi.encodePacked(_isbn)));
require(!borrowings[msg.sender][bookId].borrowed, "Book already borrowed");
require(availability[bookId] > 0, "No copies available");
borrowings[msg.sender][bookId].borrowed = true;
// insert borrower only first time they borrow a book
if (!borrowings[msg.sender][bookId].previouslyBorrowed) {
borrowings[msg.sender][bookId].previouslyBorrowed = true;
borrowersByBook[bookId].push(msg.sender);
}
availability[bookId] -= 1;
}
function returnBook(string memory _isbn) external {
uint bookId = uint(keccak256(abi.encodePacked(_isbn)));
require(borrowings[msg.sender][bookId].borrowed, "Book was not previously borrowed");
borrowings[msg.sender][bookId].borrowed = false;
availability[bookId] += 1;
}
}