@cancore/contracts 0.1.0 → 0.2.0-rc.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +448 -10
  2. package/dist/abi.d.ts +6598 -1675
  3. package/dist/abi.js +1 -1
  4. package/dist/chunk-2ELHDMZ7.js +9911 -0
  5. package/dist/chunk-2ELHDMZ7.js.map +1 -0
  6. package/dist/{chunk-CIBYXHSX.js → chunk-IAPV7XWJ.js} +2 -2
  7. package/dist/chunk-IAPV7XWJ.js.map +1 -0
  8. package/dist/index.d.ts +1559 -29
  9. package/dist/index.js +2925 -17
  10. package/dist/index.js.map +1 -1
  11. package/dist/networks.d.ts +2 -2
  12. package/dist/networks.js +1 -1
  13. package/package.json +10 -8
  14. package/spec/abi/AttestorSet.json +476 -0
  15. package/spec/abi/CNRX.json +1294 -0
  16. package/spec/abi/CNRXStaking.json +510 -0
  17. package/spec/abi/CancoreRouter.json +2666 -0
  18. package/spec/abi/FeeVault.json +604 -0
  19. package/spec/abi/HTLC.json +717 -0
  20. package/spec/abi/IAttribute.json +110 -0
  21. package/spec/abi/IBurnMintERC20.json +252 -0
  22. package/spec/abi/ICancoreRouter.json +1361 -0
  23. package/spec/abi/IFormula.json +28 -0
  24. package/spec/abi/IHTLC.json +382 -0
  25. package/spec/abi/IPayment.json +40 -0
  26. package/spec/abi/IPermit2.json +150 -0
  27. package/spec/abi/IResolver.json +55 -0
  28. package/spec/abi/IStep.json +30 -0
  29. package/spec/abi/IVariableRole.json +141 -0
  30. package/spec/abi/MultiBalanceChecker.json +34 -0
  31. package/spec/abi/PointsClaim.json +791 -0
  32. package/spec/constants.json +66 -0
  33. package/spec/protocol/asyncapi.json +1265 -0
  34. package/spec/protocol/messages.schema.json +543 -0
  35. package/spec/protocol/records.schema.json +94 -0
  36. package/spec/protocol/rest.schema.json +134 -0
  37. package/spec/protocol/typed-data/CantonTicketReceipt.json +77 -0
  38. package/spec/protocol/typed-data/FillerAuth.json +58 -0
  39. package/spec/protocol/typed-data/FillerKeyRegistration.json +69 -0
  40. package/spec/protocol/typed-data/FillerMessage.json +115 -0
  41. package/spec/protocol/typed-data/FillerQuote.json +75 -0
  42. package/spec/protocol/typed-data/GatewayMessage.json +95 -0
  43. package/spec/protocol/typed-data/StakeBinding.json +75 -0
  44. package/spec/protocol/typed-data/TicketIntent.json +113 -0
  45. package/spec/protocol/typed-data/TicketReceipt.json +51 -0
  46. package/spec/protocol/vectors/draw.json +61 -0
  47. package/spec/protocol/vectors/jcs.json +59 -0
  48. package/spec/protocol/vectors/messages.json +550 -0
  49. package/spec/protocol/vectors/records.json +81 -0
  50. package/spec/protocol/vectors/settle-attestations.json +542 -0
  51. package/spec/typed-data/FillProof.json +227 -0
  52. package/spec/typed-data/FillTicket.json +116 -0
  53. package/spec/typed-data/Order.json +169 -0
  54. package/spec/typed-data/Quote.json +79 -0
  55. package/spec/vectors/canton-destination.json +60 -0
  56. package/spec/vectors/canton-order.json +70 -0
  57. package/spec/vectors/evm-order.json +50 -0
  58. package/spec/vectors/fee-split.json +179 -0
  59. package/spec/vectors/permit-witness.json +150 -0
  60. package/dist/chunk-CIBYXHSX.js.map +0 -1
  61. package/dist/chunk-ZSX67S72.js +0 -3423
  62. package/dist/chunk-ZSX67S72.js.map +0 -1
package/README.md CHANGED
@@ -1,23 +1,25 @@
1
1
  # `@cancore/contracts`
2
2
 
3
- The Cancore EVM contracts as data: the ABIs of the deployed HTLC, FeeVault and CNRX
4
- contracts, their custom-error selectors, where each is deployed per environment, the EIP-712
3
+ The Cancore EVM contracts as data: the ABIs of the HTLC, FeeVault and CNRX contracts and of
4
+ the intent rail's `CancoreRouter` and `AttestorSet`, their custom-error selectors, where each is deployed per environment, the EIP-712
5
5
  voucher `FeeVault` redeems, and the network registry the API's chain ids refer to.
6
6
 
7
7
  ```bash
8
8
  npm install @cancore/contracts
9
9
  ```
10
10
 
11
- No runtime code beyond three lookups, no dependencies. Everything is `as const`, so viem and
12
- wagmi infer function, event and error types from the ABIs.
11
+ Everything is `as const`, so viem and wagmi infer function, event and error types from the
12
+ ABIs. The only runtime code is a few lookups and the filler protocol's hashing helpers, which
13
+ need one dependency, `@noble/hashes`.
13
14
 
14
15
  ## What is here, and where it comes from
15
16
 
16
17
  | Entry | Holds | Source of truth |
17
18
  | --- | --- | --- |
18
- | `@cancore/contracts/abi` | `HTLC_ABI`, `FEE_VAULT_ABI`, `CNRX_ABI`, `IHTLC_ABI`, `IBURN_MINT_ERC20_ABI`, `IPERMIT2_ABI`, `MULTI_BALANCE_CHECKER_ABI`; `HTLC_ERRORS`, `FEE_VAULT_ERRORS`, `CNRX_ERRORS` | `Cancore-io/evm-contracts/abi/*.json` — the reviewed snapshots that repository keeps in lock-step with its compiled contracts |
19
+ | `@cancore/contracts/abi` | `HTLC_ABI`, `FEE_VAULT_ABI`, `CNRX_ABI`, `IHTLC_ABI`, `IBURN_MINT_ERC20_ABI`, `IPERMIT2_ABI`, `MULTI_BALANCE_CHECKER_ABI`, `CANCORE_ROUTER_ABI`, `ICANCORE_ROUTER_ABI`, `ATTESTOR_SET_ABI`, `CNRX_STAKING_ABI`, `POINTS_CLAIM_ABI`; an `*_ERRORS` table for each contract that declares custom errors | `Cancore-io/evm-contracts/abi/*.json` — the reviewed snapshots that repository keeps in lock-step with its compiled contracts; `CNRX` and `IBurnMintERC20` from `evm-contracts/vendor/*.json`, a build of `cancore-token-evm` vendored there |
19
20
  | `@cancore/contracts/networks` | `NETWORKS`, `networkOf`, `networkKindOf`, `networkByChainId` | the chain ids the Cancore API uses |
20
- | `@cancore/contracts` | all of the above, plus `DEPLOYMENTS` / `deploymentOf`, `FEE_CLAIM_TYPES` / `feeClaimDomain`, `BYTECODE_HASHES`, `CONTRACTS_RELEASE`, `describeRevert` | the contracts repository's `version.json` and bytecode hashes; the FeeVault contract's own struct and domain |
21
+ | `@cancore/contracts` (filler protocol v1) | EIP-712 types and domains of the intent rail, `hashTypedData` / `jcs` / `gatewayBodyHash` / `fillerMessageBodyHash` / `requestIdHash`, one digest helper per settlement type (`hashFillTicket`, `hashFillerQuote`, `hashTicketIntent`, `hashFillerMessage`, `hashFillerKeyRegistration`), `fillerIdHash` / `repayToFromEvm` / `repayToFromParty` / `isEvmRepayTo` / `evmAddressFromRepayTo`, `isEoaSignature`, `fillerEnvelopeError`, `drawValue` / `drawWinner` / `firstRoundAtOrAfter`, wire message types and enums, `FILLER_GATEWAYS` | `docs/intents/protocol.md` and `auction-and-draw.md` in Cancore-io/meta; `CancoreRouter.sol` for the code types |
22
+ | `@cancore/contracts` | all of the above, plus `DEPLOYMENTS` / `deploymentOf`, `FEE_CLAIM_TYPES` / `feeClaimDomain`, `FILL_PROOF_TYPES` / `fillProofDomain` / `hashFillProof` / `FillProof`, `BUILD_HASHES` (and its deprecated alias `BYTECODE_HASHES`), `CONTRACTS_RELEASE`, `describeRevert` | the contracts repository's `version.json` and bytecode hashes; the FeeVault contract's own struct and domain; `evm-contracts/abi/typed-data/FillProof.json` for the router's `FillProof` |
21
23
 
22
24
  The ABIs and selector tables are **generated**, never edited: `npm run sync` reads a checkout
23
25
  of `evm-contracts` (`EVM_CONTRACTS_DIR`) and rewrites `spec/abi/*.json` and
@@ -39,6 +41,271 @@ from the deployed contract — its `Claimed` event carried seven parameters wher
39
41
  emits eight — and nothing noticed, because a copied ABI decodes what it describes and
40
42
  silently misses what it does not. This package is what the app installs now.
41
43
 
44
+ ## CancoreRouter and AttestorSet
45
+
46
+ The intent rail's router, its interface and the k-of-n attestor set it inherits. A taker reads
47
+ intents, fills and filler windows off the router and follows its events:
48
+
49
+ ```ts
50
+ import { CANCORE_ROUTER_ABI, CANCORE_ROUTER_ERRORS, describeRevert } from '@cancore/contracts';
51
+
52
+ const [status, refundAfter, openedAt] = await client.readContract({
53
+ address: router, abi: CANCORE_ROUTER_ABI, functionName: 'intents', args: [orderHash],
54
+ });
55
+ const fills = await client.getContractEvents({ address: router, abi: CANCORE_ROUTER_ABI, eventName: 'Filled' });
56
+ describeRevert(revertData, [CANCORE_ROUTER_ERRORS]); // 'AlreadyFilled()' | …
57
+ ```
58
+
59
+ `ICANCORE_ROUTER_ABI` is the narrower interface (`fill`, `settle`, `refund`, `openFor`, the hash
60
+ helpers, the events); `ATTESTOR_SET_ABI` is the set on its own (`getAttestorSet`,
61
+ `currentSetId`, `isMember`, `revokedAttestors`), which `CancoreRouter` inherits. A test pins what
62
+ the taker client relies on: those views and calls, the events `IntentOpened`, `Filled`,
63
+ `Settled` and `Refunded`, and the 12-field `Order` tuple in the order of `ORDER_TYPES`, whose
64
+ type hash is the router's `ORDER_TYPEHASH`. Router addresses are not in this package yet.
65
+
66
+ ### Orders, the Permit2 witness, the fee
67
+
68
+ Hashing helpers ship from the package root (sdk.md §7, decided: helpers, not data only). They
69
+ are what the backend, the filler node, the attestors and the web app use instead of their own
70
+ copies:
71
+
72
+ ```ts
73
+ import {
74
+ buildCantonSourceOrder, cantonInclusiveFeeSplit, hashOrder, hashPermitWitness, inclusiveFeeSplit,
75
+ MAX_FEE_BPS, MIN_FILL_TTL, sourceOrderHash,
76
+ } from '@cancore/contracts';
77
+
78
+ hashOrder(order, { chainId, verifyingContract: router }); // CancoreRouter.hashOrder: the orderHash
79
+ sourceOrderHash(order, sourceRouter); // what a destination keys `filled` on; a Canton origin needs no router
80
+
81
+ // the EVM-form Order of a Canton-source intent (protocol.md §3.7): refuses an inexact amount, fee or time
82
+ const { order, domain, orderHash } = buildCantonSourceOrder({
83
+ ownerPartyId, requestId, instrumentAdmin, instrumentId, amount: '1250.5',
84
+ destinationChainId: 1, wantToken, wantDecimals: 6, minReceived: '1200.25', recipient,
85
+ createdAt, fillDeadline, feeRate: '0.003', cantonOriginId: CANTON_ORIGIN_ID.devnet,
86
+ fillerId: 'acme', // the filler the owner picked; the order carries keccak256(utf8(fillerId))
87
+ });
88
+
89
+ // what the maker signs for openFor: Permit2 PermitWitnessTransferFrom, the order as witness (PERMIT_WITNESS_TYPES for the wallet)
90
+ const digest = hashPermitWitness({ permitted: { token, amount }, spender: router, nonce, deadline, witness: order }, chainId);
91
+
92
+ inclusiveFeeSplit(105n, 500); // { payout: 100n, fee: 5n } — EVM source, CancoreRouter.settle (floor)
93
+ cantonInclusiveFeeSplit(total, 30); // Canton source, Daml inclusiveFee (half-even at 10⁻¹⁰)
94
+ ```
95
+
96
+ | Constants | Value | Held to |
97
+ | --- | --- | --- |
98
+ | `BPS`, `MAX_FEE_BPS`, `MIN_FILL_TTL`, `PROOF_KIND_ATTESTATION` | 10 000, 1 000, 60 s, 1 | `CancoreRouter.sol` via `spec/constants.json` |
99
+ | `MAX_FILL_TTL`, `MAX_SIG_TTL`, `MAX_PROOF_WINDOW`, `GRACE`, `SET_DELAY` | 24 h, 24 h, 4 h, 28 h, 72 h (seconds) | `AttestorSet.sol` via `spec/constants.json` |
100
+ | `CANTON_ORIGIN_ID`, `CANTON_SOURCE_ANCHOR`, `EIP2294_MAX_CHAIN_ID`, `OWNER_LABEL_TAG`, `INSTRUMENT_LABEL_TAG`, `DAML_NUMERIC_SCALE` | protocol.md §3.8 | `spec/vectors/canton-order.json` |
101
+
102
+ **Canton destination** (protocol.md §3.13). An EVM-source order delivered on Canton, and the
103
+ `FillProof` of the delivery, carry Canton values in EVM fields; this is the one encoder for them:
104
+
105
+ ```ts
106
+ import {
107
+ cantonNetworkOfDestination, encodeCantonAmount, encodeCantonDestination, encodeCantonOutputAsset, encodeCantonRecipient,
108
+ } from '@cancore/contracts';
109
+
110
+ const destination = encodeCantonDestination('devnet'); // keccak256(utf8("canton:devnet"))
111
+ const outputAsset = encodeCantonOutputAsset({ admin, id: 'USDCX' }); // keccak256(abi.encode("cancore:instrument:v1", admin, id))
112
+ const minReceived = encodeCantonAmount('1200.25'); // Daml Numeric 10 × 10¹⁰, exact or refused
113
+ const recipient = encodeCantonRecipient(partyId); // keccak256(utf8(partyId))
114
+ cantonNetworkOfDestination(order.destination); // 'devnet' | 'testnet' | 'mainnet' | undefined
115
+ ```
116
+
117
+ `spec/vectors/canton-destination.json` holds such an order (devnet) with its `orderHash` and the
118
+ `FillProof` of its delivery with its digest; its instrument, party and amount are those of the
119
+ Canton-destination vector of `spec/typed-data/FillProof.json` (`canton:mainnet`), which the
120
+ router test computes with `hashFillProof`.
121
+
122
+ `spec/constants.json` is written by `npm run sync` from the Solidity source of the same
123
+ evm-contracts commit as the ABIs (`CONTRACTS_RELEASE.commit`); a test holds every exported
124
+ constant to it, fails on a numeric constant the package does not export, and checks the router's
125
+ type hashes and `WITNESS_TYPE_STRING` against the package's type strings. Vectors:
126
+ `spec/vectors/evm-order.json`, `permit-witness.json` and `fee-split.json` (both rails; each EVM
127
+ case names the router test that pins it, each Canton case carries the Daml values), generated with
128
+ ethers by `scripts/gen-router-vectors.mjs`.
129
+
130
+ ## FillProof: what attestors sign
131
+
132
+ `CancoreRouter.settle(order, proof, sigs)` pays a filler out only against k attestor
133
+ signatures over one EIP-712 `FillProof`, in the domain of the order's **source** router, and
134
+ pays `proof.repayTo`. Twelve fields: `fillerId` (`keccak256(utf8(fillerId))`) and `repayTo`
135
+ (encoded for the source chain) come from the delivery — `Filled` on an EVM destination, the
136
+ `DeliveryReceipt` on a Canton one — and sit before `attempt` and `setId`.
137
+
138
+ ```ts
139
+ import { FILL_PROOF_TYPES, fillProofDomain, hashFillProof, PROOF_KIND_ATTESTATION } from '@cancore/contracts';
140
+
141
+ const signature = await wallet.signTypedData({
142
+ domain: fillProofDomain(sourceChainId, sourceRouter),
143
+ types: FILL_PROOF_TYPES,
144
+ primaryType: 'FillProof',
145
+ message: proof, // setId: attestationSetFor(orderHash), never currentSetId
146
+ });
147
+ ```
148
+
149
+ This repository keeps golden vectors for the schema in `spec/typed-data/FillProof.json` (shipped
150
+ in the package since 0.2.0, under `@cancore/contracts/spec/*`), each with its `domainSeparator`,
151
+ `structHash` and digest, and the file's `typeHash`. The twelve-field schema and vectors are
152
+ synced from `evm-contracts/abi/typed-data/FillProof.json` at `CONTRACTS_RELEASE.commit`; the
153
+ router tests check every vector against its own `hashFillProof` (CAN-2140). Sync only from a
154
+ variant A checkout: an older eleven-field struct would overwrite this file with the old one.
155
+ The Canton-source verifier and its rollout remain a separate compatibility gate.
156
+
157
+ ## Filler protocol v1 (RC)
158
+
159
+ The wire protocol between a taker and the Cancore filler gateway, frozen as a release
160
+ candidate in `0.2.0-rc.1` (npm dist-tag `next`). In `0.x` protocol v1 is the `0.2.x` line; a
161
+ breaking protocol change is `0.3`.
162
+
163
+ ```ts
164
+ import {
165
+ cantonTicketReceipt, gatewayBodyHash, hashCantonTicketReceipt, hashFillerMessage, hashTicketIntent, repayToFromEvm, fillerIdHash,
166
+ } from '@cancore/contracts';
167
+
168
+ // what the filler's message key signs to take an offered ticket: its delivery key and payout address
169
+ const intentDigest = hashTicketIntent({
170
+ orderHash, attempt, validFrom, validUntil,
171
+ fillerId: 'acme',
172
+ deliveryKey, // the address that will send fill (zero for a Canton destination)
173
+ repayTo: repayToFromEvm(payout), // EVM source; repayToFromParty(partyId) for a Canton source
174
+ });
175
+
176
+ // what msgSig of EVERY filler → filler-gateway message is over: FillerMessage{bodyHash}
177
+ const msgDigest = hashFillerMessage(message); // bodyHash = keccak256(JCS(message without msgSig))
178
+
179
+ // what every S→F frame's `sig` is over: GatewayMessage{bodyHash} in the same domain
180
+ const bodyHash = gatewayBodyHash(frame); // keccak256(JCS(frame without sig))
181
+
182
+ fillerIdHash('acme'); // the on-chain fillerId of FillTicket, Filled, FillProof, Settled
183
+
184
+ // the receipt of a Canton-form ticket (no FillTicket, no ticketSig): built from ticket.issued
185
+ const receiptDigest = hashCantonTicketReceipt(cantonTicketReceipt(issued)); // orderHash, attempt, keccak256(cid), validUntil
186
+ ```
187
+
188
+ `hashTypedData` encodes flat structs (address, bool, bytes, bytesN, string, uintN) and throws on
189
+ anything else; it takes wire values as they come — decimal strings, numbers or bigints. There
190
+ is no signing in this package: hand the digest to your own secp256k1 key. The filler signs
191
+ everything with one message key, an EOA: 65 bytes `r ‖ s ‖ v`, low-s, `v ∈ {27, 28}`, no
192
+ EIP-1271 — `isEoaSignature` checks that shape before recovery. A message key is registered
193
+ with `FillerKeyRegistration` signed by that key, at onboarding and, with the new key, at a
194
+ manual key change by Cancore staff; there is no key-rotation type or message.
195
+
196
+ | Types | Domain | Status |
197
+ | --- | --- | --- |
198
+ | `TicketReceipt`, `StakeBinding`, `FillerAuth`, `GatewayMessage` | `CancoreFillerProtocol` v1 | v1 RC — vectors in `spec/protocol/typed-data/` |
199
+ | `FillerQuote` (`string fillerId`), `TicketIntent` (with `fillerId`, `deliveryKey`, `repayTo`), `FillerMessage`, `FillerKeyRegistration` | `CancoreFillerProtocol` v1 | variant A — vectors in `spec/protocol/typed-data/` |
200
+ | `CantonTicketReceipt` (`orderHash`, `attempt`, `deliveryOrderCidHash`, `validUntil`) | `CancoreFillerProtocol` v1 | receipt of a Canton-form ticket (§10 D-O), additive — vectors in `spec/protocol/typed-data/` |
201
+ | `Order` (12 fields, with `createdAt`; `fillerId` last), `Quote` | `CancoreRouter` v1, source router | `abi/typed-data/` in evm-contracts, synced byte for byte to `spec/typed-data/` |
202
+ | `FillTicket` (`orderHash`, `fillerId`, `deliveryKey`, `repayTo`, `attempt`, `validFrom`, `validUntil`) | `CancoreFillTicket` v1 | variant A, synced from the router (CAN-2140) |
203
+ | `FillProof` (twelve fields) | `CancoreRouter` v1, source router | variant A, synced from the router (above) |
204
+
205
+ Golden vectors are generated with ethers by `scripts/gen-protocol-vectors.mjs` from the literal
206
+ inputs in `scripts/protocol-fixtures.mjs`, and checked by this package's own encoder too. The
207
+ `canton` Order vector equals `spec/vectors/canton-order.json`, a byte copy of
208
+ `evm-contracts/test/vectors/canton-order.json` at `f936594`, which the router's test pins.
209
+ `spec/protocol/vectors/jcs.json` holds RFC 8785 cases and `draw.json` the draw of
210
+ auction-and-draw §3.7 (r = 417828, acme-markets) plus the test-kit fixture draw, both on real
211
+ drand quicknet rounds.
212
+
213
+ ### Schemas, AsyncAPI, examples
214
+
215
+ | File (`@cancore/contracts/spec/protocol/…`) | Holds |
216
+ | --- | --- |
217
+ | `messages.schema.json` | one `$def` per frame type (23), `x-direction` S2F / F2S / both, `x-rest-only` on the two login types, and the primitives they share |
218
+ | `rest.schema.json` | REST bodies; `x-endpoints` (method, path, auth, query, request/response, `errorBody` where a refusal may be unsigned), `x-error-status` |
219
+ | `records.schema.json` | the draw record, the epoch record, `GET /v1/gateway` |
220
+ | `asyncapi.json` | AsyncAPI 3.0: channel `/v1` (the upgrade's subprotocols, its HTTP refusals `x-upgrade-refusals`, the close codes `x-close-codes`), the gateway's send/receive operations, examples |
221
+ | `vectors/messages.json`, `vectors/records.json` | valid example frames and fixture records (hashes real, `sig` a placeholder: r = s = 0, v = 27) |
222
+ | `vectors/settle-attestations.json` | `settle.attestations` golden vectors: EVM and Canton source, real TEST-key signatures, the pushed frame and the REST body with one payload, and schema-valid payloads a filler must refuse |
223
+
224
+ The same objects are exported as `PROTOCOL_SCHEMAS`, `ASYNCAPI`, `MESSAGE_DIRECTIONS`,
225
+ `REST_ONLY_TYPES` and `REST_ENDPOINTS`, with TypeScript shapes of every frame (`TicketOffer`, `QuoteAck`, …) and the
226
+ enums (`DECLINE_REASONS`, `ERROR_CODES`, …) a test holds to the schemas.
227
+
228
+ ```ts
229
+ import Ajv2020 from 'ajv/dist/2020';
230
+ import { PROTOCOL_SCHEMAS, SCHEMA_VOCABULARY, messageSchemaRef } from '@cancore/contracts';
231
+
232
+ const ajv = new Ajv2020({ strict: true });
233
+ ajv.addVocabulary([...SCHEMA_VOCABULARY]);
234
+ for (const schema of Object.values(PROTOCOL_SCHEMAS)) ajv.addSchema(schema);
235
+ ajv.validate(messageSchemaRef(frame.type, 'S2F'), frame); // errors name the field: instancePath "/amountOut"
236
+ ```
237
+
238
+ The schemas describe what a v1 **sender** emits: lowercase hex, uint64 and wider as decimal
239
+ strings, times in milliseconds, every frame with `id`, `fillerId` and `sentAt`, every S→F frame
240
+ signed with `sig` and every F→S frame — `ticket.decline`, a declining `quote.reconfirm.reply`,
241
+ `fill.reported`, `pong` and `error` included — with `msgSig` (`f2sEnvelope`); REST request
242
+ bodies carry the same envelope. `fillerEnvelopeError` runs the key-free checks of §3.4 (shape of
243
+ `msgSig`, the session's `fillerId`, freshness, `id`); recovering `msgSig` against the registered
244
+ message key and refusing a replayed `id` stay with the receiver, which keeps an accepted `id` until
245
+ `messageIdRetainUntil(sentAt, receivedAt, maxMessageAgeMs)` — freshness is symmetric, so a sender
246
+ clock running ahead keeps a message fresh past `receivedAt + maxMessageAgeMs`. The `repayToEvm` definition
247
+ refuses a `repayTo` with non-zero top 12 bytes, for a receiver that knows the source is EVM. No
248
+ object is closed: a receiver ignores unknown fields and a taker ignores unknown S→F types
249
+ (V-2), so check a frame of an unknown type against `s2fEnvelope` and skip it. Every enum is
250
+ open the same way: the known values, or any UPPER_SNAKE value added within v1, which a receiver
251
+ treats as `OTHER`/generic; a `ticket.issued` of an unknown `form` is checked on its common fields
252
+ only. `ping`, `pong` and `error` go both ways: the gateway's copy carries `sig` (`pingS2F`), the
253
+ filler's `msgSig` (`pingF2S`); the second argument of `messageSchemaRef` picks one.
254
+ `scripts/gen-protocol-docs.mjs` derives the examples, records and the AsyncAPI document from
255
+ the schemas and the vectors.
256
+
257
+ ### Login and connect
258
+
259
+ A filler logs in over REST and only then opens the WebSocket:
260
+
261
+ 1. `GET /v1/filler/auth/challenge?fillerId=<fillerId>` → a signed `auth.challenge` addressed to that
262
+ `fillerId`. Check its `sig` against the published gateway key and that `fillerId` is yours.
263
+ Refusals of this anonymous route are unsigned (`unsignedErrorBody`): 400 `BAD_REQUEST`, 404
264
+ `UNKNOWN_REQUEST` (unknown or not `ACTIVE`), 429 `RATE_LIMITED` with `retryAfterMs`.
265
+ 2. `POST /v1/filler/auth` with `auth.response` (`FillerAuth` by the message key, `nonce` = the
266
+ challenge's) → `{token, expiresAt}`, bound to `(fillerId, message key)`. Refusals decided before
267
+ any signature check are unsigned too: 400 `BAD_REQUEST`, 404 `UNKNOWN_REQUEST`, 401
268
+ `UNAUTHENTICATED` (no live challenge for the fillerId: start again from step 1), 429; refusals after
269
+ the signature checks are the signed `error`.
270
+ 3. Upgrade `/v1` offering `fillerWsProtocols(token)` = `['cancore-filler.v1', 'bearer.<token>']`
271
+ (`FILLER_WS_SUBPROTOCOL`, `FILLER_WS_BEARER_PREFIX`) as `Sec-WebSocket-Protocol`; the gateway
272
+ answers `cancore-filler.v1` and sends a signed `auth.ok` first. It refuses with plain HTTP
273
+ (`FILLER_UPGRADE_REFUSALS`: 400, 401, 403, 429 with `Retry-After`, 503) and closes a session
274
+ with one of `FILLER_CLOSE_CODES` (4029: rate-limit cooldown, preceded by `error RATE_LIMITED`
275
+ whose `retryAfterMs` is the remaining cooldown).
276
+
277
+ The same token authenticates REST (`Authorization: Bearer`). `auth.challenge` and
278
+ `auth.response` never travel on the socket (`REST_ONLY_TYPES`). Over a per-fillerId rate limit
279
+ the gateway answers `error RATE_LIMITED` with `retryAfterMs` (on REST: 429, always unsigned, with
280
+ `retryAfterMs` and `Retry-After`); send nothing of that rate class before it has passed.
281
+
282
+ ### Attestation signatures for `settle`
283
+
284
+ Once filler-gateway holds at least `threshold` verified attestor signatures over a filler's
285
+ `FillProof`, it pushes `settle.attestations` to that filler and serves the same payload on
286
+ `GET /v1/filler/attestations/{orderHash}` (404 `ATTESTATIONS_NOT_READY` before that, 404
287
+ `UNKNOWN_TICKET` when the filler holds no ticket on the order); the filler node submits `settle`
288
+ itself (protocol §3.5, §3.6, §10 D-N). `proof` is the `FillProof` the source router hashes,
289
+ field for field (`FILL_PROOF_TYPES`), including variant A's `fillerId` and `repayTo`
290
+ (protocol §3.3). A signature entry follows `sourceChainId`: `{signer, signature}` with a
291
+ 65-byte signature on an EVM source, `{signer, pubKey, signature}` with the DER public key and a
292
+ minimal DER signature on a Canton source, as `SwapIntent_SettleWithProof` takes them.
293
+
294
+ ```ts
295
+ import { settleAttestationsErrors, settleAttestationsPayload, settleAttestationsPayloadHash, settleSigs } from '@cancore/contracts';
296
+
297
+ const payload = settleAttestationsPayload(frame); // the same from WebSocket and REST
298
+ settleAttestationsErrors(payload); // [] or what the schema cannot state: threshold, signer order, ids
299
+ settleAttestationsPayloadHash(frame); // dedupe the two channels
300
+ settleSigs(payload); // EVM: the sigs of settle(order, proof, sigs); Canton: cantonSigEntries(payload)
301
+ ```
302
+
303
+ Recover every signer and check it against `attestationSetFor(orderHash)` with your own
304
+ secp256k1 library (T-7). `scripts/gen-settle-attestations.mjs` writes the vectors.
305
+
306
+ `FILLER_GATEWAYS` is where the gateway key and the ticket signers of each environment are
307
+ published. It is empty in the RC: no gateway key exists yet.
308
+
42
309
  ## Reverts
43
310
 
44
311
  ```ts
@@ -54,7 +321,7 @@ decode against the same table.
54
321
  ## Deployments
55
322
 
56
323
  ```ts
57
- import { DEPLOYMENTS, deploymentOf, BYTECODE_HASHES } from '@cancore/contracts';
324
+ import { DEPLOYMENTS, deploymentOf, BUILD_HASHES } from '@cancore/contracts';
58
325
 
59
326
  const { htlc, htlcBlock } = deploymentOf('mainnet', 'arbitrum')!;
60
327
  ```
@@ -62,9 +329,16 @@ const { htlc, htlcBlock } = deploymentOf('mainnet', 'arbitrum')!;
62
329
  Three environments, three independent deployments: what is on Sepolia for the dev stand is
63
330
  not what is on Sepolia for testnet. `htlcBlock` is the floor for an event scan.
64
331
 
65
- An address is a claim; `BYTECODE_HASHES` is the proof. The runtime code at any `htlc`
66
- address hashes to `BYTECODE_HASHES.HTLC.deployedBytecodeHash` for the release it was deployed
67
- from, and `CONTRACTS_RELEASE` names that release.
332
+ `BUILD_HASHES` pins the build each release was made from, as `evm-contracts` records it in
333
+ `scripts/tools/check-bytecode-match.mjs`: `creationHexSha256` and `runtimeHexSha256` are sha256
334
+ of the UTF-8 text of the artifact's `0x`-prefixed hex (creation and runtime code) — not
335
+ keccak256, and not of the bytes — and `creationHexLength` / `runtimeHexLength` are the length
336
+ of that text, `0x` included. `BYTECODE_HASHES` is the same data under the old field names
337
+ (`bytecodeHash`, `deployedBytecodeHash`, `bytecodeLength`, `deployedBytecodeLength`); it is
338
+ deprecated and goes before `0.2.0`. It is not a hash of `eth_getCode`: a contract with
339
+ immutables (`CancoreRouter`, `FeeVault`) never matches one, so checking a live deployment
340
+ against it means rebuilding the release, not hashing the address. `CONTRACTS_RELEASE` names the
341
+ release.
68
342
 
69
343
  ## The FeeClaim voucher
70
344
 
@@ -102,11 +376,175 @@ added.
102
376
  EVM_CONTRACTS_DIR=../evm-contracts npm run sync # then review the diff and release
103
377
  ```
104
378
 
379
+ `npm run sync` is two scripts: `scripts/sync.mjs` (ABIs, error tables, release identity, the
380
+ router and AttestorSet constants in `spec/constants.json`) and
381
+ `scripts/sync-typed-data.mjs` (all four `abi/typed-data/*.json` schemas). Use the
382
+ full command above: the standalone typed-data script does not validate or stamp
383
+ source provenance.
384
+
385
+ `EVM_CONTRACTS_DIR` must be the root of a clean git checkout of `evm-contracts`: the sync records
386
+ its `HEAD` as `CONTRACTS_RELEASE.commit` and refuses a directory that is not a checkout root or
387
+ has uncommitted changes, so the release cannot name a commit its data did not come from.
388
+
389
+ EVM [#108](https://github.com/Cancore-io/evm-contracts/pull/108) and
390
+ [#114](https://github.com/Cancore-io/evm-contracts/pull/114), and SDK
391
+ [#90](https://github.com/Cancore-io/sdk/pull/90), are merged. This snapshot is fully
392
+ synced from the clean, merged EVM `main` commit
393
+ [`4056e83`](https://github.com/Cancore-io/evm-contracts/commit/4056e83cd84a94d9d00eb4486d5cabf55dd71741),
394
+ as recorded by `CONTRACTS_RELEASE.commit` and `spec/constants.json`. Before publishing
395
+ rc.10, merge SDK [#91](https://github.com/Cancore-io/sdk/pull/91) and pass its checks.
396
+ For every subsequent upstream change, run the full sync from a clean checkout of the
397
+ actual merged `main` commit, commit the resulting pins, and rerun the checks before
398
+ publishing. This resync is mandatory for merge, squash and rebase alike.
399
+
400
+ It reads `abi/*.json` except the two manifests (`bytecode-hashes.json`, `versions.json`) and
401
+ `vendor/*.json` (the `.abi` field), and refuses to run when `spec/abi/` holds a snapshot the
402
+ source no longer has — dropping a published ABI is a decision, not a side effect of a sync.
403
+
105
404
  A contract change is a release of this package. `CONTRACTS_RELEASE.version` says which
106
405
  `evm-contracts` version the data was taken from.
107
406
 
108
407
  Full documentation: <https://docs.cancore.io/sdk/contracts>
109
408
 
409
+ ## Changes
410
+
411
+ - `0.2.0-rc.10` — the order names its filler (OD-1, OD-6; CAN-2496). **Breaking**: every order
412
+ hash changes.
413
+ - `Order` gains a twelfth and last field, `bytes32 fillerId` = `fillerIdHash(fillerId)` of the
414
+ filler the user picked: `ORDER_TYPES`, `Order`, `OrderJson` (and the `order` of
415
+ `messages.schema.json`), `ORDER_TYPEHASH` `0xf68105de…9d22`, `PERMIT2_WITNESS_TYPE_STRING`.
416
+ The router fills an order only on a ticket naming that filler and settles it only on a proof
417
+ naming it (`WrongFiller`); it refuses to open an order whose `fillerId` is zero
418
+ (`ZeroFillerId`).
419
+ - `buildCantonSourceOrder` takes a required `fillerId` and refuses an empty or malformed one;
420
+ the Canton-source form carries it too (OD-6), so the Daml hash changes with it.
421
+ - ABIs and typed data synced from evm-contracts `496c12a` (evm-contracts#108): `WrongFiller`,
422
+ `ZeroFillerId`, `UnknownOrder`, `NotOrderUser`, `InvalidRefundRecipient`; `Refunded(orderHash, recipient,
423
+ amount)`.
424
+ - Vectors: `canton-order.json` is evm-contracts#108's (orderHash `0x22e3a53a…e79a`, equal to
425
+ canton-contracts#216's Daml `orderHashOf`); `evm-order.json`, `permit-witness.json`,
426
+ `canton-destination.json`, `Order.json`, `Quote.json` and the protocol vectors built on the
427
+ fixture order are regenerated. The fixture order names `acme-markets`; the Canton-source
428
+ ticket and proof name `acme`, the filler `canton-order.json` picked.
429
+
430
+ `0.2.0-rc.9` follows `0.2.0-rc.7`: no `0.2.0-rc.8` was published. Its four entries below ship
431
+ together; the first is breaking within the RC line for a filler and for filler-gateway, the other
432
+ three are additive.
433
+
434
+ - `0.2.0-rc.9` — connect only after login, limits per fillerId (CAN-2232). **Breaking within the
435
+ RC line** for a filler and for filler-gateway:
436
+ - The login is REST only: `GET /v1/filler/auth/challenge` takes a required `fillerId` query
437
+ (`challengeQuery`), and `auth.challenge` is addressed (envelope `s2fBase`, `fillerId`
438
+ required). The refusals of the login routes decided before a signature check, and every 429,
439
+ are unsigned (`unsignedErrorBody`; `errorBody` of the two login endpoints).
440
+ `auth.challenge` and `auth.response` carry `x-rest-only` (a new annotation keyword in
441
+ `SCHEMA_VOCABULARY`; `REST_ONLY_TYPES`) and leave the AsyncAPI channel.
442
+ - The WebSocket upgrade offers `cancore-filler.v1` and `bearer.<token>`:
443
+ `FILLER_WS_SUBPROTOCOL`, `FILLER_WS_BEARER_PREFIX`, `fillerWsProtocols`; its refusals
444
+ `FILLER_UPGRADE_REFUSALS` and the session close codes `FILLER_CLOSE_CODES`, also in
445
+ `asyncapi.json` (`bindings.ws`, `x-upgrade-refusals`, `x-close-codes`).
446
+ - `error` gains optional `retryAfterMs` (an integer ≥ 1, with `RATE_LIMITED`);
447
+ `ErrorMessage.retryAfterMs`, `UnsignedErrorBody`, `ChallengeQuery`, `RestEndpoint.errorBody`.
448
+ - The `auth.challenge` example and its `GatewayMessage` vector carry `fillerId` (that vector's
449
+ digest changes); a `RATE_LIMITED` example; no other digest changes.
450
+ - `0.2.0-rc.9` — router constants and order hashing helpers (CAN-1934). Additive only:
451
+ no existing export, type or digest changes.
452
+ - Constants `BPS`, `MAX_FEE_BPS`, `MIN_FILL_TTL`, `MAX_FILL_TTL`, `MAX_SIG_TTL`,
453
+ `MAX_PROOF_WINDOW`, `GRACE`, `SET_DELAY`, `CANTON_ORIGIN_ID`, `CANTON_SOURCE_ANCHOR`,
454
+ `EIP2294_MAX_CHAIN_ID`, `OWNER_LABEL_TAG`, `INSTRUMENT_LABEL_TAG`, `DAML_NUMERIC_SCALE`;
455
+ `spec/constants.json`, synced from the Solidity source, pins them (SDK-6).
456
+ - Helpers `hashOrder`, `sourceOrderHash`, `isCantonOriginId`, `buildCantonSourceOrder` (port of
457
+ evm-contracts `test/helpers/cantonOrder.ts`, EVM destinations), `PERMIT_WITNESS_TYPES`,
458
+ `PERMIT2_WITNESS_TYPE_STRING`, `permit2Domain`, `hashPermitWitness`, `inclusiveFeeSplit` (EVM
459
+ source) and `cantonInclusiveFeeSplit` (Canton source).
460
+ - Vectors `spec/vectors/evm-order.json`, `permit-witness.json`, `fee-split.json`.
461
+ - `0.2.0-rc.9` — the Canton-destination encoder (protocol.md §3.13; CAN-1935). Additive only.
462
+ - `encodeCantonDestination(network)`, `cantonNetworkOfDestination(destination)`,
463
+ `encodeCantonOutputAsset({admin, id})`, `encodeCantonRecipient(partyId)`,
464
+ `encodeCantonAmount(amount)`, type `CantonNetwork`.
465
+ - Vector `spec/vectors/canton-destination.json`: an EVM-source order to Canton devnet and the
466
+ `FillProof` of its delivery.
467
+ - `0.2.0-rc.9` — `CantonTicketReceipt`, the receipt of a Canton-form ticket (protocol.md
468
+ §3.3, §3.5, §10 D-O; CAN-2062). Additive only (V-2): no existing type, digest or vector changes.
469
+ - Type `CantonTicketReceipt(bytes32 orderHash,uint32 attempt,bytes32 deliveryOrderCidHash,uint64 validUntil)`
470
+ in the `CancoreFillerProtocol` domain, signed by the message key; `fillerId` and `repayTo` are
471
+ not part of it (they travel in `ticket.issued`). Golden vectors in
472
+ `spec/protocol/typed-data/CantonTicketReceipt.json`.
473
+ - Helpers `CANTON_TICKET_RECEIPT_TYPES`, `hashCantonTicketReceipt`, `cantonTicketReceipt` (the
474
+ struct from a Canton-form `ticket.issued` or `ticket.receipt`) and `deliveryOrderCidHash`.
475
+ - `ticket.receipt` gains the Canton form: `form: "canton"`, `deliveryOrderCid`, `validUntil`,
476
+ `sig`; the EVM form (`form` absent or `"evm"`) is unchanged. The same body is the REST
477
+ `POST /v1/filler/tickets/{orderHash}/{attempt}/receipt`; AsyncAPI carries both examples.
478
+ `TicketReceiptMessage` is now the union `TicketReceiptEvm | TicketReceiptCanton`.
479
+ - `0.2.0-rc.7` — sync the variant A `CancoreRouter` and `ICancoreRouter` ABIs from
480
+ evm-contracts commit `c214f56f6fe5a62097833c5f1335b0cb5351b225` (CAN-2140).
481
+ - Both the package root and `/abi`, and the shipped `spec/abi/` JSON, expose
482
+ `Filled(orderHash, fillerId, deliveryKey, repayTo, received, recipient, filledAt, attempt)`
483
+ and `Settled(orderHash, fillerId, repayTo, payout, fee)`. Both events index `orderHash` and
484
+ `fillerId`. **Breaking within the RC line**: consumers must decode the new event topics
485
+ and fields; the published `0.2.0-rc.6` still has the old router ABIs.
486
+ - The router's `FillTicket` and `FillProof` tuples now match the variant A typed data
487
+ already shipped in `0.2.0-rc.6`. No typed-data digest changes from `rc.6` to `rc.7`.
488
+ The generated typed-data snapshot now also includes `FillTicket` from the synced schema.
489
+ - Remove the old on-router filler registry views, `setFiller` and `FillerSet`;
490
+ `WrongDeliveryKey` replaces `WrongTicketFiller` and `NotFiller`. Refresh
491
+ `CONTRACTS_RELEASE.commit` and the router build hashes.
492
+ - This package does not deploy a router or complete the Canton/backend/trader rollout.
493
+ - `0.2.0-rc.6` (CAN-2139; previously listed as unreleased) — the settlement design of variant A (protocol.md §3.3, §3.4, §3.15,
494
+ §3.16; CAN-2139). **Breaking within the RC line**: every digest of the changed types changes.
495
+ - `FillTicket` is `(orderHash, bytes32 fillerId, address deliveryKey, bytes32 repayTo, attempt,
496
+ validFrom, validUntil)`; `FillProof` has twelve fields, `fillerId` and `repayTo` in place of
497
+ `address filler`; `TicketIntent` adds `string fillerId`, `deliveryKey`, `repayTo`;
498
+ `FillerQuote` names `string fillerId` instead of `address filler`. Type hashes:
499
+ `FillTicket` `0x3b13cc38…73ec82`, `FillProof` `0xc37e18cd…2419ae`.
500
+ - New types `FillerMessage(bytes32 bodyHash)` (the envelope signature `msgSig` of every filler
501
+ message) and `FillerKeyRegistration(string fillerId,address messageKey,uint64 issuedAt)`
502
+ (proof of possession of the message key, also for a manual key change by staff). No
503
+ key-rotation type, no `key.rotate` message, no refund-redirect type.
504
+ - Helpers: `hashFillTicket`, `hashFillProof`, `hashFillerQuote`, `hashTicketIntent`,
505
+ `hashFillerMessage`, `hashFillerKeyRegistration`, `fillerMessageBodyHash`, `fillerIdHash`,
506
+ `repayToFromEvm`, `repayToFromParty`, `isEvmRepayTo`, `evmAddressFromRepayTo`,
507
+ `isEoaSignature`, `fillerEnvelopeError`, `messageIdRetainUntil`.
508
+ - Schemas: every F→S frame carries `id`, `fillerId`, `sentAt`, `msgSig` (`f2sEnvelope`), as does
509
+ the stake-binding REST body; every S→F frame carries `id`; `error` goes both ways
510
+ (`errorS2F`, `errorF2S`); `quote` drops `filler`; `ticket.intent` adds `deliveryKey`,
511
+ `repayTo`; the issued EVM ticket is the seven-field `FillTicket` and the Canton form adds
512
+ `repayTo`; error codes `STALE_MESSAGE`, `REPLAYED_MESSAGE`, `TICKET_REFUSED` with
513
+ `reason` (`TICKET_REFUSED_REASONS`); `repayToEvm`, `fillerKeyRegistration` definitions;
514
+ `sig65` refuses an `s` with its top bit set; `GET /v1/gateway` returns `maxMessageAgeMs`.
515
+ - Vectors for every new and changed type; the router ABI catches up with these types in
516
+ `0.2.0-rc.7` (see «FillProof: what attestors sign»).
517
+ - `0.2.0-rc.6` (CAN-2018; previously listed as unreleased) — filler-gateway → filler `settle.attestations` and `GET /v1/filler/attestations/{orderHash}`
518
+ (protocol §3.5, §3.6, §10 D-N): the frame schema with the router's `FillProof` and the EVM and
519
+ Canton signature entries, the REST endpoint, the error code `ATTESTATIONS_NOT_READY` (404), an
520
+ AsyncAPI message, golden vectors (`spec/protocol/vectors/settle-attestations.json`), the
521
+ `SettleAttestations` types and the helpers `settleAttestationsPayload`,
522
+ `settleAttestationsPayloadHash`, `settleAttestationsErrors`, `settleSigs`, `cantonSigEntries`.
523
+ Additive only (V-2): no existing frame, type or vector changes.
524
+ - `0.2.0-rc.6` — `auth.response` gains an optional `nonce` (bytes32): the `auth.challenge` nonce it
525
+ answers, so filler-gateway's REST login (`POST /v1/filler/auth`) finds the challenge without trying
526
+ every live one. Additive only (V-2); the `FillerAuth` type and every digest are unchanged.
527
+ - `0.2.0-rc.5` — `CONTRACTS_RELEASE.commit`: the evm-contracts commit the data was synced from.
528
+ The sync takes it from the checkout's `HEAD` and refuses a directory that is not a clean
529
+ checkout root. Additive only.
530
+ - `0.2.0-rc.4` — adds `BUILD_HASHES`: the release's build hashes under names that say what they
531
+ are (`creationHexSha256`, `runtimeHexSha256`, `creationHexLength`, `runtimeHexLength`).
532
+ `BYTECODE_HASHES` keeps the same values under the old names, deprecated, and is removed before
533
+ `0.2.0`. Additive only.
534
+ - `0.2.0-rc.3` — adds the `CNRXStaking` and `PointsClaim` ABIs with their error tables
535
+ (`CNRX_STAKING_ABI`, `CNRX_STAKING_ERRORS`, `POINTS_CLAIM_ABI`, `POINTS_CLAIM_ERRORS`). The
536
+ generator now splits an acronym of two or more capitals from the word after it, which renames
537
+ nothing already exported. Additive only. Neither contract has an address in `DEPLOYMENTS`
538
+ yet; addresses come in a later release.
539
+ - `0.2.0-rc.2` — adds the `CancoreRouter`, `ICancoreRouter` and `AttestorSet` ABIs with their error
540
+ tables; `FeeVault` gains the `TransferFailed()` error and `IPermit2` gains
541
+ `permitWitnessTransferFrom`; CNRX and IBurnMintERC20 are now read from `evm-contracts/vendor/`.
542
+ Additive only. Documentation correction: `BYTECODE_HASHES` values have always been sha256 of
543
+ the artifact's hex text, never keccak256 or a hash of `eth_getCode`, as the `0.1.x` README
544
+ said; the values' meaning is unchanged.
545
+ - `0.2.0-rc.1` — filler protocol v1 release candidate: EIP-712 types, hashing helpers, JSON
546
+ Schemas, AsyncAPI, golden vectors; the `FillProof` schema.
547
+
110
548
  ## License
111
549
 
112
550
  Apache-2.0.