/
delayed-reveal.ts
372 lines (348 loc) · 11.6 KB
/
delayed-reveal.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import type {
DropERC721_V3,
IThirdwebContract,
SignatureDrop,
} from "@thirdweb-dev/contracts-js";
import { TokensLazyMintedEvent } from "@thirdweb-dev/contracts-js/dist/declarations/src/DropERC721";
import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { BigNumber, Contract, utils, type BigNumberish } from "ethers";
import {
CommonNFTInput,
NFTMetadata,
NFTMetadataInput,
} from "../../../core/schema/nft";
import { hasFunction } from "../../common/feature-detection/hasFunction";
import {
fetchTokenMetadataForContract,
getBaseUriFromBatch,
} from "../../common/nft";
import { buildTransactionFunction } from "../../common/transactions";
import { FeatureName } from "../../constants/contract-features";
import type { BatchToReveal } from "../../types/delayed-reveal";
import {
BaseDelayedRevealERC1155,
BaseDelayedRevealERC721,
} from "../../types/eips";
import type { UploadProgressEvent } from "../../types/events";
import type { TransactionResultWithId } from "../types";
import { ContractWrapper } from "./internal/contract-wrapper";
import { Transaction } from "./transactions";
/**
* Handles delayed reveal logic
* @public
*/
export class DelayedReveal<
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- TO BE REMOVED IN V4
T extends
| DropERC721_V3
| BaseDelayedRevealERC721
| SignatureDrop
| BaseDelayedRevealERC1155,
> {
featureName;
private contractWrapper;
private storage: ThirdwebStorage;
private nextTokenIdToMintFn: () => Promise<BigNumber>;
constructor(
contractWrapper: ContractWrapper<
| DropERC721_V3
| BaseDelayedRevealERC721
| SignatureDrop
| BaseDelayedRevealERC1155
>,
storage: ThirdwebStorage,
featureName: FeatureName,
nextTokenIdToMintFn: () => Promise<BigNumber>,
) {
this.featureName = featureName;
this.nextTokenIdToMintFn = nextTokenIdToMintFn;
this.contractWrapper = contractWrapper;
this.storage = storage;
}
/**
* Create a batch of encrypted NFTs that can be revealed at a later time.
* @remarks Create a batch of encrypted NFTs that can be revealed at a later time.
* @example
* ```javascript
* // the real NFTs, these will be encrypted until your reveal them!
* const realNFTs = [{
* name: "Common NFT #1",
* description: "Common NFT, one of many.",
* image: fs.readFileSync("path/to/image.png"),
* }, {
* name: "Super Rare NFT #2",
* description: "You got a Super Rare NFT!",
* image: fs.readFileSync("path/to/image.png"),
* }];
* // A placeholder NFT that people will get immediately in their wallet, until the reveal happens!
* const placeholderNFT = {
* name: "Hidden NFT",
* description: "Will be revealed next week!"
* };
* // Create and encrypt the NFTs
* await contract.revealer.createDelayedRevealBatch(
* placeholderNFT,
* realNFTs,
* "my secret password",
* );
* ```
* @public
* @param placeholder - the placeholder NFT to show before the reveal
* @param metadatas - the final NFTs that will be hidden
* @param password - the password that will be used to reveal these NFTs
* @param options - additional options like upload progress
*/
createDelayedRevealBatch = /* @__PURE__ */ buildTransactionFunction(
async (
placeholder: NFTMetadataInput,
metadatas: NFTMetadataInput[],
password: string,
options?: {
onProgress: (event: UploadProgressEvent) => void;
},
): Promise<Transaction<TransactionResultWithId[]>> => {
if (!password) {
throw new Error("Password is required");
}
const placeholderUris = await this.storage.uploadBatch(
[CommonNFTInput.parse(placeholder)],
{
rewriteFileNames: {
fileStartNumber: 0,
},
},
);
const placeholderUri = getBaseUriFromBatch(placeholderUris);
const startFileNumber = await this.nextTokenIdToMintFn();
const uris = await this.storage.uploadBatch(
metadatas.map((m) => CommonNFTInput.parse(m)),
{
onProgress: options?.onProgress,
rewriteFileNames: {
fileStartNumber: startFileNumber.toNumber(),
},
},
);
const baseUri = getBaseUriFromBatch(uris);
const baseUriId = await this.contractWrapper.read("getBaseURICount", []);
const hashedPassword = await this.hashDelayRevealPassword(
baseUriId,
password,
);
const encryptedBaseUri = await this.contractWrapper.read(
"encryptDecrypt",
[utils.toUtf8Bytes(baseUri), hashedPassword],
);
let data: string;
const legacyContract = await this.isLegacyContract();
if (legacyContract) {
data = encryptedBaseUri;
} else {
const chainId = await this.contractWrapper.getChainID();
const provenanceHash = utils.solidityKeccak256(
["bytes", "bytes", "uint256"],
[utils.toUtf8Bytes(baseUri), hashedPassword, chainId],
);
data = utils.defaultAbiCoder.encode(
["bytes", "bytes32"],
[encryptedBaseUri, provenanceHash],
);
}
return Transaction.fromContractWrapper({
contractWrapper: this.contractWrapper,
method: "lazyMint",
args: [
uris.length,
placeholderUri.endsWith("/") ? placeholderUri : `${placeholderUri}/`,
data,
],
parse: (receipt) => {
const events = this.contractWrapper.parseLogs<TokensLazyMintedEvent>(
"TokensLazyMinted",
receipt?.logs,
);
const startingIndex = events[0].args.startTokenId;
const endingIndex = events[0].args.endTokenId;
const results: TransactionResultWithId[] = [];
for (let id = startingIndex; id.lte(endingIndex); id = id.add(1)) {
results.push({
id,
receipt,
});
}
return results;
},
});
},
);
/**
* Reveal a batch of hidden NFTs
* @remarks Reveal the NFTs of a batch using the password.
* @example
* ```javascript
* // the batch to reveal
* const batchId = 0;
* // reveal the batch
* await contract.revealer.reveal(batchId, "my secret password");
* ```
* @public
* @param batchId - the id of the batch to reveal
* @param password - the password
*/
reveal = /* @__PURE__ */ buildTransactionFunction(
async (batchId: BigNumberish, password: string): Promise<Transaction> => {
if (!password) {
throw new Error("Password is required");
}
const key = await this.hashDelayRevealPassword(batchId, password);
// performing the reveal locally to make sure it'd succeed before sending the transaction
try {
const decryptedUri = await this.contractWrapper
.callStatic()
.reveal(batchId, key);
// basic sanity check for making sure decryptedUri is valid
// this is optional because invalid decryption key would result in non-utf8 bytes and
// ethers would throw when trying to decode it
if (!decryptedUri.includes("://") || !decryptedUri.endsWith("/")) {
throw new Error("invalid password");
}
} catch (e) {
throw new Error("invalid password");
}
return Transaction.fromContractWrapper({
contractWrapper: this.contractWrapper,
method: "reveal",
args: [batchId, key],
});
},
);
/**
* Gets the list of unrevealed NFT batches.
* @remarks Gets the list of unrevealed NFT batches.
* @example
* ```javascript
* const batches = await contract.revealer.getBatchesToReveal();
* ```
* @public
*/
public async getBatchesToReveal(): Promise<BatchToReveal[]> {
const count = await this.contractWrapper.read("getBaseURICount", []);
if (count.isZero()) {
return [];
}
const countRangeArray = Array.from(Array(count.toNumber()).keys());
// map over to get the base uri indices, which should be the end token id of every batch
const uriIndices = await Promise.all(
countRangeArray.map((i) => {
if (
hasFunction<BaseDelayedRevealERC721>(
"getBatchIdAtIndex",
this.contractWrapper,
)
) {
return this.contractWrapper.read("getBatchIdAtIndex", [i]);
}
if (
hasFunction<DropERC721_V3>("baseURIIndices", this.contractWrapper)
) {
return this.contractWrapper.read("baseURIIndices", [i]);
}
throw new Error(
"Contract does not have getBatchIdAtIndex or baseURIIndices.",
);
}),
);
// first batch always start from 0. don't need to fetch the last batch so pop it from the range array
const uriIndicesWithZeroStart = uriIndices.slice(0, uriIndices.length - 1);
// returns the token uri for each batches. first batch always starts from token id 0.
const tokenMetadatas = await Promise.all(
Array.from([0, ...uriIndicesWithZeroStart]).map((i) =>
this.getNftMetadata(i.toString()),
),
);
// index is the uri indices, which is end token id. different from uris
const legacyContract = await this.isLegacyContract();
const encryptedUriData = await Promise.all(
Array.from([...uriIndices]).map((i) =>
legacyContract
? this.getLegacyEncryptedData(i)
: this.contractWrapper.read("encryptedData", [i]),
),
);
const encryptedBaseUris = encryptedUriData.map((data) => {
if (utils.hexDataLength(data) > 0) {
if (legacyContract) {
return data;
}
const result = utils.defaultAbiCoder.decode(["bytes", "bytes32"], data);
return result[0];
} else {
return data;
}
});
return tokenMetadatas
.map((meta, index) => ({
batchId: BigNumber.from(index),
batchUri: meta.uri,
placeholderMetadata: meta,
}))
.filter((_, index) => utils.hexDataLength(encryptedBaseUris[index]) > 0);
}
/**
* Algorithm to hash delay reveal password, so we don't broadcast the input password on-chain.
*
* @internal
*/
private async hashDelayRevealPassword(
batchTokenIndex: BigNumberish,
password: string,
) {
const chainId = await this.contractWrapper.getChainID();
const contractAddress = this.contractWrapper.address;
return utils.solidityKeccak256(
["string", "uint256", "uint256", "address"],
[password, chainId, batchTokenIndex, contractAddress],
);
}
private async getNftMetadata(tokenId: BigNumberish): Promise<NFTMetadata> {
return fetchTokenMetadataForContract(
this.contractWrapper.address,
this.contractWrapper.getProvider(),
tokenId,
this.storage,
);
}
private async isLegacyContract(): Promise<boolean> {
if (
hasFunction<IThirdwebContract>("contractVersion", this.contractWrapper)
) {
try {
const version = await (
this.contractWrapper as ContractWrapper<IThirdwebContract>
).read("contractVersion", []);
return version <= 2;
} catch (e) {
return false;
}
}
return false;
}
private async getLegacyEncryptedData(index: BigNumber) {
const DeprecatedAbi = (
await import(
"@thirdweb-dev/contracts-js/dist/abis/IDelayedRevealDeprecated.json"
)
).default;
const legacy = new Contract(
this.contractWrapper.address,
DeprecatedAbi,
this.contractWrapper.getProvider(),
);
const result = await legacy.functions["encryptedBaseURI"](index);
if (result.length > 0) {
return result[0];
} else {
return "0x";
}
}
}