Source Code

;; Mosque Library - Masjid library management
;; Halal - knowledge in the masjid
(define-constant CONTRACT-OWNER tx-sender)
(define-constant ERR-AUTH (err u401))
(define-constant ERR-NONE (err u404))
(define-data-var book-count uint u0)
(define-data-var borrow-count uint u0)
(define-map lib-books uint { title: (string-utf8 100), author: (string-utf8 100), available: bool })
(define-map borrows uint { book-id: uint, borrower: principal, returned: bool, block: uint })
(define-public (add-book (title (string-utf8 100)) (author (string-utf8 100)))
  (let ((id (+ (var-get book-count) u1)))
    (asserts! (is-eq tx-sender CONTRACT-OWNER) ERR-AUTH)
    (map-set lib-books id { title: title, author: author, available: true })
    (var-set book-count id) (ok id)))
(define-public (borrow (book-id uint))
  (let ((b (unwrap! (map-get? lib-books book-id) ERR-NONE)) (bid (+ (var-get borrow-count) u1)))
    (asserts! (get available b) ERR-NONE)
    (map-set lib-books book-id (merge b { available: false }))
    (map-set borrows bid { book-id: book-id, borrower: tx-sender, returned: false, block: stacks-block-height })
    (var-set borrow-count bid) (ok bid)))
(define-public (return-book (borrow-id uint))
  (let ((br (unwrap! (map-get? borrows borrow-id) ERR-NONE)))
    (asserts! (is-eq tx-sender (get borrower br)) ERR-AUTH)
    (map-set borrows borrow-id (merge br { returned: true }))
    (map-set lib-books (get book-id br) { title: u"", author: u"", available: true }) (ok true)))
(define-read-only (get-book (id uint)) (map-get? lib-books id))
(define-read-only (get-borrow (id uint)) (map-get? borrows id))

Functions (5)

FunctionAccessArgs
add-bookpublictitle: (string-utf8 100
borrowpublicbook-id: uint
return-bookpublicborrow-id: uint
get-bookread-onlyid: uint
get-borrowread-onlyid: uint