-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmycontract.sol
81 lines (69 loc) · 2.75 KB
/
mycontract.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
80
81
pragma solidity 0.6.6;
contract Splitwise{
struct CreditAcc{
address creditor; //the person who lends money
uint32 amount; //
}
//debtor address => creditor infor
mapping (address => CreditAcc[]) creditAccMap;
address[] users; //store all registered user's addresses.
function getUsers() public view returns(address[] memory){
return users;
}
//The debtor borrows money from the creditor
function lookup(address debtor, address creditor) public view returns (uint32 ret){
if(existCreditor(debtor, creditor)){
CreditAcc[] memory ca = creditAccMap[debtor];
for(uint i = 0; i < ca.length; i++){
if(ca[i].creditor == creditor){
return ca[i].amount;
}
}
}
return 0;
}
function add_Trans(address creditor, uint32 amount)public {
require(amount > 0);
require(msg.sender != creditor);
// This debtor doesn't have any creditor
if(!existAnyCreditor(msg.sender)){
CreditAcc[] storage creditAccArray;
// creditAccArray.push(CreditAcc(creditor, amount));
// creditAccMap[msg.sender] = creditAccArray;
creditAccMap[msg.sender].push(CreditAcc(creditor, amount));
// This debtor has creditors,but doesn't have this creditor
}else if(!existCreditor(msg.sender, creditor)){
creditAccMap[msg.sender].push(CreditAcc(creditor, amount));
}else {
CreditAcc[] storage caArr = creditAccMap[msg.sender];
for(uint i = 0; i < caArr.length; i++){
if(caArr[i].creditor == creditor)
caArr[i].amount += amount;
}
}
if(!existUser(creditor)) users.push(creditor);
if(!existUser(msg.sender)) users.push(msg.sender);
}
//----------------------------------------------------------
//helper functions
//----------------------------------------------------------
function existAnyCreditor(address debtor) private view returns(bool){
if(creditAccMap[debtor].length == 0) return false;
return true;
}
function existCreditor(address debtor, address creditor) private view returns(bool){
if(!existAnyCreditor(debtor)) return false;
CreditAcc[] memory caArr = creditAccMap[debtor];
for(uint i = 0; i < caArr.length; i++){
if(caArr[i].creditor == creditor)
return true;
}
return false;
}
function existUser(address u)private view returns(bool){
for(uint i = 0; i < users.length; i++){
if(users[i] == u) return true;
}
return false;
}
}