Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. 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`

Expand Down
2 changes: 1 addition & 1 deletion examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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 ()
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion examples/token/token-cip112-custom/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
----------
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
49 changes: 43 additions & 6 deletions packages/token/token-cip112-utils/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` 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
consumption and allocation policies, pinned to one template.
- `privateAssetAllocateExtraObservers`: the allocation factory's extra
Expand Down Expand Up @@ -46,10 +52,41 @@ 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` 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
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. 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`.
Expand Down
Loading
Loading