Source Code

;; miswak-shop -- halal miswak & dental care marketplace
(define-constant CONTRACT-OWNER tx-sender)
(define-constant ERR-AUTH (err u401))
(define-constant ERR-NONE (err u404))
(define-data-var product-count uint u0)
(define-data-var order-count uint u0)
(define-map products uint { vendor: principal, name: (string-utf8 100), price: uint, stock: uint, active: bool })
(define-map orders uint { product-id: uint, buyer: principal, quantity: uint, total: uint, fulfilled: bool, block: uint })

(define-public (add-product (name (string-utf8 100)) (price uint) (stock uint))
  (let ((id (+ (var-get product-count) u1)))
    (var-set product-count id)
    (map-set products id { vendor: tx-sender, name: name, price: price, stock: stock, active: true })
    (ok id)))

(define-public (place-order (product-id uint) (quantity uint))
  (let ((id (+ (var-get order-count) u1))
        (p (unwrap! (map-get? products product-id) ERR-NONE)))
    (asserts! (>= (get stock p) quantity) ERR-AUTH)
    (var-set order-count id)
    (map-set products product-id (merge p { stock: (- (get stock p) quantity) }))
    (map-set orders id { product-id: product-id, buyer: tx-sender, quantity: quantity, total: (* quantity (get price p)), fulfilled: false, block: stacks-block-height })
    (ok id)))

(define-public (fulfill-order (id uint))
  (let ((o (unwrap! (map-get? orders id) ERR-NONE)))
    (map-set orders id (merge o { fulfilled: true })) (ok true)))

(define-read-only (get-product (id uint)) (map-get? products id))
(define-read-only (get-order (id uint)) (map-get? orders id))

Functions (5)

FunctionAccessArgs
add-productpublicname: (string-utf8 100
place-orderpublicproduct-id: uint, quantity: uint
fulfill-orderpublicid: uint
get-productread-onlyid: uint
get-orderread-onlyid: uint