;; Pottery Guild - Artisan pottery cooperative
;; Halal - honest craftsmanship
(define-constant CONTRACT-OWNER tx-sender)
(define-constant ERR-AUTH (err u401))
(define-constant ERR-NONE (err u404))
(define-data-var artisan-count uint u0)
(define-data-var piece-count uint u0)
(define-map artisans principal { name: (string-utf8 100), pieces: uint, sales: uint })
(define-map pottery uint { artisan: principal, name: (string-utf8 100), price: uint, sold: bool })
(define-public (join-guild (name (string-utf8 100)))
(begin (map-set artisans tx-sender { name: name, pieces: u0, sales: u0 })
(var-set artisan-count (+ (var-get artisan-count) u1)) (ok true)))
(define-public (create-piece (name (string-utf8 100)) (price uint))
(let ((id (+ (var-get piece-count) u1)) (a (unwrap! (map-get? artisans tx-sender) ERR-NONE)))
(map-set pottery id { artisan: tx-sender, name: name, price: price, sold: false })
(map-set artisans tx-sender (merge a { pieces: (+ (get pieces a) u1) }))
(var-set piece-count id) (ok id)))
(define-public (buy-piece (id uint))
(let ((p (unwrap! (map-get? pottery id) ERR-NONE)) (a (unwrap! (map-get? artisans (get artisan p)) ERR-NONE)))
(asserts! (not (get sold p)) ERR-NONE)
(try! (stx-transfer? (get price p) tx-sender (get artisan p)))
(map-set pottery id (merge p { sold: true }))
(map-set artisans (get artisan p) (merge a { sales: (+ (get sales a) u1) })) (ok true)))
(define-read-only (get-artisan (who principal)) (map-get? artisans who))
(define-read-only (get-piece (id uint)) (map-get? pottery id))
(define-read-only (get-stats) (ok { artisans: (var-get artisan-count), pieces: (var-get piece-count) }))