From 56d7cacda11258c6ecf3773a5f86223afbe3d354 Mon Sep 17 00:00:00 2001 From: Haseeb Rabbani Date: Wed, 18 Nov 2026 13:18:42 +0400 Subject: [PATCH 1/2] L-05: Split consumeHolding into fund, deliver and return operations Replace HoldingOps.consumeHolding with fundHolding (caller-supplied inputs), deliverHolding (locked funding paid out on accept and settle) and returnHolding (locked funding returned on reject, withdraw, expire, cancel). Each takes the exercising choice's ChoiceContext, so a spend rule runs only on its own paths and can read the submitter's context (N-10). Add holdingOpsFor @t and build the default operations with it. The custom example exercises MyHolding_Spend on funding and delivery and archives on returns, so a freeze never holds back locked funds returning to their owner. Closes #90 --- CHANGELOG.md | 6 + examples/README.md | 2 +- .../Examples/Token/Cip112/Custom/Test.daml | 92 ++- examples/token/token-cip112-custom/README.md | 2 +- .../Examples/Token/Cip112/Custom.daml | 64 +- packages/token/token-cip112-utils/README.md | 45 +- .../Token/Cip112/Utils/Allocation.daml | 23 +- .../Token/Cip112/Utils/Holding.daml | 130 +++- .../Token/Cip112/Utils/Registry.daml | 18 +- .../Token/Cip112/Utils/Transfer.daml | 31 +- .../OpenZeppelin/Token/Cip112/V1/Holding.daml | 12 +- .../Token/Cip112/V1/Transfer.daml | 6 +- .../OpenZeppelin/Token/Cip112/Utils/Test.daml | 26 +- .../Token/Cip112/Utils/Test/Hooks.daml | 629 ++++++++++++++++++ .../Token/Cip112/V1/Test/ForeignHolding.daml | 7 +- 15 files changed, 970 insertions(+), 123 deletions(-) create mode 100644 test/token-cip112-utils-test/daml/OpenZeppelin/Token/Cip112/Utils/Test/Hooks.daml diff --git a/CHANGELOG.md b/CHANGELOG.md index 083d86f..9ea761b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,6 +54,12 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) parameterised over the caller's templates through a `HoldingOps` record and constructor and pinning operations. It defines no serializable types and depends on `openzeppelin-token-cip112-types-v1`. +- `HoldingOps` consumes holdings through three operations, `fundHolding` + for caller-supplied inputs, `deliverHolding` for locked funding paid out, + and `returnHolding` for locked funding returned to its owner, so a spend + rule runs only on its own paths. Each receives the exercising choice's + `ChoiceContext` and the holding id. `holdingOpsFor @T` sets all three to + `consumeByArchive @T`. ### `openzeppelin-token-cip112-v1` diff --git a/examples/README.md b/examples/README.md index 7fcb880..3e88256 100644 --- a/examples/README.md +++ b/examples/README.md @@ -36,7 +36,7 @@ and `openzeppelin-token-cip112-utils`. | Example | Tests | Shows | |---|---|---| | [`token-cip112-trading-test`](token/token-cip112-trading-test/) | scripts only | Running the default templates of `openzeppelin-token-cip112-v1`: launching a token from the DAR, allocations funded through the standard factory, exact-cover DvP batch settlement, and the iterated-settlement deposit flow | -| [`token-cip112-custom`](token/token-cip112-custom/) | [`token-cip112-custom-test`](token/token-cip112-custom-test/) | A compliance-grade consumer that owns its own holding, instruction, allocation, and registry templates and reuses `openzeppelin-token-cip112-types-v1` and `openzeppelin-token-cip112-utils` unchanged: roles, an auditor, a compliance freeze enforced through the spend hook, a pause switch, a fee on transfer built from two workflow calls, and an executor allowlist | +| [`token-cip112-custom`](token/token-cip112-custom/) | [`token-cip112-custom-test`](token/token-cip112-custom-test/) | A compliance-grade consumer that owns its own holding, instruction, allocation, and registry templates and reuses `openzeppelin-token-cip112-types-v1` and `openzeppelin-token-cip112-utils` unchanged: roles, an auditor, a compliance freeze enforced through the funding and delivery operations, a pause switch, a fee on transfer built from two workflow calls, and an executor allowlist | ## Build and run diff --git a/examples/token/token-cip112-custom-test/daml/OpenZeppelin/Examples/Token/Cip112/Custom/Test.daml b/examples/token/token-cip112-custom-test/daml/OpenZeppelin/Examples/Token/Cip112/Custom/Test.daml index ec49624..604f7d6 100644 --- a/examples/token/token-cip112-custom-test/daml/OpenZeppelin/Examples/Token/Cip112/Custom/Test.daml +++ b/examples/token/token-cip112-custom-test/daml/OpenZeppelin/Examples/Token/Cip112/Custom/Test.daml @@ -1,7 +1,8 @@ -- | Drives `OpenZeppelin.Examples.Token.Cip112.Custom` through the Token Standard V2 interfaces and checks --- each consumer addition: the auditor sees every contract, every consumption --- runs `MyHolding_Spend`, a late acceptance creates a `MyHolding`, iteration --- successors are `MyAllocation`s, a frozen holding cannot move on any path, +-- each consumer addition: the auditor sees every contract, funding and +-- payouts run `MyHolding_Spend` while returns do not, a late acceptance +-- creates a `MyHolding`, iteration successors are `MyAllocation`s, a frozen +-- holding cannot fund any workflow, -- the pause switch blocks the factories, mint offers, and burns, the fee -- leg pays the treasury and exempts burns, the -- executor allowlist is enforced, roles are separate, expired funding is @@ -278,10 +279,10 @@ testLateAcceptCreatesMyHolding = do bobHoldings <- query @MyHolding bob all (\(_, h) -> h.roles.auditor == auditor && not h.frozen) bobHoldings === True --- | Every consumption goes through the consumer's spend choice. A one-step --- transfer funded by two inputs exercises it twice; a burn once. -testSpendChoiceRunsOnEveryConsumption : Script () -testSpendChoiceRunsOnEveryConsumption = do +-- | Funding goes through the consumer's spend choice. A one-step transfer +-- funded by two inputs exercises it twice; a burn once. +testSpendChoiceRunsOnFunding : Script () +testSpendChoiceRunsOnFunding = do app@App{..} <- setup in1 <- mint app alice 4.0 in2 <- mint app alice 6.0 @@ -296,6 +297,73 @@ testSpendChoiceRunsOnEveryConsumption = do countSpends burnTree === 1 balanceSeenBy bob bob >>= (=== []) +-- | The unlocked holdings `owner` owns. +unlockedOf : Party -> Script [ContractId HoldingV2.Holding] +unlockedOf owner = do + holdings <- queryFilter @MyHolding owner + (\h -> isNone h.holding.lock && h.holding.account.owner == Some owner) + pure [toInterfaceContractId cid | (cid, _) <- holdings] + +-- | A pending transfer of `amount` from alice to bob, funded by all of +-- alice's unlocked holdings. +alicePendingTransfer : App -> Decimal -> Script (ContractId TransferInstructionV2.TransferInstruction) +alicePendingTransfer app@App{..} amount = do + inputs <- unlockedOf alice + result <- submit (actAs alice <> discloseMany [rulesDisclosure]) + (transferCmd app [alice] (mkTransfer app alice bob amount inputs)) + pendingCid result + +-- | Paying out locked funding, on accept or settle, runs the spend choice. +-- Returning it to its owner, on reject, withdraw, cancel, or expiry, +-- archives it without the spend, so the freeze check never runs there. +testSpendRunsOnPayoutButNotOnReturn : Script () +testSpendRunsOnPayoutButNotOnReturn = do + app@App{..} <- setup + _ <- mint app alice 10.0 + + accepted <- alicePendingTransfer app 4.0 + acceptTree <- submitTree (actAs bob) do + exerciseCmd accepted TransferInstructionV2.TransferInstruction_Accept with + actors = [bob]; extraArgs = emptyExtraArgs + countSpends acceptTree === 1 + + rejected <- alicePendingTransfer app 2.0 + rejectTree <- submitTree (actAs bob) do + exerciseCmd rejected TransferInstructionV2.TransferInstruction_Reject with + actors = [bob]; extraArgs = emptyExtraArgs + countSpends rejectTree === 0 + + withdrawn <- alicePendingTransfer app 2.0 + withdrawTree <- submitTree (actAs alice) do + exerciseCmd withdrawn TransferInstructionV2.TransferInstruction_Withdraw with + actors = [alice]; extraArgs = emptyExtraArgs + countSpends withdrawTree === 0 + + let leg = mkLeg "leg-1" alice bob 3.0 + cancelled <- allocate app alice (mkSpec app alice [senderSide leg] None) =<< unlockedOf alice + cancelTree <- submitTree (actAs exchange) do + exerciseCmd cancelled AllocationV2.Allocation_Cancel with + actors = [exchange]; extraArgs = emptyExtraArgs + countSpends cancelTree === 0 + + aliceAlloc <- allocate app alice (mkSpec app alice [senderSide leg] None) =<< unlockedOf alice + bobAlloc <- allocate app bob (mkSpec app bob [receiverSide leg] None) [] + settleTree <- submitTree (actAs exchange <> discloseMany [rulesDisclosure]) + (settleBatchCmd app [leg] (map nonIteratedAllocation [aliceAlloc, bobAlloc])) + -- Alice's one locked holding; bob's allocation locks nothing. + countSpends settleTree === 1 + + expiring <- alicePendingTransfer app 1.0 + setTime t3 + expireTree <- submitTree (actAs admin) do + exerciseCmd rulesCid MyRules_ExpireTransferInstructions with + instructionCids = [fromInterfaceContractId @MyTransferInstruction expiring] + countSpends expireTree === 0 + + balanceSeenBy bob bob >>= (=== [3.0, 4.0]) + balanceSeenBy alice alice >>= (=== [1.0, 2.0]) + assertNoLocks alice + -- | The iteration successor is the consumer's `MyAllocation`, created by the -- constructor the template passed. testIteratedSuccessorIsMyAllocation : Script () @@ -385,10 +453,10 @@ testAuditorObservesEvents = do -- Compliance freeze -------------------- --- | Only the compliance officer can freeze. A frozen holding is refused on --- every consumption path, transfer, allocation, and burn, while the standard --- view still shows it as an ordinary holding. After unfreezing, the same --- transfer goes through. +-- | Only the compliance officer can freeze. A frozen holding is refused as +-- funding for a transfer, an allocation, and a burn, while the standard view +-- still shows it as an ordinary holding. After unfreezing, the same transfer +-- goes through. testFrozenHoldingCannotMove : Script () testFrozenHoldingCannotMove = do app@App{..} <- setup @@ -672,7 +740,7 @@ testSignatoriesArchive = do -- Trust boundary ----------------- --- | The consumer's `consumeHolding` pins the template, so a foreign +-- | The consumer's `fundHolding` pins the template, so a foreign -- `Holding` claiming this admin is refused as funding. template ForeignHolding with attacker : Party diff --git a/examples/token/token-cip112-custom/README.md b/examples/token/token-cip112-custom/README.md index ef74c21..49e958c 100644 --- a/examples/token/token-cip112-custom/README.md +++ b/examples/token/token-cip112-custom/README.md @@ -12,7 +12,7 @@ What it adds, and where each addition lives: |---|---| | Pauser and compliance-officer roles | Controllers of consumer choices; the admin stays the signatory and holds neither power | | Auditor observing every contract and every holdings-change event | A consumer field on each template, reached through the closure that builds `HoldingOps`, plus the `eventObservers` operation | -| Compliance freeze on holdings | A template field plus `MyHolding_Freeze` and `MyHolding_Unfreeze`; `MyHolding_Spend` refuses a frozen holding, so every workflow path refuses it | +| Compliance freeze on holdings | A template field plus `MyHolding_Freeze` and `MyHolding_Unfreeze`; `fundHolding` and `deliverHolding` exercise `MyHolding_Spend`, which refuses a frozen holding, so a frozen holding cannot fund a transfer, allocation, or burn, and a payout of locked funding runs the same check. `returnHolding` stays the pinned archive, so no return path refuses a holding for being frozen | | Pause switch on the registry | A template field plus `MyRules_Pause` and `MyRules_Unpause`, checked before each factory delegates and before a mint offer | | Fee on every transfer except a burn | Two workflow calls composed in the factory body: a one-step fee transfer to the treasury, then the main transfer on the fee leg's change | | Executor allowlist | Checked before delegating to the allocation and settlement workflows | diff --git a/examples/token/token-cip112-custom/daml/OpenZeppelin/Examples/Token/Cip112/Custom.daml b/examples/token/token-cip112-custom/daml/OpenZeppelin/Examples/Token/Cip112/Custom.daml index 7747197..61566c5 100644 --- a/examples/token/token-cip112-custom/daml/OpenZeppelin/Examples/Token/Cip112/Custom.daml +++ b/examples/token/token-cip112-custom/daml/OpenZeppelin/Examples/Token/Cip112/Custom.daml @@ -12,10 +12,14 @@ -- is an informee of every holdings-change event. A consumer field on each -- template, reached through the closure that builds the operations -- record, plus the `eventObservers` operation. --- - A compliance freeze on holdings. A template field plus two choices, and --- the `MyHolding_Spend` hook refuses a frozen holding, so every workflow --- path (transfer, allocation, burn, unlock) refuses it without the --- workflows knowing what a freeze is. +-- - A compliance freeze on holdings. A template field plus two choices. The +-- `fundHolding` and `deliverHolding` operations exercise `MyHolding_Spend`, +-- which refuses a frozen holding, so a frozen holding cannot fund a +-- transfer, an allocation, or a burn, and a payout of locked funding runs +-- the same check, without the workflows knowing what a freeze is. +-- `returnHolding` stays the pinned archive, so no return path refuses a +-- holding for being frozen. `MyHolding_OwnerUnlock` makes the check +-- itself. -- - A pause switch on the registry. A template field plus two choices, -- checked before each factory and the mint offer delegate to the workflow. -- - A fee on every transfer except a burn, paid to the admin's treasury @@ -74,23 +78,33 @@ template MyEventLog with -- | Built inside every choice body from the template's own fields. The -- closure over `roles` is how consumer fields reach `createHolding` without --- the workflows knowing about them. New holdings are never frozen. +-- the workflows knowing about them. New holdings are never frozen. No +-- operation reads the choice context. myOps : Party -> AppRoles -> HoldingOps -myOps admin roles = HoldingOps with - createHolding = \v -> toInterfaceContractId <$> create MyHolding with holding = v; roles; frozen = False - consumeHolding = \cid -> do +myOps admin roles = + (holdingOpsFor @MyHolding createMyHolding withMyEventLog auditorObserves) + with + -- The freeze stops a holding from funding a workflow and from being + -- paid out of one. `returnHolding` stays the pinned archive: a + -- reject, withdraw, expiry, or cancel returns locked funds to their + -- owner without exercising the spend. + fundHolding = const spend + deliverHolding = const spend + where + createMyHolding v = toInterfaceContractId <$> create MyHolding with holding = v; roles; frozen = False + withMyEventLog emit = do + cid <- create MyEventLog with admin + emit (toInterfaceContractId cid) + archive cid + -- The auditor is an informee of every holdings-change event, so it can + -- follow the standard event stream, not only the contracts. + auditorObserves _ = [roles.auditor] -- Pin the template first: a foreign `Holding` never reaches the spend. - fetched <- fetchFromInterface @MyHolding cid - case fetched of - None -> fail "holding is not a MyHolding" - Some (tcid, _) -> exercise tcid MyHolding_Spend - withEventLog = \emit -> do - cid <- create MyEventLog with admin - emit (toInterfaceContractId cid) - archive cid - -- The auditor is an informee of every holdings-change event, so it can - -- follow the standard event stream, not only the contracts. - eventObservers = const [roles.auditor] + spend cid = do + fetched <- fetchFromInterface @MyHolding cid + case fetched of + None -> fail "holding is not a MyHolding" + Some (tcid, _) -> exercise tcid MyHolding_Spend -- Holding ---------- @@ -107,10 +121,10 @@ template MyHolding with observer lockHolders holding.lock, roles.auditor, roles.complianceOfficer ensure isValidHoldingView holding - -- | The only way value leaves this holding. Controlled by the parties - -- whose authority a plain archive would need, so the authorization - -- model is unchanged; what changes is that the spend is a named choice - -- the auditor sees, with a consumer rule inside it. + -- | How funding and payouts consume this holding. Controlled by the + -- parties whose authority a plain archive would need, so the + -- authorization model is unchanged; what changes is that the spend is a + -- named choice the auditor sees, with a consumer rule inside it. choice MyHolding_Spend : HoldingV2.HoldingView controller holding.instrumentId.admin, accountParties holding.instrumentId.admin holding.account do @@ -163,7 +177,7 @@ template MyTransferInstruction with choice MyTransferInstruction_Expire : TransferInstructionV2.TransferInstructionResult controller state.transfer.instrumentId.admin - do transferExpireImpl (ops this) state + do transferExpireImpl (ops this) emptyChoiceContext state choice MyTransferInstruction_AdminGC : () controller state.transfer.instrumentId.admin @@ -325,7 +339,7 @@ transferWithFee rules arg = do inputs <- if fee > 0.0 then do - feeResult <- executeTransfer rules.config (ops rules) (createInstruction rules) True + feeResult <- executeTransfer rules.config (ops rules) arg.extraArgs.context (createInstruction rules) True (transfer with receiver = treasury rules; amount = fee) pure feeResult.senderChangeCids else pure transfer.inputHoldingCids diff --git a/packages/token/token-cip112-utils/README.md b/packages/token/token-cip112-utils/README.md index c672561..a06326b 100644 --- a/packages/token/token-cip112-utils/README.md +++ b/packages/token/token-cip112-utils/README.md @@ -14,10 +14,16 @@ functions, with every template decision left to the caller. ## What it provides - `HoldingOps`: the record a template owner builds inside a choice body with - `createHolding`, `consumeHolding`, `withEventLog`, and `eventObservers` - (extra informees of every holdings-change event, for auditors and - regulators who must see the standard event stream). It holds functions, - so it is never stored. + `createHolding`, three consumption operations, `withEventLog`, and + `eventObservers` (extra informees of every holdings-change event, for + auditors and regulators who must see the standard event stream). The + consumption operations split by where the value goes: `fundHolding` for + caller-supplied inputs, `deliverHolding` for locked funding paid out, and + `returnHolding` for locked funding returned to its owner. Each receives the + `ChoiceContext` the submitter passed. The record holds functions, so it is + never stored. +- `holdingOpsFor @T`: a `HoldingOps` whose three consumption operations are + `consumeByArchive @T`, ready to override one operation with `with`. - `consumeByArchive @T` and `pinAllocationTo @T`: the safe ways to write the consumption and allocation policies, pinned to one template. - `privateAssetAllocateExtraObservers`: the allocation factory's extra @@ -46,10 +52,37 @@ package. Versions follow semver, and the package name carries no `vN` suffix. The workflows trust nothing they did not just create. Every caller-supplied contract id enters through an operation the template owner wrote: -- `consumeHolding` must fail on any holding that is not an accepted - implementation. Use `consumeByArchive @YourHolding`, or a custom spend +- `fundHolding`, `deliverHolding`, and `returnHolding` must each fail on any + holding that is not an accepted implementation, and otherwise archive it + and return its view. Use `holdingOpsFor @YourHolding`, or a custom spend choice reached through `fetchFromInterface @YourHolding`. Never archive a caller-supplied id by interface. +- Each consumption operation runs on its own paths. `fundHolding` consumes + the inputs of the transfer and allocation factories, including one-step + transfers and burns. `deliverHolding` consumes all locked funding on accept + and settle, including an accept's surplus and the part of a settlement that + stays with the authorizer. `returnHolding` consumes locked funding on a + transfer's reject, withdraw, and expiry, and on an allocation's withdraw + and cancel. +- A refusal in `deliverHolding` or `returnHolding` keeps locked funds locked + until the rule passes, and after the lock expires only the holding's + owner-unlock choice recovers them. Put a rule there only if a known party + can lift it without re-creating the locked holding: pending instructions + and allocations name their locked holdings by id, so a replaced holding + orphans them. A rule that only limits new spending, such as a minimum + holding age, belongs in `fundHolding`. +- A rule that tracks live registry state reads the current policy contract + from the context and checks the contract it fetches. A value copied into + the holding does not follow later registry changes, and a policy contract + id stored in the holding fails every spend once the registry replaces that + contract. +- `settleBatchImpl` passes each `Allocation_Settle` an empty context, so a + `deliverHolding` rule that requires a context entry refuses every batch + settlement. `expireAllocationsImpl` cancels its allocations in one + transaction, so one refusing `returnHolding` fails the whole batch. +- `holdingOwnerUnlockImpl` runs none of the consumption operations. A rule + that must block an owner unlock, such as a freeze, is checked inside the + holding's own owner-unlock choice. - The `PinAllocation` passed to `settleBatchImpl` and `expireAllocationsImpl` must fail on any allocation whose choice bodies the registry does not control. Use `pinAllocationTo @YourAllocation`. diff --git a/packages/token/token-cip112-utils/daml/OpenZeppelin/Token/Cip112/Utils/Allocation.daml b/packages/token/token-cip112-utils/daml/OpenZeppelin/Token/Cip112/Utils/Allocation.daml index 84b2546..80ad3a1 100644 --- a/packages/token/token-cip112-utils/daml/OpenZeppelin/Token/Cip112/Utils/Allocation.daml +++ b/packages/token/token-cip112-utils/daml/OpenZeppelin/Token/Cip112/Utils/Allocation.daml @@ -123,7 +123,7 @@ allocationSettleImpl ops createSuccessor self s arg = do require "extra transfer-leg sides must be valid allocation legs" (isValidAllocationSpecificationV2 (const True) (s.allocation with transferLegSides = s.allocation.transferLegSides <> arg.extraTransferLegSides)) - settleAllocation ops createSuccessor self s arg.extraTransferLegSides arg.nextIterationFunding + settleAllocation ops arg.extraArgs.context createSuccessor self s arg.extraTransferLegSides arg.nextIterationFunding -- | `allocation_withdrawImpl`. allocationWithdrawImpl @@ -133,7 +133,7 @@ allocationWithdrawImpl allocationWithdrawImpl ops self s arg = do archiveAndCheckActors self arg.actors [accountParties s.allocation.admin s.allocation.authorizer] ensureWithdrawIsAllowed s.allocation - holdings <- unlockAndLog ops s "allocation withdrawn" + holdings <- unlockAndLog ops arg.extraArgs.context s "allocation withdrawn" pure AllocationV2.AllocationResult with output = AllocationV2.AllocationResult_Withdrawn authorizerHoldingCids = holdings @@ -149,7 +149,7 @@ allocationCancelImpl allocationCancelImpl ops self s arg = do this <- fetch self allocationV2_cancelDefaultImpl this self arg $ do - holdings <- unlockAndLog ops s "allocation cancelled" + holdings <- unlockAndLog ops arg.extraArgs.context s "allocation cancelled" pure (holdings, emptyMetadata) -- | Body of a consuming last-resort admin cleanup choice for an allocation @@ -237,7 +237,7 @@ allocationFactoryImpl config ops createAllocation arg = do expiresAfter = None context = Some ("allocation for settlement " <> arg.settlement.id) - inputAmounts <- debitHoldings (consumeUnlockedHolding ops admin authorizer) arg.inputHoldingCids + inputAmounts <- debitHoldings (consumeUnlockedHolding ops arg.extraArgs.context admin authorizer) arg.inputHoldingCids lockedAndChange <- forA (TextMap.toList (textMapMergeWithDefault (0.0, 0.0) inputAmounts requiredAmounts)) $ \(instrumentId, (inputAmount, requiredAmount)) -> do @@ -293,17 +293,18 @@ allocationFactoryImpl config ops createAllocation arg = do -- every total to be non-negative, reserve the requested next-iteration -- funding as freshly locked holdings, and pay out the remainder unlocked. -- When a reservation is requested a successor allocation is created through --- the owner's constructor. +-- the owner's constructor. `context` reaches `deliverHolding` for every +-- locked holding. settleAllocation - : HoldingOps -> CreateAllocation -> ContractId AllocationV2.Allocation -> AllocationState + : HoldingOps -> ChoiceContext -> CreateAllocation -> ContractId AllocationV2.Allocation -> AllocationState -> [AllocationV2.TransferLegSide] -> Optional (TextMap.TextMap Decimal) -> Update AllocationV2.AllocationResult -settleAllocation ops createSuccessor self s extraTransferLegSides nextIterationFunding = do +settleAllocation ops context createSuccessor self s extraTransferLegSides nextIterationFunding = do let admin = s.allocation.admin authorizer = s.allocation.authorizer effectiveLegSides = s.allocation.transferLegSides <> extraTransferLegSides reserveAmounts = fromOptional TextMap.empty nextIterationFunding - lockedAmounts <- debitHoldings (consumeLockedHolding ops admin authorizer) s.lockedHoldingCids + lockedAmounts <- debitHoldings (consumeLockedHolding ops context admin authorizer) s.lockedHoldingCids let netAmounts = netAllocationCreditAmounts authorizer effectiveLegSides totalAmounts = textMapUnionWith (+) lockedAmounts netAmounts @@ -363,11 +364,11 @@ settleAllocation ops createSuccessor self s extraTransferLegSides nextIterationF -- | Release the locked holdings to the authorizer and log the change. unlockAndLog - : HoldingOps -> AllocationState -> Text + : HoldingOps -> ChoiceContext -> AllocationState -> Text -> Update (TextMap.TextMap [ContractId HoldingV2.Holding]) -unlockAndLog ops s reason = do +unlockAndLog ops context s reason = do let admin = s.allocation.admin - holdings <- unlockHoldings ops admin s.allocation.authorizer s.lockedHoldingCids + holdings <- unlockHoldings ops context admin s.allocation.authorizer s.lockedHoldingCids emitHoldingsChange ops admin s.allocation.authorizer s.settlement.executors s.lockedHoldingCids (concat (textMapValues holdings)) diff --git a/packages/token/token-cip112-utils/daml/OpenZeppelin/Token/Cip112/Utils/Holding.daml b/packages/token/token-cip112-utils/daml/OpenZeppelin/Token/Cip112/Utils/Holding.daml index c0f7400..33c9508 100644 --- a/packages/token/token-cip112-utils/daml/OpenZeppelin/Token/Cip112/Utils/Holding.daml +++ b/packages/token/token-cip112-utils/daml/OpenZeppelin/Token/Cip112/Utils/Holding.daml @@ -15,10 +15,12 @@ -- choice runs. -- -- Trust boundary: the workflows trust nothing they did not just create. A --- caller-supplied holding id only ever enters through `consumeHolding`, --- which must establish that the contract is an accepted implementation --- before the workflow credits its amount. `consumeByArchive` is the safe --- default; an interface `fetch` followed by an interface `archive` is not. +-- caller-supplied holding id only ever enters through `fundHolding`, and the +-- workflows consume the funding they locked through `deliverHolding` or +-- `returnHolding`. Each must establish that the contract is an accepted +-- implementation before the workflow credits its amount. `consumeByArchive` +-- is the safe default; an interface `fetch` followed by an interface +-- `archive` is not. module OpenZeppelin.Token.Cip112.Utils.Holding where import DA.Assert (assertDeadlineExceeded) @@ -48,17 +50,64 @@ isValidRegistryConfig c = -------------------------------------------- -- | What a workflow needs from the template owner. Not serializable. +-- +-- Three operations consume holdings, one per direction the value moves: +-- `fundHolding` for inputs a caller supplies, `deliverHolding` for locked +-- funding paid out, and `returnHolding` for locked funding given back to its +-- owner. Each is both the accepted-implementation policy and the spend rule +-- for its paths, and each takes the `ChoiceContext` the submitter passed to +-- the choice the workflow runs in, followed by the holding id. All three +-- share one law: fail unless the contract is an accepted implementation, +-- then remove the holding from the ledger and return the view it had. +-- +-- A rule in `deliverHolding` or `returnHolding` runs on funding the workflow +-- locked itself, so a refusal holds the locked funds until the rule passes. +-- Once the lock expires, only the holding's owner-unlock choice recovers +-- them. Put a rule there only if a known party can lift it without +-- re-creating the locked holding, such as a compliance officer lifting a +-- freeze kept on a separate per-account contract: a pending instruction or +-- allocation names its locked holdings by id, so replacing one orphans it. +-- A rule that should only stop new spending belongs in `fundHolding` alone. +-- A minimum holding age is one: the workflow creates locked funding, change, +-- and returned holdings when it runs, so each of them is new. +-- +-- A rule that tracks live registry state reads the current policy contract +-- from the context, and the operation checks the contract it fetches: its +-- template, its signatories, and that it covers this holding's admin and +-- account. Neither of the two simpler designs follows the registry. A value +-- copied into the holding when it is created stays fixed after the registry +-- changes it, and a policy contract id stored in the holding fails every +-- spend once the registry replaces that contract. data HoldingOps = HoldingOps with createHolding : HoldingV2.HoldingView -> Update (ContractId HoldingV2.Holding) -- ^ Create a holding from its standard view. Law: the created -- contract's `Holding` view equals the argument, and its signatories -- include `view.instrumentId.admin` and the account parties. Extra -- template fields come from the closure that builds the record. - consumeHolding : ContractId HoldingV2.Holding -> Update HoldingV2.HoldingView - -- ^ Remove a holding from the ledger and return the view it had. Law: - -- fails unless the contract is an accepted implementation. This is the - -- accepted-implementation policy and the spend hook in one place: - -- archive by default, or a custom spend choice. + fundHolding : ChoiceContext -> ContractId HoldingV2.Holding -> Update HoldingV2.HoldingView + -- ^ Consume a caller-supplied input holding that funds a new transfer + -- or allocation, through `consumeUnlockedHolding`: the inputs of + -- `transferFactoryImpl` and `executeTransfer`, including a one-step + -- transfer and a burn, and of `allocationFactoryImpl`. A refusal fails + -- the factory call and leaves every input untouched. + deliverHolding : ChoiceContext -> ContractId HoldingV2.Holding -> Update HoldingV2.HoldingView + -- ^ Consume locked funding to pay it out, through + -- `consumeLockedHolding`: `transferAcceptImpl`, including the admin's + -- accept of a burn request, and `allocationSettleImpl`. Both consume + -- all of the locked funding here, including any part that stays with + -- its owner: an accept's surplus, a settlement's payout to the + -- authorizer, and a reserve rolled into the next iteration. A refusal + -- blocks accept and settle; every return path still runs. + -- `settleBatchImpl` passes each `Allocation_Settle` an empty context, + -- so a rule that requires a context entry refuses every batch + -- settlement. + returnHolding : ChoiceContext -> ContractId HoldingV2.Holding -> Update HoldingV2.HoldingView + -- ^ Consume locked funding to return it to its owner, through + -- `unlockHoldings`: `transferRejectImpl`, `transferWithdrawImpl`, + -- `transferExpireImpl`, `allocationWithdrawImpl`, and + -- `allocationCancelImpl`. A refusal blocks every one of those paths; + -- accept and settle still run. `expireAllocationsImpl` cancels its + -- allocations in turn, so one refusal fails the whole batch. withEventLog : (ContractId TransferEventsV2.EventLog -> Update ()) -> Update () -- ^ Run one emission against an `EventLog` host. The default templates -- supply a transient host created and archived within the transaction. @@ -82,6 +131,25 @@ consumeByArchive cid = do archive tcid pure (view (toInterface @HoldingV2.Holding t)) +-- | An operations record whose three consumption operations are all +-- `consumeByArchive @t`: every path accepts exactly template `t`, ignores +-- the context, and applies no spend rule. The other operations are the +-- arguments. Override a consumption operation with `with` to add a rule to +-- its paths only. +holdingOpsFor + : forall t. (HasFromInterface t HoldingV2.Holding, HasToInterface t HoldingV2.Holding, HasArchive t) + => (HoldingV2.HoldingView -> Update (ContractId HoldingV2.Holding)) + -> ((ContractId TransferEventsV2.EventLog -> Update ()) -> Update ()) + -> (HoldingV2.Account -> [Party]) + -> HoldingOps +holdingOpsFor createHolding withEventLog eventObservers = HoldingOps with + createHolding + fundHolding = \_ -> consumeByArchive @t + deliverHolding = \_ -> consumeByArchive @t + returnHolding = \_ -> consumeByArchive @t + withEventLog + eventObservers + -- Creation-time invariants --------------------------- @@ -123,6 +191,10 @@ newHolding ops admin account instrumentId amount lock = -- has expired, so recreate the holding unlocked and emit an account-local -- `EventLog_HoldingsChange` naming the consumed holding and its replacement. -- `self` is the holding being exercised; the choice itself archives it. +-- +-- None of the consumption operations runs here, so a rule that must block +-- an owner unlock, such as a freeze, is checked inside the holding's own +-- choice before it calls this body. holdingOwnerUnlockImpl : HoldingOps -> ContractId HoldingV2.Holding -> HoldingV2.HoldingView -> Update (ContractId HoldingV2.Holding) @@ -141,25 +213,34 @@ holdingOwnerUnlockImpl ops self holding = do -- Consumption -------------- --- | Consume a locked input holding after validating its identity. +-- | Consume locked funding to pay it out, through `deliverHolding`, after +-- validating its identity. `context` is the context of the choice the +-- workflow runs in. consumeLockedHolding - : HoldingOps -> Party -> HoldingV2.Account -> ContractId HoldingV2.Holding + : HoldingOps -> ChoiceContext -> Party -> HoldingV2.Account -> ContractId HoldingV2.Holding -> Update HoldingV2.HoldingView -consumeLockedHolding ops admin expectedAccount cid = do - h <- ops.consumeHolding cid +consumeLockedHolding ops context admin expectedAccount cid = + ops.deliverHolding context cid >>= checkLockedHolding admin expectedAccount + +-- | The identity checks on a consumed locked holding: this admin, the +-- expected account, and a lock. +checkLockedHolding + : Party -> HoldingV2.Account -> HoldingV2.HoldingView -> Update HoldingV2.HoldingView +checkLockedHolding admin expectedAccount h = do require' ("inputHolding.instrumentId.admin", h.instrumentId.admin) isEqualR ("admin", admin) require' ("inputHolding.account", h.account) isEqualR ("expectedAccount", expectedAccount) require "input holding must be locked" (isSome h.lock) pure h --- | Consume an unlocked input holding after validating its identity. A --- holding whose lock has expired is accepted, giving a combined --- unlock-and-use; unexpired or indefinite locks are rejected. +-- | Consume a caller-supplied input holding through `fundHolding` after +-- validating its identity. A holding whose lock has expired is accepted, +-- giving a combined unlock-and-use; unexpired or indefinite locks are +-- rejected. `context` is the context of the choice the workflow runs in. consumeUnlockedHolding - : HoldingOps -> Party -> HoldingV2.Account -> ContractId HoldingV2.Holding + : HoldingOps -> ChoiceContext -> Party -> HoldingV2.Account -> ContractId HoldingV2.Holding -> Update HoldingV2.HoldingView -consumeUnlockedHolding ops admin expectedAccount cid = do - h <- ops.consumeHolding cid +consumeUnlockedHolding ops context admin expectedAccount cid = do + h <- ops.fundHolding context cid require' ("inputHolding.instrumentId.admin", h.instrumentId.admin) isEqualR ("admin", admin) require' ("inputHolding.account", h.account) isEqualR ("expectedAccount", expectedAccount) forA_ h.lock $ \lock -> case lock.expiresAt of @@ -178,14 +259,15 @@ debitHoldings consume cids = do pure (h.instrumentId.id, h.amount) pure (TextMap.fromListWithR (+) amounts) --- | Release locked holdings back to their account, returning the new unlocked --- holdings keyed by instrument id. +-- | Release locked holdings back to their account through `returnHolding`, +-- returning the new unlocked holdings keyed by instrument id. `context` is +-- the context of the choice the workflow runs in. unlockHoldings - : HoldingOps -> Party -> HoldingV2.Account -> [ContractId HoldingV2.Holding] + : HoldingOps -> ChoiceContext -> Party -> HoldingV2.Account -> [ContractId HoldingV2.Holding] -> Update (TextMap.TextMap [ContractId HoldingV2.Holding]) -unlockHoldings ops admin expectedAccount cids = do +unlockHoldings ops context admin expectedAccount cids = do unlocked <- forA cids $ \cid -> do - h <- consumeLockedHolding ops admin expectedAccount cid + h <- ops.returnHolding context cid >>= checkLockedHolding admin expectedAccount newCid <- ops.createHolding (h with lock = None) pure (h.instrumentId.id, [newCid]) pure (TextMap.fromListWithR (++) unlocked) diff --git a/packages/token/token-cip112-utils/daml/OpenZeppelin/Token/Cip112/Utils/Registry.daml b/packages/token/token-cip112-utils/daml/OpenZeppelin/Token/Cip112/Utils/Registry.daml index 6c3f112..74b40d6 100644 --- a/packages/token/token-cip112-utils/daml/OpenZeppelin/Token/Cip112/Utils/Registry.daml +++ b/packages/token/token-cip112-utils/daml/OpenZeppelin/Token/Cip112/Utils/Registry.daml @@ -18,7 +18,9 @@ import OpenZeppelin.Token.Cip112.Utils.Allocation -- | `settlementFactory_settleBatchImpl`: pin every allocation to an accepted -- implementation, then run the vendored exact-cover settlement. No part of --- the batch's `extraArgs` reaches the allocations' `Allocation_Settle`. +-- the batch's `extraArgs` reaches the allocations' `Allocation_Settle`, so +-- each `deliverHolding` call receives an empty context: a rule there that +-- requires a context entry refuses every batch settlement. -- -- The vendored default validates each `FinalizedAllocation`'s extra legs but -- not its `nextIterationFunding`; the `validateNextIterationArgs` call in @@ -31,10 +33,11 @@ settleBatchImpl pin admin self arg = do require "a settlement batch must cover at least one transfer leg" (not (null arg.transferLegs)) -- Each authorizer witnesses its own `Allocation_Settle`, so nothing from - -- the batch's arguments should reach it: they may describe other authorizers' - -- trades, and the allocation bodies read neither context nor metadata. - -- Information meant for every participant belongs in `SettlementInfo.meta`, - -- which each authorizer already sees and agreed to. + -- the batch's arguments should reach it: they may describe other + -- authorizers' trades. The cost is that the allocation's `deliverHolding` + -- sees an empty context on this path. Information meant for every + -- participant belongs in `SettlementInfo.meta`, which each authorizer + -- already sees and agreed to. let redactedBatchArgs _allocView _settleArg = pure ExtraArgs with context = emptyChoiceContext meta = emptyMetadata @@ -43,7 +46,10 @@ settleBatchImpl pin admin self arg = do -- | Body of a batched admin-expiry choice: each allocation is pinned, and -- actors, admin, and expiry are re-verified per allocation independently of --- the cancel implementation. +-- the cancel implementation. Each cancel's own `extraArgs` reaches the +-- allocation's `returnHolding`. The cancels run in turn in one transaction, +-- so a single refusal fails the whole batch: leave out an allocation whose +-- `returnHolding` refuses, and expire it once the rule passes. expireAllocationsImpl : PinAllocation -> Party -> [(ContractId AllocationV2.Allocation, AllocationV2.Allocation_Cancel)] diff --git a/packages/token/token-cip112-utils/daml/OpenZeppelin/Token/Cip112/Utils/Transfer.daml b/packages/token/token-cip112-utils/daml/OpenZeppelin/Token/Cip112/Utils/Transfer.daml index dbb5dfc..0aa1c1c 100644 --- a/packages/token/token-cip112-utils/daml/OpenZeppelin/Token/Cip112/Utils/Transfer.daml +++ b/packages/token/token-cip112-utils/daml/OpenZeppelin/Token/Cip112/Utils/Transfer.daml @@ -78,7 +78,7 @@ transferAcceptImpl ops self s arg = do assertWithinDeadline "transfer.executeBefore" s.transfer.executeBefore let admin = s.transfer.instrumentId.admin transfer = s.transfer - lockedAmounts <- debitHoldings (consumeLockedHolding ops admin transfer.sender) s.lockedHoldingCids + lockedAmounts <- debitHoldings (consumeLockedHolding ops arg.extraArgs.context admin transfer.sender) s.lockedHoldingCids -- A mint offer locks nothing: the admin's signature on it authorizes the -- new holding. unless (transfer.sender == mintAccount) $ @@ -101,7 +101,7 @@ transferRejectImpl -> Update TransferInstructionV2.TransferInstructionResult transferRejectImpl ops self s arg = do archiveAndCheckActors self arg.actors [receiverParties s.transfer] - returnFundsToSender ops s "transfer rejected" + returnFundsToSender ops arg.extraArgs.context s "transfer rejected" -- | `transferInstruction_withdrawImpl`. transferWithdrawImpl @@ -110,16 +110,18 @@ transferWithdrawImpl -> Update TransferInstructionV2.TransferInstructionResult transferWithdrawImpl ops self s arg = do archiveAndCheckActors self arg.actors [senderParties s.transfer] - returnFundsToSender ops s "transfer withdrawn" + returnFundsToSender ops arg.extraArgs.context s "transfer withdrawn" -- | Body of a consuming admin-expiry choice: the storage bound has passed and --- the locked funds return to the sender. +-- the locked funds return to the sender. The choice has no standard +-- argument, so the template passes `returnHolding` its context, or +-- `emptyChoiceContext` when its operations read none. transferExpireImpl - : HoldingOps -> TransferInstructionState + : HoldingOps -> ChoiceContext -> TransferInstructionState -> Update TransferInstructionV2.TransferInstructionResult -transferExpireImpl ops s = do +transferExpireImpl ops context s = do assertDeadlineExceeded "expiresAt" s.expiresAt - returnFundsToSender ops s "transfer instruction expired" + returnFundsToSender ops context s "transfer instruction expired" -- | Body of a consuming last-resort admin cleanup choice for an instruction -- whose funding was already reclaimed. Creates nothing. @@ -142,26 +144,27 @@ transferFactoryImpl config ops createInstruction arg = do bothSides = dedupSort (senderParties arg.transfer <> receiverParties arg.transfer) actors = dedupSort arg.actors checkActors arg.actors [senders, bothSides] - executeTransfer config ops createInstruction (all (`elem` actors) receivers) arg.transfer + executeTransfer config ops arg.extraArgs.context createInstruction (all (`elem` actors) receivers) arg.transfer -- | Validate, debit the sender's inputs, and either complete in one step or -- lock the transfer amount and create a pending instruction. The caller is -- responsible for authorization: the debit needs the sender's and the admin's -- authority, and the one-step path also creates the receiver's holding. +-- `context` reaches `fundHolding` for every input. -- -- A transfer to the CIP-0112 burn account is a burn. executeTransfer - : RegistryConfig -> HoldingOps -> CreateTransferInstruction -> Bool + : RegistryConfig -> HoldingOps -> ChoiceContext -> CreateTransferInstruction -> Bool -> TransferInstructionV2.Transfer -> Update TransferInstructionV2.TransferInstructionResult -executeTransfer config ops createInstruction oneStep transfer = do +executeTransfer config ops context createInstruction oneStep transfer = do let admin = config.admin validateTransfer config transfer require "transfer sender must be a regular account" (isRegularAccount transfer.sender) require "transfer receiver must be a regular account or the burn account" (isRegularAccount transfer.receiver || transfer.receiver == burnAccount) - inputAmounts <- debitHoldings (consumeUnlockedHolding ops admin transfer.sender) transfer.inputHoldingCids + inputAmounts <- debitHoldings (consumeUnlockedHolding ops context admin transfer.sender) transfer.inputHoldingCids funded <- case TextMap.toList inputAmounts of [(instrumentId, amount)] | instrumentId == transfer.instrumentId.id -> pure amount [] -> fail "transfer requires input holdings to fund it" @@ -313,11 +316,11 @@ logTransferEvents ops eventLogCid transfer senderOutputHoldingCids receiverOutpu -- | Release the locked funding to the sender and log the change. returnFundsToSender - : HoldingOps -> TransferInstructionState -> Text + : HoldingOps -> ChoiceContext -> TransferInstructionState -> Text -> Update TransferInstructionV2.TransferInstructionResult -returnFundsToSender ops s reason = do +returnFundsToSender ops context s reason = do let admin = s.transfer.instrumentId.admin - holdings <- unlockHoldings ops admin s.transfer.sender s.lockedHoldingCids + holdings <- unlockHoldings ops context admin s.transfer.sender s.lockedHoldingCids let senderChangeCids = concat (textMapValues holdings) emitHoldingsChange ops admin s.transfer.sender [] s.lockedHoldingCids senderChangeCids [] reason pure TransferInstructionV2.TransferInstructionResult with diff --git a/packages/token/token-cip112-v1/daml/OpenZeppelin/Token/Cip112/V1/Holding.daml b/packages/token/token-cip112-v1/daml/OpenZeppelin/Token/Cip112/V1/Holding.daml index 3d931bb..dd86f61 100644 --- a/packages/token/token-cip112-v1/daml/OpenZeppelin/Token/Cip112/V1/Holding.daml +++ b/packages/token/token-cip112-v1/daml/OpenZeppelin/Token/Cip112/V1/Holding.daml @@ -42,11 +42,11 @@ template TokenHolding with view = holding -- | The operations the default templates run the workflows with: create --- `TokenHolding`, consume by archiving a pinned `TokenHolding`, and emit +-- `TokenHolding`, consume by archiving a pinned `TokenHolding` on every +-- path with no spend rule and no use of the choice context, and emit -- through a transient `TokenEventLog`. defaultHoldingOps : Party -> HoldingOps -defaultHoldingOps admin = HoldingOps with - createHolding = \v -> toInterfaceContractId <$> create TokenHolding with holding = v - consumeHolding = consumeByArchive @TokenHolding - withEventLog = withTempEventLog admin - eventObservers = const [] +defaultHoldingOps admin = holdingOpsFor @TokenHolding + (\v -> toInterfaceContractId <$> create TokenHolding with holding = v) + (withTempEventLog admin) + (const []) diff --git a/packages/token/token-cip112-v1/daml/OpenZeppelin/Token/Cip112/V1/Transfer.daml b/packages/token/token-cip112-v1/daml/OpenZeppelin/Token/Cip112/V1/Transfer.daml index 3397a2f..3583293 100644 --- a/packages/token/token-cip112-v1/daml/OpenZeppelin/Token/Cip112/V1/Transfer.daml +++ b/packages/token/token-cip112-v1/daml/OpenZeppelin/Token/Cip112/V1/Transfer.daml @@ -2,6 +2,7 @@ -- payload whose choices delegate to the utils package. module OpenZeppelin.Token.Cip112.V1.Transfer where +import Splice.Api.Token.MetadataV1 (emptyChoiceContext) import Splice.Api.Token.TransferInstructionV2 qualified as TransferInstructionV2 import OpenZeppelin.Token.Cip112.TypesV1 @@ -35,9 +36,10 @@ template TokenTransferInstruction with choice TokenTransferInstruction_Expire : TransferInstructionV2.TransferInstructionResult -- ^ Admin expiry of a stale instruction: the storage bound has passed - -- and any locked funds return to the sender. + -- and any locked funds return to the sender. The default operations + -- read no context, so the choice takes none. controller state.transfer.instrumentId.admin - do transferExpireImpl (instructionOps state) state + do transferExpireImpl (instructionOps state) emptyChoiceContext state choice TokenTransferInstruction_AdminGC : () -- ^ Last-resort admin cleanup for an instruction whose funding was diff --git a/test/token-cip112-utils-test/daml/OpenZeppelin/Token/Cip112/Utils/Test.daml b/test/token-cip112-utils-test/daml/OpenZeppelin/Token/Cip112/Utils/Test.daml index 2ec0002..f8d1cc5 100644 --- a/test/token-cip112-utils-test/daml/OpenZeppelin/Token/Cip112/Utils/Test.daml +++ b/test/token-cip112-utils-test/daml/OpenZeppelin/Token/Cip112/Utils/Test.daml @@ -3,9 +3,10 @@ -- against a minimal local template it accepts and a foreign template it must -- refuse. The consumption and expiry bodies are run here too, for the -- guards that only a consumer's own `HoldingOps` or allocation template can --- reach. The full workflows run under `test/token-cip112-v1-test` through the --- default templates and under `examples/token/token-cip112-custom-test` --- through a consumer's templates. +-- reach. `OpenZeppelin.Token.Cip112.Utils.Test.Hooks` runs every workflow +-- path through operations with a spend rule. The full workflows run under +-- `test/token-cip112-v1-test` through the default templates and under +-- `examples/token/token-cip112-custom-test` through a consumer's templates. module OpenZeppelin.Token.Cip112.Utils.Test where import DA.Action (unless) @@ -113,12 +114,12 @@ template Harness with nonconsuming choice Harness_ConsumeLocked : HoldingV2.HoldingView with cid : ContractId HoldingV2.Holding; expectedAccount : HoldingV2.Account; actors : [Party] controller actors - do consumeLockedHolding unitOps admin expectedAccount cid + do consumeLockedHolding unitOps emptyChoiceContext admin expectedAccount cid nonconsuming choice Harness_ConsumeUnlocked : HoldingV2.HoldingView with cid : ContractId HoldingV2.Holding; expectedAccount : HoldingV2.Account; actors : [Party] controller actors - do consumeUnlockedHolding unitOps admin expectedAccount cid + do consumeUnlockedHolding unitOps emptyChoiceContext admin expectedAccount cid nonconsuming choice Harness_ExpireAllocations : () with cancelArgs : [(ContractId AllocationV2.Allocation, AllocationV2.Allocation_Cancel)]; actors : [Party] @@ -128,11 +129,10 @@ template Harness with -- | The operations the harness runs the bodies with. Events are not under -- test here, so emission does nothing. unitOps : HoldingOps -unitOps = HoldingOps with - createHolding = \v -> toInterfaceContractId <$> create UnitHolding with holding = v - consumeHolding = consumeByArchive @UnitHolding - withEventLog = \_ -> pure () - eventObservers = const [] +unitOps = holdingOpsFor @UnitHolding + (\v -> toInterfaceContractId <$> create UnitHolding with holding = v) + (\_ -> pure ()) + (const []) basicOwner : HoldingV2.HoldingView -> Party basicOwner v = case v.account.owner of @@ -400,7 +400,9 @@ testEventObserversFor = do let account = HoldingV2.Account with owner = Some alice; provider = Some provider; id = "custody" ops = HoldingOps with createHolding = \_ -> fail "unused" - consumeHolding = \_ -> fail "unused" + fundHolding = \_ _ -> fail "unused" + deliverHolding = \_ _ -> fail "unused" + returnHolding = \_ _ -> fail "unused" withEventLog = \_ -> fail "unused" eventObservers = const [auditor, alice] eventObserversFor ops admin account === dedupSort (accountParties admin account <> [auditor]) @@ -424,7 +426,7 @@ savingsAccount owner = HoldingV2.Account with owner = Some owner; provider = Non -- | The default templates need the instrument admin's authority to consume a -- holding, so another admin's holding fails authorization first. A consumer --- whose `consumeHolding` needs less authority relies on this check. +-- whose `deliverHolding` needs less authority relies on this check. testConsumeLockedRefusesOtherAdmin : Script () testConsumeLockedRefusesOtherAdmin = do Fixture{..} <- setup diff --git a/test/token-cip112-utils-test/daml/OpenZeppelin/Token/Cip112/Utils/Test/Hooks.daml b/test/token-cip112-utils-test/daml/OpenZeppelin/Token/Cip112/Utils/Test/Hooks.daml new file mode 100644 index 0000000..ff86293 --- /dev/null +++ b/test/token-cip112-utils-test/daml/OpenZeppelin/Token/Cip112/Utils/Test/Hooks.daml @@ -0,0 +1,629 @@ +-- | The three consumption operations, path by path. A local template set +-- runs every workflow body through operations built from a `Policy` stored +-- on each contract, with one rule per operation. Each operation exercises a +-- consuming choice on the holding that takes the context it was given, so a +-- transaction tree shows which operation ran on which path and with which +-- context. +-- +-- The scripts check that a rule on new spending leaves locked funding free +-- to move, that a refusing payout or return blocks only its own paths, that +-- every operation receives the context its submitter passed, and the two +-- limits of that delivery: batch settlement passes an empty context, and one +-- refusal fails a whole expiry batch. +module OpenZeppelin.Token.Cip112.Utils.Test.Hooks where + +import DA.Action (replicateA, unless) +import DA.Assert ((===)) +import DA.Date (date, Month(Jan)) +import DA.List (sort) +import DA.Optional (isNone, isSome, optionalToList) +import DA.Text (isInfixOf) +import DA.TextMap qualified as TextMap +import DA.Time (RelTime, addRelTime, days, hours, time) +import Daml.Script + +import Splice.Api.Token.MetadataV1 +import Splice.Api.Token.HoldingV2 qualified as HoldingV2 +import Splice.Api.Token.AllocationV2 qualified as AllocationV2 +import Splice.Api.Token.AllocationInstructionV2 qualified as AllocationInstructionV2 +import Splice.Api.Token.TransferInstructionV2 qualified as TransferInstructionV2 +import Splice.TokenStandard.Utils + +import OpenZeppelin.Token.Cip112.TypesV1 +import OpenZeppelin.Token.Cip112.Utils.Holding +import OpenZeppelin.Token.Cip112.Utils.Transfer +import OpenZeppelin.Token.Cip112.Utils.Allocation +import OpenZeppelin.Token.Cip112.Utils.Registry + +-- Times +-------- + +-- | Holdings are minted at `mintedAt` and everything else happens a day +-- later. `executeBefore` is also the settlement deadline, so instructions +-- and allocations expire there, and their locks expire two hours later. +mintedAt, fundedAt, executeBefore, expiredAt, lockExpired : Time +mintedAt = time (date 2026 Jan 1) 0 0 0 +fundedAt = time (date 2026 Jan 2) 0 0 0 +executeBefore = time (date 2026 Jan 2) 1 0 0 +expiredAt = time (date 2026 Jan 2) 2 0 0 +lockExpired = time (date 2026 Jan 2) 4 0 0 + +-- Policy +--------- + +data Rule + = Allow + | Refuse + | MinAge RelTime + -- ^ The holding must be at least this old. + deriving (Eq, Show) + +-- | One rule per consumption operation. +data Policy = Policy with + fundRule : Rule + deliverRule : Rule + returnRule : Rule + deriving (Eq, Show) + +allowAll : Policy +allowAll = Policy with fundRule = Allow; deliverRule = Allow; returnRule = Allow + +applyRule : Text -> Rule -> Time -> Update () +applyRule operation rule createdAt = case rule of + Allow -> pure () + Refuse -> fail (operation <> " rule refuses") + MinAge age -> do + now <- getTime + require (operation <> " rule: holding is younger than the minimum age") + (now >= createdAt `addRelTime` age) + +-- Local templates +------------------ + +-- | A holding that carries the policy and its creation time. Each operation +-- is a consuming choice taking the context, controlled by the parties a +-- plain archive needs. +template PolicyHolding with + holding : HoldingV2.HoldingView + policy : Policy + createdAt : Time + where + signatory holding.instrumentId.admin, accountParties holding.instrumentId.admin holding.account + observer lockHolders holding.lock + ensure isValidHoldingView holding + + choice PolicyHolding_Fund : HoldingV2.HoldingView + with context : ChoiceContext + controller holding.instrumentId.admin, accountParties holding.instrumentId.admin holding.account + do applyRule "fund" policy.fundRule createdAt >> pure holding + + choice PolicyHolding_Deliver : HoldingV2.HoldingView + with context : ChoiceContext + controller holding.instrumentId.admin, accountParties holding.instrumentId.admin holding.account + do applyRule "deliver" policy.deliverRule createdAt >> pure holding + + choice PolicyHolding_Return : HoldingV2.HoldingView + with context : ChoiceContext + controller holding.instrumentId.admin, accountParties holding.instrumentId.admin holding.account + do applyRule "return" policy.returnRule createdAt >> pure holding + + choice PolicyHolding_OwnerUnlock : ContractId HoldingV2.Holding + controller accountParties holding.instrumentId.admin holding.account + do holdingOwnerUnlockImpl (policyOps policy) (toInterfaceContractId self) holding + + interface instance HoldingV2.Holding for PolicyHolding where + view = holding + +-- | Events are not under test here, so emission does nothing. +policyOps : Policy -> HoldingOps +policyOps policy = HoldingOps with + createHolding = \v -> do + now <- getTime + toInterfaceContractId <$> create PolicyHolding with holding = v; policy; createdAt = now + fundHolding = viaChoice PolicyHolding_Fund + deliverHolding = viaChoice PolicyHolding_Deliver + returnHolding = viaChoice PolicyHolding_Return + withEventLog = \_ -> pure () + eventObservers = const [] + +viaChoice + : HasExercise PolicyHolding c HoldingV2.HoldingView + => (ChoiceContext -> c) -> ChoiceContext -> ContractId HoldingV2.Holding + -> Update HoldingV2.HoldingView +viaChoice mkChoice context cid = do + fetched <- fetchFromInterface @PolicyHolding cid + case fetched of + None -> fail "holding is not a PolicyHolding" + Some (tcid, _) -> exercise tcid (mkChoice context) + +template PolicyInstruction with + state : TransferInstructionState + policy : Policy + where + signatory state.transfer.instrumentId.admin, senderParties state.transfer + observer receiverParties state.transfer + ensure isValidTransferInstructionState state + + interface instance TransferInstructionV2.TransferInstruction for PolicyInstruction where + view = transferInstructionView state + transferInstruction_acceptExtraObservers _ = observer this + transferInstruction_rejectExtraObservers _ = observer this + transferInstruction_withdrawExtraObservers _ = observer this + transferInstruction_acceptImpl self arg = transferAcceptImpl (policyOps policy) self state arg + transferInstruction_rejectImpl self arg = transferRejectImpl (policyOps policy) self state arg + transferInstruction_withdrawImpl self arg = transferWithdrawImpl (policyOps policy) self state arg + + -- | The admin expiry, taking `extraArgs` as the standard choices do. + choice PolicyInstruction_Expire : TransferInstructionV2.TransferInstructionResult + with extraArgs : ExtraArgs + controller state.transfer.instrumentId.admin + do transferExpireImpl (policyOps policy) extraArgs.context state + +template PolicyAllocation with + state : AllocationState + policy : Policy + where + signatory state.allocation.admin, accountParties state.allocation.admin state.allocation.authorizer + observer state.settlement.executors + ensure isValidAllocationState state + + interface instance AllocationV2.Allocation for PolicyAllocation where + view = allocationView state + allocation_settleExtraObservers _ = observer this + allocation_cancelExtraObservers _ = observer this + allocation_withdrawExtraObservers _ = observer this + allocation_settleImpl self arg = + allocationSettleImpl (policyOps policy) (createPolicyAllocation policy) self state arg + allocation_withdrawImpl self arg = allocationWithdrawImpl (policyOps policy) self state arg + allocation_cancelImpl self arg = allocationCancelImpl (policyOps policy) self state arg + +template PolicyRules with + config : RegistryConfig + policy : Policy + where + signatory config.admin + ensure isValidRegistryConfig config + + interface instance TransferInstructionV2.TransferFactory for PolicyRules where + view = TransferInstructionV2.TransferFactoryView with admin = config.admin; meta = emptyMetadata + transferFactory_publicFetchImpl = publicFetchDefaultImpl this + transferFactory_transferExtraObservers = transferFactoryV2_privateAsset_transferExtraObserversDefaultImpl + transferFactory_transferImpl _self arg = + transferFactoryImpl config (policyOps policy) (createPolicyInstruction policy) arg + + interface instance AllocationInstructionV2.AllocationFactory for PolicyRules where + view = AllocationInstructionV2.AllocationFactoryView with admin = config.admin; meta = emptyMetadata + allocationFactory_publicFetchImpl = publicFetchDefaultImpl this + allocationFactory_allocateExtraObservers = privateAssetAllocateExtraObservers + allocationFactory_allocateImpl _self arg = + allocationFactoryImpl config (policyOps policy) (createPolicyAllocation policy) arg + + interface instance AllocationV2.SettlementFactory for PolicyRules where + view = AllocationV2.SettlementFactoryView with admin = config.admin; meta = emptyMetadata + settlementFactory_publicFetchImpl = publicFetchDefaultImpl this + settlementFactory_settleBatchExtraObservers _ = [] + settlementFactory_settleBatchImpl self arg = + settleBatchImpl (pinAllocationTo @PolicyAllocation) config.admin self arg + + nonconsuming choice PolicyRules_ExpireAllocations : () + with cancelArgs : [(ContractId AllocationV2.Allocation, AllocationV2.Allocation_Cancel)] + controller config.admin + do expireAllocationsImpl (pinAllocationTo @PolicyAllocation) config.admin cancelArgs + +createPolicyInstruction : Policy -> CreateTransferInstruction +createPolicyInstruction policy s = + toInterfaceContractId <$> create PolicyInstruction with state = s; policy + +createPolicyAllocation : Policy -> CreateAllocation +createPolicyAllocation policy s = + toInterfaceContractId <$> create PolicyAllocation with state = s; policy + +-- Scenario +----------- + +data World = World with + admin : Party + alice : Party + bob : Party + exchange : Party + rulesCid : ContractId PolicyRules + rulesDisclosure : Disclosure + policy : Policy + +setupWith : Policy -> Script World +setupWith policy = do + admin <- allocateParty "admin" + alice <- allocateParty "alice" + bob <- allocateParty "bob" + exchange <- allocateParty "exchange" + setTime mintedAt + (rulesCid, rulesDisclosure) <- createRules admin policy + pure World with .. + +-- | The world with a new rules contract of the same admin under `policy`. +withRules : World -> Policy -> Script World +withRules w policy = do + (rulesCid, rulesDisclosure) <- createRules w.admin policy + pure w with rulesCid; rulesDisclosure; policy + +createRules : Party -> Policy -> Script (ContractId PolicyRules, Disclosure) +createRules admin policy = do + rulesCid <- submit admin do + createCmd PolicyRules with + config = RegistryConfig with admin; maxTTL = days 2; lockGrace = hours 2 + policy + Some rulesDisclosure <- queryDisclosure @PolicyRules admin rulesCid + pure (rulesCid, rulesDisclosure) + +-- | A holding of 10 for `owner`, created now under the world's policy. +mint : World -> Party -> Script (ContractId HoldingV2.Holding) +mint World{..} owner = do + now <- getTime + cid <- submit (actAs [admin, owner]) do + createCmd PolicyHolding with + holding = mkHoldingView admin (basicAccount owner) "TOK" 10.0 None + policy + createdAt = now + pure (toInterfaceContractId cid) + +ctx : Text -> ChoiceContext +ctx path = ChoiceContext with values = TextMap.fromList [("test/path", AV_Text path)] + +withContext : ChoiceContext -> ExtraArgs +withContext context = ExtraArgs with context; meta = emptyMetadata + +disclosed : World -> Party -> SubmitOptions +disclosed w party = actAs party <> discloseMany [w.rulesDisclosure] + +-- | Alice instructs a transfer of 4 to bob, funded by `inputs`. +transferCmd + : World -> ChoiceContext -> [ContractId HoldingV2.Holding] + -> Commands TransferInstructionV2.TransferInstructionResult +transferCmd World{..} context inputs = + exerciseCmd (toInterfaceContractId @TransferInstructionV2.TransferFactory rulesCid) + TransferInstructionV2.TransferFactory_Transfer with + transfer = TransferInstructionV2.Transfer with + sender = basicAccount alice + receiver = basicAccount bob + amount = 4.0 + instrumentId = HoldingV2.InstrumentId with admin; id = "TOK" + requestedAt = fundedAt + executeBefore + inputHoldingCids = inputs + meta = emptyMetadata + actors = [alice] + extraArgs = withContext context + +pendingTransfer + : World -> [ContractId HoldingV2.Holding] + -> Script (ContractId TransferInstructionV2.TransferInstruction) +pendingTransfer w inputs = do + result <- submit (disclosed w w.alice) (transferCmd w emptyChoiceContext inputs) + case result.output of + TransferInstructionV2.TransferInstructionResult_Pending cid -> pure cid + other -> abort ("expected a pending transfer, got: " <> show other) + +acceptCmd, rejectCmd, withdrawCmd + : World -> ChoiceContext -> ContractId TransferInstructionV2.TransferInstruction + -> Commands TransferInstructionV2.TransferInstructionResult +acceptCmd w context cid = exerciseCmd cid TransferInstructionV2.TransferInstruction_Accept with + actors = [w.bob]; extraArgs = withContext context +rejectCmd w context cid = exerciseCmd cid TransferInstructionV2.TransferInstruction_Reject with + actors = [w.bob]; extraArgs = withContext context +withdrawCmd w context cid = exerciseCmd cid TransferInstructionV2.TransferInstruction_Withdraw with + actors = [w.alice]; extraArgs = withContext context + +expireCmd + : ChoiceContext -> ContractId TransferInstructionV2.TransferInstruction + -> Commands TransferInstructionV2.TransferInstructionResult +expireCmd context cid = exerciseCmd (fromInterfaceContractId @PolicyInstruction cid) + PolicyInstruction_Expire with extraArgs = withContext context + +-- | Alice sends 5 to bob in "trade-1". +tradeLeg : World -> AllocationV2.TransferLeg +tradeLeg World{..} = AllocationV2.TransferLeg with + transferLegId = "leg-1" + sender = basicAccount alice + receiver = basicAccount bob + amount = 5.0 + instrumentId = "TOK" + meta = emptyMetadata + +settlementInfo : World -> AllocationV2.SettlementInfo +settlementInfo World{..} = AllocationV2.SettlementInfo with + executors = [exchange]; id = "trade-1"; cid = None; meta = emptyMetadata + +-- | Alice's sending side of the trade, funded by `inputs`. +allocateCmd + : World -> ChoiceContext -> [ContractId HoldingV2.Holding] + -> Commands AllocationInstructionV2.AllocationInstructionResult +allocateCmd w context inputs = allocateSideCmd w context w.alice (senderSide (tradeLeg w)) inputs + +allocateSideCmd + : World -> ChoiceContext -> Party -> AllocationV2.TransferLegSide -> [ContractId HoldingV2.Holding] + -> Commands AllocationInstructionV2.AllocationInstructionResult +allocateSideCmd w@World{..} context authorizer side inputs = + exerciseCmd (toInterfaceContractId @AllocationInstructionV2.AllocationFactory rulesCid) + AllocationInstructionV2.AllocationFactory_Allocate with + settlement = settlementInfo w + allocation = AllocationV2.AllocationSpecification with + admin + authorizer = basicAccount authorizer + transferLegSides = [side] + settlementDeadline = Some executeBefore + nextIterationFunding = None + committed = False + meta = emptyMetadata + requestedAt = fundedAt + inputHoldingCids = inputs + extraArgs = withContext context + actors = [authorizer] + +completedAllocation + : AllocationInstructionV2.AllocationInstructionResult -> Script (ContractId AllocationV2.Allocation) +completedAllocation result = case result.output of + AllocationInstructionV2.AllocationInstructionResult_Completed cid -> pure cid + other -> abort ("expected a completed allocation, got: " <> show other) + +-- | Alice's sending allocation, funded by `inputs`, and bob's receiving one. +allocateTrade + : World -> [ContractId HoldingV2.Holding] + -> Script (ContractId AllocationV2.Allocation, ContractId AllocationV2.Allocation) +allocateTrade w inputs = do + aliceAlloc <- completedAllocation =<< submit (disclosed w w.alice) (allocateCmd w emptyChoiceContext inputs) + bobAlloc <- completedAllocation =<< submit (disclosed w w.bob) + (allocateSideCmd w emptyChoiceContext w.bob (receiverSide (tradeLeg w)) []) + pure (aliceAlloc, bobAlloc) + +settleBatchCmd + : World -> ChoiceContext -> (ContractId AllocationV2.Allocation, ContractId AllocationV2.Allocation) + -> Commands AllocationV2.SettlementFactory_SettleBatchResult +settleBatchCmd w context (aliceAlloc, bobAlloc) = + exerciseCmd (toInterfaceContractId @AllocationV2.SettlementFactory w.rulesCid) + AllocationV2.SettlementFactory_SettleBatch with + settlement = settlementInfo w + transferLegs = [tradeLeg w] + allocations = map nonIteratedAllocation [aliceAlloc, bobAlloc] + actors = [w.exchange] + extraArgs = withContext context + +-- | `Allocation_Settle` exercised directly by the admin and the executor. +settleCmd : World -> ChoiceContext -> ContractId AllocationV2.Allocation -> Commands AllocationV2.AllocationResult +settleCmd w context cid = exerciseCmd cid AllocationV2.Allocation_Settle with + actors = [w.admin, w.exchange] + extraTransferLegSides = [] + nextIterationFunding = None + extraArgs = withContext context + +cancelCmd : World -> ChoiceContext -> ContractId AllocationV2.Allocation -> Commands AllocationV2.AllocationResult +cancelCmd w context cid = exerciseCmd cid AllocationV2.Allocation_Cancel with + actors = [w.exchange]; extraArgs = withContext context + +allocationWithdrawCmd : World -> ChoiceContext -> ContractId AllocationV2.Allocation -> Commands AllocationV2.AllocationResult +allocationWithdrawCmd w context cid = exerciseCmd cid AllocationV2.Allocation_Withdraw with + actors = [w.alice]; extraArgs = withContext context + +-- | One operation call seen in a transaction tree. +data OpCall = OpCall with + operation : Text + context : ChoiceContext + deriving (Eq, Show) + +opCalls : TransactionTree -> [OpCall] +opCalls tree = concatMap opCallsIn tree.rootEvents + +opCallsIn : TreeEvent -> [OpCall] +opCallsIn (CreatedEvent _) = [] +opCallsIn (ExercisedEvent ex) = + map (\c -> OpCall "fund" c.context) + (optionalToList (fromAnyChoice @PolicyHolding ex.argument : Optional PolicyHolding_Fund)) + <> map (\c -> OpCall "deliver" c.context) + (optionalToList (fromAnyChoice @PolicyHolding ex.argument : Optional PolicyHolding_Deliver)) + <> map (\c -> OpCall "return" c.context) + (optionalToList (fromAnyChoice @PolicyHolding ex.argument : Optional PolicyHolding_Return)) + <> concatMap opCallsIn ex.childEvents + +-- | The amounts `owner` holds. +balanceOf : Party -> Script [Decimal] +balanceOf owner = do + holdings <- query @PolicyHolding owner + pure (sort [h.holding.amount | (_, h) <- holdings, h.holding.account.owner == Some owner]) + +assertNoLocks : Party -> Script () +assertNoLocks owner = do + holdings <- query @PolicyHolding owner + all (\(_, h) -> isNone h.holding.lock) holdings === True + +mustFailWith : Text -> SubmitOptions -> Commands a -> Script () +mustFailWith expected options cmds = do + result <- trySubmit options cmds + case result of + Right _ -> abort "submission succeeded but was expected to fail" + Left err -> unless (expected `isInfixOf` show err) $ + abort ("submission failed for an unexpected reason: " <> show err) + +-- Scripts +---------- + +-- | A minimum-age rule in `fundHolding` gates only new spending. A holding +-- minted at funding time cannot fund a transfer or an allocation. The +-- funding a workflow has just locked is younger still, yet every path that +-- pays it out or returns it runs: accept, reject, withdraw, expire, batch +-- settlement, allocation withdraw, and cancel. +testMinimumAgeFundRuleGatesOnlyFunding : Script () +testMinimumAgeFundRuleGatesOnlyFunding = do + w@World{..} <- setupWith allowAll with fundRule = MinAge (days 1) + [i1, i2, i3, i4, i5, i6, i7] <- replicateA 7 (mint w alice) + setTime fundedAt + fresh <- mint w alice + mustFailWith "fund rule: holding is younger than the minimum age" (disclosed w alice) + (transferCmd w emptyChoiceContext [fresh]) + mustFailWith "fund rule: holding is younger than the minimum age" (disclosed w alice) + (allocateCmd w emptyChoiceContext [fresh]) + + accepted <- pendingTransfer w [i1] + rejected <- pendingTransfer w [i2] + withdrawn <- pendingTransfer w [i3] + expiring <- pendingTransfer w [i4] + _ <- submit (actAs bob) (acceptCmd w emptyChoiceContext accepted) + _ <- submit (actAs bob) (rejectCmd w emptyChoiceContext rejected) + _ <- submit (actAs alice) (withdrawCmd w emptyChoiceContext withdrawn) + + trade <- allocateTrade w [i5] + _ <- submit (disclosed w exchange) (settleBatchCmd w emptyChoiceContext trade) + (withdrawnAlloc, _) <- allocateTrade w [i6] + _ <- submit (actAs alice) (allocationWithdrawCmd w emptyChoiceContext withdrawnAlloc) + (cancelledAlloc, _) <- allocateTrade w [i7] + _ <- submit (actAs exchange) (cancelCmd w emptyChoiceContext cancelledAlloc) + + setTime expiredAt + _ <- submit (actAs admin) (expireCmd emptyChoiceContext expiring) + assertNoLocks alice + balanceOf bob >>= (=== [4.0, 5.0]) + -- 80 minted, 9 paid to bob. + sum <$> balanceOf alice >>= (=== 71.0) + +-- | A refusing `deliverHolding` blocks accept and settle, directly or in a +-- batch, while every return path still gives the funds back: the same +-- instruction and allocation that refused to pay out are rejected and +-- cancelled. +testRefusingDeliverRuleBlocksOnlyPayouts : Script () +testRefusingDeliverRuleBlocksOnlyPayouts = do + w@World{..} <- setupWith allowAll with deliverRule = Refuse + [i1, i2, i3, i4, i5] <- replicateA 5 (mint w alice) + setTime fundedAt + + instr <- pendingTransfer w [i1] + mustFailWith "deliver rule refuses" (actAs bob) (acceptCmd w emptyChoiceContext instr) + _ <- submit (actAs bob) (rejectCmd w emptyChoiceContext instr) + withdrawn <- pendingTransfer w [i2] + _ <- submit (actAs alice) (withdrawCmd w emptyChoiceContext withdrawn) + expiring <- pendingTransfer w [i3] + + trade@(aliceAlloc, _) <- allocateTrade w [i4] + mustFailWith "deliver rule refuses" (disclosed w exchange) (settleBatchCmd w emptyChoiceContext trade) + mustFailWith "deliver rule refuses" (actAs [admin, exchange]) (settleCmd w emptyChoiceContext aliceAlloc) + _ <- submit (actAs exchange) (cancelCmd w emptyChoiceContext aliceAlloc) + (withdrawnAlloc, _) <- allocateTrade w [i5] + _ <- submit (actAs alice) (allocationWithdrawCmd w emptyChoiceContext withdrawnAlloc) + + setTime expiredAt + _ <- submit (actAs admin) (expireCmd emptyChoiceContext expiring) + assertNoLocks alice + balanceOf bob >>= (=== []) + sum <$> balanceOf alice >>= (=== 50.0) + +-- | A refusing `returnHolding` blocks reject, withdraw, expire, allocation +-- withdraw, and cancel, while accept and settle still pay out the same +-- instruction and allocation. The owner unlock runs outside the operations, +-- so once the lock expires the owner recovers funding the rule held. +testRefusingReturnRuleBlocksOnlyReturns : Script () +testRefusingReturnRuleBlocksOnlyReturns = do + w@World{..} <- setupWith allowAll with returnRule = Refuse + [i1, i2, i3] <- replicateA 3 (mint w alice) + setTime fundedAt + + instr <- pendingTransfer w [i1] + mustFailWith "return rule refuses" (actAs bob) (rejectCmd w emptyChoiceContext instr) + mustFailWith "return rule refuses" (actAs alice) (withdrawCmd w emptyChoiceContext instr) + _ <- submit (actAs bob) (acceptCmd w emptyChoiceContext instr) + + trade@(aliceAlloc, _) <- allocateTrade w [i2] + mustFailWith "return rule refuses" (actAs exchange) (cancelCmd w emptyChoiceContext aliceAlloc) + mustFailWith "return rule refuses" (actAs alice) (allocationWithdrawCmd w emptyChoiceContext aliceAlloc) + _ <- submit (disclosed w exchange) (settleBatchCmd w emptyChoiceContext trade) + + expiring <- pendingTransfer w [i3] + setTime expiredAt + mustFailWith "return rule refuses" (actAs admin) (expireCmd emptyChoiceContext expiring) + + setTime lockExpired + [(lockedCid, _)] <- queryFilter @PolicyHolding alice (\h -> isSome h.holding.lock) + _ <- submit (actAs alice) do exerciseCmd lockedCid PolicyHolding_OwnerUnlock + assertNoLocks alice + balanceOf bob >>= (=== [4.0, 5.0]) + sum <$> balanceOf alice >>= (=== 21.0) + +-- | Each operation receives the context its submitter passed: the factory's +-- for every input it funds, and each accept, reject, withdraw, expiry, +-- direct settle, allocation withdraw, and cancel its own, including a +-- cancel run from the admin's expiry batch. Batch settlement passes +-- `deliverHolding` an empty context whatever the batch carried. +testOperationsReceiveTheSubmittersContext : Script () +testOperationsReceiveTheSubmittersContext = do + w@World{..} <- setupWith allowAll + [i1, i2, i3, i4, i5, i6, i7, i8, i9, i10] <- replicateA 10 (mint w alice) + setTime fundedAt + + (instructed, tree) <- submitResultAndTree (disclosed w alice) (transferCmd w (ctx "transfer") [i1, i2]) + opCalls tree === [OpCall "fund" (ctx "transfer"), OpCall "fund" (ctx "transfer")] + accepted <- case instructed.output of + TransferInstructionV2.TransferInstructionResult_Pending cid -> pure cid + other -> abort ("expected a pending transfer, got: " <> show other) + tree <- submitTree (actAs bob) (acceptCmd w (ctx "accept") accepted) + opCalls tree === [OpCall "deliver" (ctx "accept")] + + rejected <- pendingTransfer w [i3] + tree <- submitTree (actAs bob) (rejectCmd w (ctx "reject") rejected) + opCalls tree === [OpCall "return" (ctx "reject")] + + withdrawn <- pendingTransfer w [i4] + tree <- submitTree (actAs alice) (withdrawCmd w (ctx "withdraw") withdrawn) + opCalls tree === [OpCall "return" (ctx "withdraw")] + + expiring <- pendingTransfer w [i5] + + (allocated, tree) <- submitResultAndTree (disclosed w alice) (allocateCmd w (ctx "allocate") [i6]) + opCalls tree === [OpCall "fund" (ctx "allocate")] + aliceAlloc <- completedAllocation allocated + bobAlloc <- completedAllocation =<< submit (disclosed w bob) + (allocateSideCmd w emptyChoiceContext bob (receiverSide (tradeLeg w)) []) + -- Both sides settled directly in one submission, so value is conserved. + tree <- submitTree (actAs [admin, exchange]) + (settleCmd w (ctx "settle") aliceAlloc *> settleCmd w (ctx "settle") bobAlloc) + opCalls tree === [OpCall "deliver" (ctx "settle")] + + (cancelled, _) <- allocateTrade w [i7] + tree <- submitTree (actAs exchange) (cancelCmd w (ctx "cancel") cancelled) + opCalls tree === [OpCall "return" (ctx "cancel")] + + (withdrawnAlloc, _) <- allocateTrade w [i8] + tree <- submitTree (actAs alice) (allocationWithdrawCmd w (ctx "allocation withdraw") withdrawnAlloc) + opCalls tree === [OpCall "return" (ctx "allocation withdraw")] + + trade <- allocateTrade w [i9] + tree <- submitTree (disclosed w exchange) (settleBatchCmd w (ctx "batch") trade) + opCalls tree === [OpCall "deliver" emptyChoiceContext] + + (expiringAlloc, _) <- allocateTrade w [i10] + setTime expiredAt + tree <- submitTree (actAs admin) (expireCmd (ctx "expire") expiring) + opCalls tree === [OpCall "return" (ctx "expire")] + tree <- submitTree (actAs admin) do + exerciseCmd rulesCid PolicyRules_ExpireAllocations with + cancelArgs = + [ ( expiringAlloc + , AllocationV2.Allocation_Cancel with actors = [admin]; extraArgs = withContext (ctx "admin cancel") ) ] + opCalls tree === [OpCall "return" (ctx "admin cancel")] + assertNoLocks alice + +-- | The admin's expiry batch cancels its allocations in one transaction, so +-- one allocation whose `returnHolding` refuses fails the whole batch. The +-- batch without it goes through. +testOneRefusingReturnFailsTheExpiryBatch : Script () +testOneRefusingReturnFailsTheExpiryBatch = do + w@World{..} <- setupWith allowAll + [i1, i2] <- replicateA 2 (mint w alice) + refusing <- withRules w (allowAll with returnRule = Refuse) + setTime fundedAt + (allowed, _) <- allocateTrade w [i1] + (held, _) <- allocateTrade refusing [i2] + setTime expiredAt + let expireCmdFor allocs = exerciseCmd rulesCid PolicyRules_ExpireAllocations with + cancelArgs = + [ (cid, AllocationV2.Allocation_Cancel with actors = [admin]; extraArgs = withContext emptyChoiceContext) + | cid <- allocs ] + mustFailWith "return rule refuses" (actAs admin) (expireCmdFor [allowed, held]) + submit (actAs admin) (expireCmdFor [allowed]) + [(_, stillLocked)] <- queryFilter @PolicyHolding alice (\h -> isSome h.holding.lock) + stillLocked.policy === refusing.policy diff --git a/test/token-cip112-v1-test/daml/OpenZeppelin/Token/Cip112/V1/Test/ForeignHolding.daml b/test/token-cip112-v1-test/daml/OpenZeppelin/Token/Cip112/V1/Test/ForeignHolding.daml index a8abcd1..a04bed4 100644 --- a/test/token-cip112-v1-test/daml/OpenZeppelin/Token/Cip112/V1/Test/ForeignHolding.daml +++ b/test/token-cip112-v1-test/daml/OpenZeppelin/Token/Cip112/V1/Test/ForeignHolding.daml @@ -2,9 +2,10 @@ -- holdings are addressed by interface id, a template that implements -- `HoldingV2.Holding` with attacker-only signatories and a view naming this -- registry's admin would pass every field check in the workflows and be --- credited as funding. The `consumeHolding` operation is the guard: the --- default templates pass `consumeByArchive @TokenHolding`, which fails on any --- other implementation before the workflow reads the amount. +-- credited as funding. The `fundHolding` operation is the guard: the +-- default templates build their operations with `holdingOpsFor @TokenHolding`, +-- so it is `consumeByArchive @TokenHolding`, which fails on any other +-- implementation before the workflow reads the amount. -- -- Each script builds the attack in full and asserts the refusal carries the -- guard's message, so it cannot pass for an unrelated reason. From 7496f3d883e2bcedaced0b09160b5c107dd373d8 Mon Sep 17 00:00:00 2001 From: Nenad Date: Thu, 19 Nov 2026 13:38:20 +0100 Subject: [PATCH 2/2] L-05, N-10: Correct the HoldingOps docs and test the return-path checks (#134) Review fixes for #116 Towards #90 --- CHANGELOG.md | 10 ++-- packages/token/token-cip112-utils/README.md | 24 +++++---- .../Token/Cip112/Utils/Holding.daml | 51 ++++++++++--------- .../Token/Cip112/Utils/Registry.daml | 6 +-- .../OpenZeppelin/Token/Cip112/Utils/Test.daml | 39 ++++++++++++-- .../Test/{Hooks.daml => Operations.daml} | 2 +- 6 files changed, 85 insertions(+), 47 deletions(-) rename test/token-cip112-utils-test/daml/OpenZeppelin/Token/Cip112/Utils/Test/{Hooks.daml => Operations.daml} (99%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ea761b..1ca1e0f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,12 +54,12 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) parameterised over the caller's templates through a `HoldingOps` record and constructor and pinning operations. It defines no serializable types and depends on `openzeppelin-token-cip112-types-v1`. -- `HoldingOps` consumes holdings through three operations, `fundHolding` +- `HoldingOps` consumes holdings through three operations: `fundHolding` for caller-supplied inputs, `deliverHolding` for locked funding paid out, - and `returnHolding` for locked funding returned to its owner, so a spend - rule runs only on its own paths. Each receives the exercising choice's - `ChoiceContext` and the holding id. `holdingOpsFor @T` sets all three to - `consumeByArchive @T`. + and `returnHolding` for locked funding returned to its owner. A rule in + one operation runs only on that operation's paths. Each receives the + exercising choice's `ChoiceContext` and the holding id. `holdingOpsFor @T` + sets all three to `consumeByArchive @T`. ### `openzeppelin-token-cip112-v1` diff --git a/packages/token/token-cip112-utils/README.md b/packages/token/token-cip112-utils/README.md index a06326b..2fbc1b0 100644 --- a/packages/token/token-cip112-utils/README.md +++ b/packages/token/token-cip112-utils/README.md @@ -20,8 +20,8 @@ functions, with every template decision left to the caller. consumption operations split by where the value goes: `fundHolding` for caller-supplied inputs, `deliverHolding` for locked funding paid out, and `returnHolding` for locked funding returned to its owner. Each receives the - `ChoiceContext` the submitter passed. The record holds functions, so it is - never stored. + `ChoiceContext` of the choice the workflow runs in. The record holds + functions, so it is never stored. - `holdingOpsFor @T`: a `HoldingOps` whose three consumption operations are `consumeByArchive @T`, ready to override one operation with `with`. - `consumeByArchive @T` and `pinAllocationTo @T`: the safe ways to write the @@ -64,13 +64,15 @@ contract id enters through an operation the template owner wrote: stays with the authorizer. `returnHolding` consumes locked funding on a transfer's reject, withdraw, and expiry, and on an allocation's withdraw and cancel. -- A refusal in `deliverHolding` or `returnHolding` keeps locked funds locked - until the rule passes, and after the lock expires only the holding's - owner-unlock choice recovers them. Put a rule there only if a known party - can lift it without re-creating the locked holding: pending instructions - and allocations name their locked holdings by id, so a replaced holding - orphans them. A rule that only limits new spending, such as a minimum - holding age, belongs in `fundHolding`. +- A refusal in `deliverHolding` or `returnHolding` leaves the other + operation's paths open, and a refusal in both holds the locked funds until + the lock expires. After that the owner recovers them through the holding's + owner-unlock choice or by passing the holding to a factory, which runs + `fundHolding`. Put a rule in `deliverHolding` or `returnHolding` only if a + known party can lift it without re-creating the locked holding: pending + instructions and allocations name their locked holdings by id, so they can + neither pay out nor return a replaced holding. A rule that only limits new + spending, such as a minimum holding age, belongs in `fundHolding`. - A rule that tracks live registry state reads the current policy contract from the context and checks the contract it fetches. A value copied into the holding does not follow later registry changes, and a policy contract @@ -82,7 +84,9 @@ contract id enters through an operation the template owner wrote: transaction, so one refusing `returnHolding` fails the whole batch. - `holdingOwnerUnlockImpl` runs none of the consumption operations. A rule that must block an owner unlock, such as a freeze, is checked inside the - holding's own owner-unlock choice. + holding's own owner-unlock choice. A rule that must hold funds after the + lock expires also belongs in `fundHolding`, because `transferFactoryImpl` + and `allocationFactoryImpl` accept an input whose lock has expired. - The `PinAllocation` passed to `settleBatchImpl` and `expireAllocationsImpl` must fail on any allocation whose choice bodies the registry does not control. Use `pinAllocationTo @YourAllocation`. diff --git a/packages/token/token-cip112-utils/daml/OpenZeppelin/Token/Cip112/Utils/Holding.daml b/packages/token/token-cip112-utils/daml/OpenZeppelin/Token/Cip112/Utils/Holding.daml index 33c9508..3b93a26 100644 --- a/packages/token/token-cip112-utils/daml/OpenZeppelin/Token/Cip112/Utils/Holding.daml +++ b/packages/token/token-cip112-utils/daml/OpenZeppelin/Token/Cip112/Utils/Holding.daml @@ -55,29 +55,34 @@ isValidRegistryConfig c = -- `fundHolding` for inputs a caller supplies, `deliverHolding` for locked -- funding paid out, and `returnHolding` for locked funding given back to its -- owner. Each is both the accepted-implementation policy and the spend rule --- for its paths, and each takes the `ChoiceContext` the submitter passed to --- the choice the workflow runs in, followed by the holding id. All three --- share one law: fail unless the contract is an accepted implementation, --- then remove the holding from the ledger and return the view it had. +-- for its paths, and each takes the `ChoiceContext` of the choice the +-- workflow runs in, followed by the holding id. All three share one law: +-- fail unless the contract is an accepted implementation, then remove the +-- holding from the ledger and return the view it had. -- -- A rule in `deliverHolding` or `returnHolding` runs on funding the workflow --- locked itself, so a refusal holds the locked funds until the rule passes. --- Once the lock expires, only the holding's owner-unlock choice recovers --- them. Put a rule there only if a known party can lift it without --- re-creating the locked holding, such as a compliance officer lifting a --- freeze kept on a separate per-account contract: a pending instruction or --- allocation names its locked holdings by id, so replacing one orphans it. --- A rule that should only stop new spending belongs in `fundHolding` alone. --- A minimum holding age is one: the workflow creates locked funding, change, --- and returned holdings when it runs, so each of them is new. +-- locked itself. A refusal in one leaves the other's paths open, and a +-- refusal in both holds the funds until the lock expires. After that the +-- owner recovers them through the holding's owner-unlock choice, or by +-- passing the holding to a factory, which runs `fundHolding`. A rule that +-- must hold them longer is also checked in that choice and in `fundHolding`. +-- Put a rule in `deliverHolding` or `returnHolding` only if a known party +-- can lift it without re-creating the locked holding, such as a compliance +-- officer lifting a freeze kept on a separate per-account contract. A +-- pending instruction or allocation names its locked holdings by id, so it +-- can neither pay out nor return a holding that was replaced. A rule that +-- should only stop new spending, such as a minimum holding age, belongs in +-- `fundHolding` alone: the workflow creates locked funding, change, and +-- returned holdings when it runs, so each of them is new. -- -- A rule that tracks live registry state reads the current policy contract -- from the context, and the operation checks the contract it fetches: its -- template, its signatories, and that it covers this holding's admin and --- account. Neither of the two simpler designs follows the registry. A value --- copied into the holding when it is created stays fixed after the registry --- changes it, and a policy contract id stored in the holding fails every --- spend once the registry replaces that contract. +-- account. The submitter writes the context, so the operation fails when +-- the entry is missing, and the contract's presence is what permits the +-- spend: a context cannot show that a contract is absent. The submitter +-- also chooses which contract to pass, so the registry keeps one live +-- policy contract for each admin and account. data HoldingOps = HoldingOps with createHolding : HoldingV2.HoldingView -> Update (ContractId HoldingV2.Holding) -- ^ Create a holding from its standard view. Law: the created @@ -88,16 +93,16 @@ data HoldingOps = HoldingOps with -- ^ Consume a caller-supplied input holding that funds a new transfer -- or allocation, through `consumeUnlockedHolding`: the inputs of -- `transferFactoryImpl` and `executeTransfer`, including a one-step - -- transfer and a burn, and of `allocationFactoryImpl`. A refusal fails - -- the factory call and leaves every input untouched. + -- transfer and a burn, and of `allocationFactoryImpl`. An input may be + -- a holding whose lock has expired, such as the funding of an + -- instruction or allocation that never completed. deliverHolding : ChoiceContext -> ContractId HoldingV2.Holding -> Update HoldingV2.HoldingView -- ^ Consume locked funding to pay it out, through -- `consumeLockedHolding`: `transferAcceptImpl`, including the admin's -- accept of a burn request, and `allocationSettleImpl`. Both consume -- all of the locked funding here, including any part that stays with -- its owner: an accept's surplus, a settlement's payout to the - -- authorizer, and a reserve rolled into the next iteration. A refusal - -- blocks accept and settle; every return path still runs. + -- authorizer, and a reserve rolled into the next iteration. -- `settleBatchImpl` passes each `Allocation_Settle` an empty context, -- so a rule that requires a context entry refuses every batch -- settlement. @@ -105,9 +110,7 @@ data HoldingOps = HoldingOps with -- ^ Consume locked funding to return it to its owner, through -- `unlockHoldings`: `transferRejectImpl`, `transferWithdrawImpl`, -- `transferExpireImpl`, `allocationWithdrawImpl`, and - -- `allocationCancelImpl`. A refusal blocks every one of those paths; - -- accept and settle still run. `expireAllocationsImpl` cancels its - -- allocations in turn, so one refusal fails the whole batch. + -- `allocationCancelImpl`. withEventLog : (ContractId TransferEventsV2.EventLog -> Update ()) -> Update () -- ^ Run one emission against an `EventLog` host. The default templates -- supply a transient host created and archived within the transaction. diff --git a/packages/token/token-cip112-utils/daml/OpenZeppelin/Token/Cip112/Utils/Registry.daml b/packages/token/token-cip112-utils/daml/OpenZeppelin/Token/Cip112/Utils/Registry.daml index 74b40d6..65a47d3 100644 --- a/packages/token/token-cip112-utils/daml/OpenZeppelin/Token/Cip112/Utils/Registry.daml +++ b/packages/token/token-cip112-utils/daml/OpenZeppelin/Token/Cip112/Utils/Registry.daml @@ -34,10 +34,8 @@ settleBatchImpl pin admin self arg = do (not (null arg.transferLegs)) -- Each authorizer witnesses its own `Allocation_Settle`, so nothing from -- the batch's arguments should reach it: they may describe other - -- authorizers' trades. The cost is that the allocation's `deliverHolding` - -- sees an empty context on this path. Information meant for every - -- participant belongs in `SettlementInfo.meta`, which each authorizer - -- already sees and agreed to. + -- authorizers' trades. Information meant for every participant belongs in + -- `SettlementInfo.meta`, which each authorizer already sees and agreed to. let redactedBatchArgs _allocView _settleArg = pure ExtraArgs with context = emptyChoiceContext meta = emptyMetadata diff --git a/test/token-cip112-utils-test/daml/OpenZeppelin/Token/Cip112/Utils/Test.daml b/test/token-cip112-utils-test/daml/OpenZeppelin/Token/Cip112/Utils/Test.daml index f8d1cc5..390fb51 100644 --- a/test/token-cip112-utils-test/daml/OpenZeppelin/Token/Cip112/Utils/Test.daml +++ b/test/token-cip112-utils-test/daml/OpenZeppelin/Token/Cip112/Utils/Test.daml @@ -3,9 +3,9 @@ -- against a minimal local template it accepts and a foreign template it must -- refuse. The consumption and expiry bodies are run here too, for the -- guards that only a consumer's own `HoldingOps` or allocation template can --- reach. `OpenZeppelin.Token.Cip112.Utils.Test.Hooks` runs every workflow --- path through operations with a spend rule. The full workflows run under --- `test/token-cip112-v1-test` through the default templates and under +-- reach. `OpenZeppelin.Token.Cip112.Utils.Test.Operations` runs every +-- workflow path through operations with a spend rule. The full workflows run +-- under `test/token-cip112-v1-test` through the default templates and under -- `examples/token/token-cip112-custom-test` through a consumer's templates. module OpenZeppelin.Token.Cip112.Utils.Test where @@ -121,6 +121,13 @@ template Harness with controller actors do consumeUnlockedHolding unitOps emptyChoiceContext admin expectedAccount cid + nonconsuming choice Harness_UnlockHoldings : () + with cid : ContractId HoldingV2.Holding; expectedAccount : HoldingV2.Account; actors : [Party] + controller actors + do + _ <- unlockHoldings unitOps emptyChoiceContext admin expectedAccount [cid] + pure () + nonconsuming choice Harness_ExpireAllocations : () with cancelArgs : [(ContractId AllocationV2.Allocation, AllocationV2.Allocation_Cancel)]; actors : [Party] controller actors @@ -454,6 +461,32 @@ testConsumeLockedRefusesUnlockedHolding = do exerciseCmd harnessCid Harness_ConsumeLocked with cid; expectedAccount = basicAccount alice; actors = [admin] +-- | `unlockHoldings` makes the same three checks on the holdings it returns. +testUnlockHoldingsRefusesOtherAdmin : Script () +testUnlockHoldingsRefusesOtherAdmin = do + Fixture{..} <- setup + otherAdmin <- allocateParty "otherAdmin" + cid <- unitHolding otherAdmin alice (basicAccount alice) (Some (lockUntil otherAdmin (Some t2))) + mustFailWith "'inputHolding.instrumentId.admin' is not equal to" (actAs [admin, otherAdmin]) $ + exerciseCmd harnessCid Harness_UnlockHoldings with + cid; expectedAccount = basicAccount alice; actors = [admin, otherAdmin] + +testUnlockHoldingsRefusesOtherAccount : Script () +testUnlockHoldingsRefusesOtherAccount = do + Fixture{..} <- setup + cid <- unitHolding admin alice (savingsAccount alice) (Some (lockUntil admin (Some t2))) + mustFailWith "'inputHolding.account' is not equal to" (actAs admin) $ + exerciseCmd harnessCid Harness_UnlockHoldings with + cid; expectedAccount = basicAccount alice; actors = [admin] + +testUnlockHoldingsRefusesUnlockedHolding : Script () +testUnlockHoldingsRefusesUnlockedHolding = do + Fixture{..} <- setup + cid <- unitHolding admin alice (basicAccount alice) None + mustFailWith "input holding must be locked" (actAs admin) $ + exerciseCmd harnessCid Harness_UnlockHoldings with + cid; expectedAccount = basicAccount alice; actors = [admin] + testConsumeUnlockedRefusesOtherAdmin : Script () testConsumeUnlockedRefusesOtherAdmin = do Fixture{..} <- setup diff --git a/test/token-cip112-utils-test/daml/OpenZeppelin/Token/Cip112/Utils/Test/Hooks.daml b/test/token-cip112-utils-test/daml/OpenZeppelin/Token/Cip112/Utils/Test/Operations.daml similarity index 99% rename from test/token-cip112-utils-test/daml/OpenZeppelin/Token/Cip112/Utils/Test/Hooks.daml rename to test/token-cip112-utils-test/daml/OpenZeppelin/Token/Cip112/Utils/Test/Operations.daml index ff86293..fd1d749 100644 --- a/test/token-cip112-utils-test/daml/OpenZeppelin/Token/Cip112/Utils/Test/Hooks.daml +++ b/test/token-cip112-utils-test/daml/OpenZeppelin/Token/Cip112/Utils/Test/Operations.daml @@ -10,7 +10,7 @@ -- every operation receives the context its submitter passed, and the two -- limits of that delivery: batch settlement passes an empty context, and one -- refusal fails a whole expiry batch. -module OpenZeppelin.Token.Cip112.Utils.Test.Hooks where +module OpenZeppelin.Token.Cip112.Utils.Test.Operations where import DA.Action (replicateA, unless) import DA.Assert ((===))