@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
@@ -0,0 +1,1316 @@
1
+ // SPDX-License-Identifier: LGPL-3.0-only
2
+ pragma solidity 0.8.22;
3
+
4
+ import "../interfaces/v0.8.x/IDependencyRegistryV0.sol";
5
+ import "../interfaces/v0.8.x/IGenArt721CoreProjectScriptV0.sol";
6
+ import "../interfaces/v0.8.x/IGenArt721CoreProjectScriptV1.sol";
7
+ import "../interfaces/v0.8.x/IGenArt721CoreTokenHashProviderV0.sol";
8
+ import "../interfaces/v0.8.x/IGenArt721CoreTokenHashProviderV1.sol";
9
+ import "../interfaces/v0.8.x/IGenArt721GeneratorV0.sol";
10
+ import {IGenArt721CoreContractV3_Engine_Flex} from "../interfaces/v0.8.x/IGenArt721CoreContractV3_Engine_Flex.sol";
11
+ import {IUniversalBytecodeStorageReader} from "../interfaces/v0.8.x/IUniversalBytecodeStorageReader.sol";
12
+ import {IAbxfsFileDataReader} from "../interfaces/v0.8.x/IAbxfsFileDataReader.sol";
13
+ import {AbxfsCanonical} from "../libs/v0.8.x/AbxfsCanonical.sol";
14
+ import {IWeb3Call} from "../interfaces/v0.8.x/IWeb3Call.sol";
15
+
16
+ import "../libs/v0.8.x/Bytes32Strings.sol";
17
+ import {JsonStatic} from "../libs/v0.8.x/JsonStatic.sol";
18
+ import {ABHelpers} from "../libs/v0.8.x/ABHelpers.sol";
19
+ import {AddressChunks} from "../generator/AddressChunks.sol";
20
+
21
+ import {Base64} from "@openzeppelin-5.0/contracts/utils/Base64.sol";
22
+ import "@openzeppelin-4.7/contracts/utils/Strings.sol";
23
+ import "@openzeppelin-4.8/contracts-upgradeable/proxy/utils/Initializable.sol";
24
+
25
+ import {IScriptyBuilderV2, HTMLRequest, HTMLTagType, HTMLTag} from "scripty.sol/contracts/scripty/interfaces/IScriptyBuilderV2.sol";
26
+
27
+ // @dev legacy interface for V2 flex contracts - used to get external legacy asset dependencies
28
+ interface ILegacyGenArt721CoreV2_PBAB_Flex {
29
+ enum LegacyExternalAssetDependencyType {
30
+ IPFS,
31
+ ARWEAVE
32
+ }
33
+ // legacy struct for V2 flex contracts
34
+ struct LegacyExternalAssetDependencyWithoutData {
35
+ string cid;
36
+ LegacyExternalAssetDependencyType dependencyType;
37
+ }
38
+
39
+ function projectExternalAssetDependencyByIndex(
40
+ uint256 _projectId,
41
+ uint256 _index
42
+ ) external view returns (LegacyExternalAssetDependencyWithoutData memory);
43
+ }
44
+
45
+ /**
46
+ * @title GenArt721GeneratorV0ScriptyReferenceMock
47
+ * @author Art Blocks Inc.
48
+ * @notice TEST ONLY, never deployed. GenArt721GeneratorV0 as it was before it assembled token
49
+ * HTML in place: it builds an HTMLRequest and assembles every document through an external call
50
+ * to ScriptyBuilderV2. Tests and the fork checks compare the shipped generator's output with it.
51
+ * @dev Unchanged from that version except for this contract's name, this comment, and the path
52
+ * to AddressChunks. Its original notice: This contract is used to generate the HTML for Art
53
+ * Blocks tokens by combining the dependency script, project script, token data. It utilizes
54
+ * the ScriptyBuilder contract to generate the HTML.
55
+ */
56
+ contract GenArt721GeneratorV0ScriptyReferenceMock is
57
+ Initializable,
58
+ IGenArt721GeneratorV0
59
+ {
60
+ using Bytes32Strings for bytes32;
61
+ using Bytes32Strings for string;
62
+ using JsonStatic for JsonStatic.Json;
63
+
64
+ // @dev This is an upgradable contract so we need to maintain
65
+ // the order of the variables to ensure we don't overwrite
66
+ // storage when upgrading.
67
+ IDependencyRegistryV0 public dependencyRegistry;
68
+ IScriptyBuilderV2 public scriptyBuilder;
69
+ address public gunzipScriptBytecodeAddress;
70
+ IUniversalBytecodeStorageReader public universalBytecodeStorageReader;
71
+
72
+ // @dev contants do not use sequential storage slots, and may be added/removed from upgradeable contracts
73
+ bytes32 constant JS_AT_NA_BYTES32 =
74
+ 0x6a73406e61000000000000000000000000000000000000000000000000000000; // "js@na"
75
+ bytes32 constant SVG_AT_NA_BYTES32 =
76
+ 0x737667406e610000000000000000000000000000000000000000000000000000; // "svg@na"
77
+ // @dev The ABX FS FileDataReader, through which dependency scripts are read from ABX FS (the
78
+ // same address on every chain ABX FS supports; see AbxfsCanonical).
79
+ IAbxfsFileDataReader public constant ABXFS_FILE_DATA_READER =
80
+ IAbxfsFileDataReader(AbxfsCanonical.FILE_DATA_READER);
81
+
82
+ function _onlySupportedCoreContract(address coreContract) internal view {
83
+ require(
84
+ dependencyRegistry.isSupportedCoreContract(coreContract),
85
+ "Unsupported core contract"
86
+ );
87
+ }
88
+
89
+ function _onlyDependencyRegistryAdminACL(bytes4 selector) internal {
90
+ require(
91
+ dependencyRegistry.adminACLAllowed({
92
+ sender: msg.sender,
93
+ contract_: address(this),
94
+ selector: selector
95
+ }),
96
+ "Only DependencyRegistry AdminACL"
97
+ );
98
+ }
99
+
100
+ /**
101
+ * @notice Initializer for the GenArt721GeneratorV0 contract.
102
+ * @param _dependencyRegistry The address of the DependencyRegistry
103
+ * contract to be used for retrieving dependency scripts.
104
+ * @param _scriptyBuilder The address of the ScriptyBuilderV2 contract
105
+ * to be used for generating the HTML for tokens.
106
+ * @param _gunzipScriptBytecodeAddress The address of the gunzip script bytecode
107
+ * storage contract used to gunzip the dependency scripts in the browser.
108
+ * @param _universalBytecodeStorageReader The address of the universal bytecode storage reader contract.
109
+ */
110
+ function initialize(
111
+ address _dependencyRegistry,
112
+ address _scriptyBuilder,
113
+ address _gunzipScriptBytecodeAddress,
114
+ address _universalBytecodeStorageReader
115
+ ) public initializer {
116
+ dependencyRegistry = IDependencyRegistryV0(_dependencyRegistry);
117
+ scriptyBuilder = IScriptyBuilderV2(_scriptyBuilder);
118
+ gunzipScriptBytecodeAddress = _gunzipScriptBytecodeAddress;
119
+ universalBytecodeStorageReader = IUniversalBytecodeStorageReader(
120
+ _universalBytecodeStorageReader
121
+ );
122
+
123
+ emit DependencyRegistryUpdated(_dependencyRegistry);
124
+ emit ScriptyBuilderUpdated(_scriptyBuilder);
125
+ emit GunzipScriptBytecodeAddressUpdated(_gunzipScriptBytecodeAddress);
126
+ emit UniversalBytecodeStorageReaderUpdated(
127
+ _universalBytecodeStorageReader
128
+ );
129
+ }
130
+
131
+ /**
132
+ * @notice Set the DependencyRegistry contract address.
133
+ * @param _dependencyRegistry The address of the DependencyRegistry
134
+ * contract to be used for retrieving dependency scripts.
135
+ * @dev This function is gated to only the DependencyRegistry AdminACL.
136
+ * If an address is passed that does not implement the adminACLAllowed
137
+ * function, we will lose access to the write functions on this contract.
138
+ */
139
+ function updateDependencyRegistry(address _dependencyRegistry) external {
140
+ _onlyDependencyRegistryAdminACL(this.updateDependencyRegistry.selector);
141
+
142
+ dependencyRegistry = IDependencyRegistryV0(_dependencyRegistry);
143
+ emit DependencyRegistryUpdated(_dependencyRegistry);
144
+ }
145
+
146
+ /**
147
+ * @notice Set the ScriptyBuilder contract address.
148
+ * @param _scriptyBuilder The address of the ScriptyBuilderV2 contract
149
+ * to be used for generating the HTML for tokens.
150
+ * @dev This function is gated to only the DependencyRegistry AdminACL.
151
+ */
152
+ function updateScriptyBuilder(address _scriptyBuilder) external {
153
+ _onlyDependencyRegistryAdminACL(this.updateScriptyBuilder.selector);
154
+
155
+ scriptyBuilder = IScriptyBuilderV2(_scriptyBuilder);
156
+ emit ScriptyBuilderUpdated(_scriptyBuilder);
157
+ }
158
+
159
+ /**
160
+ * @notice Set the gunzip script address.
161
+ * @param _gunzipScriptBytecodeAddress The address of the gunzip script bytecode
162
+ * storage contract used to gunzip the dependency scripts in the browser.
163
+ * @dev This function is gated to only the DependencyRegistry AdminACL.
164
+ */
165
+ function updateGunzipScriptBytecodeAddress(
166
+ address _gunzipScriptBytecodeAddress
167
+ ) external {
168
+ _onlyDependencyRegistryAdminACL(
169
+ this.updateGunzipScriptBytecodeAddress.selector
170
+ );
171
+
172
+ gunzipScriptBytecodeAddress = _gunzipScriptBytecodeAddress;
173
+ emit GunzipScriptBytecodeAddressUpdated(_gunzipScriptBytecodeAddress);
174
+ }
175
+
176
+ /**
177
+ * @notice Set the universalBytecodeStorageReader contract address.
178
+ * @param _universalBytecodeStorageReader The address of the universal bytecode storage reader contract.
179
+ * @dev This function is gated to only the DependencyRegistry AdminACL.
180
+ */
181
+ function updateUniversalBytecodeStorageReader(
182
+ address _universalBytecodeStorageReader
183
+ ) external {
184
+ _onlyDependencyRegistryAdminACL(
185
+ this.updateUniversalBytecodeStorageReader.selector
186
+ );
187
+
188
+ universalBytecodeStorageReader = IUniversalBytecodeStorageReader(
189
+ _universalBytecodeStorageReader
190
+ );
191
+ emit UniversalBytecodeStorageReaderUpdated(
192
+ _universalBytecodeStorageReader
193
+ );
194
+ }
195
+
196
+ /**
197
+ * @notice Get the dependency script for a given dependency name and version string, as the
198
+ * generator inlines it.
199
+ * @param dependencyNameAndVersion The name and version of the dependency
200
+ * to retrieve the script for.
201
+ * @return The dependency's ABX FS file (its gzip bytes), base64 encoded, or empty if the
202
+ * generator does not inline the dependency (no ABX FS file, or an ES module dependency).
203
+ * @dev Reverts if the dependency's ABX FS file is not a gzip file on this chain's ABX FS.
204
+ */
205
+ function getDependencyScript(
206
+ string memory dependencyNameAndVersion
207
+ ) external view returns (string memory) {
208
+ bytes32 abxfsFileCid = _getInlinedAbxfsFileCid(
209
+ dependencyRegistry.getDependencyDetailsV2(
210
+ dependencyNameAndVersion.stringToBytes32()
211
+ )
212
+ );
213
+ if (abxfsFileCid == bytes32(0)) {
214
+ return "";
215
+ }
216
+ return _getAbxfsFileBase64(abxfsFileCid);
217
+ }
218
+
219
+ /**
220
+ * @notice Get the project script for a given core contract address and
221
+ * project ID.
222
+ * @param coreContract The address of the core contract to retrieve
223
+ * the project script from.
224
+ * @param projectId The ID of the project to retrieve the script for.
225
+ * @return The project script stiched together from all of the script chunks as a string.
226
+ * @dev This function will revert if the core contract address is not
227
+ * supported by the DependencyRegistry or if the contract at the address
228
+ * does not implement the IGenArt721CoreProjectScriptV0 or IGenArt721CoreProjectScriptV1.
229
+ */
230
+ function getProjectScript(
231
+ address coreContract,
232
+ uint256 projectId
233
+ ) external view returns (string memory) {
234
+ bytes memory projectScript = _getProjectScriptBytes(
235
+ coreContract,
236
+ projectId
237
+ );
238
+
239
+ return string(projectScript);
240
+ }
241
+
242
+ /**
243
+ * @notice Get the data URI for the HTML for a given token (e.g. data:text/html;base64,[html])
244
+ * @param coreContract The address of the core contract the token belongs to.
245
+ * @param tokenId The ID of the token to retrieve the HTML for.
246
+ * @return The data URI for the HTML for the token.
247
+ */
248
+ function getTokenHtmlBase64EncodedDataUri(
249
+ address coreContract,
250
+ uint256 tokenId
251
+ ) external view returns (string memory) {
252
+ HTMLRequest memory htmlRequest = _getTokenHtmlRequest(
253
+ coreContract,
254
+ tokenId
255
+ );
256
+ string memory base64EncodedHTMLDataURI = scriptyBuilder
257
+ .getEncodedHTMLString(htmlRequest);
258
+
259
+ return base64EncodedHTMLDataURI;
260
+ }
261
+
262
+ /**
263
+ * @notice Get the HTML for a given token.
264
+ * @param coreContract The address of the core contract the token belongs to.
265
+ * @param tokenId The ID of the token to retrieve the HTML for.
266
+ * @return The HTML for the token.
267
+ */
268
+ function getTokenHtml(
269
+ address coreContract,
270
+ uint256 tokenId
271
+ ) external view returns (string memory) {
272
+ HTMLRequest memory htmlRequest = _getTokenHtmlRequest(
273
+ coreContract,
274
+ tokenId
275
+ );
276
+ string memory html = scriptyBuilder.getHTMLString(htmlRequest);
277
+
278
+ return html;
279
+ }
280
+
281
+ /**
282
+ * @notice Gets summary of details of how on-chain a project is.
283
+ * @param coreContract The core contract address to query.
284
+ * @param projectId The project ID to query.
285
+ * @return dependencyFullyOnChain Whether the project's dependency is fully on-chain.
286
+ * @return injectsDecentralizedStorageNetworkAssets Whether the project injects decentralized storage network assets.
287
+ * @return hasOffChainFlexDepRegDependencies True if the project uses flex assets of type ART_BLOCKS_DEPENDENCY_REGISTRY
288
+ * that are not fully on-chain; false otherwise.
289
+ */
290
+ function getOnChainStatus(
291
+ address coreContract,
292
+ uint256 projectId
293
+ )
294
+ external
295
+ view
296
+ returns (
297
+ bool dependencyFullyOnChain,
298
+ bool injectsDecentralizedStorageNetworkAssets,
299
+ bool hasOffChainFlexDepRegDependencies
300
+ )
301
+ {
302
+ // get dependency name and version
303
+ bytes32 dependencyNameAndVersion = dependencyRegistry
304
+ .getDependencyNameAndVersionForProject(coreContract, projectId)
305
+ .stringToBytes32();
306
+ dependencyFullyOnChain = _getIsDependencyOnChain(
307
+ dependencyNameAndVersion
308
+ );
309
+
310
+ // iterate over project's flex dependencies to check if they are fully on-chain
311
+ if (_getIsFlex(coreContract)) {
312
+ // @dev all flex (V2, V3) contracts have the function projectExternalAssetDependencyCount()
313
+ uint256 externalAssetDependencyCount = IGenArt721CoreContractV3_Engine_Flex(
314
+ coreContract
315
+ ).projectExternalAssetDependencyCount({_projectId: projectId});
316
+ for (uint256 i = 0; i < externalAssetDependencyCount; i++) {
317
+ // get external asset dependency with data
318
+ IGenArt721CoreContractV3_Engine_Flex.ExternalAssetDependencyWithData
319
+ memory externalAssetDependencyWithData = _getProjectExternalAssetDependencyByIndex({
320
+ coreContract: coreContract,
321
+ projectId: projectId,
322
+ index: i
323
+ });
324
+ // if ipfs or arweave, label injectsDecentralizedStorageNetworkAssets as true
325
+ if (
326
+ externalAssetDependencyWithData.dependencyType ==
327
+ IGenArt721CoreContractV3_Engine_Flex
328
+ .ExternalAssetDependencyType
329
+ .IPFS ||
330
+ externalAssetDependencyWithData.dependencyType ==
331
+ IGenArt721CoreContractV3_Engine_Flex
332
+ .ExternalAssetDependencyType
333
+ .ARWEAVE
334
+ ) {
335
+ // if any dependency is IPFS or ARWEAVE, label injectsDecentralizedStorageNetworkAssets as true
336
+ injectsDecentralizedStorageNetworkAssets = true;
337
+ } else if (
338
+ externalAssetDependencyWithData.dependencyType ==
339
+ IGenArt721CoreContractV3_Engine_Flex
340
+ .ExternalAssetDependencyType
341
+ .ART_BLOCKS_DEPENDENCY_REGISTRY
342
+ ) {
343
+ // get the bytes representation of the dependencyRegistryAsset
344
+ bytes32 currentDependencyNameAndVersion = externalAssetDependencyWithData
345
+ .cid
346
+ .stringToBytes32();
347
+ bool currentDependencyFullyOnChain = _getIsDependencyOnChain(
348
+ currentDependencyNameAndVersion
349
+ );
350
+ if (!(currentDependencyFullyOnChain)) {
351
+ // return (true, true, true);
352
+ // // if any dependency is not fully on-chain, label usesDependencyRegistryFlexAssetsNotFullyOnChain as true
353
+ hasOffChainFlexDepRegDependencies = true;
354
+ }
355
+ }
356
+ }
357
+ }
358
+
359
+ // @dev all return values previously populated or remain at initial values of false
360
+ }
361
+
362
+ /**
363
+ * @notice Get a dependency's ABX FS file, base64 encoded: the payload of the gzip data URI
364
+ * the generator inlines.
365
+ * @param abxfsFileCid CID of the dependency's gzip-codec ABX FS file.
366
+ * @return base64 The base64-encoded gzip bytes of the file.
367
+ * @dev Reverts if `abxfsFileCid` is not a gzip-codec file on this chain's ABX FS (the
368
+ * registry checks both when a CID is set; ABX FS content is permanent), or with the
369
+ * FileDataReader's own error if the read fails.
370
+ * @dev The return value is decoded in place. A high-level call copies the returned base64
371
+ * twice into this frame (returndatacopy, then ABI decoding into new memory), and the
372
+ * whole token document is assembled in this frame, where memory cost is quadratic: for
373
+ * Babylon (1.2 MB of base64) the second copy costs about 28M gas, for p5 1.0.0 about 1.4M.
374
+ * FileDataReader returns canonical `abi.encode(mimeType, codec, outputHash, base64)`: a
375
+ * four-word head whose fourth word is the offset of `base64`, which is length-prefixed.
376
+ * The offset and length are bounds-checked against the returned size before use.
377
+ */
378
+ function _getAbxfsFileBase64(
379
+ bytes32 abxfsFileCid
380
+ ) internal view returns (string memory base64) {
381
+ bytes memory callData = abi.encodeCall(
382
+ IAbxfsFileDataReader.readFileDataBase64,
383
+ (abxfsFileCid, type(uint256).max, type(uint256).max)
384
+ );
385
+ address reader = address(ABXFS_FILE_DATA_READER);
386
+ bytes32 codec;
387
+ bool wellFormed;
388
+ assembly ("memory-safe") {
389
+ let ptr := mload(0x40)
390
+ if iszero(
391
+ staticcall(
392
+ gas(),
393
+ reader,
394
+ add(callData, 0x20),
395
+ mload(callData),
396
+ 0,
397
+ 0
398
+ )
399
+ ) {
400
+ returndatacopy(ptr, 0, returndatasize())
401
+ revert(ptr, returndatasize())
402
+ }
403
+ let size := returndatasize()
404
+ returndatacopy(ptr, 0, size)
405
+ // head: [mimeType offset, codec, outputHash, base64 offset]
406
+ if gt(size, 0x7f) {
407
+ codec := mload(add(ptr, 0x20))
408
+ let offset := mload(add(ptr, 0x60))
409
+ if lt(offset, sub(size, 0x1f)) {
410
+ let length := mload(add(ptr, offset))
411
+ if iszero(gt(length, sub(sub(size, offset), 0x20))) {
412
+ wellFormed := 1
413
+ base64 := add(ptr, offset)
414
+ // claim the string's memory, rounded up to a whole word
415
+ mstore(
416
+ 0x40,
417
+ add(
418
+ add(base64, 0x20),
419
+ and(add(length, 0x1f), not(0x1f))
420
+ )
421
+ )
422
+ }
423
+ }
424
+ }
425
+ }
426
+ require(wellFormed, "ABX FS read malformed");
427
+ require(codec == AbxfsCanonical.GZIP_CODEC, "ABX FS file not gzip");
428
+ }
429
+
430
+ /**
431
+ * @notice Get the ABX FS file CID the generator inlines a dependency's script from, or zero.
432
+ * @dev An ES module dependency is never inlined: it is reached through an import map
433
+ * pointing at its preferred CDN, and a gzipped module cannot be loaded from a data URI.
434
+ * @param dependencyDetails The dependency's details from the dependency registry.
435
+ */
436
+ function _getInlinedAbxfsFileCid(
437
+ IDependencyRegistryV0.DependencyDetails memory dependencyDetails
438
+ ) internal pure returns (bytes32) {
439
+ return
440
+ dependencyDetails.loadAsModule
441
+ ? bytes32(0)
442
+ : dependencyDetails.abxfsFileCid;
443
+ }
444
+
445
+ /**
446
+ * @notice Get the project script for a given core contract address and
447
+ * project ID.
448
+ * @param coreContract The address of the core contract to retrieve
449
+ * the project script from.
450
+ * @param projectId The ID of the project to retrieve the script for.
451
+ * @return The project script stiched together from all of the script chunks.
452
+ * @dev This function will revert if the core contract address is not
453
+ * supported by the DependencyRegistry or if the contract at the address
454
+ * does not implement the IGenArt721CoreProjectScriptV0 or IGenArt721CoreProjectScriptV1.
455
+ */
456
+ function _getProjectScriptBytes(
457
+ address coreContract,
458
+ uint256 projectId
459
+ ) internal view returns (bytes memory) {
460
+ _onlySupportedCoreContract(coreContract);
461
+
462
+ // @dev Attempt to get project script info from V3 and up core contracts first.
463
+ try
464
+ IGenArt721CoreProjectScriptV1(coreContract).projectScriptDetails(
465
+ projectId
466
+ )
467
+ returns (string memory, string memory, uint256 scriptCount) {
468
+ if (scriptCount == 0) {
469
+ return "";
470
+ }
471
+
472
+ address[] memory scriptBytecodeAddresses = new address[](
473
+ scriptCount
474
+ );
475
+
476
+ for (uint256 i = 0; i < scriptCount; i++) {
477
+ scriptBytecodeAddresses[i] = IGenArt721CoreProjectScriptV1(
478
+ coreContract
479
+ ).projectScriptBytecodeAddressByIndex(projectId, i);
480
+ }
481
+
482
+ // @dev We concatenate the script chunks together with assembly
483
+ // in AddressChunks for gas efficiency.
484
+ return
485
+ AddressChunks.mergeChunks(
486
+ scriptBytecodeAddresses,
487
+ address(universalBytecodeStorageReader)
488
+ );
489
+ } catch {
490
+ // Noop try again for older contracts.
491
+ }
492
+
493
+ // @dev If we failed to get the project script info try again using the interface
494
+ // for V2 and older core contracts.
495
+ try
496
+ IGenArt721CoreProjectScriptV0(coreContract).projectScriptInfo(
497
+ projectId
498
+ )
499
+ returns (string memory, uint256 scriptCount) {
500
+ if (scriptCount == 0) {
501
+ return "";
502
+ }
503
+
504
+ string memory script;
505
+ for (uint256 i = 0; i < scriptCount; i++) {
506
+ string memory scriptChunk = IGenArt721CoreProjectScriptV0(
507
+ coreContract
508
+ ).projectScriptByIndex(projectId, i);
509
+ script = string.concat(script, scriptChunk);
510
+ }
511
+
512
+ return bytes(script);
513
+ } catch {
514
+ revert("Unable to retrieve project script info");
515
+ }
516
+ }
517
+
518
+ /**
519
+ * @notice Get the isFlex status for a given core contract.
520
+ * @dev uses the existence of preferredIPFSGateway function as indicator for flex contracts.
521
+ * @param coreContract The core contract address to check if it is a flex contract.
522
+ */
523
+ function _getIsFlex(address coreContract) internal view returns (bool) {
524
+ try
525
+ // @dev all flex (V2, V3) contracts have this function, so use as isFlex indicator
526
+ IGenArt721CoreContractV3_Engine_Flex(coreContract)
527
+ .preferredIPFSGateway()
528
+ returns (string memory) {
529
+ // if contract did not revert, interpret it is a flex contract
530
+ return true;
531
+ } catch {
532
+ // if contract reverted, interpret it is not a flex contract
533
+ return false;
534
+ }
535
+ }
536
+
537
+ /**
538
+ * @notice Get if a flex contract is a V2 flex contract.
539
+ * Assumes that the core contract is a flex contract.
540
+ * @param flexCoreContract The core contract address to check if it is a V2 flex contract.
541
+ * @return isV2Flex Whether the core contract is a V2 flex contract.
542
+ */
543
+ function _getIsV2Flex(
544
+ address flexCoreContract
545
+ ) internal view returns (bool) {
546
+ // @dev all flex (V2, V3) contracts have the function coreType(),
547
+ // and all V2 flex contracts have the coreType "GenArt721CoreV2_ENGINE_FLEX"
548
+ string memory coreType = IGenArt721CoreContractV3_Engine_Flex(
549
+ flexCoreContract
550
+ ).coreType();
551
+ return
552
+ keccak256(abi.encodePacked(coreType)) ==
553
+ keccak256(abi.encodePacked("GenArt721CoreV2_ENGINE_FLEX"));
554
+ }
555
+
556
+ /**
557
+ * @notice Get the external asset dependency for a given project and index.
558
+ * @dev This function handles both V2 and V3 flex contracts, and converts the legacy V2 external asset dependency
559
+ * type to the V3 external asset dependency type, as the V3 type is a superset of the V2 type.
560
+ * @param coreContract The core contract address the project belongs to.
561
+ * @param projectId The ID of the project to retrieve the external asset dependency for.
562
+ * @param index The index of the external asset dependency to retrieve.
563
+ * @return The external asset dependency for the project and index.
564
+ */
565
+ function _getProjectExternalAssetDependencyByIndex(
566
+ address coreContract,
567
+ uint256 projectId,
568
+ uint256 index
569
+ )
570
+ internal
571
+ view
572
+ returns (
573
+ IGenArt721CoreContractV3_Engine_Flex.ExternalAssetDependencyWithData
574
+ memory
575
+ )
576
+ {
577
+ // pre-allocate generic externalAssetDependencyWithData to avoid dynamic memory allocation
578
+ IGenArt721CoreContractV3_Engine_Flex.ExternalAssetDependencyWithData
579
+ memory externalAssetDependencyWithData = IGenArt721CoreContractV3_Engine_Flex
580
+ .ExternalAssetDependencyWithData({
581
+ cid: "",
582
+ dependencyType: IGenArt721CoreContractV3_Engine_Flex
583
+ .ExternalAssetDependencyType
584
+ .IPFS, // default to IPFS, index 0 of enum
585
+ bytecodeAddress: address(0),
586
+ data: ""
587
+ });
588
+ // @dev flex V2 and V3 have different return types for the function projectExternalAssetDependencyByIndex - must branch logic
589
+ // @dev reference change in return type between V2 and V3 here: https://github.com/ArtBlocks/artblocks-contracts/pull/450
590
+ // @dev acknowledge that this could be function input parameter to avoid one call per dependency, but
591
+ // stack to deep error limits memoization opportunity in functions calling this function
592
+ if (_getIsV2Flex(coreContract)) {
593
+ ILegacyGenArt721CoreV2_PBAB_Flex.LegacyExternalAssetDependencyWithoutData
594
+ memory legacyExternalAssetDependencyWithoutData = ILegacyGenArt721CoreV2_PBAB_Flex(
595
+ coreContract
596
+ ).projectExternalAssetDependencyByIndex({
597
+ _projectId: projectId,
598
+ _index: index
599
+ });
600
+ // populate external asset dependency json object
601
+ externalAssetDependencyWithData
602
+ .cid = legacyExternalAssetDependencyWithoutData.cid;
603
+ // @dev legacy external asset dependency types are a subset of V3 external asset dependency types,
604
+ // so we can safely cast the legacy type to the V3 type
605
+ externalAssetDependencyWithData
606
+ .dependencyType = IGenArt721CoreContractV3_Engine_Flex
607
+ .ExternalAssetDependencyType(
608
+ uint256(
609
+ legacyExternalAssetDependencyWithoutData.dependencyType
610
+ )
611
+ );
612
+ // leave data as empty string - V2 contracts do not support data
613
+ } else {
614
+ externalAssetDependencyWithData = IGenArt721CoreContractV3_Engine_Flex(
615
+ coreContract
616
+ ).projectExternalAssetDependencyByIndex({
617
+ _projectId: projectId,
618
+ _index: index
619
+ });
620
+ }
621
+ return externalAssetDependencyWithData;
622
+ }
623
+
624
+ /**
625
+ * @notice get external asset dependency and populate json keys and values,
626
+ * as well as any dependency name and version if the dependency is an
627
+ * ART_BLOCKS_DEPENDENCY_REGISTRY dependency.
628
+ * @param coreContract The core contract address the project belongs to.
629
+ * @param tokenId The ID of the token to retrieve the external asset dependency for.
630
+ * @param index The index of the external asset dependency to retrieve.
631
+ */
632
+ function _getExternalAssetDependencyKeysAndValues(
633
+ address coreContract,
634
+ uint256 tokenId,
635
+ uint256 index
636
+ )
637
+ internal
638
+ view
639
+ returns (
640
+ string[] memory /*keys*/,
641
+ JsonStatic.Json[] memory /*values*/,
642
+ bytes32 /*dependencyNameAndVersion*/
643
+ )
644
+ {
645
+ // get project id from token id
646
+ uint256 projectId = ABHelpers.tokenIdToProjectId(tokenId);
647
+ // default as not an art blocks dependency registry dependency
648
+ bytes32 dependencyNameAndVersion; // default as not an art blocks dependency registry dependency
649
+ // each external asset dependency has 3 fields, so pre-allocate array to avoid dynamic memory allocation
650
+ JsonStatic.Json[] memory dependencyValues = JsonStatic.newValuesArray(
651
+ 3
652
+ );
653
+ string[] memory dependencyKeys = JsonStatic.newKeysArray(3);
654
+ // get external asset dependency with data
655
+ IGenArt721CoreContractV3_Engine_Flex.ExternalAssetDependencyWithData
656
+ memory externalAssetDependencyWithData = _getProjectExternalAssetDependencyByIndex({
657
+ coreContract: coreContract,
658
+ projectId: projectId,
659
+ index: index
660
+ });
661
+ // populate external asset dependency json object
662
+ dependencyKeys[0] = "dependency_type";
663
+ dependencyValues[0] = JsonStatic.newStringElement({
664
+ value: _dependencyTypeToString(
665
+ externalAssetDependencyWithData.dependencyType
666
+ ),
667
+ stringEncodingFlag: JsonStatic.StringEncodingFlag.NONE
668
+ });
669
+ dependencyKeys[1] = "cid";
670
+ dependencyValues[1] = JsonStatic.newStringElement({
671
+ value: externalAssetDependencyWithData.cid,
672
+ stringEncodingFlag: JsonStatic.StringEncodingFlag.NONE
673
+ });
674
+ dependencyKeys[2] = "data";
675
+ if (
676
+ externalAssetDependencyWithData.dependencyType ==
677
+ IGenArt721CoreContractV3_Engine_Flex
678
+ .ExternalAssetDependencyType
679
+ .ONCHAIN
680
+ ) {
681
+ if (
682
+ keccak256(
683
+ abi.encodePacked(externalAssetDependencyWithData.data)
684
+ ) == keccak256(abi.encodePacked("#web3call_contract#")) // @dev special string indicating a web3call contract
685
+ ) {
686
+ // treat as a web3call contract, inject token parameters based on the web3call contract
687
+ // @dev prepend with "#web3call#" to indicate that the data should be decoded as a web3call
688
+ // with base64 encoded key/value pairs
689
+ dependencyValues[2] = JsonStatic.newStringElement({
690
+ value: string.concat(
691
+ "#web3call#",
692
+ _getWeb3CallParameters({
693
+ web3callContract: externalAssetDependencyWithData
694
+ .bytecodeAddress,
695
+ coreContract: coreContract,
696
+ tokenId: tokenId
697
+ })
698
+ ),
699
+ stringEncodingFlag: JsonStatic.StringEncodingFlag.NONE // we base64 encode everything in the _getWeb3CallParameters function
700
+ });
701
+ } else {
702
+ // @dev typical ONCHAIN dependency, assign data for ONCHAIN dependencies
703
+ dependencyValues[2] = JsonStatic.newStringElement({
704
+ value: externalAssetDependencyWithData.data,
705
+ stringEncodingFlag: JsonStatic.StringEncodingFlag.BASE64
706
+ });
707
+ }
708
+ } else {
709
+ dependencyValues[2] = JsonStatic.newStringElement({
710
+ value: "", // empty string for non-ONCHAIN dependencies
711
+ stringEncodingFlag: JsonStatic.StringEncodingFlag.BASE64
712
+ });
713
+ if (
714
+ externalAssetDependencyWithData.dependencyType ==
715
+ IGenArt721CoreContractV3_Engine_Flex
716
+ .ExternalAssetDependencyType
717
+ .ART_BLOCKS_DEPENDENCY_REGISTRY
718
+ ) {
719
+ // get the bytes representation of the dependencyRegistryAsset
720
+ dependencyNameAndVersion = externalAssetDependencyWithData
721
+ .cid
722
+ .stringToBytes32();
723
+ }
724
+ }
725
+ return (dependencyKeys, dependencyValues, dependencyNameAndVersion);
726
+ }
727
+
728
+ /**
729
+ * @notice Get the token data for a given token.
730
+ * @param coreContract The core contract address the token belongs to.
731
+ * @param tokenId The ID of the token to retrieve the data for.
732
+ * @return tokenDataJson The token data as a JSON string as bytes.
733
+ * @return dependencyRegistryAssetNameAndVersions Any dependency registry asset name and versions
734
+ * as bytes32 (will contain default-value bytes32 if not an ART_BLOCKS_DEPENDENCY_REGISTRY dependency).
735
+ */
736
+ function _getTokenDataAndDependencyRegistryAssets(
737
+ address coreContract,
738
+ uint256 tokenId
739
+ )
740
+ internal
741
+ view
742
+ returns (
743
+ bytes memory tokenDataJson,
744
+ bytes32[] memory dependencyRegistryAssetNameAndVersions
745
+ )
746
+ {
747
+ // get any flex assets
748
+ bool isFlex = _getIsFlex({coreContract: coreContract});
749
+
750
+ // build tokenData json object
751
+ string[] memory tokenDataKeys = isFlex
752
+ ? JsonStatic.newKeysArray(5)
753
+ : JsonStatic.newKeysArray(2);
754
+ JsonStatic.Json[] memory tokenDataValues = isFlex
755
+ ? JsonStatic.newValuesArray(5)
756
+ : JsonStatic.newValuesArray(2);
757
+
758
+ // token id
759
+ tokenDataKeys[0] = "tokenId";
760
+ tokenDataValues[0] = JsonStatic.newStringElement({
761
+ value: Strings.toString(tokenId),
762
+ stringEncodingFlag: JsonStatic.StringEncodingFlag.NONE
763
+ });
764
+
765
+ // token hash
766
+ // @dev block scope to avoid stack too deep error
767
+ {
768
+ // @dev Attempt to get token hash from V1 and up core contracts first.
769
+ (bytes32 tokenHash, bool isV0CoreContract) = _getTokenHash(
770
+ coreContract,
771
+ tokenId
772
+ );
773
+ if (isV0CoreContract) {
774
+ // @dev V0 contracts return an array of hashes, with only one hash
775
+ tokenDataKeys[1] = "hashes";
776
+ JsonStatic.Json[] memory tokenDataValuesHashes = JsonStatic
777
+ .newValuesArray(1);
778
+ tokenDataValuesHashes[0] = JsonStatic.newStringElement({
779
+ value: Strings.toHexString(uint256(tokenHash)),
780
+ stringEncodingFlag: JsonStatic.StringEncodingFlag.NONE
781
+ });
782
+ tokenDataValues[1] = JsonStatic.newArrayElement({
783
+ values: tokenDataValuesHashes
784
+ });
785
+ } else {
786
+ tokenDataKeys[1] = "hash";
787
+ tokenDataValues[1] = JsonStatic.newStringElement({
788
+ value: Strings.toHexString(uint256(tokenHash)),
789
+ stringEncodingFlag: JsonStatic.StringEncodingFlag.NONE
790
+ });
791
+ }
792
+ }
793
+
794
+ // flex contracts have additional fields
795
+ dependencyRegistryAssetNameAndVersions = new bytes32[](0); // default if no assets or not flex
796
+ if (isFlex) {
797
+ // preferredIPFSGateway
798
+ tokenDataKeys[2] = "preferredArweaveGateway";
799
+ // @dev all flex (V2, V3) contracts have the function preferredArweaveGateway()
800
+ tokenDataValues[2] = JsonStatic.newStringElement({
801
+ value: IGenArt721CoreContractV3_Engine_Flex(coreContract)
802
+ .preferredArweaveGateway(),
803
+ stringEncodingFlag: JsonStatic.StringEncodingFlag.NONE
804
+ });
805
+
806
+ // preferredArweaveGateway
807
+ tokenDataKeys[3] = "preferredIPFSGateway";
808
+ // @dev all flex (V2, V3) contracts have the function preferredIPFSGateway()
809
+ tokenDataValues[3] = JsonStatic.newStringElement({
810
+ value: IGenArt721CoreContractV3_Engine_Flex(coreContract)
811
+ .preferredIPFSGateway(),
812
+ stringEncodingFlag: JsonStatic.StringEncodingFlag.NONE
813
+ });
814
+
815
+ // externalAssetDependencies (variable length array)
816
+ tokenDataKeys[4] = "externalAssetDependencies";
817
+ // @dev pre-allocate array to avoid dynamic memory allocation of variable-length array
818
+ uint256 projectId = ABHelpers.tokenIdToProjectId(tokenId);
819
+ // @dev all flex (V2, V3) contracts have the function projectExternalAssetDependencyCount()
820
+ uint256 externalAssetDependencyCount = IGenArt721CoreContractV3_Engine_Flex(
821
+ coreContract
822
+ ).projectExternalAssetDependencyCount({_projectId: projectId});
823
+ JsonStatic.Json[] memory externalAssetDependencies = JsonStatic
824
+ .newValuesArray(externalAssetDependencyCount);
825
+ // populate the type and version of all ART_BLOCKS_DEPENDENCY_REGISTRY dependencies
826
+ dependencyRegistryAssetNameAndVersions = new bytes32[](
827
+ externalAssetDependencyCount
828
+ );
829
+ for (uint256 i = 0; i < externalAssetDependencyCount; i++) {
830
+ (
831
+ string[] memory dependencyKeys,
832
+ JsonStatic.Json[] memory dependencyValues,
833
+ bytes32 dependencyNameAndVersion
834
+ ) = _getExternalAssetDependencyKeysAndValues({
835
+ coreContract: coreContract,
836
+ tokenId: tokenId,
837
+ index: i
838
+ });
839
+ // handle ART_BLOCKS_DEPENDENCY_REGISTRY dependency type
840
+ if (dependencyNameAndVersion != bytes32(0)) {
841
+ dependencyRegistryAssetNameAndVersions[
842
+ i
843
+ ] = dependencyNameAndVersion;
844
+ }
845
+
846
+ // build tokenData json object
847
+ externalAssetDependencies[i] = JsonStatic.newObjectElement({
848
+ keys: dependencyKeys,
849
+ values: dependencyValues
850
+ });
851
+ }
852
+
853
+ // assign externalAssetDependencies array to tokenDataValues
854
+ tokenDataValues[4] = JsonStatic.newArrayElement(
855
+ externalAssetDependencies
856
+ );
857
+ }
858
+
859
+ // build tokenData json object
860
+ JsonStatic.Json memory tokenData = JsonStatic.newObjectElement({
861
+ keys: tokenDataKeys,
862
+ values: tokenDataValues
863
+ });
864
+
865
+ // return tokenData as bytes-encoded JSON string via write function
866
+ return (
867
+ bytes(tokenData.write()),
868
+ dependencyRegistryAssetNameAndVersions
869
+ );
870
+ }
871
+
872
+ /**
873
+ * @notice populates an empty HTMLTag with script information for a given dependency.
874
+ * Assumes the dependency is available on the dependencyRegistry.
875
+ * Inlines the dependency's ABX FS file if it has one - otherwise injects script tag with src
876
+ * pointing to the preferred CDN.
877
+ * @param dependencyNameAndVersion The name and version of the dependency to populate the script for.
878
+ * @param htmlTag The HTMLTag to populate with the script information, memory reference; modified in place.
879
+ */
880
+ function _populateDependencyScriptHtmlTag(
881
+ bytes32 dependencyNameAndVersion,
882
+ HTMLTag memory htmlTag
883
+ ) internal view {
884
+ // Get ABX FS file and preferred CDN for the dependency.
885
+ IDependencyRegistryV0.DependencyDetails
886
+ memory dependencyDetails = dependencyRegistry
887
+ .getDependencyDetailsV2(dependencyNameAndVersion);
888
+ string memory preferredCDN = dependencyDetails.preferredCDN;
889
+ bytes32 abxfsFileCid = _getInlinedAbxfsFileCid(dependencyDetails);
890
+
891
+ // If not on chain, load the script from the preferred CDN.
892
+ if (abxfsFileCid == bytes32(0)) {
893
+ bool cdnAvailable = bytes(preferredCDN).length > 0;
894
+ // If no CDN is available, we don't need to add any tags.
895
+ // Expected for dependencies like "js@na" and "svg@na".
896
+ htmlTag.tagOpen = cdnAvailable
897
+ ? abi.encodePacked(
898
+ '<script type="text/javascript" src="',
899
+ preferredCDN,
900
+ '">'
901
+ )
902
+ : bytes("");
903
+ htmlTag.tagClose = bytes(cdnAvailable ? "</script>" : "");
904
+ } else {
905
+ // @dev the gunzip script inflates the gzip data URI in the browser
906
+ htmlTag.tagContent = bytes(_getAbxfsFileBase64(abxfsFileCid));
907
+ htmlTag.tagType = HTMLTagType.scriptGZIPBase64DataURI; // <script type="text/javascript+gzip" src="data:text/javascript;base64,[script]"></script>
908
+ }
909
+ }
910
+
911
+ /**
912
+ * @notice Get the HTMLRequest for a given token.
913
+ * @param coreContract The core contract address the token belongs to.
914
+ * @param tokenId The ID of the token to retrieve the HTMLRequest for.
915
+ * @return The HTMLRequest for the token.
916
+ */
917
+ function _getTokenHtmlRequest(
918
+ address coreContract,
919
+ uint256 tokenId
920
+ ) internal view returns (HTMLRequest memory) {
921
+ _onlySupportedCoreContract(coreContract);
922
+
923
+ uint256 projectId = ABHelpers.tokenIdToProjectId(tokenId);
924
+ // This will revert for older contracts that do not have an override set.
925
+ bytes32 dependencyNameAndVersion = dependencyRegistry
926
+ .getDependencyNameAndVersionForProject(coreContract, projectId)
927
+ .stringToBytes32();
928
+
929
+ // @dev All rendering directives are prescribed by the dependency registry, so that
930
+ // supporting a new kind of dependency is an admin configuration change rather than a
931
+ // contract upgrade.
932
+ IDependencyRegistryV0.DependencyDetails
933
+ memory dependencyDetails = dependencyRegistry
934
+ .getDependencyDetailsV2(dependencyNameAndVersion);
935
+
936
+ // @dev A raw HTML dependency stores a complete HTML document as its project script
937
+ // rather than a JavaScript program. Such a document must be injected verbatim -
938
+ // wrapping it in a script tag both breaks HTML parsing (the document's own
939
+ // "</script>" terminates the wrapper early) and is semantically wrong, since markup
940
+ // inside a script tag is never rendered.
941
+ bool isRawHtmlDep = dependencyDetails.projectScriptTagType ==
942
+ IDependencyRegistryV0.ProjectScriptTagType.RawHtml;
943
+
944
+ // Create head tags
945
+ // pre-fetch data to properly allocate memory for HTML tags
946
+ (
947
+ bytes memory tokenDataJson,
948
+ bytes32[] memory dependencyRegistryAssetNameAndVersions
949
+ ) = _getTokenDataAndDependencyRegistryAssets({
950
+ coreContract: coreContract,
951
+ tokenId: tokenId
952
+ });
953
+ // @dev memoize length for efficiency
954
+ uint256 dependencyRegistryAssetNamesAndVersionsLength = dependencyRegistryAssetNameAndVersions
955
+ .length;
956
+ // @dev length is 3 (style, tokenData, import map) + number of external asset dependencies
957
+ HTMLTag[] memory headTags = new HTMLTag[](
958
+ 3 + dependencyRegistryAssetNamesAndVersionsLength
959
+ );
960
+ // @dev The default style reset is omitted for raw HTML documents, which supply
961
+ // their own document-level styling. This matches Art Blocks' hosted generator.
962
+ if (!isRawHtmlDep) {
963
+ headTags[0].tagOpen = "<style>";
964
+ headTags[0]
965
+ .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}";
966
+ headTags[0].tagClose = "</style>";
967
+ }
968
+
969
+ // @dev decode any base64 encoded flex data in the browser while parsing the json
970
+ headTags[1].tagContent = abi.encodePacked(
971
+ "let tokenData = JSON.parse(`",
972
+ tokenDataJson,
973
+ '`, (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);'
974
+ );
975
+ headTags[1].tagType = HTMLTagType.script;
976
+
977
+ // @dev An ES module dependency cannot be loaded with a plain script tag, and project
978
+ // scripts import it by bare specifier (e.g. `import * as THREE from "three"`). An
979
+ // import map maps that specifier to the dependency's URL, and must appear in the head
980
+ // before any module is loaded.
981
+ _populateImportMapHtmlTag({
982
+ dependencyNameAndVersion: dependencyNameAndVersion,
983
+ dependencyDetails: dependencyDetails,
984
+ htmlTag: headTags[2]
985
+ });
986
+
987
+ for (
988
+ uint256 i = 0;
989
+ i < dependencyRegistryAssetNamesAndVersionsLength;
990
+ i++
991
+ ) {
992
+ // skip if empty (not a dependency registry asset)
993
+ // @dev okay to have empty html tags - they will be ignored
994
+ if (dependencyRegistryAssetNameAndVersions[i] == bytes32(0)) {
995
+ continue;
996
+ }
997
+ // populate head tags with dependency registry scripts
998
+ _populateDependencyScriptHtmlTag(
999
+ dependencyRegistryAssetNameAndVersions[i],
1000
+ headTags[3 + i]
1001
+ );
1002
+ }
1003
+
1004
+ // Create body tags
1005
+ HTMLTag[] memory bodyTags = new HTMLTag[](4);
1006
+
1007
+ // Dependency script tag
1008
+ // @dev A module dependency is reached through the import map emitted in the head, so
1009
+ // emitting a script tag for it here would load the module as a classic script and
1010
+ // raise a syntax error on its `export` statements.
1011
+ if (!dependencyDetails.loadAsModule) {
1012
+ _populateDependencyScriptHtmlTag(
1013
+ dependencyNameAndVersion,
1014
+ bodyTags[0]
1015
+ );
1016
+ }
1017
+
1018
+ // @dev We expect all of our dependencies to be added gzip'd and base64 encoded
1019
+ // so we need to include this so we can gunzip them in the browser.
1020
+ bodyTags[1].name = "gunzipScripts-0.0.1.js";
1021
+ bodyTags[1].tagType = HTMLTagType.scriptBase64DataURI; // <script src="data:text/javascript;base64,[script]"></script>
1022
+ bodyTags[1].tagContent = bytes(
1023
+ universalBytecodeStorageReader.readFromBytecode(
1024
+ gunzipScriptBytecodeAddress
1025
+ )
1026
+ );
1027
+
1028
+ HTMLTag memory canvasTag = _createCanvasTagIfNeeded(
1029
+ dependencyNameAndVersion,
1030
+ dependencyDetails.canvasTagType
1031
+ );
1032
+
1033
+ bytes memory projectScript = _getProjectScriptBytes(
1034
+ coreContract,
1035
+ projectId
1036
+ );
1037
+
1038
+ HTMLTag memory projectScriptTag = HTMLTag({
1039
+ tagOpen: _getProjectScriptTagOpen(dependencyDetails),
1040
+ tagClose: isRawHtmlDep ? bytes("") : bytes("</script>"),
1041
+ tagType: HTMLTagType.useTagOpenAndClose,
1042
+ name: "",
1043
+ contractAddress: address(0),
1044
+ contractData: "",
1045
+ tagContent: projectScript
1046
+ });
1047
+
1048
+ if (
1049
+ dependencyDetails.canvasTagType ==
1050
+ IDependencyRegistryV0.CanvasTagType.CanvasAfterProjectScript
1051
+ ) {
1052
+ bodyTags[2] = projectScriptTag;
1053
+ bodyTags[3] = canvasTag;
1054
+ } else {
1055
+ bodyTags[2] = canvasTag;
1056
+ bodyTags[3] = projectScriptTag;
1057
+ }
1058
+
1059
+ HTMLRequest memory htmlRequest;
1060
+ htmlRequest.headTags = headTags;
1061
+ htmlRequest.bodyTags = bodyTags;
1062
+
1063
+ return htmlRequest;
1064
+ }
1065
+
1066
+ /**
1067
+ * @dev Helper function to get token hash with fallback support
1068
+ * @return tokenHash The hash for the token
1069
+ * @return isV0CoreContract Whether the contract is a V0 core contract
1070
+ */
1071
+ function _getTokenHash(
1072
+ address coreContract,
1073
+ uint256 tokenId
1074
+ ) private view returns (bytes32 tokenHash, bool isV0CoreContract) {
1075
+ // Try V1+ contracts first
1076
+ try
1077
+ IGenArt721CoreTokenHashProviderV1(coreContract).tokenIdToHash(
1078
+ tokenId
1079
+ )
1080
+ returns (bytes32 hash) {
1081
+ if (hash != bytes32(0)) {
1082
+ return (hash, false);
1083
+ }
1084
+ } catch {}
1085
+
1086
+ // Fallback to V0 contracts
1087
+ try
1088
+ IGenArt721CoreTokenHashProviderV0(coreContract).showTokenHashes(
1089
+ tokenId
1090
+ )
1091
+ returns (bytes32[] memory hashes) {
1092
+ require(hashes[0] != bytes32(0), "Invalid token hash");
1093
+ return (hashes[0], true);
1094
+ } catch {
1095
+ revert("Unable to retrieve token hash");
1096
+ }
1097
+ }
1098
+
1099
+ /**
1100
+ * @dev Helper function to check if a dependency is on chain: it has an ABX FS file, which the
1101
+ * generator inlines (ES module dependencies are loaded from their CDN, so are not on chain).
1102
+ * @param dependencyNameAndVersion The name and version of the dependency to check.
1103
+ */
1104
+ function _getIsDependencyOnChain(
1105
+ bytes32 dependencyNameAndVersion
1106
+ ) internal view returns (bool availableOnChain) {
1107
+ // special case for "js@na" and "svg@na" - consider fully on chain
1108
+ if (
1109
+ dependencyNameAndVersion == JS_AT_NA_BYTES32 ||
1110
+ dependencyNameAndVersion == SVG_AT_NA_BYTES32
1111
+ ) {
1112
+ return true;
1113
+ }
1114
+ // query dependency registry for on-chain status
1115
+ IDependencyRegistryV0.DependencyDetails
1116
+ memory dependencyDetails = dependencyRegistry
1117
+ .getDependencyDetailsV2(dependencyNameAndVersion);
1118
+ return _getInlinedAbxfsFileCid(dependencyDetails) != bytes32(0);
1119
+ }
1120
+
1121
+ /**
1122
+ * @dev Helper function to get the web3call parameters for a given token.
1123
+ * Assumes the contract supports the IWeb3Call interface.
1124
+ * @param web3callContract The address of the contract to call.
1125
+ * @param coreContract The address of the core contract.
1126
+ * @param tokenId The ID of the token.
1127
+ * @return The web3call parameters for the token as a json string, keys and values encoded
1128
+ * as base64 strings, then the entire json string is encoded as base64.
1129
+ */
1130
+ function _getWeb3CallParameters(
1131
+ address web3callContract,
1132
+ address coreContract,
1133
+ uint256 tokenId
1134
+ ) internal view returns (string memory) {
1135
+ // get the onchain data for the contract
1136
+ IWeb3Call.TokenParam[] memory tokenParams = IWeb3Call(web3callContract)
1137
+ .getTokenParams({coreContract: coreContract, tokenId: tokenId});
1138
+ uint256 tokenParamsLength = tokenParams.length;
1139
+ // build key/value arrays for the token params
1140
+ string[] memory keys = JsonStatic.newKeysArray(tokenParamsLength);
1141
+ JsonStatic.Json[] memory values = JsonStatic.newValuesArray(
1142
+ tokenParamsLength
1143
+ );
1144
+ for (uint256 i = 0; i < tokenParamsLength; i++) {
1145
+ // @dev encode the key here as base64 string, to handle any special characters
1146
+ IWeb3Call.TokenParam memory tokenParam = tokenParams[i];
1147
+ keys[i] = Base64.encode(bytes(tokenParam.key));
1148
+ values[i] = JsonStatic.newStringElement({
1149
+ value: (tokenParam.value),
1150
+ stringEncodingFlag: JsonStatic.StringEncodingFlag.BASE64
1151
+ });
1152
+ }
1153
+ // use JsonStatic to build a printable json object from the key/value arrays
1154
+ JsonStatic.Json memory tokenParamsJson = JsonStatic.newObjectElement({
1155
+ keys: keys,
1156
+ values: values
1157
+ });
1158
+ // @dev base64 encode the entire json object for consistent encoding of data field
1159
+ return Base64.encode(bytes(tokenParamsJson.write()));
1160
+ }
1161
+
1162
+ /**
1163
+ * @dev Helper function to extract the dependency name preceding the "@" separator.
1164
+ * @param dependencyNameAndVersion Dependency identifier of the form "name@version".
1165
+ * @return The dependency name, e.g. "three" for "three@0.167.0".
1166
+ */
1167
+ function _getDependencyName(
1168
+ bytes32 dependencyNameAndVersion
1169
+ ) internal pure returns (bytes memory) {
1170
+ uint atSignIndex;
1171
+ for (uint i = 0; i < dependencyNameAndVersion.length; i++) {
1172
+ if (dependencyNameAndVersion[i] == "@") {
1173
+ atSignIndex = i;
1174
+ break;
1175
+ }
1176
+ }
1177
+
1178
+ bytes memory nameBeforeAt = new bytes(atSignIndex);
1179
+ for (uint i = 0; i < atSignIndex; i++) {
1180
+ nameBeforeAt[i] = dependencyNameAndVersion[i];
1181
+ }
1182
+ return nameBeforeAt;
1183
+ }
1184
+
1185
+ /**
1186
+ * @dev Helper function to build the opening tag wrapping a project's script.
1187
+ * @param dependencyDetails Details of the project's dependency, prescribing how the
1188
+ * project script must be injected.
1189
+ * @return The opening tag, or an empty value when the script is raw HTML.
1190
+ */
1191
+ function _getProjectScriptTagOpen(
1192
+ IDependencyRegistryV0.DependencyDetails memory dependencyDetails
1193
+ ) internal pure returns (bytes memory) {
1194
+ IDependencyRegistryV0.ProjectScriptTagType tagType = dependencyDetails
1195
+ .projectScriptTagType;
1196
+ if (tagType == IDependencyRegistryV0.ProjectScriptTagType.RawHtml) {
1197
+ return bytes("");
1198
+ }
1199
+ if (tagType == IDependencyRegistryV0.ProjectScriptTagType.Module) {
1200
+ return bytes('<script type="module">');
1201
+ }
1202
+ if (tagType == IDependencyRegistryV0.ProjectScriptTagType.SpecialType) {
1203
+ return
1204
+ abi.encodePacked(
1205
+ "<script type='",
1206
+ dependencyDetails.projectScriptSpecialType,
1207
+ "'>"
1208
+ );
1209
+ }
1210
+ return bytes("<script>");
1211
+ }
1212
+
1213
+ /**
1214
+ * @dev Helper function to populate an import map tag, which maps a module dependency's
1215
+ * bare specifier (its name) to the URL the module is served from. Left empty for
1216
+ * dependencies that are not loaded as modules.
1217
+ * @param dependencyNameAndVersion Dependency identifier of the form "name@version".
1218
+ * @param dependencyDetails Details of the dependency.
1219
+ * @param htmlTag The HTMLTag to populate.
1220
+ */
1221
+ function _populateImportMapHtmlTag(
1222
+ bytes32 dependencyNameAndVersion,
1223
+ IDependencyRegistryV0.DependencyDetails memory dependencyDetails,
1224
+ HTMLTag memory htmlTag
1225
+ ) internal pure {
1226
+ if (!dependencyDetails.loadAsModule) {
1227
+ return;
1228
+ }
1229
+
1230
+ htmlTag.tagType = HTMLTagType.useTagOpenAndClose;
1231
+ htmlTag.tagOpen = abi.encodePacked(
1232
+ '<script type="importmap">{"imports":{"',
1233
+ _getDependencyName(dependencyNameAndVersion),
1234
+ '":"',
1235
+ dependencyDetails.preferredCDN,
1236
+ '"}}'
1237
+ );
1238
+ htmlTag.tagClose = bytes("</script>");
1239
+ }
1240
+
1241
+ /**
1242
+ * @dev Helper function to get a canvas tag or an empty tag, per the dependency's
1243
+ * registry-prescribed canvas requirement.
1244
+ * @param dependencyNameAndVersion Dependency identifier, used to name the canvas element.
1245
+ * @param canvasTagType Whether a canvas is required.
1246
+ * @return The canvas tag or an empty tag.
1247
+ */
1248
+ function _createCanvasTagIfNeeded(
1249
+ bytes32 dependencyNameAndVersion,
1250
+ IDependencyRegistryV0.CanvasTagType canvasTagType
1251
+ ) internal pure returns (HTMLTag memory) {
1252
+ if (canvasTagType != IDependencyRegistryV0.CanvasTagType.NoCanvasTag) {
1253
+ return
1254
+ HTMLTag({
1255
+ tagOpen: abi.encodePacked(
1256
+ "<canvas id='",
1257
+ _getDependencyName(dependencyNameAndVersion),
1258
+ "-canvas'>"
1259
+ ),
1260
+ tagClose: bytes("</canvas>"),
1261
+ tagType: HTMLTagType.useTagOpenAndClose,
1262
+ name: "",
1263
+ contractAddress: address(0),
1264
+ contractData: "",
1265
+ tagContent: ""
1266
+ });
1267
+ } else {
1268
+ return
1269
+ HTMLTag({
1270
+ tagOpen: "",
1271
+ tagClose: "",
1272
+ tagType: HTMLTagType.useTagOpenAndClose,
1273
+ name: "",
1274
+ contractAddress: address(0),
1275
+ contractData: "",
1276
+ tagContent: ""
1277
+ });
1278
+ }
1279
+ }
1280
+
1281
+ function _dependencyTypeToString(
1282
+ IGenArt721CoreContractV3_Engine_Flex.ExternalAssetDependencyType dependencyType
1283
+ ) internal pure returns (string memory) {
1284
+ if (
1285
+ dependencyType ==
1286
+ IGenArt721CoreContractV3_Engine_Flex
1287
+ .ExternalAssetDependencyType
1288
+ .IPFS
1289
+ ) {
1290
+ return "IPFS";
1291
+ } else if (
1292
+ dependencyType ==
1293
+ IGenArt721CoreContractV3_Engine_Flex
1294
+ .ExternalAssetDependencyType
1295
+ .ARWEAVE
1296
+ ) {
1297
+ return "ARWEAVE";
1298
+ } else if (
1299
+ dependencyType ==
1300
+ IGenArt721CoreContractV3_Engine_Flex
1301
+ .ExternalAssetDependencyType
1302
+ .ONCHAIN
1303
+ ) {
1304
+ return "ONCHAIN";
1305
+ } else if (
1306
+ dependencyType ==
1307
+ IGenArt721CoreContractV3_Engine_Flex
1308
+ .ExternalAssetDependencyType
1309
+ .ART_BLOCKS_DEPENDENCY_REGISTRY
1310
+ ) {
1311
+ return "ART_BLOCKS_DEPENDENCY_REGISTRY";
1312
+ } else {
1313
+ return "UNKNOWN"; // never expected to happen
1314
+ }
1315
+ }
1316
+ }