@artblocks/contracts 1.5.0 → 1.7.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 (53) hide show
  1. package/artifacts/contracts/DependencyRegistryV0.sol/DependencyRegistryV0.json +61 -148
  2. package/artifacts/contracts/generator/GenArt721GeneratorV0.sol/GenArt721GeneratorV0.json +15 -2
  3. package/artifacts/contracts/generator/InPlaceDocument.sol/InPlaceDocument.json +10 -0
  4. package/artifacts/contracts/interfaces/v0.8.x/IAbxfsFileDataReader.sol/IAbxfsFileDataReader.json +109 -0
  5. package/artifacts/contracts/interfaces/v0.8.x/IAbxfsFileStore.sol/IAbxfsFileStore.json +86 -0
  6. package/artifacts/contracts/interfaces/v0.8.x/IDependencyRegistryV0.sol/IDependencyRegistryV0.json +41 -27
  7. package/artifacts/contracts/interfaces/v0.8.x/IFormPaletteBindingHooks.sol/IFormPaletteBindingHooks.json +723 -0
  8. package/artifacts/contracts/interfaces/v0.8.x/IPMPProjectViewsV0.sol/IPMPProjectViewsV0.json +126 -0
  9. package/artifacts/contracts/interfaces/v0.8.x/ISharedMinterRequiredPMPV0.sol/ISharedMinterRequiredPMPV0.json +36 -0
  10. package/artifacts/contracts/libs/v0.8.x/AbxfsCanonical.sol/AbxfsCanonical.json +10 -0
  11. package/artifacts/contracts/libs/v0.8.x/DependencyRegistryStorageLib.sol/DependencyRegistryStorageLib.json +2 -2
  12. package/artifacts/contracts/libs/v0.8.x/minter-libs/RequiredPMPLib.sol/RequiredPMPLib.json +10 -0
  13. package/artifacts/contracts/minter-suite/Minters/MinterSetPricePMPV0.sol/MinterSetPricePMPV0.json +613 -0
  14. package/artifacts/contracts/mock/CallProbeMock.sol/CallProbeMock.json +45 -0
  15. package/artifacts/contracts/mock/GasProbeMock.sol/GasProbeMock.json +45 -0
  16. package/artifacts/contracts/mock/GenArt721GeneratorV0ScriptyReferenceMock.sol/GenArt721GeneratorV0ScriptyReferenceMock.json +346 -0
  17. package/artifacts/contracts/mock/GenArt721GeneratorV0ScriptyReferenceMock.sol/ILegacyGenArt721CoreV2_PBAB_Flex.json +47 -0
  18. package/artifacts/contracts/mock/InPlaceDocumentHarnessMock.sol/InPlaceDocumentHarnessMock.json +161 -0
  19. package/artifacts/contracts/mock/MockAbxfsFileDataReader.sol/IMockFileStore.json +91 -0
  20. package/artifacts/contracts/mock/MockAbxfsFileDataReader.sol/MockAbxfsFileDataReader.json +183 -0
  21. package/artifacts/contracts/mock/MockAbxfsFileStore.sol/MockAbxfsFileStore.json +204 -0
  22. package/artifacts/contracts/mock/MockPMPMinterReentrantConfigureHook.sol/IMinterPMPPurchase.json +91 -0
  23. package/artifacts/contracts/mock/MockPMPMinterReentrantConfigureHook.sol/MockPMPMinterReentrantConfigureHook.json +180 -0
  24. package/artifacts/contracts/mock/MockPMPReentrantConfigureHook.sol/MockPMPReentrantConfigureHook.json +158 -0
  25. package/artifacts/contracts/mock/RawResponseMock.sol/RawResponseMock.json +61 -0
  26. package/artifacts/contracts/mock/ReentrancyPMPMockShared.sol/IMinterPurchaseWithPMPs.json +67 -0
  27. package/artifacts/contracts/mock/ReentrancyPMPMockShared.sol/ReentrancyPMPMockShared.json +154 -0
  28. package/artifacts/contracts/web3call/combined-hooks/FormPaletteBindingHooks.sol/FormPaletteBindingHooks.json +919 -0
  29. package/contracts/DependencyRegistryV0.sol +136 -226
  30. package/contracts/generator/GenArt721GeneratorV0.sol +541 -280
  31. package/contracts/generator/InPlaceDocument.sol +306 -0
  32. package/contracts/interfaces/v0.8.x/IAbxfsFileDataReader.sol +67 -0
  33. package/contracts/interfaces/v0.8.x/IAbxfsFileStore.sol +40 -0
  34. package/contracts/interfaces/v0.8.x/IDependencyRegistryV0.sol +33 -22
  35. package/contracts/interfaces/v0.8.x/IFormPaletteBindingHooks.sol +339 -0
  36. package/contracts/interfaces/v0.8.x/IPMPProjectViewsV0.sol +59 -0
  37. package/contracts/interfaces/v0.8.x/ISharedMinterRequiredPMPV0.sol +27 -0
  38. package/contracts/libs/v0.8.x/AbxfsCanonical.sol +23 -0
  39. package/contracts/libs/v0.8.x/DependencyRegistryStorageLib.sol +10 -4
  40. package/contracts/libs/v0.8.x/minter-libs/RequiredPMPLib.sol +336 -0
  41. package/contracts/minter-suite/Minters/MinterSetPricePMPV0.sol +664 -0
  42. package/contracts/mock/CallProbeMock.sol +20 -0
  43. package/contracts/mock/GasProbeMock.sol +21 -0
  44. package/contracts/mock/GenArt721GeneratorV0ScriptyReferenceMock.sol +1316 -0
  45. package/contracts/mock/InPlaceDocumentHarnessMock.sol +189 -0
  46. package/contracts/mock/MockAbxfsFileDataReader.sol +134 -0
  47. package/contracts/mock/MockAbxfsFileStore.sol +125 -0
  48. package/contracts/mock/MockPMPMinterReentrantConfigureHook.sol +85 -0
  49. package/contracts/mock/MockPMPReentrantConfigureHook.sol +59 -0
  50. package/contracts/mock/RawResponseMock.sol +58 -0
  51. package/contracts/mock/ReentrancyPMPMockShared.sol +81 -0
  52. package/contracts/web3call/combined-hooks/FormPaletteBindingHooks.sol +1392 -0
  53. package/package.json +1 -1
@@ -9,18 +9,21 @@ import "../interfaces/v0.8.x/IGenArt721CoreTokenHashProviderV1.sol";
9
9
  import "../interfaces/v0.8.x/IGenArt721GeneratorV0.sol";
10
10
  import {IGenArt721CoreContractV3_Engine_Flex} from "../interfaces/v0.8.x/IGenArt721CoreContractV3_Engine_Flex.sol";
11
11
  import {IUniversalBytecodeStorageReader} from "../interfaces/v0.8.x/IUniversalBytecodeStorageReader.sol";
12
+ import {IBytecodeStorageReader_Base} from "../interfaces/v0.8.x/IBytecodeStorageReader_Base.sol";
13
+ import {IAbxfsFileDataReader} from "../interfaces/v0.8.x/IAbxfsFileDataReader.sol";
14
+ import {AbxfsCanonical} from "../libs/v0.8.x/AbxfsCanonical.sol";
12
15
  import {IWeb3Call} from "../interfaces/v0.8.x/IWeb3Call.sol";
13
16
 
14
17
  import "../libs/v0.8.x/Bytes32Strings.sol";
15
18
  import {JsonStatic} from "../libs/v0.8.x/JsonStatic.sol";
16
19
  import {ABHelpers} from "../libs/v0.8.x/ABHelpers.sol";
17
- import {AddressChunks} from "./AddressChunks.sol";
20
+ import {InPlaceDocument} from "./InPlaceDocument.sol";
18
21
 
19
22
  import {Base64} from "@openzeppelin-5.0/contracts/utils/Base64.sol";
20
23
  import "@openzeppelin-4.7/contracts/utils/Strings.sol";
21
24
  import "@openzeppelin-4.8/contracts-upgradeable/proxy/utils/Initializable.sol";
22
25
 
23
- import {IScriptyBuilderV2, HTMLRequest, HTMLTagType, HTMLTag} from "scripty.sol/contracts/scripty/interfaces/IScriptyBuilderV2.sol";
26
+ import {IScriptyBuilderV2} from "scripty.sol/contracts/scripty/interfaces/IScriptyBuilderV2.sol";
24
27
 
25
28
  // @dev legacy interface for V2 flex contracts - used to get external legacy asset dependencies
26
29
  interface ILegacyGenArt721CoreV2_PBAB_Flex {
@@ -44,8 +47,15 @@ interface ILegacyGenArt721CoreV2_PBAB_Flex {
44
47
  * @title GenArt721GeneratorV0
45
48
  * @author Art Blocks Inc.
46
49
  * @notice This contract is used to generate the HTML for Art Blocks tokens
47
- * by combining the dependency script, project script, token data. It utilizes
48
- * the ScriptyBuilder contract to generate the HTML.
50
+ * by combining the dependency script, project script, token data.
51
+ * @dev A token's document is `<html><head>[head tags]</head><body>[body tags]</body></html>`,
52
+ * the format ScriptyBuilderV2 builds, and this contract assembled it through ScriptyBuilderV2
53
+ * until it began assembling it itself. It gathers the document's parts first, then writes them in
54
+ * order into one buffer at the end of memory, copying the large ones (ABX FS dependency files, the
55
+ * gunzip script, the project script) straight from return data, and returns the buffer in place,
56
+ * base64-encoding it in place for the data URI (see InPlaceDocument). A view's memory costs
57
+ * quadratically in its size, and each copy of an inlined dependency multiplied it. `scriptyBuilder`
58
+ * is no longer read; it is kept, with its setter and event, for storage layout and ABI.
49
59
  */
50
60
  contract GenArt721GeneratorV0 is Initializable, IGenArt721GeneratorV0 {
51
61
  using Bytes32Strings for bytes32;
@@ -65,6 +75,68 @@ contract GenArt721GeneratorV0 is Initializable, IGenArt721GeneratorV0 {
65
75
  0x6a73406e61000000000000000000000000000000000000000000000000000000; // "js@na"
66
76
  bytes32 constant SVG_AT_NA_BYTES32 =
67
77
  0x737667406e610000000000000000000000000000000000000000000000000000; // "svg@na"
78
+ // @dev The ABX FS FileDataReader, through which dependency scripts are read from ABX FS (the
79
+ // same address on every chain ABX FS supports; see AbxfsCanonical).
80
+ IAbxfsFileDataReader public constant ABXFS_FILE_DATA_READER =
81
+ IAbxfsFileDataReader(AbxfsCanonical.FILE_DATA_READER);
82
+
83
+ // @dev The fixed text of a token's document.
84
+ bytes constant HTML_HEAD_OPEN = "<html><head>";
85
+ bytes constant STYLE_TAG =
86
+ "<style>html{height:100%}body{min-height:100%;margin:0;padding:0}canvas{padding:0;margin:auto;display:block;position:absolute;top:0;bottom:0;left:0;right:0}</style>";
87
+ bytes constant TOKEN_DATA_SCRIPT_OPEN =
88
+ "<script>let tokenData = JSON.parse(`";
89
+ // @dev decode any base64 encoded flex data in the browser while parsing the json
90
+ bytes constant TOKEN_DATA_SCRIPT_CLOSE =
91
+ '`, (key, value) => key === "data" && value !== null ? value.startsWith("#web3call#") ? Object.entries(JSON.parse(atob(value.slice(10)))).reduce((acc, [k, v]) => ((acc[atob(k)] = atob(v)), acc), {}) : atob(value) : value);</script>';
92
+ bytes constant HTML_HEAD_CLOSE_BODY_OPEN = "</head><body>";
93
+ bytes constant HTML_BODY_CLOSE = "</body></html>";
94
+ bytes constant SCRIPT_TAG_CLOSE = "</script>";
95
+ // @dev <script type="text/javascript+gzip" src="data:text/javascript;base64,[script]"></script>
96
+ bytes constant GZIP_DATA_URI_SCRIPT_TAG_OPEN =
97
+ '<script type="text/javascript+gzip" src="data:text/javascript;base64,';
98
+ // @dev <script src="data:text/javascript;base64,[script]"></script>
99
+ bytes constant DATA_URI_SCRIPT_TAG_OPEN =
100
+ '<script src="data:text/javascript;base64,';
101
+ bytes constant DATA_URI_SCRIPT_TAG_CLOSE = '"></script>';
102
+ bytes32 constant HTML_BASE64_DATA_URI_PREFIX = "data:text/html;base64,";
103
+ uint256 constant HTML_BASE64_DATA_URI_PREFIX_LENGTH = 22;
104
+
105
+ // @dev Kinds of DocumentPart.
106
+ uint256 constant PART_LITERAL = 0;
107
+ uint256 constant PART_ABXFS_FILE = 1;
108
+ uint256 constant PART_GUNZIP_SCRIPT = 2;
109
+ uint256 constant PART_PROJECT_SCRIPT = 3;
110
+
111
+ /**
112
+ * @dev A part of a token's document: `literal`, or content read into the document as it is
113
+ * written: the ABX FS file `abxfsFileCid`, base64 encoded (PART_ABXFS_FILE), the gunzip
114
+ * script (PART_GUNZIP_SCRIPT), or the project script (PART_PROJECT_SCRIPT).
115
+ */
116
+ struct DocumentPart {
117
+ uint256 kind;
118
+ bytes32 abxfsFileCid;
119
+ bytes literal;
120
+ }
121
+
122
+ /**
123
+ * @dev Where a project's script is read from, found before any of it is read: the bytecode
124
+ * addresses of its chunks (V3 and later cores), or the number of its chunks (older cores, read
125
+ * with projectScriptByIndex). Neither, for an empty script.
126
+ */
127
+ struct ProjectScriptSource {
128
+ address coreContract;
129
+ uint256 projectId;
130
+ address[] bytecodeChunks;
131
+ uint256 legacyChunkCount;
132
+ }
133
+
134
+ /// @dev A token's document: `parts[0 .. partCount)` in order.
135
+ struct TokenDocument {
136
+ DocumentPart[] parts;
137
+ uint256 partCount;
138
+ ProjectScriptSource projectScript;
139
+ }
68
140
 
69
141
  function _onlySupportedCoreContract(address coreContract) internal view {
70
142
  require(
@@ -88,8 +160,8 @@ contract GenArt721GeneratorV0 is Initializable, IGenArt721GeneratorV0 {
88
160
  * @notice Initializer for the GenArt721GeneratorV0 contract.
89
161
  * @param _dependencyRegistry The address of the DependencyRegistry
90
162
  * contract to be used for retrieving dependency scripts.
91
- * @param _scriptyBuilder The address of the ScriptyBuilderV2 contract
92
- * to be used for generating the HTML for tokens.
163
+ * @param _scriptyBuilder The address of a ScriptyBuilderV2 contract. Recorded only: token
164
+ * HTML is assembled by this contract.
93
165
  * @param _gunzipScriptBytecodeAddress The address of the gunzip script bytecode
94
166
  * storage contract used to gunzip the dependency scripts in the browser.
95
167
  * @param _universalBytecodeStorageReader The address of the universal bytecode storage reader contract.
@@ -132,9 +204,10 @@ contract GenArt721GeneratorV0 is Initializable, IGenArt721GeneratorV0 {
132
204
 
133
205
  /**
134
206
  * @notice Set the ScriptyBuilder contract address.
135
- * @param _scriptyBuilder The address of the ScriptyBuilderV2 contract
136
- * to be used for generating the HTML for tokens.
137
- * @dev This function is gated to only the DependencyRegistry AdminACL.
207
+ * @param _scriptyBuilder The address of a ScriptyBuilderV2 contract.
208
+ * @dev This function is gated to only the DependencyRegistry AdminACL. The address is
209
+ * recorded only: token HTML is assembled by this contract, which no longer calls it. Kept for
210
+ * the storage layout and ABI.
138
211
  */
139
212
  function updateScriptyBuilder(address _scriptyBuilder) external {
140
213
  _onlyDependencyRegistryAdminACL(this.updateScriptyBuilder.selector);
@@ -181,22 +254,31 @@ contract GenArt721GeneratorV0 is Initializable, IGenArt721GeneratorV0 {
181
254
  }
182
255
 
183
256
  /**
184
- * @notice Get the dependency script for a given dependency name and version string.
257
+ * @notice Get the dependency script for a given dependency name and version string, as the
258
+ * generator inlines it.
185
259
  * @param dependencyNameAndVersion The name and version of the dependency
186
260
  * to retrieve the script for.
187
- * @return The dependency script stiched together from all of the script chunks as a string.
188
- * @dev This function will revert if the dependency name and version is not
189
- * supported by the DependencyRegistry or if the script storage version is
190
- * not supported.
261
+ * @return The dependency's ABX FS file (its gzip bytes), base64 encoded, or empty if the
262
+ * generator does not inline the dependency (no ABX FS file, or an ES module dependency).
263
+ * @dev Reverts if the dependency's ABX FS file is not a gzip file on this chain's ABX FS.
191
264
  */
192
265
  function getDependencyScript(
193
266
  string memory dependencyNameAndVersion
194
267
  ) external view returns (string memory) {
195
- bytes memory dependencyScript = _getDependencyScriptBytes(
196
- dependencyNameAndVersion.stringToBytes32()
268
+ bytes32 abxfsFileCid = _getInlinedAbxfsFileCid(
269
+ dependencyRegistry.getDependencyDetailsV2(
270
+ dependencyNameAndVersion.stringToBytes32()
271
+ )
197
272
  );
198
-
199
- return string(dependencyScript);
273
+ if (abxfsFileCid == bytes32(0)) {
274
+ return "";
275
+ }
276
+ (uint256 doc, uint256 end) = InPlaceDocument.open();
277
+ return
278
+ InPlaceDocument.returnDocument(
279
+ doc,
280
+ _appendAbxfsFile(end, abxfsFileCid)
281
+ );
200
282
  }
201
283
 
202
284
  /**
@@ -214,12 +296,16 @@ contract GenArt721GeneratorV0 is Initializable, IGenArt721GeneratorV0 {
214
296
  address coreContract,
215
297
  uint256 projectId
216
298
  ) external view returns (string memory) {
217
- bytes memory projectScript = _getProjectScriptBytes(
299
+ ProjectScriptSource memory source = _getProjectScriptSource(
218
300
  coreContract,
219
301
  projectId
220
302
  );
221
-
222
- return string(projectScript);
303
+ (uint256 doc, uint256 end) = InPlaceDocument.open();
304
+ return
305
+ InPlaceDocument.returnDocument(
306
+ doc,
307
+ _appendProjectScript(end, source)
308
+ );
223
309
  }
224
310
 
225
311
  /**
@@ -232,14 +318,16 @@ contract GenArt721GeneratorV0 is Initializable, IGenArt721GeneratorV0 {
232
318
  address coreContract,
233
319
  uint256 tokenId
234
320
  ) external view returns (string memory) {
235
- HTMLRequest memory htmlRequest = _getTokenHtmlRequest(
236
- coreContract,
237
- tokenId
321
+ (uint256 doc, uint256 end) = _writeTokenDocument(
322
+ _getTokenDocument(coreContract, tokenId)
238
323
  );
239
- string memory base64EncodedHTMLDataURI = scriptyBuilder
240
- .getEncodedHTMLString(htmlRequest);
241
-
242
- return base64EncodedHTMLDataURI;
324
+ return
325
+ InPlaceDocument.returnBase64DataUri(
326
+ doc,
327
+ end,
328
+ HTML_BASE64_DATA_URI_PREFIX,
329
+ HTML_BASE64_DATA_URI_PREFIX_LENGTH
330
+ );
243
331
  }
244
332
 
245
333
  /**
@@ -252,13 +340,10 @@ contract GenArt721GeneratorV0 is Initializable, IGenArt721GeneratorV0 {
252
340
  address coreContract,
253
341
  uint256 tokenId
254
342
  ) external view returns (string memory) {
255
- HTMLRequest memory htmlRequest = _getTokenHtmlRequest(
256
- coreContract,
257
- tokenId
343
+ (uint256 doc, uint256 end) = _writeTokenDocument(
344
+ _getTokenDocument(coreContract, tokenId)
258
345
  );
259
- string memory html = scriptyBuilder.getHTMLString(htmlRequest);
260
-
261
- return html;
346
+ return InPlaceDocument.returnDocument(doc, end);
262
347
  }
263
348
 
264
349
  /**
@@ -343,60 +428,100 @@ contract GenArt721GeneratorV0 is Initializable, IGenArt721GeneratorV0 {
343
428
  }
344
429
 
345
430
  /**
346
- * @notice Get the dependency script for a given dependency name and version.
347
- * @param dependencyNameAndVersion The name and version of the dependency
348
- * to retrieve the script for.
349
- * @return The dependency script stiched together from all of the script chunks.
350
- * @dev This function will revert if the dependency name and version is not
351
- * supported by the DependencyRegistry or if the script storage version is
352
- * not supported.
431
+ * @notice Append a dependency's ABX FS file, base64 encoded (the payload of the gzip data URI
432
+ * the generator inlines), to the document ending at `end`, copied straight from
433
+ * FileDataReader's return data.
434
+ * @param end The document's end (see InPlaceDocument).
435
+ * @param abxfsFileCid CID of the dependency's gzip-codec ABX FS file.
436
+ * @return The document's new end.
437
+ * @dev Reverts if `abxfsFileCid` is not a gzip-codec file on this chain's ABX FS (the
438
+ * registry checks both when a CID is set; ABX FS content is permanent), or with the
439
+ * FileDataReader's own error if the read fails.
440
+ * @dev FileDataReader returns canonical `abi.encode(mimeType, codec, outputHash, base64)`: a
441
+ * four-word head whose fourth word is the offset of `base64`, which is length-prefixed. The
442
+ * offset and length are bounds-checked against the returned size before anything is copied.
443
+ * The call data is written at `end`, where the file's base64 then goes.
353
444
  */
354
- function _getDependencyScriptBytes(
355
- bytes32 dependencyNameAndVersion
356
- ) internal view returns (bytes memory) {
357
- uint256 scriptCount = dependencyRegistry.getDependencyScriptCount(
358
- dependencyNameAndVersion
359
- );
360
-
361
- if (scriptCount == 0) {
362
- return "";
363
- }
364
-
365
- address[] memory scriptBytecodeAddresses = new address[](scriptCount);
366
-
367
- for (uint256 i = 0; i < scriptCount; i++) {
368
- scriptBytecodeAddresses[i] = dependencyRegistry
369
- .getDependencyScriptBytecodeAddress(
370
- dependencyNameAndVersion,
371
- i
372
- );
445
+ function _appendAbxfsFile(
446
+ uint256 end,
447
+ bytes32 abxfsFileCid
448
+ ) internal view returns (uint256) {
449
+ address reader = address(ABXFS_FILE_DATA_READER);
450
+ bytes4 selector = IAbxfsFileDataReader.readFileDataBase64.selector;
451
+ bytes32 gzipCodec = AbxfsCanonical.GZIP_CODEC;
452
+ bytes32 codec;
453
+ bool wellFormed;
454
+ assembly ("memory-safe") {
455
+ // readFileDataBase64(abxfsFileCid, type(uint256).max, type(uint256).max)
456
+ mstore(end, selector)
457
+ mstore(add(end, 0x04), abxfsFileCid)
458
+ mstore(add(end, 0x24), not(0))
459
+ mstore(add(end, 0x44), not(0))
460
+ if iszero(staticcall(gas(), reader, end, 0x64, 0, 0)) {
461
+ returndatacopy(end, 0, returndatasize())
462
+ revert(end, returndatasize())
463
+ }
464
+ let size := returndatasize()
465
+ // head: [mimeType offset, codec, outputHash, base64 offset]
466
+ if gt(size, 0x7f) {
467
+ returndatacopy(0, 0x20, 0x20)
468
+ codec := mload(0)
469
+ returndatacopy(0, 0x60, 0x20)
470
+ let offset := mload(0)
471
+ if lt(offset, sub(size, 0x1f)) {
472
+ returndatacopy(0, offset, 0x20)
473
+ let length := mload(0)
474
+ if iszero(gt(length, sub(sub(size, offset), 0x20))) {
475
+ wellFormed := 1
476
+ if eq(codec, gzipCodec) {
477
+ returndatacopy(end, add(offset, 0x20), length)
478
+ end := add(end, length)
479
+ }
480
+ }
481
+ }
482
+ }
373
483
  }
484
+ require(wellFormed, "ABX FS read malformed");
485
+ require(codec == gzipCodec, "ABX FS file not gzip");
486
+ InPlaceDocument.claim(end);
487
+ return end;
488
+ }
374
489
 
375
- // @dev We concatenate the script chunks together with assembly
376
- // in AddressChunks for gas efficiency.
490
+ /**
491
+ * @notice Get the ABX FS file CID the generator inlines a dependency's script from, or zero.
492
+ * @dev An ES module dependency is never inlined: it is reached through an import map
493
+ * pointing at its preferred CDN, and a gzipped module cannot be loaded from a data URI.
494
+ * @param dependencyDetails The dependency's details from the dependency registry.
495
+ */
496
+ function _getInlinedAbxfsFileCid(
497
+ IDependencyRegistryV0.DependencyDetails memory dependencyDetails
498
+ ) internal pure returns (bytes32) {
377
499
  return
378
- AddressChunks.mergeChunks(
379
- scriptBytecodeAddresses,
380
- address(universalBytecodeStorageReader)
381
- );
500
+ dependencyDetails.loadAsModule
501
+ ? bytes32(0)
502
+ : dependencyDetails.abxfsFileCid;
382
503
  }
383
504
 
384
505
  /**
385
- * @notice Get the project script for a given core contract address and
386
- * project ID.
506
+ * @notice Find where a project's script is read from, for a given core contract address and
507
+ * project ID, without reading it.
387
508
  * @param coreContract The address of the core contract to retrieve
388
509
  * the project script from.
389
510
  * @param projectId The ID of the project to retrieve the script for.
390
- * @return The project script stiched together from all of the script chunks.
511
+ * @return source The script's chunks: their bytecode addresses on V3 and later core
512
+ * contracts, their number on older ones.
391
513
  * @dev This function will revert if the core contract address is not
392
514
  * supported by the DependencyRegistry or if the contract at the address
393
515
  * does not implement the IGenArt721CoreProjectScriptV0 or IGenArt721CoreProjectScriptV1.
516
+ * The chunks are read by `_appendProjectScript`.
394
517
  */
395
- function _getProjectScriptBytes(
518
+ function _getProjectScriptSource(
396
519
  address coreContract,
397
520
  uint256 projectId
398
- ) internal view returns (bytes memory) {
521
+ ) internal view returns (ProjectScriptSource memory source) {
399
522
  _onlySupportedCoreContract(coreContract);
523
+ source.coreContract = coreContract;
524
+ source.projectId = projectId;
400
525
 
401
526
  // @dev Attempt to get project script info from V3 and up core contracts first.
402
527
  try
@@ -405,26 +530,18 @@ contract GenArt721GeneratorV0 is Initializable, IGenArt721GeneratorV0 {
405
530
  )
406
531
  returns (string memory, string memory, uint256 scriptCount) {
407
532
  if (scriptCount == 0) {
408
- return "";
533
+ return source;
409
534
  }
410
535
 
411
- address[] memory scriptBytecodeAddresses = new address[](
412
- scriptCount
413
- );
536
+ source.bytecodeChunks = new address[](scriptCount);
414
537
 
415
538
  for (uint256 i = 0; i < scriptCount; i++) {
416
- scriptBytecodeAddresses[i] = IGenArt721CoreProjectScriptV1(
539
+ source.bytecodeChunks[i] = IGenArt721CoreProjectScriptV1(
417
540
  coreContract
418
541
  ).projectScriptBytecodeAddressByIndex(projectId, i);
419
542
  }
420
543
 
421
- // @dev We concatenate the script chunks together with assembly
422
- // in AddressChunks for gas efficiency.
423
- return
424
- AddressChunks.mergeChunks(
425
- scriptBytecodeAddresses,
426
- address(universalBytecodeStorageReader)
427
- );
544
+ return source;
428
545
  } catch {
429
546
  // Noop try again for older contracts.
430
547
  }
@@ -436,22 +553,132 @@ contract GenArt721GeneratorV0 is Initializable, IGenArt721GeneratorV0 {
436
553
  projectId
437
554
  )
438
555
  returns (string memory, uint256 scriptCount) {
439
- if (scriptCount == 0) {
440
- return "";
556
+ source.legacyChunkCount = scriptCount;
557
+ return source;
558
+ } catch {
559
+ revert("Unable to retrieve project script info");
560
+ }
561
+ }
562
+
563
+ /**
564
+ * @notice Append a project's script, stitched together from all of its chunks, to the
565
+ * document ending at `end`, each chunk copied straight from return data.
566
+ * @param end The document's end (see InPlaceDocument).
567
+ * @param source The script's chunks, from `_getProjectScriptSource`.
568
+ * @return The document's new end.
569
+ * @dev A V3 core's chunk is read through the universal bytecode storage reader as
570
+ * AddressChunks reads it: the chunk's length from the return data's second word, its bytes
571
+ * from the third, and no revert data if the call fails. An older core's chunks are read with
572
+ * projectScriptByIndex, as a high-level call reads them (see `_appendReturnedString`), and
573
+ * joined in order, which `string.concat` did with a copy of the whole script per chunk.
574
+ */
575
+ function _appendProjectScript(
576
+ uint256 end,
577
+ ProjectScriptSource memory source
578
+ ) internal view returns (uint256) {
579
+ address reader = address(universalBytecodeStorageReader);
580
+ bytes4 readSelector = IBytecodeStorageReader_Base
581
+ .readFromBytecode
582
+ .selector;
583
+ address[] memory bytecodeChunks = source.bytecodeChunks;
584
+ for (uint256 i = 0; i < bytecodeChunks.length; i++) {
585
+ address chunk = bytecodeChunks[i];
586
+ assembly ("memory-safe") {
587
+ // readFromBytecode(chunk), written at the document's end
588
+ mstore(end, readSelector)
589
+ mstore(add(end, 0x04), chunk)
590
+ if iszero(staticcall(gas(), reader, end, 0x24, 0, 0)) {
591
+ revert(0, 0)
592
+ }
593
+ // the string's length is at 0x20 and its bytes start at 0x40 (ABI spec)
594
+ returndatacopy(0, 0x20, 0x20)
595
+ let length := mload(0)
596
+ returndatacopy(end, 0x40, length)
597
+ end := add(end, length)
441
598
  }
599
+ InPlaceDocument.claim(end);
600
+ }
442
601
 
443
- string memory script;
444
- for (uint256 i = 0; i < scriptCount; i++) {
445
- string memory scriptChunk = IGenArt721CoreProjectScriptV0(
446
- coreContract
447
- ).projectScriptByIndex(projectId, i);
448
- script = string.concat(script, scriptChunk);
602
+ bytes4 chunkSelector = IGenArt721CoreProjectScriptV0
603
+ .projectScriptByIndex
604
+ .selector;
605
+ address coreContract = source.coreContract;
606
+ uint256 projectId = source.projectId;
607
+ for (uint256 i = 0; i < source.legacyChunkCount; i++) {
608
+ assembly ("memory-safe") {
609
+ // projectScriptByIndex(projectId, i), written at the document's end
610
+ mstore(end, chunkSelector)
611
+ mstore(add(end, 0x04), projectId)
612
+ mstore(add(end, 0x24), i)
449
613
  }
614
+ end = _appendReturnedString(end, coreContract, 0x44);
615
+ }
616
+ return end;
617
+ }
450
618
 
451
- return bytes(script);
452
- } catch {
453
- revert("Unable to retrieve project script info");
619
+ /**
620
+ * @notice Append the gunzip script to the document ending at `end`, copied straight from the
621
+ * universal bytecode storage reader's return data.
622
+ * @param end The document's end (see InPlaceDocument).
623
+ * @return The document's new end.
624
+ */
625
+ function _appendGunzipScript(uint256 end) internal view returns (uint256) {
626
+ address gunzipScript = gunzipScriptBytecodeAddress;
627
+ bytes4 readSelector = IBytecodeStorageReader_Base
628
+ .readFromBytecode
629
+ .selector;
630
+ assembly ("memory-safe") {
631
+ // readFromBytecode(gunzipScriptBytecodeAddress), written at the document's end
632
+ mstore(end, readSelector)
633
+ mstore(add(end, 0x04), gunzipScript)
454
634
  }
635
+ return
636
+ _appendReturnedString(
637
+ end,
638
+ address(universalBytecodeStorageReader),
639
+ 0x24
640
+ );
641
+ }
642
+
643
+ /**
644
+ * @notice Call `target` with the `calldataSize` bytes of call data at `end`, and append the
645
+ * `string` it returns to the document ending at `end`, copied straight from return data.
646
+ * @return The document's new end.
647
+ * @dev Behaves as a high-level call returning `string memory`: a failed call's revert data is
648
+ * forwarded, and return data the ABI decoder refuses (shorter than a word, an offset past
649
+ * 2^64 - 1 or the data, a length past the data) reverts with no data. (For a length of 2^64 or
650
+ * more the decoder panics instead; the contracts read here never return one.)
651
+ */
652
+ function _appendReturnedString(
653
+ uint256 end,
654
+ address target,
655
+ uint256 calldataSize
656
+ ) internal view returns (uint256) {
657
+ assembly ("memory-safe") {
658
+ if iszero(staticcall(gas(), target, end, calldataSize, 0, 0)) {
659
+ returndatacopy(end, 0, returndatasize())
660
+ revert(end, returndatasize())
661
+ }
662
+ let size := returndatasize()
663
+ if lt(size, 0x20) {
664
+ revert(0, 0)
665
+ }
666
+ returndatacopy(0, 0, 0x20)
667
+ let offset := mload(0)
668
+ // the offset is at most 2^64 - 1, so the sum cannot overflow
669
+ if or(gt(offset, 0xffffffffffffffff), gt(add(offset, 0x20), size)) {
670
+ revert(0, 0)
671
+ }
672
+ returndatacopy(0, offset, 0x20)
673
+ let length := mload(0)
674
+ if gt(length, sub(sub(size, offset), 0x20)) {
675
+ revert(0, 0)
676
+ }
677
+ returndatacopy(end, add(offset, 0x20), length)
678
+ end := add(end, length)
679
+ }
680
+ InPlaceDocument.claim(end);
681
+ return end;
455
682
  }
456
683
 
457
684
  /**
@@ -809,61 +1036,87 @@ contract GenArt721GeneratorV0 is Initializable, IGenArt721GeneratorV0 {
809
1036
  }
810
1037
 
811
1038
  /**
812
- * @notice populates an empty HTMLTag with script information for a given dependency.
1039
+ * @notice Adds a part to a token's document.
1040
+ * @param document The document, memory reference; modified in place.
1041
+ */
1042
+ function _pushPart(
1043
+ TokenDocument memory document,
1044
+ uint256 kind,
1045
+ bytes32 abxfsFileCid,
1046
+ bytes memory literal
1047
+ ) internal pure {
1048
+ document.parts[document.partCount++] = DocumentPart({
1049
+ kind: kind,
1050
+ abxfsFileCid: abxfsFileCid,
1051
+ literal: literal
1052
+ });
1053
+ }
1054
+
1055
+ /**
1056
+ * @notice Adds literal text to a token's document.
1057
+ * @param document The document, memory reference; modified in place.
1058
+ */
1059
+ function _pushLiteral(
1060
+ TokenDocument memory document,
1061
+ bytes memory literal
1062
+ ) internal pure {
1063
+ _pushPart(document, PART_LITERAL, bytes32(0), literal);
1064
+ }
1065
+
1066
+ /**
1067
+ * @notice Adds the script tag for a given dependency to a token's document.
813
1068
  * Assumes the dependency is available on the dependencyRegistry.
814
- * Populates the script via on-chain information if available, otherwise injects script tag with src
1069
+ * Inlines the dependency's ABX FS file if it has one - otherwise injects script tag with src
815
1070
  * pointing to the preferred CDN.
816
- * @param dependencyNameAndVersion The name and version of the dependency to populate the script for.
817
- * @param htmlTag The HTMLTag to populate with the script information, memory reference; modified in place.
1071
+ * @param document The document, memory reference; modified in place.
1072
+ * @param dependencyNameAndVersion The name and version of the dependency to add the script for.
818
1073
  */
819
- function _populateDependencyScriptHtmlTag(
820
- bytes32 dependencyNameAndVersion,
821
- HTMLTag memory htmlTag
1074
+ function _pushDependencyScriptTag(
1075
+ TokenDocument memory document,
1076
+ bytes32 dependencyNameAndVersion
822
1077
  ) internal view {
823
- // Get script count and preferred CDN for the dependency.
824
- string memory preferredCDN;
825
- uint24 scriptCount;
826
- // @dev block scope to limit stack usage
827
- {
828
- IDependencyRegistryV0.DependencyDetails
829
- memory dependencyDetails = dependencyRegistry
830
- .getDependencyDetailsV2(dependencyNameAndVersion);
831
- preferredCDN = dependencyDetails.preferredCDN;
832
- scriptCount = dependencyDetails.scriptCount;
833
- }
1078
+ // Get ABX FS file and preferred CDN for the dependency.
1079
+ IDependencyRegistryV0.DependencyDetails
1080
+ memory dependencyDetails = dependencyRegistry
1081
+ .getDependencyDetailsV2(dependencyNameAndVersion);
1082
+ string memory preferredCDN = dependencyDetails.preferredCDN;
1083
+ bytes32 abxfsFileCid = _getInlinedAbxfsFileCid(dependencyDetails);
834
1084
 
835
- // If no scripts on-chain, load the script from the preferred CDN.
836
- if (scriptCount == 0) {
837
- bool cdnAvailable = bytes(preferredCDN).length > 0;
1085
+ // If not on chain, load the script from the preferred CDN.
1086
+ if (abxfsFileCid == bytes32(0)) {
838
1087
  // If no CDN is available, we don't need to add any tags.
839
1088
  // Expected for dependencies like "js@na" and "svg@na".
840
- htmlTag.tagOpen = cdnAvailable
841
- ? abi.encodePacked(
842
- '<script type="text/javascript" src="',
843
- preferredCDN,
844
- '">'
845
- )
846
- : bytes("");
847
- htmlTag.tagClose = bytes(cdnAvailable ? "</script>" : "");
1089
+ if (bytes(preferredCDN).length > 0) {
1090
+ _pushLiteral(
1091
+ document,
1092
+ abi.encodePacked(
1093
+ '<script type="text/javascript" src="',
1094
+ preferredCDN,
1095
+ '">',
1096
+ SCRIPT_TAG_CLOSE
1097
+ )
1098
+ );
1099
+ }
848
1100
  } else {
849
- bytes memory dependencyScript = _getDependencyScriptBytes(
850
- dependencyNameAndVersion
851
- );
852
- htmlTag.tagContent = dependencyScript;
853
- htmlTag.tagType = HTMLTagType.scriptGZIPBase64DataURI; // <script type="text/javascript+gzip" src="data:text/javascript;base64,[script]"></script>
1101
+ // @dev the gunzip script inflates the gzip data URI in the browser
1102
+ _pushLiteral(document, GZIP_DATA_URI_SCRIPT_TAG_OPEN);
1103
+ _pushPart(document, PART_ABXFS_FILE, abxfsFileCid, "");
1104
+ _pushLiteral(document, DATA_URI_SCRIPT_TAG_CLOSE);
854
1105
  }
855
1106
  }
856
1107
 
857
1108
  /**
858
- * @notice Get the HTMLRequest for a given token.
1109
+ * @notice Get the parts of the HTML document for a given token, in order, reading nothing
1110
+ * large: the ABX FS files, gunzip script and project script are read as the document is
1111
+ * written (`_writeTokenDocument`).
859
1112
  * @param coreContract The core contract address the token belongs to.
860
- * @param tokenId The ID of the token to retrieve the HTMLRequest for.
861
- * @return The HTMLRequest for the token.
1113
+ * @param tokenId The ID of the token to retrieve the document for.
1114
+ * @return document The token's document.
862
1115
  */
863
- function _getTokenHtmlRequest(
1116
+ function _getTokenDocument(
864
1117
  address coreContract,
865
1118
  uint256 tokenId
866
- ) internal view returns (HTMLRequest memory) {
1119
+ ) internal view returns (TokenDocument memory document) {
867
1120
  _onlySupportedCoreContract(coreContract);
868
1121
 
869
1122
  uint256 projectId = ABHelpers.tokenIdToProjectId(tokenId);
@@ -879,134 +1132,160 @@ contract GenArt721GeneratorV0 is Initializable, IGenArt721GeneratorV0 {
879
1132
  memory dependencyDetails = dependencyRegistry
880
1133
  .getDependencyDetailsV2(dependencyNameAndVersion);
881
1134
 
882
- // @dev A raw HTML dependency stores a complete HTML document as its project script
883
- // rather than a JavaScript program. Such a document must be injected verbatim -
884
- // wrapping it in a script tag both breaks HTML parsing (the document's own
885
- // "</script>" terminates the wrapper early) and is semantically wrong, since markup
886
- // inside a script tag is never rendered.
887
- bool isRawHtmlDep = dependencyDetails.projectScriptTagType ==
888
- IDependencyRegistryV0.ProjectScriptTagType.RawHtml;
889
-
890
- // Create head tags
891
- // pre-fetch data to properly allocate memory for HTML tags
892
- (
893
- bytes memory tokenDataJson,
894
- bytes32[] memory dependencyRegistryAssetNameAndVersions
895
- ) = _getTokenDataAndDependencyRegistryAssets({
896
- coreContract: coreContract,
897
- tokenId: tokenId
898
- });
899
- // @dev memoize length for efficiency
900
- uint256 dependencyRegistryAssetNamesAndVersionsLength = dependencyRegistryAssetNameAndVersions
901
- .length;
902
- // @dev length is 3 (style, tokenData, import map) + number of external asset dependencies
903
- HTMLTag[] memory headTags = new HTMLTag[](
904
- 3 + dependencyRegistryAssetNamesAndVersionsLength
905
- );
906
- // @dev The default style reset is omitted for raw HTML documents, which supply
907
- // their own document-level styling. This matches Art Blocks' hosted generator.
908
- if (!isRawHtmlDep) {
909
- headTags[0].tagOpen = "<style>";
910
- headTags[0]
911
- .tagContent = "html{height:100%}body{min-height:100%;margin:0;padding:0}canvas{padding:0;margin:auto;display:block;position:absolute;top:0;bottom:0;left:0;right:0}";
912
- headTags[0].tagClose = "</style>";
913
- }
914
-
915
- // @dev decode any base64 encoded flex data in the browser while parsing the json
916
- headTags[1].tagContent = abi.encodePacked(
917
- "let tokenData = JSON.parse(`",
918
- tokenDataJson,
919
- '`, (key, value) => key === "data" && value !== null ? value.startsWith("#web3call#") ? Object.entries(JSON.parse(atob(value.slice(10)))).reduce((acc, [k, v]) => ((acc[atob(k)] = atob(v)), acc), {}) : atob(value) : value);'
1135
+ // Head
1136
+ bytes32[] memory dependencyRegistryAssetNameAndVersions = _pushHead(
1137
+ document,
1138
+ coreContract,
1139
+ tokenId,
1140
+ dependencyNameAndVersion,
1141
+ dependencyDetails
920
1142
  );
921
- headTags[1].tagType = HTMLTagType.script;
922
-
923
- // @dev An ES module dependency cannot be loaded with a plain script tag, and project
924
- // scripts import it by bare specifier (e.g. `import * as THREE from "three"`). An
925
- // import map maps that specifier to the dependency's URL, and must appear in the head
926
- // before any module is loaded.
927
- _populateImportMapHtmlTag({
928
- dependencyNameAndVersion: dependencyNameAndVersion,
929
- dependencyDetails: dependencyDetails,
930
- htmlTag: headTags[2]
931
- });
932
-
933
1143
  for (
934
1144
  uint256 i = 0;
935
- i < dependencyRegistryAssetNamesAndVersionsLength;
1145
+ i < dependencyRegistryAssetNameAndVersions.length;
936
1146
  i++
937
1147
  ) {
938
1148
  // skip if empty (not a dependency registry asset)
939
- // @dev okay to have empty html tags - they will be ignored
940
1149
  if (dependencyRegistryAssetNameAndVersions[i] == bytes32(0)) {
941
1150
  continue;
942
1151
  }
943
- // populate head tags with dependency registry scripts
944
- _populateDependencyScriptHtmlTag(
945
- dependencyRegistryAssetNameAndVersions[i],
946
- headTags[3 + i]
1152
+ // dependency registry scripts go in the head
1153
+ _pushDependencyScriptTag(
1154
+ document,
1155
+ dependencyRegistryAssetNameAndVersions[i]
947
1156
  );
948
1157
  }
1158
+ _pushLiteral(document, HTML_HEAD_CLOSE_BODY_OPEN);
949
1159
 
950
- // Create body tags
951
- HTMLTag[] memory bodyTags = new HTMLTag[](4);
952
-
1160
+ // Body
953
1161
  // Dependency script tag
954
1162
  // @dev A module dependency is reached through the import map emitted in the head, so
955
1163
  // emitting a script tag for it here would load the module as a classic script and
956
1164
  // raise a syntax error on its `export` statements.
957
1165
  if (!dependencyDetails.loadAsModule) {
958
- _populateDependencyScriptHtmlTag(
959
- dependencyNameAndVersion,
960
- bodyTags[0]
961
- );
1166
+ _pushDependencyScriptTag(document, dependencyNameAndVersion);
962
1167
  }
963
1168
 
964
1169
  // @dev We expect all of our dependencies to be added gzip'd and base64 encoded
965
1170
  // so we need to include this so we can gunzip them in the browser.
966
- bodyTags[1].name = "gunzipScripts-0.0.1.js";
967
- bodyTags[1].tagType = HTMLTagType.scriptBase64DataURI; // <script src="data:text/javascript;base64,[script]"></script>
968
- bodyTags[1].tagContent = bytes(
969
- universalBytecodeStorageReader.readFromBytecode(
970
- gunzipScriptBytecodeAddress
971
- )
972
- );
1171
+ _pushLiteral(document, DATA_URI_SCRIPT_TAG_OPEN);
1172
+ _pushPart(document, PART_GUNZIP_SCRIPT, bytes32(0), "");
1173
+ _pushLiteral(document, DATA_URI_SCRIPT_TAG_CLOSE);
973
1174
 
974
- HTMLTag memory canvasTag = _createCanvasTagIfNeeded(
1175
+ bytes memory canvasTag = _getCanvasTag(
975
1176
  dependencyNameAndVersion,
976
1177
  dependencyDetails.canvasTagType
977
1178
  );
978
-
979
- bytes memory projectScript = _getProjectScriptBytes(
1179
+ document.projectScript = _getProjectScriptSource(
980
1180
  coreContract,
981
1181
  projectId
982
1182
  );
1183
+ bool canvasAfterProjectScript = dependencyDetails.canvasTagType ==
1184
+ IDependencyRegistryV0.CanvasTagType.CanvasAfterProjectScript;
1185
+ if (!canvasAfterProjectScript) {
1186
+ _pushLiteral(document, canvasTag);
1187
+ }
1188
+ _pushLiteral(document, _getProjectScriptTagOpen(dependencyDetails));
1189
+ _pushPart(document, PART_PROJECT_SCRIPT, bytes32(0), "");
1190
+ // @dev A raw HTML document is injected verbatim, with no closing tag.
1191
+ _pushLiteral(
1192
+ document,
1193
+ dependencyDetails.projectScriptTagType ==
1194
+ IDependencyRegistryV0.ProjectScriptTagType.RawHtml
1195
+ ? bytes("")
1196
+ : SCRIPT_TAG_CLOSE
1197
+ );
1198
+ if (canvasAfterProjectScript) {
1199
+ _pushLiteral(document, canvasTag);
1200
+ }
1201
+ _pushLiteral(document, HTML_BODY_CLOSE);
1202
+ }
983
1203
 
984
- HTMLTag memory projectScriptTag = HTMLTag({
985
- tagOpen: _getProjectScriptTagOpen(dependencyDetails),
986
- tagClose: isRawHtmlDep ? bytes("") : bytes("</script>"),
987
- tagType: HTMLTagType.useTagOpenAndClose,
988
- name: "",
989
- contractAddress: address(0),
990
- contractData: "",
991
- tagContent: projectScript
1204
+ /**
1205
+ * @notice Allocates a token's document parts and adds the start of its head: the default
1206
+ * style, token data and import map.
1207
+ * @param document The document, memory reference; modified in place.
1208
+ * @return dependencyRegistryAssetNameAndVersions The token's flex dependency registry assets,
1209
+ * whose script tags follow in the head (zero for other assets).
1210
+ */
1211
+ function _pushHead(
1212
+ TokenDocument memory document,
1213
+ address coreContract,
1214
+ uint256 tokenId,
1215
+ bytes32 dependencyNameAndVersion,
1216
+ IDependencyRegistryV0.DependencyDetails memory dependencyDetails
1217
+ )
1218
+ internal
1219
+ view
1220
+ returns (bytes32[] memory dependencyRegistryAssetNameAndVersions)
1221
+ {
1222
+ // pre-fetch data to properly allocate memory for the document's parts
1223
+ bytes memory tokenDataJson;
1224
+ (
1225
+ tokenDataJson,
1226
+ dependencyRegistryAssetNameAndVersions
1227
+ ) = _getTokenDataAndDependencyRegistryAssets({
1228
+ coreContract: coreContract,
1229
+ tokenId: tokenId
992
1230
  });
1231
+ // @dev at most 3 parts per external asset dependency (an inlined dependency's tag), and 13
1232
+ // others: this head, the tag closing it, the dependency's tag (3), the gunzip script's tag
1233
+ // (3), the canvas tag, the project script's tag (3), and the tag closing the body
1234
+ document.parts = new DocumentPart[](
1235
+ 13 + 3 * dependencyRegistryAssetNameAndVersions.length
1236
+ );
993
1237
 
994
- if (
995
- dependencyDetails.canvasTagType ==
996
- IDependencyRegistryV0.CanvasTagType.CanvasAfterProjectScript
997
- ) {
998
- bodyTags[2] = projectScriptTag;
999
- bodyTags[3] = canvasTag;
1000
- } else {
1001
- bodyTags[2] = canvasTag;
1002
- bodyTags[3] = projectScriptTag;
1003
- }
1004
-
1005
- HTMLRequest memory htmlRequest;
1006
- htmlRequest.headTags = headTags;
1007
- htmlRequest.bodyTags = bodyTags;
1238
+ // @dev A raw HTML dependency stores a complete HTML document as its project script
1239
+ // rather than a JavaScript program. Such a document must be injected verbatim -
1240
+ // wrapping it in a script tag both breaks HTML parsing (the document's own
1241
+ // "</script>" terminates the wrapper early) and is semantically wrong, since markup
1242
+ // inside a script tag is never rendered.
1243
+ // @dev The default style reset is omitted for raw HTML documents, which supply
1244
+ // their own document-level styling. This matches Art Blocks' hosted generator.
1245
+ _pushLiteral(
1246
+ document,
1247
+ abi.encodePacked(
1248
+ HTML_HEAD_OPEN,
1249
+ dependencyDetails.projectScriptTagType ==
1250
+ IDependencyRegistryV0.ProjectScriptTagType.RawHtml
1251
+ ? bytes("")
1252
+ : STYLE_TAG,
1253
+ TOKEN_DATA_SCRIPT_OPEN,
1254
+ tokenDataJson,
1255
+ TOKEN_DATA_SCRIPT_CLOSE,
1256
+ // @dev An ES module dependency cannot be loaded with a plain script tag, and
1257
+ // project scripts import it by bare specifier (e.g. `import * as THREE from
1258
+ // "three"`). An import map maps that specifier to the dependency's URL, and must
1259
+ // appear in the head before any module is loaded.
1260
+ _getImportMapTag(dependencyNameAndVersion, dependencyDetails)
1261
+ )
1262
+ );
1263
+ }
1008
1264
 
1009
- return htmlRequest;
1265
+ /**
1266
+ * @notice Writes a token's document into one buffer at the end of memory, reading each large
1267
+ * part into its place.
1268
+ * @param document The token's document, from `_getTokenDocument`.
1269
+ * @return doc The document (see InPlaceDocument).
1270
+ * @return end The document's end.
1271
+ */
1272
+ function _writeTokenDocument(
1273
+ TokenDocument memory document
1274
+ ) internal view returns (uint256 doc, uint256 end) {
1275
+ (doc, end) = InPlaceDocument.open();
1276
+ // @dev nothing below allocates memory while the document is open
1277
+ for (uint256 i = 0; i < document.partCount; i++) {
1278
+ DocumentPart memory part = document.parts[i];
1279
+ if (part.kind == PART_LITERAL) {
1280
+ end = InPlaceDocument.appendBytes(end, part.literal);
1281
+ } else if (part.kind == PART_ABXFS_FILE) {
1282
+ end = _appendAbxfsFile(end, part.abxfsFileCid);
1283
+ } else if (part.kind == PART_GUNZIP_SCRIPT) {
1284
+ end = _appendGunzipScript(end);
1285
+ } else {
1286
+ end = _appendProjectScript(end, document.projectScript);
1287
+ }
1288
+ }
1010
1289
  }
1011
1290
 
1012
1291
  /**
@@ -1043,7 +1322,8 @@ contract GenArt721GeneratorV0 is Initializable, IGenArt721GeneratorV0 {
1043
1322
  }
1044
1323
 
1045
1324
  /**
1046
- * @dev Helper function to check if a dependency is on chain.
1325
+ * @dev Helper function to check if a dependency is on chain: it has an ABX FS file, which the
1326
+ * generator inlines (ES module dependencies are loaded from their CDN, so are not on chain).
1047
1327
  * @param dependencyNameAndVersion The name and version of the dependency to check.
1048
1328
  */
1049
1329
  function _getIsDependencyOnChain(
@@ -1056,11 +1336,11 @@ contract GenArt721GeneratorV0 is Initializable, IGenArt721GeneratorV0 {
1056
1336
  ) {
1057
1337
  return true;
1058
1338
  }
1059
- // query and return result of dependency registry for on-chain status
1060
- return
1061
- dependencyRegistry
1062
- .getDependencyDetailsV2(dependencyNameAndVersion)
1063
- .availableOnChain;
1339
+ // query dependency registry for on-chain status
1340
+ IDependencyRegistryV0.DependencyDetails
1341
+ memory dependencyDetails = dependencyRegistry
1342
+ .getDependencyDetailsV2(dependencyNameAndVersion);
1343
+ return _getInlinedAbxfsFileCid(dependencyDetails) != bytes32(0);
1064
1344
  }
1065
1345
 
1066
1346
  /**
@@ -1156,71 +1436,52 @@ contract GenArt721GeneratorV0 is Initializable, IGenArt721GeneratorV0 {
1156
1436
  }
1157
1437
 
1158
1438
  /**
1159
- * @dev Helper function to populate an import map tag, which maps a module dependency's
1160
- * bare specifier (its name) to the URL the module is served from. Left empty for
1439
+ * @dev Helper function to get an import map tag, which maps a module dependency's
1440
+ * bare specifier (its name) to the URL the module is served from. Empty for
1161
1441
  * dependencies that are not loaded as modules.
1162
1442
  * @param dependencyNameAndVersion Dependency identifier of the form "name@version".
1163
1443
  * @param dependencyDetails Details of the dependency.
1164
- * @param htmlTag The HTMLTag to populate.
1444
+ * @return The import map tag, or empty.
1165
1445
  */
1166
- function _populateImportMapHtmlTag(
1446
+ function _getImportMapTag(
1167
1447
  bytes32 dependencyNameAndVersion,
1168
- IDependencyRegistryV0.DependencyDetails memory dependencyDetails,
1169
- HTMLTag memory htmlTag
1170
- ) internal pure {
1448
+ IDependencyRegistryV0.DependencyDetails memory dependencyDetails
1449
+ ) internal pure returns (bytes memory) {
1171
1450
  if (!dependencyDetails.loadAsModule) {
1172
- return;
1451
+ return "";
1173
1452
  }
1174
1453
 
1175
- htmlTag.tagType = HTMLTagType.useTagOpenAndClose;
1176
- htmlTag.tagOpen = abi.encodePacked(
1177
- '<script type="importmap">{"imports":{"',
1178
- _getDependencyName(dependencyNameAndVersion),
1179
- '":"',
1180
- dependencyDetails.preferredCDN,
1181
- '"}}'
1182
- );
1183
- htmlTag.tagClose = bytes("</script>");
1454
+ return
1455
+ abi.encodePacked(
1456
+ '<script type="importmap">{"imports":{"',
1457
+ _getDependencyName(dependencyNameAndVersion),
1458
+ '":"',
1459
+ dependencyDetails.preferredCDN,
1460
+ '"}}',
1461
+ SCRIPT_TAG_CLOSE
1462
+ );
1184
1463
  }
1185
1464
 
1186
1465
  /**
1187
- * @dev Helper function to get a canvas tag or an empty tag, per the dependency's
1466
+ * @dev Helper function to get a canvas tag or nothing, per the dependency's
1188
1467
  * registry-prescribed canvas requirement.
1189
1468
  * @param dependencyNameAndVersion Dependency identifier, used to name the canvas element.
1190
1469
  * @param canvasTagType Whether a canvas is required.
1191
- * @return The canvas tag or an empty tag.
1470
+ * @return The canvas tag, or empty.
1192
1471
  */
1193
- function _createCanvasTagIfNeeded(
1472
+ function _getCanvasTag(
1194
1473
  bytes32 dependencyNameAndVersion,
1195
1474
  IDependencyRegistryV0.CanvasTagType canvasTagType
1196
- ) internal pure returns (HTMLTag memory) {
1475
+ ) internal pure returns (bytes memory) {
1197
1476
  if (canvasTagType != IDependencyRegistryV0.CanvasTagType.NoCanvasTag) {
1198
1477
  return
1199
- HTMLTag({
1200
- tagOpen: abi.encodePacked(
1201
- "<canvas id='",
1202
- _getDependencyName(dependencyNameAndVersion),
1203
- "-canvas'>"
1204
- ),
1205
- tagClose: bytes("</canvas>"),
1206
- tagType: HTMLTagType.useTagOpenAndClose,
1207
- name: "",
1208
- contractAddress: address(0),
1209
- contractData: "",
1210
- tagContent: ""
1211
- });
1212
- } else {
1213
- return
1214
- HTMLTag({
1215
- tagOpen: "",
1216
- tagClose: "",
1217
- tagType: HTMLTagType.useTagOpenAndClose,
1218
- name: "",
1219
- contractAddress: address(0),
1220
- contractData: "",
1221
- tagContent: ""
1222
- });
1478
+ abi.encodePacked(
1479
+ "<canvas id='",
1480
+ _getDependencyName(dependencyNameAndVersion),
1481
+ "-canvas'></canvas>"
1482
+ );
1223
1483
  }
1484
+ return "";
1224
1485
  }
1225
1486
 
1226
1487
  function _dependencyTypeToString(