제33장. 원자적 교환: DvP, PvP, 다자 일괄 정산

시야 분리와 전부-또는-전무 결제

핵심 키워드: Atomic DvP (Delivery versus Payment) · Cross-Currency PvP · Sub-transaction Privacy · SettlementInstruction · CIP-0056 Allocation · ExecuteBatchSettlement
"인도 대 지급이란, 지급이 이루어질 때에만 인도가 이루어지도록 보장하는 장치를 만드는 일이다." — 지급결제제도위원회, 「증권결제시스템의 인도 대 지급」 제2.14절, 바젤, 1992년 9월

1. 패턴 33.1 · 인터페이스 기반 양자 DvP (AtomicDvPProposal)

문제

증권과 대금을 맞바꿀 때 어느 쪽도 먼저 넘기고 싶어 하지 않습니다. 먼저 인도한 쪽은 상대가 지급하지 않을 위험, 곧 원금 위험(principal risk)을 집니다. 제2장의 1974년 헤르슈타트 은행(Bankhaus Herstatt) 사례는 시차 때문에 마르크화를 먼저 받고 뉴욕의 달러 지급이 이행되지 않은 순차 결제의 실패였습니다. 해법은 인도와 지급을 하나의 원자적 단위로 묶는 인도결제(Delivery versus Payment, DvP)입니다.

계약 설계

Daml에서는 인도와 지급을 한 초이스(SettleDvP) 안의 두 하위 행사로 둡니다. 한 트랜잭션은 통째로 커밋되거나 통째로 거절되므로 한쪽만 이전되는 상태가 생기지 않습니다. 결제 계약은 제32장의 interface Holding만 다룹니다. 매도인의 자산이 국채든 주식이든 토큰화 증권이든, 매수인의 대금이 예금 토큰이든 기관용 스테이블코인이든 Holding을 구현하면 결제 코드를 고치지 않고 당일 결제(T+0)할 수 있습니다.

1970년대 벨 연구소 매뉴얼 스타일로 그려진 정밀한 양방향 황동 회전문 교환기: 왼쪽 칸에 놓인 증권 증서와 오른쪽 칸에 놓인 현금 예금 증서가 단일 기어 축으로 맞물려 정확히 180도 동시 회전하며 두 거래 당사자의 손으로 한 치의 시차 없이 넘어가는 스팟 일러스트
[FIG 33.1] 인터페이스 기반 DvP(AtomicDvPProposal). 증권 보유분과 현금 보유분의 이전이 한 Daml 초이스에 묶여 함께 커밋되거나 함께 거절된다.
삽화 구성 및 생성 프롬프트 보기 열기 / 닫기
연출 의도: 두 당사자가 서로를 신뢰하지 않아도 원금 리스크 없이 T+0 즉시 맞교환을 달성하는 원자적 DvP 메커니즘을 단일 기어 축으로만 회전하는 정밀 황동 회전문으로 시각화.
Minimalist abstract 1970s Bell Labs engineering manual doodle and vintage Saul Steinberg editorial spot cartoon on empty aged warm-gray newsprint paper. In the center, a precision two-compartment brass revolving transfer turnstile locked to a single central gear shaft: on the left side, a bond certificate rests in chamber A; on the right side, a stack of crisp bank notes rests in chamber B. Two minimalist figures stand on opposite sides as the single gear rotates both chambers 180 degrees simultaneously—impossible for one side to move without the other. Dry intellectual wit, 75% negative space, warm off-white newsprint background, coarse off-register gray Zip-A-Tone screen-tone shading, raw dip-pen black ink linework, flat 2D graphic art, zero gradients, zero text, zero letters or words anywhere in the image. --ar 16:9
패턴 / 결제 계약 서명자 (signatory) 결제 실행자 (controller) 원자적 소비·생성 및 프라이버시 경계
33.1 AtomicDvPProposal seller (sellerCashAccount.owner) buyer (SettleDvP) 증권·현금 Holding 이전과 DvPSettlementReceipt 생성을 한 트랜잭션에서 실행 (원자성으로 원금 위험 제거)
33.2 CrossCurrencyPvP partyA (제안) / partyA, partyB (체결) partyB (ExecutePvP) 두 통화 다리를 한 트랜잭션에서 교환, 각 발행 은행에는 자기 통화 다리만 전달(서브트랜잭션 프라이버시)
33.3 BatchSettlementCoordinator operator (다리별 AllocatedLeg는 operator·송신인·수신인) operator (ExecuteBatchSettlement) \(K\)개 다리를 모두 할당한 뒤 전부 체결 또는 전부 거절(All-or-Nothing)

코드

패턴 33.1 · Holding 인터페이스 기반 양자 DvP (AtomicDvPProposal) Daml
module Patterns.AtomicDvP where

import Patterns.HoldingStandard
  ( InstrumentKey(..), AccountKey(..), Holding, Transfer(..) )

-- 결제 후 양 당사자에게 남는 결제 확인 기록
template DvPSettlementReceipt
  with
    tradeId          : Text
    seller           : Party
    buyer            : Party
    deliveryInst     : InstrumentKey
    deliveryAmount   : Decimal
    paymentInst      : InstrumentKey
    paymentAmount    : Decimal
    settledAt        : Time
  where
    signatory seller, buyer

-- 매도인이 증권 보유분과 결제 조건을 걸어 제안하는 DvP 계약
template AtomicDvPProposal
  with
    tradeId             : Text
    sellerAssetCid      : ContractId Holding
    sellerCashAccount   : AccountKey
    buyerAssetAccount   : AccountKey
    expectedAssetInst   : InstrumentKey
    expectedAssetAmount : Decimal
    expectedCashInst    : InstrumentKey
    expectedCashAmount  : Decimal
    expiresAt           : Time
  where
    signatory sellerCashAccount.owner
    observer buyerAssetAccount.owner
    ensure expectedAssetAmount > 0.0 && expectedCashAmount > 0.0 && tradeId /= ""

    -- 매수인이 현금 Holding을 넣어 행사하면 증권 이전과 현금 이전이 한 트랜잭션에서 실행된다
    choice SettleDvP : (ContractId Holding, ContractId Holding, ContractId DvPSettlementReceipt)
      with
        buyerCashCid : ContractId Holding
      controller buyerAssetAccount.owner
      do
        now <- getTime
        assertMsg "DVP_OFFER_EXPIRED" (now <= expiresAt)

        assetHolding <- fetch sellerAssetCid
        cashHolding  <- fetch buyerCashCid
        let assetView = view assetHolding
        let cashView  = view cashHolding

        -- 1. 인도 증권 다리(Delivery Leg) 정합성 검증
        assertMsg "SELLER_NOT_ASSET_OWNER" (assetView.account.owner == sellerCashAccount.owner)
        assertMsg "ASSET_INSTRUMENT_MISMATCH" (assetView.instrument == expectedAssetInst)
        assertMsg "ASSET_AMOUNT_MISMATCH" (assetView.amount == expectedAssetAmount)
        assertMsg "ASSET_IS_LOCKED" (not assetView.isLocked)

        -- 2. 대금 지급 다리(Payment Leg) 정합성 검증
        assertMsg "BUYER_NOT_CASH_OWNER" (cashView.account.owner == buyerAssetAccount.owner)
        assertMsg "CASH_INSTRUMENT_MISMATCH" (cashView.instrument == expectedCashInst)
        assertMsg "CASH_AMOUNT_MISMATCH" (cashView.amount == expectedCashAmount)
        assertMsg "CASH_IS_LOCKED" (not cashView.isLocked)

        -- 3. 양방향 원자적 이전 실행 (어느 한쪽이라도 실패하면 전체 롤백)
        deliveredAssetCid <- exercise sellerAssetCid (Transfer buyerAssetAccount)
        paidCashCid       <- exercise buyerCashCid (Transfer sellerCashAccount)
        receiptCid        <- create DvPSettlementReceipt with
          tradeId
          seller         = sellerCashAccount.owner
          buyer          = buyerAssetAccount.owner
          deliveryInst   = expectedAssetInst
          deliveryAmount = expectedAssetAmount
          paymentInst    = expectedCashInst
          paymentAmount  = expectedCashAmount
          settledAt      = now
        pure (deliveredAssetCid, paidCashCid, receiptCid)

    choice WithdrawDvPProposal : ()
      controller sellerCashAccount.owner
      do
        pure ()

실패 양상 — 위조 자산 투입: ContractId Holding은 인터페이스를 구현한 어떤 템플릿이든 받습니다. SettleDvP에서 cashView.instrument == expectedCashInst 검사를 빼면, 매수인이 직접 발행한(issuer = buyer) 가짜 USD 토큰 10,000,000 units를 넣고 진짜 국채를 받아 갈 수 있습니다. 발행자(issuer), 기호, 버전을 모두 담은 InstrumentKey 전체를 대조해야 합니다. 인터페이스 뷰는 구현 템플릿이 공급하므로, 신뢰할 수 있는 것은 뷰의 issuer가 실제 서명자로 들어가 있다는 템플릿의 보장뿐입니다. 받을 템플릿을 허용 목록으로 제한하는 것도 방법입니다.

상태 전이와 그 밖의 실패 양상

SettleDvP는 제안서, 매도인의 증권 보유분, 매수인의 현금 보유분을 아카이브하고 매수인의 증권 보유분, 매도인의 현금 보유분, 결제 확인 기록을 생성합니다. 권한 검산: 본문 권한 \(\{\mathrm{seller}, \mathrm{buyer}\}\)는 두 Transfer의 controller(현재 소유자와 새 소유자)를 모두 덮습니다. 두 가지는 별도로 챙겨야 합니다. 첫째, 커맨드를 해석하는 매수인의 참여자 노드는 매도인의 증권 보유분을 볼 수 있어야 하므로, 매도인이 그 보유분을 명시적 공개로 넘기거나 보유분 observers에 매수인을 넣어야 합니다. 둘째, 제32장의 Transfer는 같은 수탁기관 안에서만 동작하므로(CUSTODIAN_MISMATCH), 수탁기관이 다른 다리는 이 패턴으로 결제할 수 없고 수탁기관 간 이전 경로가 따로 필요합니다.

2. 패턴 33.2 · 외환 PvP와 시야 분리 (CrossCurrencyPvP)

문제

독일의 장비 수출기업(deExporter)과 미국의 수입기업(usImporter)이 프랑크푸르트 은행(frankfurtBank)이 발행한 EUR 예금 토큰 920,000과 뉴욕 결제은행(nyBank)이 발행한 USD 예금 토큰 1,000,000을 맞바꾸는 외환 동시결제(Payment versus Payment, PvP)를 체결합니다(환율은 예시 수치). 두 다리는 원자적으로 결제되어야 하고, 동시에 기밀 요건이 있습니다. 프랑크푸르트 은행은 EUR 토큰이 정당한 소유자 사이에서 이전되는지만 확인해야 하고, 고객이 어느 은행의 USD를 얼마의 환율로 받았는지는 알면 안 됩니다. 뉴욕 은행도 USD 다리만 보고 EUR 다리는 보지 못해야 합니다.

계약 설계

제11장의 뷰 분해 규칙에 따르면, 하위 액션의 정보 수신자(informee)를 호스팅하는 참여자 집합이 상위 뷰의 참여자 집합에 포함되지 않을 때 그 하위 액션은 별도 뷰가 됩니다. 루트 교환 계약의 이해관계자를 두 기업으로만 제한하면, 각 통화의 Transfer는 발행 은행이라는 새 정보 수신자 때문에 별도 뷰로 분리됩니다. 각 발행 은행은 자기 통화 다리의 뷰만 받고, 루트 뷰와 반대편 다리는 블라인드 처리된 해시로만 봅니다.

1970년대 벨 연구소 매뉴얼 스타일의 외환 동시결제 도해: 중앙 교환 테이블에서 두 기업이 파운드 증서와 달러 증서를 동시에 맞바꾸지만, 양옆의 두꺼운 프라이버시 커튼 창구 너머에 앉은 런던 은행과 뉴욕 은행 서기는 오직 자기 은행이 발행한 통화 증서의 직인만 확인할 뿐 반대편 창구는 전혀 볼 수 없는 스팟 일러스트
[FIG 33.2] 시야를 분리한 외환 동시결제(CrossCurrencyPvP). 전체 교환은 하나의 원자적 트랜잭션이지만, 두 발행 은행은 각자의 서브트랜잭션 뷰(자기 통화의 이전)만 검증한다.
삽화 구성 및 생성 프롬프트 보기 열기 / 닫기
연출 의도: 크로스보더 외환 PvP에서 원자성과 서브트랜잭션 프라이버시가 어떻게 동시에 달성되는지를 양쪽 은행 창구 사이에 드리워진 불투명 커튼과 중앙 연동 교환기로 표현.
Minimalist abstract 1970s Bell Labs security architecture manual doodle and vintage Saul Steinberg editorial spot cartoon on empty aged warm-gray newsprint paper. A symmetrical three-zone room divided by two heavy opaque privacy curtains: in the center zone, two corporate traders simultaneously swap two distinct currency notes across a linked mechanical tray; behind the left curtain window, Bank A's clerk inspects only the domestic note stamp through a narrow slot; behind the right curtain window, Bank B's clerk inspects only the foreign note stamp—neither bank can see across the center curtain. Dry intellectual wit, 75% negative space, warm off-white newsprint background, coarse off-register gray Zip-A-Tone screen-tone shading, raw dip-pen black ink linework, flat 2D graphic art, zero gradients, zero text, zero letters or words anywhere in the image. --ar 16:9

아래 코드는 루트 계약의 이해관계자를 최소로 둔 권장 설계(좌측)와, 루트 계약의 observer에 두 은행을 넣어 환율과 상대 은행을 노출하는 안티패턴(우측)을 비교합니다.

코드

패턴 33.2A · [권장] 서브트랜잭션 시야를 분리한 외환 PvP (CrossCurrencyPvP) Daml
module Patterns.CrossCurrencyPvP where

import Patterns.HoldingStandard
  ( InstrumentKey(..), AccountKey(..), Holding, Transfer(..) )

-- 루트 계약의 이해관계자는 두 거래 기업뿐이다.
-- frankfurtBank와 nyBank는 루트 계약과 환율을 보지 못한다
template CrossCurrencyPvP
  with
    fxDealId          : Text
    eurSellerAcct     : AccountKey
    eurBuyerAcct      : AccountKey
    usdSellerAcct     : AccountKey
    usdBuyerAcct      : AccountKey
    eurHoldingCid     : ContractId Holding
    eurInstrument     : InstrumentKey
    eurAmount         : Decimal
    usdInstrument     : InstrumentKey
    usdAmount         : Decimal
    valueCutoff       : Time
  where
    signatory eurSellerAcct.owner
    observer usdSellerAcct.owner
    ensure eurAmount > 0.0 && usdAmount > 0.0
      && eurSellerAcct.owner == usdBuyerAcct.owner
      && usdSellerAcct.owner == eurBuyerAcct.owner

    choice ExecutePvP : (ContractId Holding, ContractId Holding)
      with
        usdHoldingCid : ContractId Holding
      controller usdSellerAcct.owner
      do
        now <- getTime
        assertMsg "FX_CUTOFF_PASSED" (now <= valueCutoff)

        eurH <- fetch eurHoldingCid
        usdH <- fetch usdHoldingCid
        let ev = view eurH
        let uv = view usdH

        assertMsg "EUR_LEG_INVALID"
          (ev.instrument == eurInstrument && ev.amount == eurAmount && not ev.isLocked)
        assertMsg "USD_LEG_INVALID"
          (uv.instrument == usdInstrument && uv.amount == usdAmount && not uv.isLocked)

        -- 하위 뷰 1: frankfurtBank가 EUR 다리만 검증 / 하위 뷰 2: nyBank가 USD 다리만 검증
        settledEur <- exercise eurHoldingCid (Transfer eurBuyerAcct)
        settledUsd <- exercise usdHoldingCid (Transfer usdBuyerAcct)
        pure (settledEur, settledUsd)
패턴 33.2B · [안티패턴] 루트 observer 과다 지정으로 인한 환율·상대 은행 노출 Daml
module Patterns.LeakyPvPAntiPattern where

import Patterns.HoldingStandard
  ( InstrumentKey(..), AccountKey(..), Holding, Transfer(..) )

-- 잘못된 설계: 발행 은행들을 루트 계약의 observer에 두면
-- 두 은행 모두 루트 초이스의 전체 트리를 받는다
template LeakyCrossCurrencyPvP
  with
    eurSellerAcct : AccountKey
    eurBuyerAcct  : AccountKey
    usdSellerAcct : AccountKey
    usdBuyerAcct  : AccountKey
    eurInstrument : InstrumentKey
    eurAmount     : Decimal
    usdInstrument : InstrumentKey
    usdAmount     : Decimal
  where
    signatory eurSellerAcct.owner
    -- frankfurtBank가 usdAmount와 nyBank의 다리까지 보게 된다
    observer usdSellerAcct.owner, eurInstrument.issuer, usdInstrument.issuer

    choice LeakyExecute : (ContractId Holding, ContractId Holding)
      with
        eurCid : ContractId Holding
        usdCid : ContractId Holding
      controller usdSellerAcct.owner
      do
        -- 결제는 되지만 양 은행에 고객 정보(적용 환율·상대 은행 계좌)가 노출된다
        c1 <- exercise eurCid (Transfer eurBuyerAcct)
        c2 <- exercise usdCid (Transfer usdBuyerAcct)
        pure (c1, c2)

상태 전이와 실패 양상

ExecutePvP는 두 통화 보유분을 아카이브하고 반대 소유자의 보유분 두 개를 생성합니다. 권한 검산: 본문 권한 \(\{A, B\}\)(제안 서명자와 controller)는 두 Transfer의 controller를 덮습니다. 커맨드를 해석하는 B의 참여자 노드는 A의 EUR 보유분을 볼 수 있어야 하므로 A가 이를 명시적 공개로 넘겨야 합니다. 안티패턴에서는 두 은행이 루트 계약의 이해관계자이므로 루트 뷰와 그 하위 뷰 전체, 즉 반대편 통화 다리와 금액이 두 은행 모두에게 전달됩니다. 동작은 같지만 기밀성이 깨집니다.

3. 패턴 33.3 · 결제 지시, 할당, 다자 일괄 정산 (BatchSettlement)

문제

양자 거래를 넘어서면 결제 구조가 복잡해집니다. 증권사 A가 B에게 국채를 넘기고, B가 C에게 EUR를 지급하고, C가 A에게 USD를 지급하는 3자 순환 거래나 환매조건부채권(Repurchase Agreement, Repo) 바스켓 거래에서는 여러 결제 다리(SettlementLeg)가 함께 결제되어야 합니다. 기관 시장에서는 체결 엔진이 먼저 결제 지시(SettlementInstruction)를 내고, 마감 시각 전까지 각 기관(또는 제30장의 수탁 대리인)이 보유분을 분할해(제32장) 지시에 할당(Allocation)하며, 마감 시각에 코디네이터가 모든 다리를 한 번에 결제하는 3단계로 움직입니다.

1970년대 벨 연구소 매뉴얼 화풍의 다자 일괄 정산 기계 도교: 세 개의 독립된 결제 다리 슬롯에 각 기관의 잠긴 보유분 캡슐이 모두 딸깍 끼워져야만 마스터 레버가 내려가며 세 구간의 도개교가 동시에 연결되고, 하나라도 비어 있으면 시계 태엽 만료와 함께 모든 캡슐이 원주인에게 되돌아가는 스팟 일러스트
[FIG 33.3] 다자 할당과 일괄 정산(ExecuteBatchSettlement). 모든 결제 다리가 마감 시각 전에 할당되어야 전체 정산이 실행되고, 한 다리라도 빠지면 어느 다리도 이전되지 않는다.
삽화 구성 및 생성 프롬프트 보기 열기 / 닫기
연출 의도: CIP-0056 Allocation 철학과 Daml Finance Batch Settlement가 구현하는 K-다리 All-or-Nothing 정산 메커니즘을 세 개의 키 캡슐이 모두 장착되어야만 내려가는 연동식 도개교 스위치로 시각화.
Minimalist abstract 1970s Bell Labs control-system manual doodle and vintage Saul Steinberg editorial spot cartoon on empty aged warm-gray newsprint paper. In the center, a multi-slot mechanical interlock bridge with three parallel tracks: three locked asset capsules click into three aligned allocation sockets connected to a single master release bar and a ticking deadline clock dial. Only when all three sockets are filled does the master bar drop cleanly to glide all three capsules across simultaneously. Dry intellectual wit, 75% negative space, warm off-white newsprint background, coarse off-register gray Zip-A-Tone screen-tone shading, raw dip-pen black ink linework, flat 2D graphic art, zero gradients, zero text, zero letters or words anywhere in the image. --ar 16:9
ℬ = {ℓ₁, ℓ₂, …, ℓ_K}, σ(ℬ) ∈ {AllCommitted, AllAborted}

아래 식은 확률이 아니라 원자성에서 나오는 구조적 보장입니다. 결제 묶음 ℬ의 K개 다리가 한 트랜잭션에서 실행되므로, 한 다리라도 할당 누락이나 잔고 부족으로 실패하면 묶음 전체가 거절되어 일부 다리만 결제된 상태가 존재하지 않습니다.

R_principal(ℬ) = [ ∑_{i=1..K} v_i · 𝕀(Settled(ℓ_i) ∧ ∃ j≠i, ¬Settled(ℓ_j)) ] / [ ∑_{i=1..K} v_i ] = 0

예시 수치(단위: USD 백만 상당): 기관 A가 B에 국채 USD 10M 상당(\(\ell_1, v_1 = 10\)), B가 C에 USD 10M 상당의 EUR 예금 토큰(\(\ell_2, v_2 = 10\)), C가 A에 USD 예금 토큰 10M(\(\ell_3, v_3 = 10\))을 지급하는 \(K = 3\) 순환 묶음(총 명목가치 \(\sum v_i = 30\))을 가정하자.

마감 시각까지 A와 B가 할당을 마쳤더라도 C의 USD 잔고가 9.9뿐이어서 0.1이 부족해 \(\ell_3\) 할당이 빠지면, ExecuteBatchSettlement는 INCOMPLETE_OR_REORDERED_LEGS로 거절되고 A·B·C의 유출액은 모두 0이다.

분자의 지시함수는 어떤 실행 결과에서도 0이므로 \(R_{\mathrm{principal}}(\mathcal{B}) = 0 / 30 = 0\)이다.

[INVARIANT 33.1] \(K\)-다리 일괄 결제 묶음의 원자적 전이(All-or-Nothing)와 그에 따른 원금 위험 제거.

코드

패턴 33.3 · 결제 지시(SettlementInstruction)·대리 할당(Allocate)·다자 일괄 정산(BatchSettlement) Daml
module Patterns.BatchSettlement where

import Patterns.HoldingStandard
  ( InstrumentKey(..), AccountKey(..), Holding, Transfer(..) )

-- 제30장 위임 패턴: 자산운용사가 수탁은행에 결제 할당 대리권을 부여
template CustodyDelegation
  with
    ownerAccount : AccountKey
    agent        : Party
  where
    signatory ownerAccount.owner
    observer agent

    nonconsuming choice AllocateOnBehalf : ContractId PendingAllocation
      with
        instructionCid : ContractId SettlementInstruction
        holdingCid     : ContractId Holding
      controller agent
      do
        exercise instructionCid (AllocateSenderHolding holdingCid)

-- 결제 다리에 할당된 보유분의 참조 기록 (원본 보유분을 소비하지는 않는다)
template LockedHolding
  with
    batchId        : Text
    legId          : Text
    operator       : Party
    senderAccount  : AccountKey
    underlyingCid  : ContractId Holding
    unlockAfter    : Time
  where
    signatory operator, senderAccount.owner

    -- 마감 후 정산이 실행되지 않았으면 원소유자가 단독으로 할당을 해제
    choice UnlockExpiredHolding : ContractId Holding
      controller senderAccount.owner
      do
        now <- getTime
        assertMsg "DEADLINE_NOT_YET_PASSED" (now > unlockAfter)
        pure underlyingCid

    choice ReleaseForSettlement : ContractId Holding
      controller operator
      do
        pure underlyingCid

data SettlementLeg = SettlementLeg
  with
    legId           : Text
    senderAccount   : AccountKey
    receiverAccount : AccountKey
    instrument      : InstrumentKey
    amount          : Decimal
  deriving (Eq, Show)

-- 1단계: 체결·청산 엔진이 다리마다 내는 결제 지시
template SettlementInstruction
  with
    batchId            : Text
    operator           : Party
    leg                : SettlementLeg
    settlementDeadline : Time
  where
    signatory operator
    observer leg.senderAccount.owner, leg.receiverAccount.owner
    ensure leg.amount > 0.0 && batchId /= ""

    -- 2A단계: 인도자(또는 CustodyDelegation 대리인)가 보유분을 할당
    choice AllocateSenderHolding : ContractId PendingAllocation
      with
        holdingCid : ContractId Holding
      controller leg.senderAccount.owner
      do
        h <- fetch holdingCid
        let hv = view h
        assertMsg "ALLOC_OWNER_MISMATCH" (hv.account == leg.senderAccount)
        assertMsg "ALLOC_INST_MISMATCH" (hv.instrument == leg.instrument)
        assertMsg "ALLOC_AMOUNT_MISMATCH" (hv.amount == leg.amount)
        assertMsg "ALLOC_ALREADY_LOCKED" (not hv.isLocked)
        lockedCid <- create LockedHolding with
          batchId
          legId         = leg.legId
          operator
          senderAccount = leg.senderAccount
          underlyingCid = holdingCid
          unlockAfter   = settlementDeadline
        create PendingAllocation with
          batchId
          operator
          leg
          lockedCid
          settlementDeadline

template PendingAllocation
  with
    batchId            : Text
    operator           : Party
    leg                : SettlementLeg
    lockedCid          : ContractId LockedHolding
    settlementDeadline : Time
  where
    signatory operator, leg.senderAccount.owner
    observer leg.receiverAccount.owner

    -- 2B단계: 수취인이 입고에 동의해 실행 대기 상태로 전환
    choice ConfirmReceiverLeg : ContractId AllocatedLeg
      controller leg.receiverAccount.owner
      do
        create AllocatedLeg with
          batchId
          operator
          leg
          lockedCid
          settlementDeadline

template AllocatedLeg
  with
    batchId            : Text
    operator           : Party
    leg                : SettlementLeg
    lockedCid          : ContractId LockedHolding
    settlementDeadline : Time
  where
    signatory operator, leg.senderAccount.owner, leg.receiverAccount.owner

    choice SettleLeg : ContractId Holding
      controller operator
      do
        unlockedHoldingCid <- exercise lockedCid ReleaseForSettlement
        exercise unlockedHoldingCid (Transfer leg.receiverAccount)

    choice AbortExpiredLeg : ContractId Holding
      controller leg.senderAccount.owner
      do
        exercise lockedCid UnlockExpiredHolding

-- 3단계: K개 다리가 모두 할당되면 한 트랜잭션에서 일괄 정산
template BatchSettlementCoordinator
  with
    batchId            : Text
    operator           : Party
    expectedLegIds     : [Text]
    settlementDeadline : Time
  where
    signatory operator
    ensure not (null expectedLegIds)

    choice ExecuteBatchSettlement : [ContractId Holding]
      with
        allocatedLegCids : [ContractId AllocatedLeg]
      controller operator
      do
        now <- getTime
        assertMsg "BATCH_DEADLINE_EXCEEDED" (now <= settlementDeadline)
        allocatedLegs <- mapA fetch allocatedLegCids
        let providedIds = map (\al -> al.leg.legId) allocatedLegs
        let allSameBatch = all (\al -> al.batchId == batchId) allocatedLegs
        assertMsg "BATCH_ID_MISMATCH" allSameBatch
        assertMsg "INCOMPLETE_OR_REORDERED_LEGS" (providedIds == expectedLegIds)
        mapA (\cid -> exercise cid SettleLeg) allocatedLegCids

상태 전이와 실패 양상

할당 단계는 다리마다 LockedHolding과 PendingAllocation을 만들고, 수취인 동의가 PendingAllocation을 AllocatedLeg로 바꿉니다. ExecuteBatchSettlement는 모든 AllocatedLeg와 LockedHolding, 송신인의 보유분을 아카이브하고 수신인의 보유분 \(K\)개를 생성합니다. 권한 검산: SettleLeg 본문 권한은 \(\{\mathrm{operator}, \mathrm{sender}, \mathrm{receiver}\}\)이므로 보유분 Transfer의 controller(송신인과 수신인)를 덮습니다. 수취인 동의 단계(ConfirmReceiverLeg)가 있어야 이 권한 집합이 만들어집니다. 가시성은 따로 챙겨야 합니다. 운영자는 송신인 보유분의 이해관계자가 아니므로 ExecuteBatchSettlement를 제출할 때 각 다리의 보유분을 명시적 공개로 받아야 하고, AllocateOnBehalf를 제출하는 수탁 대리인도 결제 지시와 보유분을 같은 방식으로 받아야 합니다.

5자 일괄 정산에서 한 증권사가 장애로 마감 시각까지 할당하지 못하면, 먼저 할당한 4개 기관의 국채와 현금은 묶이는가?

마감 후 단독 해제

묶이지 않습니다. ExecuteBatchSettlement는 providedIds == expectedLegIds가 아니면 실행되지 않으므로 일부 다리만 결제되는 일은 없습니다. settlementDeadline이 지나면 먼저 할당한 4개 기관은 운영자나 미응답 증권사의 서명 없이 각자 AbortExpiredLeg를 행사해 할당을 해제합니다. 정산 실행(now <= settlementDeadline)과 해제(now > unlockAfter)는 원장 시간 기준으로 겹치지 않습니다.

수탁은행 자동화

시차가 큰 해외 자산운용사는 제30장의 CustodyDelegation을 현지 수탁은행에 미리 발급해, 현지 업무 시간에 수탁은행 시스템이 AllocateOnBehalf로 지시 대조와 할당을 자동 처리하게 할 수 있습니다.

실패 양상 — 할당은 동결이 아니다: 이 코드의 LockedHolding은 할당된 보유분의 ContractId만 기록하고 원본 보유분을 소비하지 않습니다. 제32장의 interface Holding에는 잠금 상태를 바꾸는 초이스가 없기 때문입니다. 송신인이 할당 후 마감 전에 그 보유분을 분할하거나 이전하면 SettleLeg가 아카이브된 계약을 참조하게 되어 묶음 전체가 거절됩니다. 원자성은 유지되지만 정산은 실패합니다. 할당 시점에 실제로 동결하려면 제31장의 LockedHolding처럼 원본을 소비하고 잠금 계약을 만들거나, CIP-0056의 AllocationFactory/Allocation 흐름처럼 할당을 등록기관이 처리하게 해서 할당 시점에 자산을 예약하도록 하십시오. 원자성의 범위: 열 개 다리 중 열 번째에서 0.01이 모자라도 앞의 아홉 다리를 포함한 트랜잭션 전체가 거절됩니다. 결제가 늦어질 수는 있지만 일부만 결제되지는 않습니다.

4. 변형과 조합, 규제 대응

변형과 조합

패턴 33.1의 DvP 수락 단계에 제30장의 자격 증명 검사를 넣으면 적격투자자만 매수할 수 있습니다. 패턴 33.3의 할당에 제31장의 잠금 계약을 쓰면 할당 시점에 보유분이 실제로 동결됩니다. 제34장은 이 DvP를 노베이션과 토큰화 증권의 장외 유통에 다시 씁니다.

규제 대응

가치교환 결제와 결제완결성: CPMI-IOSCO의 「금융시장인프라 원칙」(PFMI) 원칙 12(가치교환 결제시스템)는 연결된 두 의무를 결제하는 시스템이 한쪽 의무의 최종 결제를 다른 쪽 의무의 최종 결제에 조건부로 묶어(DvP·PvP) 원금 위험을 제거하도록 요구합니다. EU 결제완결성 지침(Settlement Finality Directive 98/26/EC)은 지정된 시스템에 들어간 이체 지시와 상계가 참가자의 도산 절차 개시 후에도 효력을 유지하도록 보호합니다. 다른 관할도 지정 결제시스템에 비슷한 보호를 둡니다.

법적 완결 시점은 결제시스템의 규칙과 지정 여부가 정합니다. Daml 트랜잭션 커밋은 두 의무를 기술적으로 함께 종결하므로, 시스템 규칙에서 커밋 시점을 완결 시점으로 정의하기 쉽습니다. 그렇게 정의하면 정산 도중 한 참가기관에 도산 절차가 개시되어도 이미 커밋된 교환은 한쪽만 이행된 상태로 남지 않습니다.

이 장에서 남는 것

  1. 인터페이스 기반 T+0 원자적 DvP. AtomicDvPProposal은 구체 템플릿에 의존하지 않고 interface Holding만 다루므로, 국채·주식·토큰화 증권과 예금 토큰을 코드 변경 없이 한 초이스에서 교환한다. InstrumentKey 전체 대조로 위조 자산을 막는다.
  2. 서브트랜잭션 시야를 분리한 외환 PvP. CrossCurrencyPvP의 루트 계약 이해관계자를 거래 당사자로 제한하고 발행 은행을 루트 observer에서 빼면, 원자적 결제를 유지하면서 각 은행은 자기 통화 다리만 검증한다.
  3. 지시·할당·일괄 정산 3단계. 체결 엔진의 SettlementInstruction, 수탁 대리인의 할당, 코디네이터의 ExecuteBatchSettlement를 결합하면 \(K\)개 다리 순환 거래가 원자적으로 결제되어 부분 결제에 따른 원금 위험이 없다(\(R_{\mathrm{principal}} = 0\), 확률이 아닌 원자성의 보장). 할당 시점의 동결은 별도로 설계해야 한다.
  4. 시간 창 기반 데드락 방어와 결제완결성. 미응답 참가자가 발생해도 마감 시각(settlementDeadline) 경과 즉시 각 참가자가 단독으로 잠금을 해제할 수 있으며, 커밋된 교환은 PFMI 원칙 12의 가치교환 요건을 충족한다.