Skip to content

Instantly share code, notes, and snippets.

@ivanbreet
Forked from poffdeluxe/loan.sol
Created October 23, 2018 15:40
Show Gist options
  • Save ivanbreet/af63840b6228b538ae2b470d792c66ea to your computer and use it in GitHub Desktop.
Save ivanbreet/af63840b6228b538ae2b470d792c66ea to your computer and use it in GitHub Desktop.
Smart Loan Contract for SmartFin
pragma solidity ^0.4.0;
contract Loan {
uint principal;
uint public total; // principal + interest rate
uint interest;
uint public dueDate;
bool public isFunded;
bool public isComplete;
uint public amountPaid; // amount of the total that has been paid by borrower
uint public collateralPaid; // amount paid in collateral -- TODO: collateral system is not implemented atm
address backendAddr;
address lenderAddr;
address borrowerAddr;
event ContractIsFunded(address lenderAddress, uint amount);
event ContractIsComplete();
event ListingIsCancelled();
// Called by our backend to create the loan and get going
function Loan(uint _principal, uint _interest, uint _numDays, address _lenderAddr) {
backendAddr = msg.sender;
lenderAddr = _lenderAddr;
principal = _principal;
interest = _interest;
total = _interest + _principal;
dueDate = now + _numDays * 1 days;
isFunded = false;
amountPaid = 0;
collateralPaid = 0;
isComplete = false;
}
// Called by the creditor to put their money into the loan
function fund() payable {
if(msg.sender != lenderAddr) throw;
if(msg.value != principal) throw;
if(isFunded) throw;
isFunded = true;
ContractIsFunded(msg.sender, msg.value);
}
// Cancel the loan but only if no one has borrowed
function cancel() {
if(msg.sender == lenderAddr && borrowerAddr != address(0)) {
ListingIsCancelled();
selfdestruct(msg.sender);
}
}
// Tell contract where the loan is coming from
function setBorrower(address _borrowerAddr) {
if(borrowerAddr != address(0) || msg.sender != backendAddr) throw;
borrowerAddr = _borrowerAddr;
if(!borrowerAddr.send(principal))
throw;
}
function pay() payable {
// prevent overpayment
//if (amountPaid >= total || amountPaid + msg.value > total)
// throw;
amountPaid += msg.value;
if(amountPaid >= total && collateralPaid > 0) {
// Release collateral -- this loan is complete!
if(!borrowerAddr.send(collateralPaid))
throw;
}
isComplete = (amountPaid >= total);
if (isComplete)
ContractIsComplete();
}
function withdraw() {
if(msg.sender != lenderAddr) throw;
if(amountPaid > 0) {
if(!lenderAddr.send(amountPaid))
throw;
}
if(now > dueDate && amountPaid <= total) {
// TODO: this isn't super accurate since someone could have partially
// paid the loan
if(!lenderAddr.send(collateralPaid))
throw;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment