-
Notifications
You must be signed in to change notification settings - Fork 0
/
bookchain.sol
79 lines (62 loc) · 1.8 KB
/
bookchain.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
pragma solidity ^0.4.2;
contract Bookchain {
mapping(uint => Book) books;
uint nextId = 0;
struct Book {
uint id;
address origin;
address user;
uint price;
uint donated;
bytes[] comments;
string isbn;
}
event bookAdded(uint id);
event bookFreed(uint id);
function addBook(uint _price, string _isbn) {
uint _id = nextId++;
var book = books[_id];
book.origin = msg.sender;
book.user = msg.sender;
book.price = _price;
book.isbn = _isbn;
bookAdded(_id);
}
function free_book(uint _id) {
var book = books[_id];
if (msg.sender != book.origin) throw;
book.user = 0x0;
bookFreed(_id);
}
function borrow_book(uint _id) {
var book = books[_id];
if (book.user != 0x0) throw;
book.user = msg.sender;
}
function comment(uint _id, bytes _ipfs_hash) {
var book = books[_id];
book.comments.push(_ipfs_hash);
}
function donate(uint _id) {
// Get book
Book book = books[_id];
// If donation limit reached -> throw
if (book.donated >= book.price) throw;
// Calculate remaining donation space
uint remaining = book.price - book.donated;
// Default: donation == amount sent, diff == 0
uint donation = msg.value;
uint diff = 0;
// Cap donation to remaining space
if (donation > remaining) {
donation = remaining;
diff = msg.value - donation;
}
// Send donation to owner
if (!book.origin.send(donation)) throw;
// If diff between amount sent and donation, refund sender
if (diff > 0) {
if (!msg.sender.send(diff)) throw;
}
}
}