제32장. 보유분과 계좌: Holding 인터페이스, 분할·병합, 3계층 분리

계좌 유일성을 지키는 두 가지 방법과 발행·소각 통제

핵심 키워드: interface Holding (CIP-0056) · Split & Merge · AccountRegistry vs Contract Keys · Participant Query Store (PQS) · Instrument-Account-Holding · MintAndBurnDesk
"대체 가능 물품이란, 본성상이나 거래 관행상 어느 단위든 같은 종류의 다른 단위와 동등한 물품이거나, 약정에 따라 동등한 것으로 다루어지는 물품이다." — 미국 Uniform Commercial Code(UCC) §1-201(b)(18)

1. 패턴 32.1 · 보유분 인터페이스와 분할·병합

문제

관계형 데이터베이스 기반 원장에서는 지급 한 건이 UPDATE accounts SET balance = balance - 30 한 줄입니다. 활성 계약 집합(Active Contract Set, ACS)을 쓰는 Daml 원장은 미사용 트랜잭션 출력(Unspent Transaction Output, UTXO) 모델처럼 기존 계약을 제자리에서 고치지 않습니다. 50 units짜리 보유분에서 30 units를 지급하려면 원래 계약을 소비하고 30 units와 거스름 20 units 두 계약을 새로 만들어야 합니다(분할 Split). 소액 지급이 쌓여 작은 보유분이 수십 개 생기면 하나로 합쳐야 합니다(병합 Merge). 두 연산은 발행 총량을 바꾸지 않아야 합니다.

두 번째 문제는 자산 종류입니다. 은행 예금 토큰, 국채, 신탁 수익권은 템플릿이 서로 다릅니다. 제33장의 결제 로직이 자산마다 따로 쓰이지 않으려면 모든 보유분이 같은 인터페이스(Interface)를 구현해야 합니다. Daml 인터페이스는 명목적(nominal)입니다. 인터페이스가 자기 초이스를 선언하고, 템플릿은 interface instance로 메서드와 뷰를 공급합니다.

CIP-0056 Holding과의 관계

패키지 배치에도 주의해야 합니다. 인터페이스와 그것을 구현하는 템플릿을 한 패키지에 두면, 컴파일러는 그 패키지를 나중에 업그레이드하기 어렵다는 이유로 오류를 냅니다. 실무에서는 Holding 같은 인터페이스를 별도 패키지로 분리하고, 구현 템플릿 패키지가 그것을 의존하도록 구성합니다. 이 장의 목록을 한 프로젝트에서 그대로 빌드해 보려면 이 검사를 끄는 빌드 옵션이 필요합니다.

이 장의 interface Holding은 분할·병합·이전 초이스를 직접 선언하는 설명용 인터페이스입니다. 토큰 표준 CIP-0056의 Holding은 이름이 같지만 초이스가 하나도 없고, 뷰만 제공합니다. 그 뷰의 필드는 owner, instrumentId(admin, id), amount, lock(Optional), meta입니다. CIP-0056에서 이전과 결제는 별도 인터페이스(TransferFactory/TransferInstruction, AllocationFactory/Allocation/AllocationInstruction, AllocationRequest)로 하고, 분할·병합은 각 등록기관의 이전 구현이 입력 보유분을 소비하고 출력을 만드는 방식으로 처리합니다. CIP-0056과 연동하는 시스템을 만든다면 보유분 템플릿이 CIP-0056 Holding 뷰도 함께 구현하게 하십시오.

1970년대 벨 연구소 매뉴얼 스타일로 그려진 정밀한 황동 지폐 재단기와 압착 프레스 기계: 왼쪽 투입구로 들어간 100달러 지폐 계약 카드가 정확히 60달러와 40달러 두 장으로 재단되고, 아래쪽 컨베이어에서는 자잘한 잔돈 조각들이 하나의 묵직한 단일 보유분 카드로 합쳐지는 스팟 일러스트
[FIG 32.1] 분할과 병합(Split & Merge). 보유분 계약 하나를 소비해 두 계약으로 나누거나, 여러 보유분을 소비해 하나로 합친다. 전후 수량 합계는 같다.
삽화 구성 및 생성 프롬프트 보기 열기 / 닫기
연출 의도: UTXO 기반 Daml 보유분 계약의 불변성과 대체 가능성(Split & Merge)을 지갑 속 지폐 재단기 및 잔돈 압착 프레스라는 친근한 물리 기계 장치로 시각화.
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 charming dual-chamber mechanical brass press: on the upper track, one crisp rectangular certificate slips into a precision rotary cutter and emerges cleanly as two smaller proportional certificates while a balance scale stays perfectly level; on the lower track, a stack of tiny scattered coin-tickets feeds into a neat binding press and emerges as one tidy consolidated certificate. 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
∀ c' ∈ Out(τ), amt(c') > 0 ∧ ∀ c ∈ In(τ), key(c) = (k_inst, k_acct)

같은 종목·같은 계좌 안의 분할·병합 전이 τ가 입력 합계와 출력 합계를 같게 만들면 종목의 발행 총량은 변하지 않는다. 양수 조건은 음수 출력으로 합계를 맞추는 위조를 막는다.

∑_{c ∈ In(τ)} amt(c) = ∑_{c' ∈ Out(τ)} amt(c') ⟹ ΔSupply(k_inst) = 0

예시 수치(단위: units): 한 계좌에 예금 토큰 보유분 50,000 units 1개(\(c_1 = 50{,}000\))와 10,000 units 3개(\(c_2 = c_3 = c_4 = 10{,}000\))가 있을 때,

  • Merge를 실행하면 입력 합계 \(50{,}000 + 3 \times 10{,}000 = 80{,}000\)이 단일 계약 \(c_{\mathrm{merged}} = 80{,}000\)으로 합쳐진다.
  • 이어서 37,500 units를 지급하려고 Split을 호출하면 지급분 \(c_{\mathrm{pay}} = 37{,}500\)과 거스름 \(c_{\mathrm{change}} = 42{,}500\)이 생성되고, \(37{,}500 + 42{,}500 = 80{,}000\)으로 보존식이 성립한다.

0 이하의 수량을 허용하면 \((-100{,}000) + (+100{,}000) = 0\)처럼 합계를 유지하면서 담보 없는 보유분을 만들 수 있으므로, 모든 출력 계약의 양수 조건(\(v_i > 0\))은 필수 불변식이다.

[INVARIANT 32.1] 대체 가능 보유분의 엄밀 양수 조건 및 분할·병합 총량 보존 법칙 (Conservation of Fungible Supply).

대표 업무는 예금 토큰 분할·병합과 국채 부분 매도입니다. 아래 표는 이 장의 네 패턴에서 종목 정의, 수탁 계좌, 보유분 사이의 서명 권한과 상태 전이가 어떻게 나뉘는지 요약합니다. 패턴 32.1의 코드는 제33~34장이 그대로 가져다 쓰는 InstrumentKey, AccountKey, HoldingView, interface Holding과 구현 템플릿 FungibleHolding을 Daml 3 문법으로 정의합니다.

당사자와 권한

패턴 / 계약·인터페이스 서명자 (signatory) 행위자 (controller) 소멸·생성 및 총량 보존 역할
32.1 interface Holding / FungibleHolding instrument.issuer, account.custodian, account.owner account.owner (Split, Merge) / account.owner와 newAccount.owner (Transfer) 원 보유분 소비 후 양수 액면 조각 생성 (\(\Delta\mathrm{Supply} = 0\) 보존)
32.2 AccountRegistry / ManagedAccount custodian / custodian, owner custodian (IssueAccountInvite) / owner (AcceptAccountInvite) 수탁기관의 개설 절차(오프체인 유일성 검사)로 AccountKey 유일성 유지
32.3 Instrument / CustodyAccount instrumentKey.issuer / custodian, owner custodian (SetAccountStatus) / owner (AssertAccountActive, nonconsuming) 상품 정의와 개별 보유분(Holding)을 분리하는 3계층 구조, 계좌 상태 통제
32.4 MintAndBurnDesk instrument.issuer, custodian instrument.issuer (ProposeMint) / 보유자 (BurnAndRedeem) 공급량을 늘리거나 줄이는 유일한 경로 (일반 이전 초이스와 권한 분리)

코드

패턴 32.1 · 보유분 인터페이스(interface Holding)와 FungibleHolding의 Split·Merge 구현 Daml
module Patterns.HoldingStandard where

-- 종목 식별자: 발행자, 종목 기호, 라이프사이클 버전을 묶은 불변 값 레코드
data InstrumentKey = InstrumentKey
  with
    issuer  : Party
    symbol  : Text
    version : Text
  deriving (Eq, Show, Ord)

-- 수탁 계좌 식별자: 수탁기관, 실질 소유자, 계좌 번호를 묶은 불변 값 레코드
data AccountKey = AccountKey
  with
    custodian : Party
    owner     : Party
    accountId : Text
  deriving (Eq, Show, Ord)

-- 설명용 보유분 인터페이스의 뷰 (CIP-0056 Holding 뷰와 필드가 다르다)
data HoldingView = HoldingView
  with
    instrument : InstrumentKey
    account    : AccountKey
    amount     : Decimal
    isLocked   : Bool
  deriving (Eq, Show)

interface Holding where
  viewtype HoldingView

  splitImpl          : Decimal -> Update (ContractId Holding, ContractId Holding)
  mergeImpl          : [ContractId Holding] -> Update (ContractId Holding)
  transferImpl       : AccountKey -> Update (ContractId Holding)
  consumeSiblingImpl : InstrumentKey -> AccountKey -> Update Decimal

  choice Split : (ContractId Holding, ContractId Holding)
    with
      splitAmount : Decimal
    controller (view this).account.owner
    do
      assertMsg "HOLDING_LOCKED" (not (view this).isLocked)
      splitImpl this splitAmount

  choice Merge : ContractId Holding
    with
      otherCids : [ContractId Holding]
    controller (view this).account.owner
    do
      assertMsg "HOLDING_LOCKED" (not (view this).isLocked)
      assertMsg "EMPTY_MERGE_LIST" (not (null otherCids))
      mergeImpl this otherCids

  choice ConsumeForMerge : Decimal
    with
      expectedInstrument : InstrumentKey
      expectedAccount    : AccountKey
    controller (view this).account.owner
    do
      assertMsg "SIBLING_LOCKED" (not (view this).isLocked)
      consumeSiblingImpl this expectedInstrument expectedAccount

  choice Transfer : ContractId Holding
    with
      newAccount : AccountKey
    controller (view this).account.owner, newAccount.owner
    do
      assertMsg "HOLDING_LOCKED" (not (view this).isLocked)
      assertMsg "CUSTODIAN_MISMATCH" ((view this).account.custodian == newAccount.custodian)
      transferImpl this newAccount

-- 대체 가능 보유분 템플릿
template FungibleHolding
  with
    instrument : InstrumentKey
    account    : AccountKey
    amount     : Decimal
    observers  : [Party]
  where
    signatory instrument.issuer, account.custodian, account.owner
    observer observers
    ensure amount > 0.0 && instrument.symbol /= "" && account.accountId /= ""

    interface instance Holding for FungibleHolding where
      view = HoldingView with
        instrument
        account
        amount
        isLocked = False

      splitImpl splitAmount = do
        assertMsg "SPLIT_AMOUNT_OUT_OF_BOUNDS" (splitAmount > 0.0 && splitAmount < amount)
        exactCid  <- create this with amount = splitAmount
        changeCid <- create this with amount = amount - splitAmount
        pure (toInterfaceContractId exactCid, toInterfaceContractId changeCid)

      consumeSiblingImpl expectedInst expectedAcct = do
        assertMsg "INSTRUMENT_MISMATCH" (instrument == expectedInst)
        assertMsg "ACCOUNT_MISMATCH" (account == expectedAcct)
        pure amount

      mergeImpl otherCids = do
        siblingAmounts <- mapA
          (\cid -> exercise cid (ConsumeForMerge instrument account))
          otherCids
        let totalAmount = foldl (+) amount siblingAmounts
        mergedCid <- create this with amount = totalAmount
        pure (toInterfaceContractId mergedCid)

      transferImpl newAccount = do
        nextCid <- create this with
          account   = newAccount
          observers = []
        pure (toInterfaceContractId nextCid)

상태 전이

Split은 입력 보유분 1개를 아카이브하고 2개를 생성합니다. Merge는 자신과 otherCids의 보유분을 모두 아카이브하고 1개를 생성합니다. 형제 보유분은 ConsumeForMerge(소비형 인터페이스 초이스)로 소비되며, 종목과 계좌가 다르면 INSTRUMENT_MISMATCH·ACCOUNT_MISMATCH로 트랜잭션 전체가 거절됩니다. 같은 ContractId를 목록에 두 번 넣으면 두 번째 행사가 이미 아카이브된 계약을 참조하므로 실패합니다. 권한 검산: Merge 본문의 권한은 \(\{\mathrm{issuer}, \mathrm{custodian}, \mathrm{owner}\}\)이고, 형제의 ConsumeForMerge가 요구하는 controller(형제의 owner)는 계좌가 같을 때만 이 집합에 들어갑니다. Transfer는 현재 소유자와 새 소유자를 모두 controller로 요구하므로 수취인의 동의 없이 보유분을 떠넘길 수 없습니다.

실패 양상 — 작은 보유분 누적(UTXO dust)과 주기적 병합: 소액 정산이 많은 기관 계좌에 거스름 보유분이 수천 개 쌓이면, 큰 지급 한 건에 입력 계약 수천 개를 넣어야 합니다. 입력 계약이 많을수록 확인 요청이 커지고 검증 시간이 늘어납니다. 요청 크기는 동기화기 매개변수(최대 요청 크기)로 제한되고, 참여자는 확인 응답 시한(confirmationResponseTimeout, 기본 30초) 안에 검증을 끝내야 합니다. 그래서 지갑 서비스는 한가한 시간대에 오프체인 자동화로 보유분을 적당한 묶음(예: 20~50개, 운영 예시)으로 Merge해 계좌의 활성 보유분 수를 낮게 유지합니다. 적정 묶음 크기는 계약 크기와 노드 성능에 따라 다르므로 측정해서 정하십시오.

2. 패턴 32.2 · 계좌 유일성: 멀티 동기화기 환경의 두 길

문제

수탁은행이나 중앙예탁기관(Central Securities Depository, CSD) 실무자가 Daml 3로 넘어오며 가장 먼저 묻는 질문이 있습니다. “고객 Alice의 USD-MAIN-01 계좌가 원장 전체에 하나만 존재하도록 어떻게 보장합니까?” 단일 원장에서는 계약 키(Contract Key)와 부재 조회(negative key lookup, lookupByKey == None)로 이를 확인했습니다.

제11장과 제16장에서 보았듯, 여러 동기화기(Synchronizer)를 쓰는 토폴로지에서 “이 계약이 다른 어느 동기화기에도 없다”를 원장 위에서 증명하려면 자기가 연결되지 않은 동기화기의 상태까지 알아야 합니다. 이는 서브트랜잭션 프라이버시(Sub-transaction Privacy)와 동기화기 독립성에 어긋납니다. 계약이 재할당(Reassignment)되는 동안 유일성 검사가 두 동기화기 사이에서 어긋날 수도 있습니다. Canton 운영 문서도 유일 계약 키는 단일 동기화기 안으로 제한된다고 명시합니다.

1970년대 벨 연구소 매뉴얼 화풍의 비교 일러스트: 왼쪽에는 수탁기관 서기가 인가 대장 서랍장을 확인해 단 하나의 번호표 초대장을 발급하고 참여자 쿼리 스토어 색인 카드로 즉시 계좌를 찾는 모습, 오른쪽에는 단일 폐쇄 방 안에서만 작동하는 무거운 자물쇠 열쇠 판이 대조되는 스팟 일러스트
[FIG 32.2] 계좌 유일성을 지키는 두 가지 방법. 멀티 동기화기 환경에서 쓰는 AccountRegistry 초대·수락과 참여자 쿼리 스토어(PQS) 조회 경로(좌), 단일 동기화기에서만 쓰는 계약 키 경로(우).
삽화 구성 및 생성 프롬프트 보기 열기 / 닫기
연출 의도: Canton 원장에서 계좌 중복 개설을 방지하는 주력 권장안(수탁원장 역할 계약 + 오프체인 PQS 조회)과 대조안(단일 동기화기 안에서만 쓰는 계약 키 조회)의 구조적 차이를 벨 연구소 도해 스타일의 서랍장 색인 대조도로 표현.
Minimalist abstract 1970s Bell Labs architecture manual doodle and vintage Saul Steinberg editorial spot cartoon on empty aged warm-gray newsprint paper. Split composition: on the left, an orderly custodian registry desk with an index card drawer issuing a single stamped account pass across multiple connected rooms smoothly; on the right, a heavy iron keyboard bolted strictly inside a single walled room unable to pass through doors. 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

계약 설계

방법은 두 가지입니다. 권장안에서는 계좌 생성 권한을 가진 수탁기관(custodian)이 역할 계약(AccountRegistry)을 통해서만 개설 초대(OpenAccountInvite)를 냅니다. 초대를 내기 전에 수탁기관은 자기 참여자 쿼리 스토어(Participant Query Store, PQS)나 업무 DB에서 같은 AccountKey가 이미 있는지 확인합니다. 이후 거래는 PQS에서 찾은 ContractId를 인자로 명시적으로 넘겨 검증합니다. 유일성은 원장이 아니라 계좌를 개설할 수 있는 유일한 주체인 수탁기관의 절차가 보장합니다. 모든 거래가 하나의 동기화기 안에서만 일어나고 재할당이 없다면, key와 maintainer를 선언하는 대조안을 쓸 수 있습니다. 이때는 기준 버전의 컴파일 대상과 동기화기 설정이 계약 키를 지원하는지 먼저 확인하십시오. 대조안에서도 키는 유일성 제약이 아닙니다. 두 서명자가 다른 경로로 같은 키의 KeyedAccount를 만들면 원장은 그대로 받아들이므로, 중복을 거르는 것은 OpenUniqueKeyedAccount 안의 부재 조회입니다.

코드

패턴 32.2A · [권장] 멀티 동기화기 환경 (AccountRegistry + PQS 조회 후 명시 전달) Daml
module Patterns.RegistryAccount where

import Patterns.HoldingStandard (AccountKey(..))

data AccountStatus = Active | Frozen
  deriving (Eq, Show)

-- 계좌 개설을 수탁기관 한 곳으로 모으는 레지스트리
template AccountRegistry
  with
    custodian    : Party
    jurisdiction : Text
  where
    signatory custodian
    ensure jurisdiction /= ""

    -- 수탁기관이 PQS·업무 DB에서 중복을 확인한 뒤 초대를 발행
    nonconsuming choice IssueAccountInvite : ContractId OpenAccountInvite
      with
        prospectiveOwner : Party
        accountId        : Text
      controller custodian
      do
        assertMsg "EMPTY_ACCOUNT_ID" (accountId /= "")
        create OpenAccountInvite with
          accountKey = AccountKey custodian prospectiveOwner accountId

template OpenAccountInvite
  with
    accountKey : AccountKey
  where
    signatory accountKey.custodian
    observer accountKey.owner

    choice AcceptAccountInvite : ContractId ManagedAccount
      controller accountKey.owner
      do
        create ManagedAccount with
          accountKey
          status = Active

-- 계약 키가 없어 동기화기 간 재할당에 제약이 없는 계좌
template ManagedAccount
  with
    accountKey : AccountKey
    status     : AccountStatus
  where
    signatory accountKey.custodian, accountKey.owner
패턴 32.2B · [대조안] 단일 동기화기 전용 계약 키 Daml
module Patterns.SingleDomainKeyAccount where

-- 주의: 단일 동기화기 전용 환경에서만 제한적으로 사용
import Patterns.HoldingStandard (AccountKey(..))

template KeyedAccount
  with
    accountKey : AccountKey
    isFrozen   : Bool
  where
    signatory accountKey.custodian, accountKey.owner

    -- 키는 조회 색인이다. 원장은 같은 키의 계약을 거부하지 않는다
    key accountKey : AccountKey
    maintainer key.custodian

template SingleDomainOnboarding
  with
    custodian : Party
    owner     : Party
    accountId : Text
  where
    signatory custodian
    observer owner

    choice OpenUniqueKeyedAccount : ContractId KeyedAccount
      controller owner
      do
        let targetKey = AccountKey custodian owner accountId
        -- 이 경로의 중복은 아래 부재 조회가 거른다
        existingOpt <- lookupByKey @KeyedAccount targetKey
        assertMsg "DUPLICATE_ACCOUNT_KEY" (existingOpt == None)
        create KeyedAccount with
          accountKey = targetKey
          isFrozen   = False

PQS가 원장보다 수십 밀리초 늦게 반영되는 사이에 같은 고객의 계좌 개설 요청이 두 번 들어오면 어떻게 막습니까?

수탁기관 단일 경로

ManagedAccount의 서명자에는 accountKey.custodian이 반드시 들어가므로 고객 혼자서는 계좌를 만들 수 없습니다. 개설 경로는 수탁기관의 제출 서비스 하나뿐이므로, 그 서비스가 (owner, accountId)별로 요청을 직렬화하고 자체 DB의 유니크 제약으로 중복을 거부하면 됩니다. PQS는 커밋된 상태를 뒤따라 읽는 조회 모델이므로 동시 요청을 막는 데 쓸 수 없습니다. 명령 중복 제거(commandId)는 재시도로 같은 명령이 두 번 커밋되는 것을 막지만 중복 제거 기간 안에서만 동작하므로, 영구적인 유일성 보장으로 쓰지 마십시오.

멀티 동기화기 이점

계약 키에 의존하지 않는 ManagedAccount는 USD 결제 동기화기에서 EUR 결제 동기화기나 담보 관리 동기화기로 재할당(Reassignment)할 때 키 제약을 받지 않습니다. 이해관계자들의 참여자 노드가 대상 동기화기에도 연결되어 있으면 됩니다.

3. 패턴 32.3 · 상품·계좌·보유분 3계층 분리

문제

흔한 실수는 계좌 템플릿에 usdBalance : Decimal, eurBalance : Decimal 같은 필드를 직접 두는 것입니다. 그러면 “이번 달부터 3년 만기 국채와 항공기 엔진 리스 신탁 수익권도 같은 위탁계좌에 담아 달라”는 요청이 올 때마다 모든 계좌 계약을 마이그레이션해야 합니다. 반대로 압류 명령이나 자금세탁방지(Anti-Money Laundering, AML) 경보가 오면 계좌의 모든 종목을 한 번에 동결할 수 있어야 합니다.

계약 설계

계좌(CustodyAccount), 상품 정의(Instrument), 보유분(Holding)을 세 계층으로 나눕니다. 세 계약은 값 식별자 AccountKey와 InstrumentKey로만 연결됩니다. 새 통화나 채권을 담을 때 계좌 계약을 고칠 필요가 없고, 계좌 상태를 Frozen으로 바꾸면 그 계좌를 거치는 모든 종목의 이전이 막힙니다. 단, 동결은 이전 경로가 계좌 상태를 검사할 때만 효과가 있습니다. 아래 VerifiedTransferRequest처럼 모든 이전 경로가 송신·수신 계좌를 fetch로 확인해야 합니다.

1970년대 벨 연구소 매뉴얼 화풍의 3단 병풍 도해: 왼쪽 칸에는 종목 규격서 도감, 가운데 칸에는 활성·동결 레버가 달린 통장 표지 프레임, 오른쪽 칸에는 다양한 채권과 예금 토큰 보유분 카드들이 깔끔한 점선 식별자로 연결된 스팟 일러스트
[FIG 32.3] 상품(Instrument)·계좌(CustodyAccount)·보유분(Holding) 3계층 분리. 계좌 계약을 고치지 않고 새 자산을 담고, 계좌 상태 하나로 모든 종목의 이전을 통제한다.
삽화 구성 및 생성 프롬프트 보기 열기 / 닫기
연출 의도: 글로벌 커스터디 종합계좌와 증권사 다통화 위탁계좌의 핵심 설계 원리인 Instrument·Account·Holding 3단 분리 아키텍처를 세 칸의 정갈한 벨 연구소 카탈로그 시스템으로 형상화.
Minimalist abstract 1970s Bell Labs systems manual doodle and vintage Saul Steinberg editorial spot cartoon on empty aged warm-gray newsprint paper. A clean three-panel architectural triptych: Panel 1 shows a master specification blueprint card (Instrument); Panel 2 shows a sturdy passbook binder cover equipped with a crisp Active/Frozen toggle switch (Account); Panel 3 shows diverse interchangeable asset slips—currency notes, bond coupons, and equity tickets—neatly referencing both via dotted alignment lines (Holdings). 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

코드

패턴 32.3 · 상품(Instrument)·수탁계좌(CustodyAccount)·검증 이전(VerifiedTransfer) Daml
module Patterns.AccountTriptych where

import Patterns.HoldingStandard
import Patterns.RegistryAccount (AccountStatus(..))

-- 1계층: 상품 정의 (설명·표시 소수점 등 메타데이터)
template Instrument
  with
    instrumentKey : InstrumentKey
    description   : Text
    decimalPlaces : Int
    observers     : [Party]
  where
    signatory instrumentKey.issuer
    observer observers
    ensure decimalPlaces >= 0 && decimalPlaces <= 10 && description /= ""

-- 2계층: 수탁 계좌 (동결·해제 통제와 비소비 상태 확인)
template CustodyAccount
  with
    accountKey : AccountKey
    status     : AccountStatus
  where
    signatory accountKey.custodian, accountKey.owner

    choice SetAccountStatus : ContractId CustodyAccount
      with
        newStatus : AccountStatus
      controller accountKey.custodian
      do
        create this with status = newStatus

    nonconsuming choice AssertAccountActive : ()
      controller accountKey.owner
      do
        assertMsg "ACCOUNT_IS_FROZEN" (status == Active)

-- 3계층 결합: 송신·수신 CustodyAccount가 모두 Active인지 확인한 뒤 보유분 이전
template VerifiedTransferRequest
  with
    senderAccount   : AccountKey
    receiverAccount : AccountKey
    holdingCid      : ContractId Holding
  where
    signatory senderAccount.owner
    observer receiverAccount.owner

    choice AcceptVerifiedTransfer : ContractId Holding
      with
        senderAcctCid   : ContractId CustodyAccount
        receiverAcctCid : ContractId CustodyAccount
      controller receiverAccount.owner
      do
        senderAcct   <- fetch senderAcctCid
        receiverAcct <- fetch receiverAcctCid
        assertMsg "SENDER_ACCT_KEY_MISMATCH" (senderAcct.accountKey == senderAccount)
        assertMsg "RECEIVER_ACCT_KEY_MISMATCH" (receiverAcct.accountKey == receiverAccount)
        assertMsg "SENDER_ACCOUNT_FROZEN" (senderAcct.status == Active)
        assertMsg "RECEIVER_ACCOUNT_FROZEN" (receiverAcct.status == Active)
        exercise holdingCid (Transfer receiverAccount)

상태 전이와 실패 양상

AcceptVerifiedTransfer는 이전 요청과 송신인의 보유분을 아카이브하고 수신 계좌의 보유분을 생성합니다. 두 CustodyAccount는 조회만 되므로 남습니다. 권한 검산: 본문 권한 \(\{\mathrm{sender}, \mathrm{receiver}\}\)는 Transfer의 controller(현재 소유자와 새 소유자)를 덮습니다. 가시성은 따로 챙겨야 합니다. 커맨드를 해석하는 수신인의 참여자 노드는 송신인의 CustodyAccount와 보유분의 이해관계자가 아니므로, 송신인이 두 계약을 명시적 공개(DisclosedContract)로 넘기거나 보유분의 observers에 수신인을 넣어야 합니다. 계좌 동결과 이전 수락이 경합하면 먼저 순서가 정해진 쪽이 이깁니다. 동결이 먼저 커밋되면 수락 트랜잭션이 참조한 CustodyAccount가 이미 아카이브되어 거절됩니다.

4. 패턴 32.4 · 발행과 소각 창구 (MintAndBurnDesk)

문제

분할·병합·이전은 보유자와 수탁기관의 권한으로 충분하지만, 공급량을 늘리는 발행(Mint)과 상환하며 줄이는 소각(Burn)은 발행기관(issuer), 수탁기관(custodian), 보유자(owner)의 권한이 모두 필요합니다. 기관용 예금 토큰이나 머니마켓펀드(Money Market Fund, MMF) 좌수 발행에서는 제30장의 자격 증명 IssuerAuthorization이 유효한지와 입고 계좌 CustodyAccount가 Active인지를 함께 확인해야 무자격 계좌로 발행되지 않습니다.

계약 설계

발행기관과 수탁기관이 함께 서명한 MintAndBurnDesk가 공급량을 바꾸는 유일한 경로입니다. 발행은 두 단계입니다. 발행기관이 ProposeMint로 자격과 계좌를 확인한 뒤 MintOffer를 만들고, 보유자가 AcceptMint로 수락하면 세 당사자가 서명한 FungibleHolding이 생성됩니다. 소각은 한 트랜잭션에서 보유분을 아카이브하고 RedemptionReceipt를 생성합니다.

코드

패턴 32.4 · 자격 확인 발행(Mint)과 상환 영수증을 남기는 소각(Burn) Daml
module Patterns.MintAndBurn where

import Patterns.HoldingStandard
import Patterns.AccountTriptych (CustodyAccount(..))
import Patterns.RegistryAccount (AccountStatus(..))

-- 제30장 자격 증명 패턴: 발행기관이 적격 고객에게 부여한 보유 자격 (발행 한도 포함)
template IssuerAuthorization
  with
    issuer     : Party
    holder     : Party
    maxMintCap : Decimal
    expiresAt  : Time
  where
    signatory issuer
    observer holder
    ensure maxMintCap > 0.0

-- 소각과 같은 트랜잭션에서 생성되는 상환 증빙
template RedemptionReceipt
  with
    instrument   : InstrumentKey
    redeemer     : Party
    burnedAmount : Decimal
    redeemedAt   : Time
    wireRef      : Text
  where
    signatory instrument.issuer, redeemer

-- 발행·소각 창구 (예금 토큰 발행·상환, MMF 설정·환매)
template MintAndBurnDesk
  with
    instrument : InstrumentKey
    custodian  : Party
  where
    signatory instrument.issuer, custodian

    -- 고객 입금 확인 후 발행기관이 자격·계좌를 검사하고 발행 제안을 만든다
    nonconsuming choice ProposeMint : ContractId MintOffer
      with
        targetAccount : AccountKey
        mintAmount    : Decimal
        authCid       : ContractId IssuerAuthorization
        accountCid    : ContractId CustodyAccount
      controller instrument.issuer
      do
        now  <- getTime
        auth <- fetch authCid
        acct <- fetch accountCid
        assertMsg "AUTH_ISSUER_MISMATCH" (auth.issuer == instrument.issuer)
        assertMsg "AUTH_HOLDER_MISMATCH" (auth.holder == targetAccount.owner)
        assertMsg "AUTH_EXPIRED" (now < auth.expiresAt)
        assertMsg "EXCEEDS_MINT_CAP" (mintAmount > 0.0 && mintAmount <= auth.maxMintCap)
        assertMsg "TARGET_ACCT_MISMATCH" (acct.accountKey == targetAccount && targetAccount.custodian == custodian)
        assertMsg "TARGET_ACCT_FROZEN" (acct.status == Active)
        create MintOffer with
          instrument
          targetAccount
          mintAmount

    -- 보유자가 환매를 청구하면 보유분 소각과 상환 영수증 생성을 한 트랜잭션에서 실행
    nonconsuming choice BurnAndRedeem : ContractId RedemptionReceipt
      with
        holdingCid : ContractId FungibleHolding
        redeemer   : Party
        wireRef    : Text
      controller redeemer
      do
        holding <- fetch holdingCid
        assertMsg "BURN_INSTRUMENT_MISMATCH" (holding.instrument == instrument)
        assertMsg "NOT_HOLDING_OWNER" (holding.account.owner == redeemer)
        assertMsg "CUSTODIAN_MISMATCH" (holding.account.custodian == custodian)
        now <- getTime
        archive holdingCid
        create RedemptionReceipt with
          instrument
          redeemer
          burnedAmount = holding.amount
          redeemedAt   = now
          wireRef

template MintOffer
  with
    instrument    : InstrumentKey
    targetAccount : AccountKey
    mintAmount    : Decimal
  where
    signatory instrument.issuer, targetAccount.custodian
    observer targetAccount.owner

    choice AcceptMint : ContractId Holding
      controller targetAccount.owner
      do
        hCid <- create FungibleHolding with
          instrument
          account   = targetAccount
          amount    = mintAmount
          observers = []
        pure (toInterfaceContractId hCid)

실패 양상 — 증빙 없는 소각: 소각 초이스에 archive holdingCid 한 줄만 두면, 원장에서 예금 토큰은 사라졌는데 은행의 지급 시스템에 장애가 났을 때 고객에게 남는 청구 증빙이 없습니다. 패턴 32.4처럼 소각과 RedemptionReceipt(또는 지급 지시 계약) 생성을 한 트랜잭션에 묶어야 원장 공급량과 오프체인 지급을 대사할 수 있습니다. 가시성: MintAndBurnDesk에는 observer가 없으므로, 보유자가 BurnAndRedeem을 행사하려면 창구 계약을 명시적 공개로 받거나 창구에 보유자를 observer로 추가해야 합니다. 권한 검산: BurnAndRedeem 본문 권한 \(\{\mathrm{issuer}, \mathrm{custodian}, \mathrm{redeemer}\}\)은 보유분 아카이브(서명자 issuer·custodian·owner, owner = redeemer)와 영수증 생성(서명자 issuer·redeemer)을 모두 덮습니다.

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

변형과 조합

패턴 32.1의 Split은 제31장의 잠금과 함께 쓰여, 보유분 일부만 잘라 잠글 수 있게 합니다. 패턴 32.3의 계좌 상태 검사는 제33장의 DvP 다리마다 넣을 수 있습니다. 패턴 32.4의 발행 창구는 제34장의 기업행위(배당·상환)에서 신규 발행과 소각의 경로로 다시 쓰입니다.

규제 대응

증권 장부 무결성의 일반 원칙: 증권을 전자적으로 기록하는 중앙예탁기관과 계좌관리기관은 권리자별·종목별 수량을 정확히 기록하고, 계좌들의 합계가 발행 총량을 넘지 않도록 해야 합니다(초과 기재 금지). EU 중앙예탁기관 규정(CSDR)의 발행 무결성(integrity of the issue) 요건과 미국 Uniform Commercial Code(UCC) 제8편의 증권 계좌 보유 원칙이 대표적입니다. 장부 기재는 권리 추정과 선의취득 보호의 근거가 되므로, 장부 오류는 곧 권리 분쟁이 됩니다.

FungibleHolding의 ensure amount > 0.0과 Split·Merge의 총량 보존식(INVARIANT 32.1)은 일반 이전 경로에서 초과 기재가 생기지 않게 하고, 공급량 변경은 패턴 32.4의 창구로만 일어나게 합니다. Instrument·CustodyAccount·Holding의 3계층 분리와 공통 인터페이스는 예금 토큰부터 국채·신탁 수익권까지 하나의 계좌 체계에 담습니다.

이 장에서 남는 것

  1. 보유분 인터페이스와 총량 보존. 이 장의 설명용 interface Holding은 자산 템플릿을 추상화하고 Split·Merge·Transfer를 선언하며, 두 연산은 양수 조건(\(v_i > 0\)) 아래 입력 합계와 출력 합계를 정확히 보존한다. CIP-0056 Holding은 초이스 없이 뷰(owner, instrumentId, amount, lock, meta)만 제공한다.
  2. 멀티 동기화기 환경의 두 길. 멀티 동기화기 환경에서는 부재 키 조회 대신 수탁기관의 AccountRegistry 초대·수락과 PQS 조회 후 계약 ID를 명시적으로 넘기는 방식을 쓰고, 계약 키는 재할당이 없는 단일 동기화기 환경에서만 쓴다.
  3. 상품·계좌·보유분 3계층 분리. 계좌(CustodyAccount), 상품 정의(Instrument), 보유분(Holding)을 분리하면 코드 수정 없이 다통화·다종목 계좌를 구성하고, 모든 이전 경로가 계좌 상태를 검사하는 한 계좌 상태 하나로 이전을 통제할 수 있다.
  4. 자격 확인 발행과 영수증을 남기는 소각. MintAndBurnDesk는 제30장의 IssuerAuthorization과 계좌 상태를 확인한 뒤에만 발행하고, 소각할 때는 RedemptionReceipt를 같은 트랜잭션에서 생성해 원장 공급량과 오프체인 준비금을 대사할 수 있게 한다.