-- Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
-- SPDX-License-Identifier: Apache-2.0


module IouTrade where

import DA.Assert

import Iou

template IouTrade
  with
    buyer : Party
    seller : Party
    baseIouCid : IouCid
    baseIssuer : Party
    baseCurrency : Text
    baseAmount : Decimal
    quoteIssuer : Party
    quoteCurrency : Text
    quoteAmount : Decimal
  where
    signatory buyer

    controller seller can
      IouTrade_Accept : (IouCid, IouCid)
        with
          quoteIouCid : IouCid
        do
          baseIou <- fetch baseIouCid
          baseIssuer === baseIou.issuer
          baseCurrency === baseIou.currency
          baseAmount === baseIou.amount
          buyer === baseIou.owner
          quoteIou <- fetch quoteIouCid
          quoteIssuer === quoteIou.issuer
          quoteCurrency === quoteIou.currency
          quoteAmount === quoteIou.amount
          seller === quoteIou.owner
          quoteIouTransferCid <- exercise quoteIouCid Iou_Transfer with
            newOwner = buyer
          transferredQuoteIouCid <- exercise quoteIouTransferCid IouTransfer_Accept
          baseIouTransferCid <- exercise baseIouCid Iou_Transfer with
            newOwner = seller
          transferredBaseIouCid <- exercise baseIouTransferCid IouTransfer_Accept
          return (transferredQuoteIouCid, transferredBaseIouCid)

      TradeProposal_Reject : ()
        do return ()
