@artblocks/contracts 1.5.0 → 1.6.0

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 (21) hide show
  1. package/artifacts/contracts/interfaces/v0.8.x/IFormPaletteBindingHooks.sol/IFormPaletteBindingHooks.json +723 -0
  2. package/artifacts/contracts/interfaces/v0.8.x/IPMPProjectViewsV0.sol/IPMPProjectViewsV0.json +126 -0
  3. package/artifacts/contracts/interfaces/v0.8.x/ISharedMinterRequiredPMPV0.sol/ISharedMinterRequiredPMPV0.json +36 -0
  4. package/artifacts/contracts/libs/v0.8.x/minter-libs/RequiredPMPLib.sol/RequiredPMPLib.json +10 -0
  5. package/artifacts/contracts/minter-suite/Minters/MinterSetPricePMPV0.sol/MinterSetPricePMPV0.json +613 -0
  6. package/artifacts/contracts/mock/MockPMPMinterReentrantConfigureHook.sol/IMinterPMPPurchase.json +91 -0
  7. package/artifacts/contracts/mock/MockPMPMinterReentrantConfigureHook.sol/MockPMPMinterReentrantConfigureHook.json +180 -0
  8. package/artifacts/contracts/mock/MockPMPReentrantConfigureHook.sol/MockPMPReentrantConfigureHook.json +158 -0
  9. package/artifacts/contracts/mock/ReentrancyPMPMockShared.sol/IMinterPurchaseWithPMPs.json +67 -0
  10. package/artifacts/contracts/mock/ReentrancyPMPMockShared.sol/ReentrancyPMPMockShared.json +154 -0
  11. package/artifacts/contracts/web3call/combined-hooks/FormPaletteBindingHooks.sol/FormPaletteBindingHooks.json +919 -0
  12. package/contracts/interfaces/v0.8.x/IFormPaletteBindingHooks.sol +339 -0
  13. package/contracts/interfaces/v0.8.x/IPMPProjectViewsV0.sol +59 -0
  14. package/contracts/interfaces/v0.8.x/ISharedMinterRequiredPMPV0.sol +27 -0
  15. package/contracts/libs/v0.8.x/minter-libs/RequiredPMPLib.sol +336 -0
  16. package/contracts/minter-suite/Minters/MinterSetPricePMPV0.sol +664 -0
  17. package/contracts/mock/MockPMPMinterReentrantConfigureHook.sol +85 -0
  18. package/contracts/mock/MockPMPReentrantConfigureHook.sol +59 -0
  19. package/contracts/mock/ReentrancyPMPMockShared.sol +81 -0
  20. package/contracts/web3call/combined-hooks/FormPaletteBindingHooks.sol +1392 -0
  21. package/package.json +1 -1
@@ -0,0 +1,1392 @@
1
+ // SPDX-License-Identifier: LGPL-3.0-only
2
+ // Created By: Art Blocks Inc.
3
+
4
+ // @dev fixed to specific solidity version for clarity and for more clear
5
+ // source code verification purposes.
6
+ pragma solidity 0.8.22;
7
+
8
+ import {AbstractTransferHook} from "../../engine/V3/transfer-hooks/AbstractTransferHook.sol";
9
+ import {AbstractPMPAugmentHook} from "../augment-hooks/AbstractPMPAugmentHook.sol";
10
+ import {AbstractPMPConfigureHook} from "../configure-hooks/AbstractPMPConfigureHook.sol";
11
+
12
+ import {IFormPaletteBindingHooks} from "../../interfaces/v0.8.x/IFormPaletteBindingHooks.sol";
13
+ import {ITransferHook} from "../../interfaces/v0.8.x/ITransferHook.sol";
14
+ import {IPMPAugmentHook} from "../../interfaces/v0.8.x/IPMPAugmentHook.sol";
15
+ import {IPMPConfigureHook} from "../../interfaces/v0.8.x/IPMPConfigureHook.sol";
16
+ import {IPMPV0} from "../../interfaces/v0.8.x/IPMPV0.sol";
17
+ import {IWeb3Call} from "../../interfaces/v0.8.x/IWeb3Call.sol";
18
+ import {IGenArt721CoreContractV3_Base} from "../../interfaces/v0.8.x/IGenArt721CoreContractV3_Base.sol";
19
+ import {IGenArt721CoreContractV3_Engine} from "../../interfaces/v0.8.x/IGenArt721CoreContractV3_Engine.sol";
20
+
21
+ import {ABHelpers} from "../../libs/v0.8.x/ABHelpers.sol";
22
+ import {ImmutableStringArray} from "../../libs/v0.8.x/ImmutableStringArray.sol";
23
+
24
+ import {Strings} from "@openzeppelin-5.0/contracts/utils/Strings.sol";
25
+ import {IERC721} from "@openzeppelin-5.0/contracts/interfaces/IERC721.sol";
26
+ import {IERC165} from "@openzeppelin-5.0/contracts/interfaces/IERC165.sol";
27
+
28
+ /**
29
+ * @title Form/palette binding combined hook
30
+ * @author Art Blocks Inc.
31
+ * @notice Binds one token of a "palette" project to one token of a "form"
32
+ * project. The form project is the artwork whose image depends on the pairing;
33
+ * a palette project supplies the palette its script paints with.
34
+ *
35
+ * This contract is also the registry and the resolver for that palette data. A
36
+ * palette project is registered together with its complete, ordered list of
37
+ * palette entries, and the contract decides which entry each palette token
38
+ * resolves to. Both projects' scripts read that answer rather than computing
39
+ * it, so there is exactly one implementation of the mapping and nothing to keep
40
+ * in sync across two languages.
41
+ *
42
+ * Only the form project is fixed at deployment. Palette projects are
43
+ * registered afterwards, on any core contract — the form project's own or any
44
+ * other — so collections released long after the form project can still be
45
+ * bound and painted. Registering one is the contract's only administrative
46
+ * operation, it is append-only, and a project's entries are immutable once
47
+ * written. There is no owner, no removal, and nothing else to configure. Every
48
+ * other state change is a collector binding or unbinding.
49
+ * ----------------------------------------------------------------------------
50
+ * The pairing is 1:1 and requires common ownership: a palette token may be
51
+ * bound to at most one form token, a form token to at most one palette token,
52
+ * and both must be held by the same wallet at the moment of binding. Either
53
+ * token changing hands breaks the pairing.
54
+ * ----------------------------------------------------------------------------
55
+ * THREE HOOKS, ONE STATE MACHINE. Canonical state is this contract's pair of
56
+ * mappings; everything else derives from them.
57
+ *
58
+ * - The **configure hook** is the only way a collector changes state. It runs
59
+ * on every write of the form project's binding param and either binds,
60
+ * unbinds, or reverts.
61
+ * - The **transfer hook** runs on the form project and on every palette
62
+ * project. When a bound token moves, it clears the pairing directly, then
63
+ * writes the form token's binding param so the off-chain pipeline re-renders
64
+ * the form token.
65
+ * - The **augment hook** runs on the form project and on every palette project.
66
+ * It reports canonical state on read, resolves palette data, and strips the
67
+ * raw binding param so a stale value can never reach an artwork script.
68
+ * ----------------------------------------------------------------------------
69
+ * ONE WRITE, ONE RE-RENDER. `PMPV1.configureTokenParams` is `nonReentrant` and
70
+ * invokes the configure hook inside that call, so a configure hook cannot write
71
+ * any PostParam — not on the configured token, not on another one. A single
72
+ * `configureTokenParams` call is also scoped to a single token. Since writing a
73
+ * PostParam is the only thing that triggers an off-chain re-render, exactly one
74
+ * token can re-render per write.
75
+ *
76
+ * That is why binding is strict: a write that binds a palette to a form token
77
+ * is rejected unless **both** sides are currently unbound. Re-pointing either
78
+ * side would silently change a third token's image without writing it, leaving
79
+ * a stored render that no longer matches the chain. Every transition therefore
80
+ * moves through the unbound state, and the token whose image changed is always
81
+ * the token that was written.
82
+ *
83
+ * Strict does not mean two transactions. `configureTokenParams` applies its
84
+ * `pmpInputs` in order and invokes the configure hook after each, so passing
85
+ * `[unbound, newPalette]` for the binding key moves one form token from one
86
+ * palette to another in a single atomic write: the pairing still passes through
87
+ * the unbound state, and PMP emits one `TokenParamsConfigured` for that token,
88
+ * so it re-renders once. Prefer that over two transactions.
89
+ *
90
+ * What the strict rule actually forbids is taking a palette that is bound to a
91
+ * *different* form token. No input list on one token can do that, because the
92
+ * other form token would not be written: `PaletteAlreadyBound` is raised no
93
+ * matter how the inputs are ordered. That move needs a write on each form
94
+ * token, which is two `configureTokenParams` calls — one user action, one
95
+ * transaction on a wallet that batches, two otherwise. `previewBind` reports
96
+ * which case a front end is in.
97
+ * ----------------------------------------------------------------------------
98
+ * PALETTE PROJECTS GROW. A form project is expected to outlive its first
99
+ * palette collection. `registerPaletteProject` adds another, callable only by
100
+ * the form project's artist, read live from the core so no owner is stored.
101
+ *
102
+ * Registration is append-only. Deregistration is not offered because it would
103
+ * strand every pairing already made against that project: the palette holder
104
+ * has no write path, and only the form token's owner can express an unbind.
105
+ * Growing the set can never invalidate an existing pairing, which is what makes
106
+ * appending safe to do at any time.
107
+ *
108
+ * Because the palette entries live here and both scripts read `paletteData`,
109
+ * **neither art script changes when a palette project is added.** The form
110
+ * project's script can be locked on day one and still paint collections that do
111
+ * not exist yet. That is the whole reason palette data is on chain rather than
112
+ * in the script.
113
+ *
114
+ * One thing does not happen automatically on registration: **configure this
115
+ * contract as the new project's transfer hook** on its core. Without it,
116
+ * binding works but a transfer of one of its tokens does not break the pairing
117
+ * — the degraded mode described below.
118
+ *
119
+ * A palette project may be on any core, including the form project's own. That
120
+ * is what the packed binding param below buys: nothing here assumes the artist
121
+ * will still be minting on the same Art Blocks contract in five years.
122
+ * ----------------------------------------------------------------------------
123
+ * THE BINDING PARAM VALUE IS A PACKED TOKEN. A PostParam is a `uint256`, so the
124
+ * value a collector writes has to name a `(coreContract, tokenId)` pair in one
125
+ * number. It does so by packing them:
126
+ *
127
+ * value = (uint256(uint160(coreContract)) << 96) | paletteTokenId
128
+ *
129
+ * An address is 160 bits and an Art Blocks token ID needs at most 96, so the
130
+ * two fit a `uint256` exactly. Registration rejects a project ID whose tokens
131
+ * could not fit, which makes the packing lossless rather than merely unlikely
132
+ * to collide.
133
+ *
134
+ * Three properties follow, and each of them is the reason for the choice:
135
+ *
136
+ * - The value is derivable and decodable off chain by arithmetic alone. No
137
+ * contract call and no contract state are needed to compute what to write,
138
+ * though `bindingParamValueFor(coreContract, paletteTokenId)` is provided and
139
+ * also answers whether the project is registered.
140
+ * - A mistyped value fails loudly. A collector who enters a bare token ID
141
+ * writes a number far below the core contract's bits, so it unpacks to the
142
+ * zero address, which is never a registered project. An encoding whose values
143
+ * resembled token IDs could instead have bound a different real token.
144
+ * - `0` is free to mean unbound, because a registered core is never the zero
145
+ * address. Project `0` of any core is registrable, unlike under a bare
146
+ * token-ID scheme.
147
+ *
148
+ * Everything else in the interface — `boundPaletteOf`, `isPaletteProject`,
149
+ * `previewBind`, `paletteDataFor`, every event and every error — speaks in
150
+ * plain `(coreContract, tokenId)` terms. The packed value appears in one other
151
+ * place, the stored `boundPaletteRef` param, and the augment hook strips that
152
+ * before any art script sees it. The injected `boundPaletteTokenId` is the real
153
+ * token ID, which is why the written key is named `boundPaletteRef` rather than
154
+ * repeating it: a field called `...TokenId` invites a bare token ID, the exact
155
+ * mistake this encoding rejects.
156
+ * ----------------------------------------------------------------------------
157
+ * REQUIRED SETUP, ONE TIME. All of it concerns the form project, and steps 2-4
158
+ * need the address deployed in step 1.
159
+ *
160
+ * 1. Deploy with the PMP contract every project here uses and the form
161
+ * project's `(core, projectId)`.
162
+ *
163
+ * 2. Configure the binding param on the **form** project, via `configureProject`
164
+ * on the bound PMP:
165
+ * - key: `boundPaletteRef` (`PARAM_KEY_BOUND_PALETTE_REF`)
166
+ * - `paramType`: `Uint256Range`
167
+ * - `authOption`: `TokenOwnerAndAddress`
168
+ * - `authAddress`: this hook. Required — without it the transfer hook cannot
169
+ * write the unbind that triggers the form token's re-render.
170
+ * - `minRange`: `0` (`UNBOUND_PARAM_VALUE`)
171
+ * - `maxRange`: `BINDING_PARAM_MAX_RANGE` (`type(uint256).max`). Deliberately
172
+ * unbounded: the palette project set grows, so any fixed range would need
173
+ * widening on every palette drop, and forgetting would surface as an
174
+ * opaque PMP range error instead of this hook's own. Which token IDs
175
+ * actually bind is decided here, against the registry and `ownerOf`.
176
+ * - `pmpLockedAfterTimestamp`: `0`. Do not lock. On PMPV1 a passed lock
177
+ * timestamp freezes the param's value for every party, which would make
178
+ * existing pairings permanent and unbreakable.
179
+ *
180
+ * Verify these off chain after deployment by reading `getProjectPMPConfig`
181
+ * on the bound PMP — this contract deliberately does not re-check them, as
182
+ * nothing on chain branches on the answer.
183
+ *
184
+ * 3. `configureProjectHooks(formCore, formProjectId, thisHook, thisHook)` on the
185
+ * bound PMP — the form project needs this address as **both** the
186
+ * post-config hook and the read-augmentation hook.
187
+ *
188
+ * 4. `configureProjectTransferHook(formProjectId, thisHook)` on `formCore`.
189
+ * ----------------------------------------------------------------------------
190
+ * REQUIRED SETUP, PER PALETTE PROJECT. Repeat all three for every palette
191
+ * collection, the first one included. Each omission breaks the collection in a
192
+ * different and silent way, named below.
193
+ *
194
+ * A. `registerPaletteProject(coreContract, projectId, palettes)` on this
195
+ * contract, as the form project's artist. The entries are written once and
196
+ * can never be changed, replaced, or grown. Any core and any project ID are
197
+ * accepted except the form project itself.
198
+ * *Omitted:* `isPaletteProject` stays false, nothing in the collection can
199
+ * be bound, and its tokens resolve no palette.
200
+ *
201
+ * B. `configureProjectHooks(coreContract, projectId, address(0), thisHook)` on
202
+ * the bound PMP — read-augmentation hook only. A palette project carries no
203
+ * binding param, so it needs no configure hook.
204
+ * *Omitted:* binding still works and form tokens still paint correctly, but
205
+ * the collection's own tokens receive no `paletteData` and render whatever
206
+ * their script does with nothing.
207
+ *
208
+ * C. `configureProjectTransferHook(projectId, thisHook)` on that same core.
209
+ * *Omitted:* binding still works, but moving one of its tokens does not
210
+ * break the pairing. This is the only one of the three that leaves wrong
211
+ * state behind rather than absent state — see the degraded mode below.
212
+ *
213
+ * Each palette project also needs the PMP contract registered as an on-chain
214
+ * flex asset dependency (`addProjectAssetDependencyOnChainAtAddress`), the same
215
+ * as any project that uses PostParams, or nothing injected here reaches its
216
+ * script.
217
+ *
218
+ * `boundPaletteRef` is the only key the artist configures. On neither side may
219
+ * they configure `boundPaletteTokenId`, `boundPaletteCoreContract`,
220
+ * `boundPaletteTokenHash`, `boundFormTokenId` or `paletteData` — those are
221
+ * inject-only and are stripped on read.
222
+ * ----------------------------------------------------------------------------
223
+ * POSTPARAMS. On every read this hook copies the input params, drops the
224
+ * written `boundPaletteRef` along with any entry colliding with the five keys
225
+ * below, and appends the ones for that token's side. Values are canonical
226
+ * state, never the raw stored param.
227
+ *
228
+ * On a **form** token:
229
+ * - `boundPaletteTokenId`: decimal token ID of the bound palette token, or the
230
+ * empty string when unbound.
231
+ * - `boundPaletteCoreContract`: the core contract that token lives on, as a
232
+ * `0x`-prefixed lowercase hex address; empty when unbound. Paired with
233
+ * `boundPaletteTokenId` it is the token's full identity, which a token ID
234
+ * alone is not once palette projects may live on several contracts. Its
235
+ * project ID is `boundPaletteTokenId / 1_000_000` if a script wants to label
236
+ * or vary by collection.
237
+ * - `boundPaletteTokenHash`: that palette token's `tokenIdToHash`, always
238
+ * `0x` + 64 lowercase hex characters, zero-padded. Empty string when unbound.
239
+ * Provenance and a seed for any extra variation the form script wants to draw
240
+ * from the specific palette token it holds. **Do not derive the palette from
241
+ * it** — that is what `paletteData` is for, and re-deriving in JavaScript
242
+ * reintroduces exactly the second implementation this design removes.
243
+ * (For the record, the on-chain `GenArt721GeneratorV0` stringifies hashes
244
+ * with the unpadded `Strings.toHexString(uint256)`, dropping leading zero
245
+ * bytes on roughly one hash in 256; this key is always padded, so the two
246
+ * spellings differ for those tokens.)
247
+ * - `paletteData`: the registered palette entry the bound palette token
248
+ * resolves to. Empty string when unbound.
249
+ *
250
+ * On a **palette** token:
251
+ * - `boundFormTokenId`: decimal token ID of the form token it is bound to, or
252
+ * the empty string when unbound.
253
+ * - `paletteData`: the entry that token resolves to, always — a palette token
254
+ * carries its own palette whether or not anything is bound to it.
255
+ *
256
+ * `paletteData` is the same key on both sides, and that is the point. The form
257
+ * script and the palette script read one key and receive one answer, produced
258
+ * once, here. Neither derives a palette, so there is no second implementation
259
+ * to drift from and no bit-exactness contract between Solidity and JavaScript.
260
+ *
261
+ * Selection is `uint256(tokenIdToHash(paletteToken)) % paletteCount`. Because
262
+ * this contract is the only thing that computes it, the rule is chosen to be
263
+ * trivially auditable rather than to reproduce any existing script. Weighted
264
+ * rarity is expressed by repeating an entry in the registered list.
265
+ *
266
+ * The entries themselves are opaque to this contract — JSON, packed hex, a
267
+ * name, whatever the two scripts agree on. It stores and returns strings.
268
+ * ----------------------------------------------------------------------------
269
+ * ART SCRIPT. Every injected key arrives as a string on the web3call flex
270
+ * dependency, and a palette costs one of them:
271
+ *
272
+ * const params = tokenData.externalAssetDependencies
273
+ * .find((d) => d.dependency_type === "ONCHAIN")?.data;
274
+ * const paletteData = params?.["paletteData"]; // "" when none is in effect
275
+ * const palette = paletteData ? JSON.parse(paletteData) : defaultPalette;
276
+ *
277
+ * Identical in both projects. The palette project's script reads its own
278
+ * entry; the form project's script reads the bound token's. Neither holds a
279
+ * palette list, and neither needs updating when a collection is added, so both
280
+ * may be locked.
281
+ *
282
+ * A form token is unbound at mint and returns to unbound on every transfer, so
283
+ * the form script must render something meaningful for the empty case. A
284
+ * palette token's own `paletteData` is never empty once its project is
285
+ * registered.
286
+ * ----------------------------------------------------------------------------
287
+ * READ-TIME OWNERSHIP BACKSTOP. The augment hook re-checks that both tokens
288
+ * still share an owner before reporting a pairing. In a correctly configured
289
+ * deployment the transfer hook has already cleared it and the check never
290
+ * fires. It exists because a project that never configured the transfer hook,
291
+ * or cleared it later, would otherwise render a pairing across two wallets —
292
+ * violating the piece's core rule.
293
+ *
294
+ * That degraded mode is the most likely operator-facing failure, so be precise
295
+ * about what it costs. The mappings still occupy both slots, so: the artwork
296
+ * renders unbound while `boundPaletteOf` and `previewBind` still report the
297
+ * pairing; the palette cannot be bound to any other form token
298
+ * (`PaletteAlreadyBound`); the palette's new holder has no way to clear it,
299
+ * because only the form token's owner or this hook may write the binding param;
300
+ * and returning the token to its former owner makes the pairing render again,
301
+ * because nothing cleared the mapping. The palette token keeps rendering its
302
+ * own `paletteData` throughout — only the pairing is hidden. The single repair
303
+ * is the form token's owner writing `UNBOUND_PARAM_VALUE`. Configuring the
304
+ * transfer hook on the form project and on every palette project is what
305
+ * prevents all of it.
306
+ * ----------------------------------------------------------------------------
307
+ * SCALING. Every operation on the binding path is O(1). Deciding whether a
308
+ * token is bindable is one `SLOAD` of `_isPaletteProject[core][projectId]`,
309
+ * however many palette projects exist, and the pairing itself is two mappings
310
+ * keyed by the packed value. Converting between a token and its packed value is
311
+ * arithmetic, not storage. No list of tokens, projects, or palettes is ever
312
+ * walked on the binding, transfer, or read path; palette projects are
313
+ * enumerated through `paletteProjectCount` and `paletteProjectAt`, which a
314
+ * caller pages at its own pace.
315
+ *
316
+ * Palette entries are held in SSTORE2 bytecode, one contract per registered
317
+ * project, written once at registration. Resolving a token reads that blob and
318
+ * indexes into it — no unbounded storage array, and registering a collection
319
+ * costs a fraction of what a Solidity `string[]` would.
320
+ *
321
+ * The pairing mappings are not keyed by core contract and do not need to be.
322
+ * `_formToPalette` is keyed by form token ID, and the form project is a single
323
+ * immutable `(core, projectId)`. `_paletteToForm` is keyed by the packed value,
324
+ * which carries the core contract, so two contracts hosting projects with the
325
+ * same ID cannot collide.
326
+ * ----------------------------------------------------------------------------
327
+ * GAS. Transfer figures are deltas against an identical project with no hook,
328
+ * on `GenArt721CoreV3_Engine_Flex` with PMPV1, so they may be compared
329
+ * directly. Whoever moves the token pays them, on every transfer, forever.
330
+ *
331
+ * - transferring an **unbound** token costs about 20,600 gas more. That is the
332
+ * core's reentrancy flag, the configuration check, and one cold mapping read
333
+ * that comes back empty. Any hook pays most of it.
334
+ * - transferring a **bound form** token costs about 50,300 gas more — the above
335
+ * plus clearing two slots and the PMP write that re-renders the form token.
336
+ * - transferring a **bound palette** token costs about 52,300 gas more: the
337
+ * same work plus the registry lookup that identifies it as a palette token.
338
+ *
339
+ * Binding is about 164,500 gas and unbinding about 72,000, both absolute and
340
+ * both paid by the collector. Binding is the expensive direction because it
341
+ * writes three cold slots: the PMP's stored value plus both mappings.
342
+ *
343
+ * `registerPaletteProject` is paid once per collection by the artist and is
344
+ * dominated by the SSTORE2 write of the entries, so it scales with the total
345
+ * byte length of the palette list: about 198,000 gas for three short entries,
346
+ * rising roughly 200 gas per additional byte. Reads load that blob, which is
347
+ * why entries should be as compact as the art scripts can tolerate.
348
+ *
349
+ * See the gas tests in `form-palette-binding-hooks.test.ts` for the bounds that
350
+ * keep these figures honest.
351
+ * ----------------------------------------------------------------------------
352
+ * SAFETY. A reverting transfer hook makes a token permanently non-transferable,
353
+ * so `_onTokenTransfer` cannot revert on any path that a configured project can
354
+ * reach: state clearing is pure storage, and the PMP write is `try`/`catch`'d.
355
+ * A swallowed write emits `BindingParamSyncFailed`; the pairing is still broken
356
+ * on chain and reads are still correct, and any authorized party repairs the
357
+ * stored render by writing the binding param.
358
+ *
359
+ * The configure hook is the opposite: it reverts loudly, because a rejected
360
+ * write costs a collector a transaction rather than a collection. It also
361
+ * accepts calls only from the bound PMP — it mutates state, and PMP hooks are
362
+ * otherwise callable by anyone.
363
+ *
364
+ * `registerPaletteProject` is the only other state-changing entry point, and it
365
+ * is restricted to the form project's artist, read live from `formCore` on each
366
+ * call. Nothing here stores an owner, so the right follows the project: if the
367
+ * artist address is updated on the core, the new address holds it.
368
+ */
369
+ contract FormPaletteBindingHooks is
370
+ AbstractTransferHook,
371
+ AbstractPMPAugmentHook,
372
+ AbstractPMPConfigureHook,
373
+ IFormPaletteBindingHooks
374
+ {
375
+ using Strings for uint256;
376
+ using ImmutableStringArray for ImmutableStringArray.StringArray;
377
+
378
+ /// @notice Binding param on the form project, written by collectors to
379
+ /// bind and unbind, and by this hook to unbind on transfer. Its value is a
380
+ /// packed reference, not a token ID; see `bindingParamValueFor`.
381
+ string public constant PARAM_KEY_BOUND_PALETTE_REF = "boundPaletteRef";
382
+ /// @notice Inject-only key on form tokens carrying the bound palette
383
+ /// token's ID. Must not be configured as a project param.
384
+ string public constant PARAM_KEY_BOUND_PALETTE_TOKEN_ID =
385
+ "boundPaletteTokenId";
386
+ /// @notice Inject-only key on form tokens carrying the core contract of the
387
+ /// bound palette token. Must not be configured as a project param.
388
+ string public constant PARAM_KEY_BOUND_PALETTE_CORE_CONTRACT =
389
+ "boundPaletteCoreContract";
390
+ /// @notice Inject-only key on form tokens carrying the bound palette
391
+ /// token's hash. Must not be configured as a project param.
392
+ string public constant PARAM_KEY_BOUND_PALETTE_TOKEN_HASH =
393
+ "boundPaletteTokenHash";
394
+ /// @notice Inject-only key on palette tokens carrying the form token they
395
+ /// are bound to. Must not be configured as a project param.
396
+ string public constant PARAM_KEY_BOUND_FORM_TOKEN_ID = "boundFormTokenId";
397
+ /// @notice Inject-only key carrying the palette entry in effect for the
398
+ /// token: on a form token the bound palette's, on a palette token its own.
399
+ /// Must not be configured as a project param.
400
+ string public constant PARAM_KEY_PALETTE_DATA = "paletteData";
401
+
402
+ /**
403
+ * @notice Binding param value meaning "not bound".
404
+ * @dev Unambiguous by construction: a bindable value carries a non-zero
405
+ * core contract in its high bits, so it can never be `0`.
406
+ */
407
+ uint256 public constant UNBOUND_PARAM_VALUE = 0;
408
+
409
+ /**
410
+ * @notice Required `maxRange` of the binding param.
411
+ * @dev Unbounded on purpose. The set of palette projects grows over the
412
+ * life of the form project, so no fixed range could stay correct without
413
+ * the artist re-running `configureProject` on every palette drop — a step
414
+ * that is easy to forget and whose omission surfaces as an opaque PMP
415
+ * range error. This hook is the sole authority on which values bind.
416
+ */
417
+ uint256 public constant BINDING_PARAM_MAX_RANGE = type(uint256).max;
418
+
419
+ /// @dev Low bits of the binding param value that hold the token ID. The
420
+ /// remaining 160 are the core contract, so the two pack exactly.
421
+ uint256 private constant _TOKEN_ID_BITS = 96;
422
+ uint256 private constant _TOKEN_ID_MASK = (1 << _TOKEN_ID_BITS) - 1;
423
+
424
+ // @dev derived from the constants above rather than restated as literals,
425
+ // so a key and its hash cannot drift apart
426
+ bytes32 private constant _HASHED_PARAM_KEY_BOUND_PALETTE_REF =
427
+ keccak256(bytes(PARAM_KEY_BOUND_PALETTE_REF));
428
+ bytes32 private constant _HASHED_PARAM_KEY_BOUND_PALETTE_TOKEN_ID =
429
+ keccak256(bytes(PARAM_KEY_BOUND_PALETTE_TOKEN_ID));
430
+ bytes32 private constant _HASHED_PARAM_KEY_BOUND_PALETTE_CORE_CONTRACT =
431
+ keccak256(bytes(PARAM_KEY_BOUND_PALETTE_CORE_CONTRACT));
432
+ bytes32 private constant _HASHED_PARAM_KEY_BOUND_PALETTE_TOKEN_HASH =
433
+ keccak256(bytes(PARAM_KEY_BOUND_PALETTE_TOKEN_HASH));
434
+ bytes32 private constant _HASHED_PARAM_KEY_BOUND_FORM_TOKEN_ID =
435
+ keccak256(bytes(PARAM_KEY_BOUND_FORM_TOKEN_ID));
436
+ bytes32 private constant _HASHED_PARAM_KEY_PALETTE_DATA =
437
+ keccak256(bytes(PARAM_KEY_PALETTE_DATA));
438
+
439
+ /// @notice PMP contract this hook writes transfer-driven unbinds to.
440
+ IPMPV0 public immutable pmp;
441
+ /// @notice Core contract hosting the form project.
442
+ address public immutable formCore;
443
+ /// @notice Project ID of the form project on `formCore`.
444
+ uint256 public immutable formProjectId;
445
+
446
+ /// @dev Whether a project's tokens may be bound. The only registration
447
+ /// check any path needs.
448
+ mapping(address coreContract => mapping(uint256 projectId => bool))
449
+ private _isPaletteProject;
450
+
451
+ /// @dev Registration order, for enumeration only. Bounded by the number of
452
+ /// palette drops the artist makes, not by any token count.
453
+ PaletteProject[] private _paletteProjects;
454
+
455
+ /**
456
+ * @dev Each project's palette entries, written once via SSTORE2 and never
457
+ * mutable afterwards. Immutability is load-bearing: the entry a token
458
+ * resolves to is `hash % length`, so a list that could grow would silently
459
+ * repaint tokens that had already minted.
460
+ */
461
+ mapping(address coreContract => mapping(uint256 projectId => ImmutableStringArray.StringArray))
462
+ private _palettes;
463
+
464
+ /**
465
+ * @notice Canonical state. Keyed and valued by binding param values, which
466
+ * are globally unique across cores, so no core needs to appear in the key.
467
+ * @dev `_formToPalette` needs no offset because a bindable value is never
468
+ * `0`. `_paletteToForm` stores `formTokenId + 1` because form token `0` is
469
+ * a real token.
470
+ */
471
+ mapping(uint256 formTokenId => uint256 bindingParamValue)
472
+ private _formToPalette;
473
+ mapping(uint256 bindingParamValue => uint256 formTokenIdPlusOne)
474
+ private _paletteToForm;
475
+
476
+ /**
477
+ * @param pmp_ PMP contract every project here uses. Must be non-zero: this
478
+ * hook writes transfer-driven unbinds to it.
479
+ * @param formCore_ Core contract hosting the form project.
480
+ * @param formProjectId_ Project ID of the form project. `0` is allowed.
481
+ * @dev No palette projects are registered here. Every registration goes
482
+ * through `registerPaletteProject`, so there is exactly one code path and
483
+ * one authorization rule for it. Until the artist registers the first one,
484
+ * nothing can bind.
485
+ */
486
+ constructor(address pmp_, address formCore_, uint256 formProjectId_) {
487
+ if (pmp_ == address(0) || formCore_ == address(0)) {
488
+ revert InvalidConstructorArgs();
489
+ }
490
+ pmp = IPMPV0(pmp_);
491
+ formCore = formCore_;
492
+ formProjectId = formProjectId_;
493
+ }
494
+
495
+ // ---- palette project registry ----
496
+
497
+ /**
498
+ * @inheritdoc IFormPaletteBindingHooks
499
+ */
500
+ function registerPaletteProject(
501
+ address coreContract,
502
+ uint256 projectId,
503
+ string[] calldata palettes
504
+ ) external {
505
+ // @dev the form project's artist owns this decision: it changes what
506
+ // their form tokens may bind to. Read live from the core, so no owner
507
+ // is stored here and a transferred project carries the right with it.
508
+ address artist = IGenArt721CoreContractV3_Base(formCore)
509
+ .projectIdToArtistAddress(formProjectId);
510
+ if (msg.sender != artist) {
511
+ revert OnlyFormProjectArtist({caller: msg.sender, artist: artist});
512
+ }
513
+ bool isFormProject = coreContract == formCore &&
514
+ projectId == formProjectId;
515
+ if (coreContract == address(0) || isFormProject) {
516
+ revert InvalidPaletteProject({
517
+ coreContract: coreContract,
518
+ projectId: projectId
519
+ });
520
+ }
521
+ // @dev the packing below is lossless only while a token ID fits the low
522
+ // bits; no Art Blocks project comes close, but the encoding depends on
523
+ // it, so it is enforced rather than assumed
524
+ bool projectIdFits = projectId <=
525
+ (_TOKEN_ID_MASK - (ABHelpers.ONE_MILLION - 1)) /
526
+ ABHelpers.ONE_MILLION;
527
+ if (!projectIdFits) {
528
+ revert InvalidPaletteProject({
529
+ coreContract: coreContract,
530
+ projectId: projectId
531
+ });
532
+ }
533
+ if (_isPaletteProject[coreContract][projectId]) {
534
+ revert PaletteProjectAlreadyRegistered({
535
+ coreContract: coreContract,
536
+ projectId: projectId
537
+ });
538
+ }
539
+ if (palettes.length == 0) {
540
+ revert EmptyPaletteList();
541
+ }
542
+ _isPaletteProject[coreContract][projectId] = true;
543
+ _paletteProjects.push(
544
+ PaletteProject({coreContract: coreContract, projectId: projectId})
545
+ );
546
+ _palettes[coreContract][projectId].store(palettes);
547
+ emit PaletteProjectRegistered({
548
+ coreContract: coreContract,
549
+ projectId: projectId,
550
+ paletteCount: palettes.length
551
+ });
552
+ }
553
+
554
+ // ---- configure hook ----
555
+
556
+ /**
557
+ * @notice Apply a write of the form project's binding param.
558
+ * @dev Called by the PMP inside `configureTokenParams`, after the value has
559
+ * been stored and authorized. Reverting here reverts the collector's whole
560
+ * transaction, including the stored value.
561
+ * @dev Writes of any other key are ignored, so the form project may carry
562
+ * unrelated params freely.
563
+ * @param coreContract Core contract whose token was configured.
564
+ * @param tokenId Token that was configured.
565
+ * @param pmpInput The param input that was stored.
566
+ */
567
+ function onTokenPMPConfigure(
568
+ address coreContract,
569
+ uint256 tokenId,
570
+ IPMPV0.PMPInput calldata pmpInput
571
+ ) external override(AbstractPMPConfigureHook, IPMPConfigureHook) {
572
+ // @dev this hook mutates state; PMP hook entry points are otherwise
573
+ // callable by anyone, which would let a caller forge bindings
574
+ if (msg.sender != address(pmp)) {
575
+ revert OnlyPMP({caller: msg.sender});
576
+ }
577
+ if (
578
+ keccak256(bytes(pmpInput.key)) !=
579
+ _HASHED_PARAM_KEY_BOUND_PALETTE_REF
580
+ ) {
581
+ return;
582
+ }
583
+ // @dev the binding param belongs to the form project only; reaching
584
+ // here from anywhere else means this hook is misconfigured
585
+ if (
586
+ coreContract != formCore ||
587
+ ABHelpers.tokenIdToProjectId(tokenId) != formProjectId
588
+ ) {
589
+ revert ConfigureHookOnUnexpectedProject({
590
+ coreContract: coreContract,
591
+ tokenId: tokenId
592
+ });
593
+ }
594
+ _applyBindingParam({
595
+ formTokenId: tokenId,
596
+ newValue: uint256(pmpInput.configuredValue)
597
+ });
598
+ }
599
+
600
+ // ---- transfer hook ----
601
+
602
+ /**
603
+ * @notice Break the pairing of a token that changed hands, and re-render
604
+ * the form token.
605
+ * @dev Called by the core after the ERC-721 ownership write. Must not
606
+ * revert on any reachable path: a reverting transfer hook makes the token
607
+ * permanently non-transferable.
608
+ * @param coreContract Core that performed the ownership update. Guaranteed
609
+ * by `AbstractTransferHook` to equal `msg.sender`.
610
+ * @param tokenId Token whose ownership changed.
611
+ * @param from Previous owner; `address(0)` on mint.
612
+ * @param to New owner.
613
+ */
614
+ function _onTokenTransfer(
615
+ address coreContract,
616
+ uint256 tokenId,
617
+ address from,
618
+ address to,
619
+ address /* operator */
620
+ ) internal override {
621
+ uint256 projectId = ABHelpers.tokenIdToProjectId(tokenId);
622
+ _onlyConfiguredForProject({
623
+ coreContract: coreContract,
624
+ projectId: projectId
625
+ });
626
+
627
+ // @dev ERC-721 permits `transferFrom(a, a, id)`; ownership did not
628
+ // change, so the pairing is still valid
629
+ if (from == to) {
630
+ return;
631
+ }
632
+ // @dev mint: a token cannot be bound before it exists
633
+ if (from == address(0)) {
634
+ return;
635
+ }
636
+
637
+ if (coreContract == formCore && projectId == formProjectId) {
638
+ uint256 boundValue = _formToPalette[tokenId];
639
+ if (boundValue == UNBOUND_PARAM_VALUE) {
640
+ return;
641
+ }
642
+ _clearBinding({
643
+ formTokenId: tokenId,
644
+ paramValue: boundValue,
645
+ reason: UnbindReason.FormTransferred
646
+ });
647
+ _syncBindingParam({formTokenId: tokenId});
648
+ return;
649
+ }
650
+
651
+ if (_isPaletteProject[coreContract][projectId]) {
652
+ uint256 paramValue = _encode({
653
+ coreContract: coreContract,
654
+ paletteTokenId: tokenId
655
+ });
656
+ (bool isBound, uint256 formTokenId) = _boundFormOf({
657
+ paramValue: paramValue
658
+ });
659
+ if (!isBound) {
660
+ return;
661
+ }
662
+ _clearBinding({
663
+ formTokenId: formTokenId,
664
+ paramValue: paramValue,
665
+ reason: UnbindReason.PaletteTransferred
666
+ });
667
+ _syncBindingParam({formTokenId: formTokenId});
668
+ }
669
+ // @dev configured on a project this hook does not serve: do nothing.
670
+ // Reverting would brick that project's transfers for no benefit.
671
+ }
672
+
673
+ // ---- augment hook ----
674
+
675
+ /**
676
+ * @notice Replace this hook's keys with canonical binding state.
677
+ * @dev Copies the input params, drops any entry whose key collides with one
678
+ * of this hook's five keys — including the collector's own raw binding
679
+ * param, so a value that disagrees with canonical state can never reach an
680
+ * artwork script — then appends the keys for the token's side.
681
+ * @dev This must return all desired tokenParams, not just additional data.
682
+ * @param coreContract The address of the core contract of the queried token.
683
+ * @param tokenId The tokenId of the queried token.
684
+ * @param tokenParams The token parameters for the queried token.
685
+ * @return augmentedTokenParams The augmented token parameters.
686
+ */
687
+ function onTokenPMPReadAugmentation(
688
+ address coreContract,
689
+ uint256 tokenId,
690
+ IWeb3Call.TokenParam[] calldata tokenParams
691
+ )
692
+ external
693
+ view
694
+ override(AbstractPMPAugmentHook, IPMPAugmentHook)
695
+ returns (IWeb3Call.TokenParam[] memory augmentedTokenParams)
696
+ {
697
+ uint256 projectId = ABHelpers.tokenIdToProjectId(tokenId);
698
+ bool isFormToken = coreContract == formCore &&
699
+ projectId == formProjectId;
700
+ bool isPaletteToken = _isPaletteProject[coreContract][projectId];
701
+ // @dev configured on a project this hook does not serve: pass through
702
+ // untouched rather than stripping keys that belong to someone else
703
+ if (!isFormToken && !isPaletteToken) {
704
+ return tokenParams;
705
+ }
706
+
707
+ uint256 originalLength = tokenParams.length;
708
+ // at most originalLength kept entries + 4 injected keys
709
+ augmentedTokenParams = new IWeb3Call.TokenParam[](originalLength + 4);
710
+
711
+ uint256 j;
712
+ for (uint256 i; i < originalLength; ) {
713
+ bytes32 hashedKey = keccak256(bytes(tokenParams[i].key));
714
+ if (
715
+ hashedKey != _HASHED_PARAM_KEY_BOUND_PALETTE_REF &&
716
+ hashedKey != _HASHED_PARAM_KEY_BOUND_PALETTE_TOKEN_ID &&
717
+ hashedKey != _HASHED_PARAM_KEY_BOUND_PALETTE_CORE_CONTRACT &&
718
+ hashedKey != _HASHED_PARAM_KEY_BOUND_PALETTE_TOKEN_HASH &&
719
+ hashedKey != _HASHED_PARAM_KEY_BOUND_FORM_TOKEN_ID &&
720
+ hashedKey != _HASHED_PARAM_KEY_PALETTE_DATA
721
+ ) {
722
+ augmentedTokenParams[j] = tokenParams[i];
723
+ unchecked {
724
+ ++j;
725
+ }
726
+ }
727
+ unchecked {
728
+ ++i;
729
+ }
730
+ }
731
+
732
+ if (isFormToken) {
733
+ // @dev resolved in one call so the four injected strings are the
734
+ // only form-side locals this frame has to hold
735
+ (
736
+ string memory coreValue,
737
+ string memory tokenIdValue,
738
+ string memory hashValue,
739
+ string memory paletteDataValue
740
+ ) = _formInjectedValues({formTokenId: tokenId});
741
+ augmentedTokenParams[j] = IWeb3Call.TokenParam({
742
+ key: PARAM_KEY_BOUND_PALETTE_CORE_CONTRACT,
743
+ value: coreValue
744
+ });
745
+ unchecked {
746
+ ++j;
747
+ }
748
+ augmentedTokenParams[j] = IWeb3Call.TokenParam({
749
+ key: PARAM_KEY_BOUND_PALETTE_TOKEN_ID,
750
+ value: tokenIdValue
751
+ });
752
+ unchecked {
753
+ ++j;
754
+ }
755
+ augmentedTokenParams[j] = IWeb3Call.TokenParam({
756
+ key: PARAM_KEY_BOUND_PALETTE_TOKEN_HASH,
757
+ value: hashValue
758
+ });
759
+ unchecked {
760
+ ++j;
761
+ }
762
+ augmentedTokenParams[j] = IWeb3Call.TokenParam({
763
+ key: PARAM_KEY_PALETTE_DATA,
764
+ value: paletteDataValue
765
+ });
766
+ unchecked {
767
+ ++j;
768
+ }
769
+ } else {
770
+ // @dev extracted for the same reason as the form side: keeps this
771
+ // frame down to the injected strings
772
+ (
773
+ string memory boundFormValue,
774
+ string memory paletteDataValue
775
+ ) = _paletteInjectedValues({
776
+ coreContract: coreContract,
777
+ paletteTokenId: tokenId
778
+ });
779
+ augmentedTokenParams[j] = IWeb3Call.TokenParam({
780
+ key: PARAM_KEY_BOUND_FORM_TOKEN_ID,
781
+ value: boundFormValue
782
+ });
783
+ unchecked {
784
+ ++j;
785
+ }
786
+ augmentedTokenParams[j] = IWeb3Call.TokenParam({
787
+ key: PARAM_KEY_PALETTE_DATA,
788
+ value: paletteDataValue
789
+ });
790
+ unchecked {
791
+ ++j;
792
+ }
793
+ }
794
+
795
+ // shorten to the populated length (original minus stripped plus injected)
796
+ assembly {
797
+ mstore(augmentedTokenParams, j)
798
+ }
799
+ return augmentedTokenParams;
800
+ }
801
+
802
+ // ---- views ----
803
+
804
+ /**
805
+ * @inheritdoc IFormPaletteBindingHooks
806
+ */
807
+ function boundPaletteOf(
808
+ uint256 formTokenId
809
+ )
810
+ external
811
+ view
812
+ returns (bool isBound, address coreContract, uint256 paletteTokenId)
813
+ {
814
+ uint256 paramValue = _formToPalette[formTokenId];
815
+ if (paramValue == UNBOUND_PARAM_VALUE) {
816
+ return (false, address(0), 0);
817
+ }
818
+ (coreContract, paletteTokenId) = _paletteTokenOf({
819
+ paramValue: paramValue
820
+ });
821
+ isBound = true;
822
+ }
823
+
824
+ /**
825
+ * @inheritdoc IFormPaletteBindingHooks
826
+ */
827
+ function boundFormOf(
828
+ address coreContract,
829
+ uint256 paletteTokenId
830
+ ) external view returns (bool isBound, uint256 formTokenId) {
831
+ (bool registered, uint256 paramValue) = _bindingParamValue({
832
+ coreContract: coreContract,
833
+ paletteTokenId: paletteTokenId
834
+ });
835
+ if (!registered) {
836
+ return (false, 0);
837
+ }
838
+ return _boundFormOf({paramValue: paramValue});
839
+ }
840
+
841
+ /**
842
+ * @inheritdoc IFormPaletteBindingHooks
843
+ */
844
+ function bindingParamValueFor(
845
+ address coreContract,
846
+ uint256 paletteTokenId
847
+ ) external view returns (bool registered, uint256 paramValue) {
848
+ return
849
+ _bindingParamValue({
850
+ coreContract: coreContract,
851
+ paletteTokenId: paletteTokenId
852
+ });
853
+ }
854
+
855
+ /**
856
+ * @inheritdoc IFormPaletteBindingHooks
857
+ */
858
+ function previewBind(
859
+ uint256 formTokenId,
860
+ address paletteCoreContract,
861
+ uint256 paletteTokenId
862
+ ) external view returns (bool allowed, BindBlocker blocker) {
863
+ // @dev checks follow the order `_applyBindingParam` applies them, so the
864
+ // reported blocker is the condition that would actually fail first
865
+ if (ABHelpers.tokenIdToProjectId(formTokenId) != formProjectId) {
866
+ return (false, BindBlocker.FormTokenNotInFormProject);
867
+ }
868
+ (bool registered, uint256 paramValue) = _bindingParamValue({
869
+ coreContract: paletteCoreContract,
870
+ paletteTokenId: paletteTokenId
871
+ });
872
+ uint256 currentValue = _formToPalette[formTokenId];
873
+ // @dev re-writing the pairing that already exists is accepted as a
874
+ // no-op, so report it as allowed; a front end that unbound first here
875
+ // would flicker the form token through the unbound state for nothing
876
+ if (
877
+ registered &&
878
+ currentValue != UNBOUND_PARAM_VALUE &&
879
+ currentValue == paramValue
880
+ ) {
881
+ return (true, BindBlocker.None);
882
+ }
883
+ if (currentValue != UNBOUND_PARAM_VALUE) {
884
+ return (false, BindBlocker.FormAlreadyBound);
885
+ }
886
+ if (!registered) {
887
+ return (false, BindBlocker.PaletteProjectNotRegistered);
888
+ }
889
+ (bool paletteBound, ) = _boundFormOf({paramValue: paramValue});
890
+ if (paletteBound) {
891
+ return (false, BindBlocker.PaletteAlreadyBound);
892
+ }
893
+ address formOwner;
894
+ try IERC721(formCore).ownerOf(formTokenId) returns (address owner_) {
895
+ formOwner = owner_;
896
+ } catch {
897
+ return (false, BindBlocker.FormTokenDoesNotExist);
898
+ }
899
+ address paletteOwner;
900
+ try IERC721(paletteCoreContract).ownerOf(paletteTokenId) returns (
901
+ address owner_
902
+ ) {
903
+ paletteOwner = owner_;
904
+ } catch {
905
+ return (false, BindBlocker.PaletteTokenDoesNotExist);
906
+ }
907
+ if (formOwner != paletteOwner) {
908
+ return (false, BindBlocker.OwnerMismatch);
909
+ }
910
+ return (true, BindBlocker.None);
911
+ }
912
+
913
+ /**
914
+ * @inheritdoc IFormPaletteBindingHooks
915
+ */
916
+ function isPaletteProject(
917
+ address coreContract,
918
+ uint256 projectId
919
+ ) external view returns (bool registered) {
920
+ return _isPaletteProject[coreContract][projectId];
921
+ }
922
+
923
+ /**
924
+ * @inheritdoc IFormPaletteBindingHooks
925
+ */
926
+ function paletteProjectCount() external view returns (uint256 count) {
927
+ return _paletteProjects.length;
928
+ }
929
+
930
+ /**
931
+ * @inheritdoc IFormPaletteBindingHooks
932
+ */
933
+ function paletteProjectAt(
934
+ uint256 index
935
+ ) external view returns (address coreContract, uint256 projectId) {
936
+ if (index >= _paletteProjects.length) {
937
+ return (address(0), 0);
938
+ }
939
+ PaletteProject memory project = _paletteProjects[index];
940
+ return (project.coreContract, project.projectId);
941
+ }
942
+
943
+ /**
944
+ * @inheritdoc IFormPaletteBindingHooks
945
+ */
946
+ function paletteCount(
947
+ address coreContract,
948
+ uint256 projectId
949
+ ) external view returns (uint256 count) {
950
+ return _palettes[coreContract][projectId].length();
951
+ }
952
+
953
+ /**
954
+ * @inheritdoc IFormPaletteBindingHooks
955
+ */
956
+ function paletteAt(
957
+ address coreContract,
958
+ uint256 projectId,
959
+ uint256 index
960
+ ) external view returns (string memory palette) {
961
+ return _palettes[coreContract][projectId].get(index);
962
+ }
963
+
964
+ /**
965
+ * @inheritdoc IFormPaletteBindingHooks
966
+ */
967
+ function paletteDataFor(
968
+ address coreContract,
969
+ uint256 paletteTokenId
970
+ ) external view returns (string memory palette) {
971
+ if (
972
+ !_isPaletteProject[coreContract][
973
+ ABHelpers.tokenIdToProjectId(paletteTokenId)
974
+ ]
975
+ ) {
976
+ return "";
977
+ }
978
+ return
979
+ _resolvePaletteData({
980
+ coreContract: coreContract,
981
+ paletteTokenId: paletteTokenId
982
+ });
983
+ }
984
+
985
+ /**
986
+ * @notice Indicates support for `ITransferHook` (required by v3.3 cores),
987
+ * `IPMPAugmentHook` and `IPMPConfigureHook` (required by the PMP before
988
+ * either hook may be configured).
989
+ */
990
+ function supportsInterface(
991
+ bytes4 interfaceId
992
+ )
993
+ public
994
+ view
995
+ virtual
996
+ override(
997
+ AbstractTransferHook,
998
+ AbstractPMPAugmentHook,
999
+ AbstractPMPConfigureHook,
1000
+ IERC165
1001
+ )
1002
+ returns (bool)
1003
+ {
1004
+ return
1005
+ interfaceId == type(IFormPaletteBindingHooks).interfaceId ||
1006
+ interfaceId == type(ITransferHook).interfaceId ||
1007
+ interfaceId == type(IPMPAugmentHook).interfaceId ||
1008
+ interfaceId == type(IPMPConfigureHook).interfaceId ||
1009
+ super.supportsInterface(interfaceId);
1010
+ }
1011
+
1012
+ // ---- internals ----
1013
+
1014
+ /**
1015
+ * @notice Apply a binding param value to canonical state.
1016
+ * @dev The strict state machine lives here. A write that would change an
1017
+ * existing pairing is rejected rather than applied, because the other token
1018
+ * involved would not be written and so would not re-render.
1019
+ * @param formTokenId Form token whose param was written.
1020
+ * @param newValue Written value; `UNBOUND_PARAM_VALUE` to unbind.
1021
+ */
1022
+ function _applyBindingParam(uint256 formTokenId, uint256 newValue) private {
1023
+ uint256 currentValue = _formToPalette[formTokenId];
1024
+
1025
+ if (newValue == UNBOUND_PARAM_VALUE) {
1026
+ // @dev idempotent: unbinding an unbound token is a no-op, which is
1027
+ // what makes the transfer hook's own write safe to replay
1028
+ if (currentValue == UNBOUND_PARAM_VALUE) {
1029
+ return;
1030
+ }
1031
+ _clearBinding({
1032
+ formTokenId: formTokenId,
1033
+ paramValue: currentValue,
1034
+ reason: UnbindReason.Configured
1035
+ });
1036
+ return;
1037
+ }
1038
+
1039
+ // @dev idempotent: re-writing the current pairing changes nothing
1040
+ if (currentValue == newValue) {
1041
+ return;
1042
+ }
1043
+ if (currentValue != UNBOUND_PARAM_VALUE) {
1044
+ (address boundCore, uint256 boundTokenId) = _paletteTokenOf({
1045
+ paramValue: currentValue
1046
+ });
1047
+ revert FormAlreadyBound({
1048
+ formTokenId: formTokenId,
1049
+ paletteCoreContract: boundCore,
1050
+ paletteTokenId: boundTokenId
1051
+ });
1052
+ }
1053
+ (
1054
+ address paletteCoreContract,
1055
+ uint256 paletteTokenId
1056
+ ) = _paletteTokenOf({paramValue: newValue});
1057
+ // @dev a value that does not unpack to a registered project fails here,
1058
+ // including a bare token ID mistyped into the field: it is far below
1059
+ // the core contract's bits, so it unpacks to the zero address
1060
+ if (
1061
+ !_isPaletteProject[paletteCoreContract][
1062
+ ABHelpers.tokenIdToProjectId(paletteTokenId)
1063
+ ]
1064
+ ) {
1065
+ revert UnknownBindingParamValue({bindingParamValue: newValue});
1066
+ }
1067
+ (bool paletteBound, uint256 boundFormTokenId) = _boundFormOf({
1068
+ paramValue: newValue
1069
+ });
1070
+ if (paletteBound) {
1071
+ revert PaletteAlreadyBound({
1072
+ paletteCoreContract: paletteCoreContract,
1073
+ paletteTokenId: paletteTokenId,
1074
+ formTokenId: boundFormTokenId
1075
+ });
1076
+ }
1077
+ // @dev `ownerOf` reverts for a token that does not exist, so this also
1078
+ // rejects binding to an unminted palette token
1079
+ address formOwner = IERC721(formCore).ownerOf(formTokenId);
1080
+ address paletteOwner = IERC721(paletteCoreContract).ownerOf(
1081
+ paletteTokenId
1082
+ );
1083
+ if (formOwner != paletteOwner) {
1084
+ revert OwnerMismatch({
1085
+ formOwner: formOwner,
1086
+ paletteOwner: paletteOwner
1087
+ });
1088
+ }
1089
+
1090
+ _formToPalette[formTokenId] = newValue;
1091
+ unchecked {
1092
+ // @dev cannot overflow: the `ownerOf` above established that
1093
+ // `formTokenId` is a minted Art Blocks token, so it is nowhere near
1094
+ // `type(uint256).max`
1095
+ _paletteToForm[newValue] = formTokenId + 1;
1096
+ }
1097
+ emit Bound({
1098
+ formTokenId: formTokenId,
1099
+ paletteCoreContract: paletteCoreContract,
1100
+ paletteTokenId: paletteTokenId,
1101
+ owner: formOwner
1102
+ });
1103
+ }
1104
+
1105
+ /**
1106
+ * @notice Clear both directions of a pairing.
1107
+ */
1108
+ function _clearBinding(
1109
+ uint256 formTokenId,
1110
+ uint256 paramValue,
1111
+ UnbindReason reason
1112
+ ) private {
1113
+ delete _formToPalette[formTokenId];
1114
+ delete _paletteToForm[paramValue];
1115
+ (
1116
+ address paletteCoreContract,
1117
+ uint256 paletteTokenId
1118
+ ) = _paletteTokenOf({paramValue: paramValue});
1119
+ emit Unbound({
1120
+ formTokenId: formTokenId,
1121
+ paletteCoreContract: paletteCoreContract,
1122
+ paletteTokenId: paletteTokenId,
1123
+ reason: reason
1124
+ });
1125
+ }
1126
+
1127
+ /**
1128
+ * @notice Write `UNBOUND_PARAM_VALUE` to a form token's binding param so
1129
+ * the off-chain pipeline re-renders it.
1130
+ * @dev Called only after canonical state is already cleared, so the
1131
+ * re-entrant `onTokenPMPConfigure` this triggers is a no-op. Failures are
1132
+ * swallowed: this runs inside a transfer, and a revert would make the token
1133
+ * non-transferable.
1134
+ */
1135
+ function _syncBindingParam(uint256 formTokenId) private {
1136
+ IPMPV0.PMPInput[] memory pmpInputs = new IPMPV0.PMPInput[](1);
1137
+ pmpInputs[0] = IPMPV0.PMPInput({
1138
+ key: PARAM_KEY_BOUND_PALETTE_REF,
1139
+ configuredParamType: IPMPV0.ParamType.Uint256Range,
1140
+ configuredValue: bytes32(UNBOUND_PARAM_VALUE),
1141
+ configuringArtistString: false,
1142
+ configuredValueString: ""
1143
+ });
1144
+ try
1145
+ pmp.configureTokenParams(formCore, formTokenId, pmpInputs)
1146
+ {} catch {
1147
+ emit BindingParamSyncFailed({formTokenId: formTokenId});
1148
+ }
1149
+ }
1150
+
1151
+ /**
1152
+ * @notice The binding param value naming a palette token, if its project is
1153
+ * registered.
1154
+ */
1155
+ function _bindingParamValue(
1156
+ address coreContract,
1157
+ uint256 paletteTokenId
1158
+ ) private view returns (bool registered, uint256 paramValue) {
1159
+ if (
1160
+ !_isPaletteProject[coreContract][
1161
+ ABHelpers.tokenIdToProjectId(paletteTokenId)
1162
+ ]
1163
+ ) {
1164
+ return (false, UNBOUND_PARAM_VALUE);
1165
+ }
1166
+ return (
1167
+ true,
1168
+ _encode({
1169
+ coreContract: coreContract,
1170
+ paletteTokenId: paletteTokenId
1171
+ })
1172
+ );
1173
+ }
1174
+
1175
+ /**
1176
+ * @notice The palette token a binding param value names.
1177
+ * @dev Pure unpacking. A value whose project is not registered still
1178
+ * decodes; callers check `_isPaletteProject` on the result.
1179
+ */
1180
+ function _paletteTokenOf(
1181
+ uint256 paramValue
1182
+ ) private pure returns (address coreContract, uint256 paletteTokenId) {
1183
+ return (
1184
+ address(uint160(paramValue >> _TOKEN_ID_BITS)),
1185
+ paramValue & _TOKEN_ID_MASK
1186
+ );
1187
+ }
1188
+
1189
+ /**
1190
+ * @notice Binding param value naming a palette token.
1191
+ * @dev The core contract in the high 160 bits, the token ID in the low 96.
1192
+ * Lossless because registration rejects a project ID whose tokens could not
1193
+ * fit, and never `0` because a registered core is never the zero address.
1194
+ */
1195
+ function _encode(
1196
+ address coreContract,
1197
+ uint256 paletteTokenId
1198
+ ) private pure returns (uint256) {
1199
+ return
1200
+ (uint256(uint160(coreContract)) << _TOKEN_ID_BITS) | paletteTokenId;
1201
+ }
1202
+
1203
+ /**
1204
+ * @notice Canonical pairing for a binding param value.
1205
+ */
1206
+ function _boundFormOf(
1207
+ uint256 paramValue
1208
+ ) private view returns (bool isBound, uint256 formTokenId) {
1209
+ uint256 stored = _paletteToForm[paramValue];
1210
+ if (stored == 0) {
1211
+ return (false, 0);
1212
+ }
1213
+ unchecked {
1214
+ return (true, stored - 1);
1215
+ }
1216
+ }
1217
+
1218
+ /**
1219
+ * @notice The palette entry a palette token resolves to.
1220
+ * @dev Caller must have established that the project is registered.
1221
+ */
1222
+ function _resolvePaletteData(
1223
+ address coreContract,
1224
+ uint256 paletteTokenId
1225
+ ) private view returns (string memory) {
1226
+ ImmutableStringArray.StringArray storage palettes = _palettes[
1227
+ coreContract
1228
+ ][ABHelpers.tokenIdToProjectId(paletteTokenId)];
1229
+ // @dev non-zero for any registered project: registration rejects an
1230
+ // empty list and the entries can never be replaced, so there is no
1231
+ // path to a registered project with nothing to select from
1232
+ uint256 paletteCount_ = palettes.length();
1233
+ bytes32 tokenHash = IGenArt721CoreContractV3_Base(coreContract)
1234
+ .tokenIdToHash(paletteTokenId);
1235
+ return palettes.get(_paletteIndex(tokenHash, paletteCount_));
1236
+ }
1237
+
1238
+ /**
1239
+ * @notice The four values a form token injects, resolved together.
1240
+ * @dev Every one is the empty string when the token is unbound, so an art
1241
+ * script has a single "no palette" case.
1242
+ */
1243
+ function _formInjectedValues(
1244
+ uint256 formTokenId
1245
+ )
1246
+ private
1247
+ view
1248
+ returns (
1249
+ string memory coreValue,
1250
+ string memory tokenIdValue,
1251
+ string memory hashValue,
1252
+ string memory paletteDataValue
1253
+ )
1254
+ {
1255
+ (bool isBound, uint256 paramValue) = _resolveBoundPalette({
1256
+ formTokenId: formTokenId
1257
+ });
1258
+ if (!isBound) {
1259
+ return ("", "", "", "");
1260
+ }
1261
+ (address coreContract, uint256 paletteTokenId) = _paletteTokenOf({
1262
+ paramValue: paramValue
1263
+ });
1264
+ coreValue = uint256(uint160(coreContract)).toHexString(20);
1265
+ tokenIdValue = paletteTokenId.toString();
1266
+ hashValue = uint256(
1267
+ IGenArt721CoreContractV3_Base(coreContract).tokenIdToHash(
1268
+ paletteTokenId
1269
+ )
1270
+ ).toHexString(32);
1271
+ paletteDataValue = _resolvePaletteData({
1272
+ coreContract: coreContract,
1273
+ paletteTokenId: paletteTokenId
1274
+ });
1275
+ }
1276
+
1277
+ /**
1278
+ * @notice The two values a palette token injects, resolved together.
1279
+ * @dev `paletteDataValue` is never empty for a registered project: a palette
1280
+ * token carries its own entry whether or not anything is bound to it. Only
1281
+ * the pairing is subject to the ownership backstop.
1282
+ */
1283
+ function _paletteInjectedValues(
1284
+ address coreContract,
1285
+ uint256 paletteTokenId
1286
+ )
1287
+ private
1288
+ view
1289
+ returns (string memory boundFormValue, string memory paletteDataValue)
1290
+ {
1291
+ (bool isBound, uint256 formTokenId) = _resolveBoundForm({
1292
+ paramValue: _encode({
1293
+ coreContract: coreContract,
1294
+ paletteTokenId: paletteTokenId
1295
+ })
1296
+ });
1297
+ boundFormValue = isBound ? formTokenId.toString() : "";
1298
+ paletteDataValue = _resolvePaletteData({
1299
+ coreContract: coreContract,
1300
+ paletteTokenId: paletteTokenId
1301
+ });
1302
+ }
1303
+
1304
+ /**
1305
+ * @notice Which entry of a `paletteCount_`-long list a hash selects.
1306
+ * @dev This contract is the single definition of that mapping — both the
1307
+ * form and the palette projects read the injected result rather than
1308
+ * deriving it — so the rule is chosen to be trivially auditable rather than
1309
+ * to match any particular script. Modulo bias across a 256-bit hash and a
1310
+ * list of realistic length is not measurable. Weighted rarity is expressed
1311
+ * by repeating an entry in the registered list.
1312
+ */
1313
+ function _paletteIndex(
1314
+ bytes32 tokenHash,
1315
+ uint256 paletteCount_
1316
+ ) private pure returns (uint256) {
1317
+ return uint256(tokenHash) % paletteCount_;
1318
+ }
1319
+
1320
+ /**
1321
+ * @notice Canonical pairing for a form token, reported only while both
1322
+ * tokens still share an owner.
1323
+ * @dev See the read-time ownership backstop note in the contract natspec.
1324
+ */
1325
+ function _resolveBoundPalette(
1326
+ uint256 formTokenId
1327
+ ) private view returns (bool isBound, uint256 paramValue) {
1328
+ paramValue = _formToPalette[formTokenId];
1329
+ if (paramValue == UNBOUND_PARAM_VALUE) {
1330
+ return (false, UNBOUND_PARAM_VALUE);
1331
+ }
1332
+ if (!_sharesOwner({formTokenId: formTokenId, paramValue: paramValue})) {
1333
+ return (false, UNBOUND_PARAM_VALUE);
1334
+ }
1335
+ isBound = true;
1336
+ }
1337
+
1338
+ /**
1339
+ * @notice Canonical pairing for a palette token, reported only while both
1340
+ * tokens still share an owner.
1341
+ */
1342
+ function _resolveBoundForm(
1343
+ uint256 paramValue
1344
+ ) private view returns (bool isBound, uint256 formTokenId) {
1345
+ (isBound, formTokenId) = _boundFormOf({paramValue: paramValue});
1346
+ if (!isBound) {
1347
+ return (false, 0);
1348
+ }
1349
+ if (!_sharesOwner({formTokenId: formTokenId, paramValue: paramValue})) {
1350
+ return (false, 0);
1351
+ }
1352
+ }
1353
+
1354
+ /// @notice Whether a form token and the palette token a value names are
1355
+ /// still held by one wallet.
1356
+ function _sharesOwner(
1357
+ uint256 formTokenId,
1358
+ uint256 paramValue
1359
+ ) private view returns (bool) {
1360
+ (
1361
+ address paletteCoreContract,
1362
+ uint256 paletteTokenId
1363
+ ) = _paletteTokenOf({paramValue: paramValue});
1364
+ return
1365
+ IERC721(formCore).ownerOf(formTokenId) ==
1366
+ IERC721(paletteCoreContract).ownerOf(paletteTokenId);
1367
+ }
1368
+
1369
+ /**
1370
+ * @notice Revert unless `coreContract` has this hook configured as the
1371
+ * transfer hook for `projectId`.
1372
+ * @dev This is the `ITransferHook` requirement that an implementation
1373
+ * verify which cores it serves. A contract impersonating a core could
1374
+ * answer dishonestly, but the immutable form project and the registry
1375
+ * checked in `_onTokenTransfer` confine it to doing nothing.
1376
+ */
1377
+ function _onlyConfiguredForProject(
1378
+ address coreContract,
1379
+ uint256 projectId
1380
+ ) private view {
1381
+ (address configuredHook, ) = IGenArt721CoreContractV3_Engine(
1382
+ coreContract
1383
+ ).projectTransferHookConfig(projectId);
1384
+ if (configuredHook != address(this)) {
1385
+ revert HookNotConfiguredForProject({
1386
+ coreContract: coreContract,
1387
+ projectId: projectId,
1388
+ configuredHook: configuredHook
1389
+ });
1390
+ }
1391
+ }
1392
+ }