
;; mega-escrow-v1
;; Mega Escrow

;; constants
(define-constant CONTRACT-OWNER tx-sender)

(define-constant ERR-NOT-AUTHORIZED (err u401))

;; data maps and vars
(define-data-var balanceMEGA uint u0)
(define-data-var price uint u10)


;; read-only functions
(define-read-only (get-balances)
  {balanceSTX: (stx-get-balance (as-contract tx-sender)), balanceMEGA: (var-get balanceMEGA)}
)

(define-read-only (get-price)
  (var-get price)
)

;; private functions
(define-private (is-valid-caller)
    (is-eq CONTRACT-OWNER tx-sender)
)

;; public functions
;;

(define-public (buy (amount uint))
  (begin
    (try! (stx-transfer? (* amount (var-get price)) tx-sender (as-contract tx-sender)))
    (try! (as-contract (contract-call? .mega transfer amount tx-sender CONTRACT-OWNER none)))
    (var-set balanceMEGA (- (var-get balanceMEGA) amount))
    (ok "Successfully sold")
  )
)

;; everybody can deposit STX to the escrow account
(define-public (depositSTX (amount uint))
  ;;(asserts! (is-valid-caller) ERR-NOT-AUTHORIZED)
  (stx-transfer? amount tx-sender (as-contract tx-sender))
)

;; everybody can deposit MEGA to the escrow account
(define-public (depositMEGA (amount uint))
  ;;(asserts! (is-valid-caller) ERR-NOT-AUTHORIZED)
  (begin 
    (var-set balanceMEGA (+ (var-get balanceMEGA) amount))
    (contract-call? .mega transfer amount tx-sender (as-contract tx-sender) none)
  )
)

;; sends the deposited amounts back to contract owner
(define-public (payout-balance)
  (begin
    (asserts! (is-valid-caller) ERR-NOT-AUTHORIZED)
    (try! (as-contract (stx-transfer? (stx-get-balance tx-sender) tx-sender CONTRACT-OWNER)))
    (try! (as-contract (contract-call? .mega transfer (var-get balanceMEGA) tx-sender CONTRACT-OWNER none)))
    ;; (try! (as-contract (contract-call? .mega transfer u1 tx-sender CONTRACT-OWNER none)))
    (var-set balanceMEGA u0)
    (ok "Deposited amount sent back to contract")
  )
)
