-
Notifications
You must be signed in to change notification settings - Fork 524
/
Copy patherc-721.ts
1300 lines (1230 loc) · 40.1 KB
/
erc-721.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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type {
DropERC721,
IBurnableERC721,
IClaimableERC721,
IERC721Supply,
ILoyaltyCard,
IMintableERC721,
INFTMetadata,
ISignatureMintERC721,
Multiwrap,
OpenEditionERC721,
SharedMetadata,
SignatureDrop,
TieredDrop,
TokenERC721,
Zora_IERC721Drop,
} from "@thirdweb-dev/contracts-js";
import type { ThirdwebStorage } from "@thirdweb-dev/storage";
import { BigNumber, BigNumberish, constants } from "ethers";
import {
DEFAULT_QUERY_ALL_COUNT,
type QueryAllParams,
} from "../../../core/schema/QueryParams";
import type {
NFT,
NFTMetadata,
NFTMetadataOrUri,
NFTWithoutMetadata,
} from "../../../core/schema/nft";
import { resolveAddress } from "../../common/ens/resolveAddress";
import {
ExtensionNotImplementedError,
NotFoundError,
} from "../../common/error";
import { assertEnabled } from "../../common/feature-detection/assertEnabled";
import { detectContractFeature } from "../../common/feature-detection/detectContractFeature";
import { hasFunction } from "../../common/feature-detection/hasFunction";
import { FALLBACK_METADATA, fetchTokenMetadata } from "../../common/nft";
import { buildTransactionFunction } from "../../common/transactions";
import {
FEATURE_NFT,
FEATURE_NFT_BATCH_MINTABLE,
FEATURE_NFT_BURNABLE,
FEATURE_NFT_CLAIM_CONDITIONS_V2,
FEATURE_NFT_CLAIM_CUSTOM,
FEATURE_NFT_LAZY_MINTABLE,
FEATURE_NFT_LOYALTY_CARD,
FEATURE_NFT_MINTABLE,
FEATURE_NFT_REVEALABLE,
FEATURE_NFT_SHARED_METADATA,
FEATURE_NFT_SIGNATURE_MINTABLE_V2,
FEATURE_NFT_SUPPLY,
FEATURE_NFT_TIERED_DROP,
FEATURE_NFT_UPDATABLE_METADATA,
} from "../../constants/erc721-features";
import type { Address } from "../../schema/shared/Address";
import type { AddressOrEns } from "../../schema/shared/AddressOrEnsSchema";
import type { ClaimOptions } from "../../types/claim-conditions/claim-conditions";
import type {
BaseClaimConditionERC721,
BaseDropERC721,
BaseERC721,
} from "../../types/eips";
import type { UploadProgressEvent } from "../../types/events";
import { DetectableFeature } from "../interfaces/DetectableFeature";
import { UpdateableNetwork } from "../interfaces/contract";
import type { NetworkInput, TransactionResultWithId } from "../types";
import type { ContractWrapper } from "./contract-wrapper";
import { Erc721Burnable } from "./erc-721-burnable";
import { Erc721ClaimableWithConditions } from "./erc-721-claim-conditions";
import { Erc721ClaimableZora } from "./erc-721-claim-zora";
import { Erc721Claimable } from "./erc-721-claimable";
import { Erc721LazyMintable } from "./erc-721-lazy-mintable";
import { Erc721LoyaltyCard } from "./erc-721-loyalty-card";
import { Erc721UpdatableMetadata } from "./erc-721-metadata";
import { Erc721Mintable } from "./erc-721-mintable";
import { Erc721SharedMetadata } from "./erc-721-shared-metadata";
import { Erc721Supply } from "./erc-721-supply";
import { Erc721TieredDrop } from "./erc-721-tiered-drop";
import { Erc721WithQuantitySignatureMintable } from "./erc-721-with-quantity-signature-mintable";
import { Transaction } from "./transactions";
/**
* Standard ERC721 NFT functions
* @remarks Basic functionality for a ERC721 contract that handles IPFS storage for you.
* @example
* ```javascript
* const contract = await sdk.getContract("{{contract_address}}");
* await contract.erc721.transfer(walletAddress, tokenId);
* ```
* @public
*/
export class Erc721<
T extends
| Multiwrap
| SignatureDrop
| DropERC721
| TokenERC721
| BaseERC721 = BaseERC721,
>
implements UpdateableNetwork, DetectableFeature
{
featureName = FEATURE_NFT.name;
private query: Erc721Supply | undefined;
private mintable: Erc721Mintable | undefined;
private burnable: Erc721Burnable | undefined;
private lazyMintable: Erc721LazyMintable | undefined;
private tieredDropable: Erc721TieredDrop | undefined;
private signatureMintable: Erc721WithQuantitySignatureMintable | undefined;
private claimWithConditions: Erc721ClaimableWithConditions | undefined;
private claimCustom: Erc721Claimable | undefined;
private erc721SharedMetadata: Erc721SharedMetadata | undefined;
private claimZora: Erc721ClaimableZora | undefined;
private loyaltyCard: Erc721LoyaltyCard | undefined;
private updatableMetadata: Erc721UpdatableMetadata | undefined;
protected contractWrapper: ContractWrapper<T>;
protected storage: ThirdwebStorage;
private _chainId: number;
get chainId() {
return this._chainId;
}
constructor(
contractWrapper: ContractWrapper<T>,
storage: ThirdwebStorage,
chainId: number,
) {
this.contractWrapper = contractWrapper;
this.storage = storage;
this.query = this.detectErc721Enumerable();
this.mintable = this.detectErc721Mintable();
this.burnable = this.detectErc721Burnable();
this.lazyMintable = this.detectErc721LazyMintable();
this.tieredDropable = this.detectErc721TieredDrop();
this.signatureMintable = this.detectErc721SignatureMintable();
this.claimWithConditions = this.detectErc721ClaimableWithConditions();
this.claimCustom = this.detectErc721Claimable();
this.claimZora = this.detectErc721ClaimableZora();
this.erc721SharedMetadata = this.detectErc721SharedMetadata();
this.loyaltyCard = this.detectErc721LoyaltyCard();
this.updatableMetadata = this.detectErc721UpdatableMetadata();
this._chainId = chainId;
}
/**
* @internal
*/
onNetworkUpdated(network: NetworkInput): void {
this.contractWrapper.updateSignerOrProvider(network);
}
getAddress(): Address {
return this.contractWrapper.address;
}
////// Standard ERC721 Extension //////
/**
* Get a single NFT
*
* @example
* ```javascript
* const tokenId = 0;
* const nft = await contract.erc721.get(tokenId);
* ```
* @param tokenId - the tokenId of the NFT to retrieve
* @returns The NFT metadata
* @twfeature ERC721
*/
public async get<T extends boolean | undefined = undefined>(
tokenId: BigNumberish,
loadMetadata?: T,
): Promise<T extends true | undefined ? NFT : NFTWithoutMetadata> {
if (loadMetadata === false) {
const owner = await this.ownerOf(tokenId).catch(
() => constants.AddressZero,
);
const nft: NFTWithoutMetadata = {
owner,
metadata: {
id: tokenId.toString(),
},
type: "ERC721",
supply: "1",
};
return nft as T extends true | undefined ? NFT : NFTWithoutMetadata;
} else {
const [owner, metadata] = await Promise.all([
this.ownerOf(tokenId).catch(() => constants.AddressZero),
this.getTokenMetadata(tokenId).catch(() => ({
id: tokenId.toString(),
uri: "",
...FALLBACK_METADATA,
})),
]);
return { owner, metadata, type: "ERC721", supply: "1" };
}
}
/**
* Get the current owner of an NFT
*
* @param tokenId - the tokenId of the NFT
* @returns the address of the owner
* @twfeature ERC721
*/
public async ownerOf(tokenId: BigNumberish): Promise<string> {
return await (this.contractWrapper as ContractWrapper<BaseERC721>).read(
"ownerOf",
[tokenId],
);
}
/**
* Get NFT balance of a specific wallet
*
* @remarks Get a wallets NFT balance (number of NFTs in this contract owned by the wallet).
*
* @example
* ```javascript
* const walletAddress = "{{wallet_address}}";
* const balance = await contract.erc721.balanceOf(walletAddress);
* console.log(balance);
* ```
* @twfeature ERC721
*/
public async balanceOf(address: AddressOrEns): Promise<BigNumber> {
return await (this.contractWrapper as ContractWrapper<BaseERC721>).read(
"balanceOf",
[await resolveAddress(address)],
);
}
/**
* Get NFT balance for the currently connected wallet
*/
public async balance(): Promise<BigNumber> {
return await this.balanceOf(await this.contractWrapper.getSignerAddress());
}
/**
* Get whether this wallet has approved transfers from the given operator
* @param address - the wallet address
* @param operator - the operator address
*/
public async isApproved(
address: AddressOrEns,
operator: AddressOrEns,
): Promise<boolean> {
const [_address, _operator] = await Promise.all([
resolveAddress(address),
resolveAddress(operator),
]);
return await (this.contractWrapper as ContractWrapper<BaseERC721>).read(
"isApprovedForAll",
[_address, _operator],
);
}
/**
* Transfer an NFT
*
* @remarks Transfer an NFT from the connected wallet to another wallet.
*
* @example
* ```javascript
* const walletAddress = "{{wallet_address}}";
* const tokenId = 0;
* await contract.erc721.transfer(walletAddress, tokenId);
* ```
* @twfeature ERC721
*/
transfer = /* @__PURE__ */ buildTransactionFunction(
async (to: AddressOrEns, tokenId: BigNumberish) => {
const [from, _to] = await Promise.all([
this.contractWrapper.getSignerAddress(),
resolveAddress(to),
]);
return Transaction.fromContractWrapper({
contractWrapper: this.contractWrapper,
method: "transferFrom(address,address,uint256)",
args: [from, _to, tokenId],
});
},
);
/**
* Transfer an NFT from a specific wallet
*
* @remarks Transfer an NFT from the given wallet to another wallet.
*
* @example
* ```javascript
* const fromWalletAddress = "{{wallet_address}}";
* const toWalletAddress = "{{wallet_address}}";
* const tokenId = 0;
* await contract.erc721.transferFrom(fromWalletAddress, toWalletAddress, tokenId);
* ```
* @twfeature ERC721
*/
transferFrom = /* @__PURE__ */ buildTransactionFunction(
async (from: AddressOrEns, to: AddressOrEns, tokenId: BigNumberish) => {
const [fromAddress, toAddress] = await Promise.all([
resolveAddress(from),
resolveAddress(to),
]);
return Transaction.fromContractWrapper({
contractWrapper: this.contractWrapper,
method: "transferFrom(address,address,uint256)",
args: [fromAddress, toAddress, tokenId],
});
},
);
/**
* Set approval for all NFTs
* @remarks Approve or remove operator as an operator for the caller. Operators can call transferFrom or safeTransferFrom for any token owned by the caller.
* @example
* ```javascript
* const operator = "{{wallet_address}}";
* await contract.erc721.setApprovalForAll(operator, true);
* ```
* @param operator - the operator's address
* @param approved - whether to approve or remove
* @twfeature ERC721
*/
setApprovalForAll = /* @__PURE__ */ buildTransactionFunction(
async (operator: AddressOrEns, approved: boolean) => {
return Transaction.fromContractWrapper({
contractWrapper: this.contractWrapper,
method: "setApprovalForAll",
args: [await resolveAddress(operator), approved],
});
},
);
/**
* Set approval for a single NFT
* @remarks Approve an operator for the NFT owner. Operators can call transferFrom or safeTransferFrom for the specified token.
* @example
* ```javascript
* const operator = "{{wallet_address}}";
* const tokenId = 0;
* await contract.erc721.setApprovalForToken(operator, tokenId);
* ```
* @param operator - the operator's address
* @param tokenId - the tokenId to give approval for
*
* @internal
*/
setApprovalForToken = /* @__PURE__ */ buildTransactionFunction(
async (operator: AddressOrEns, tokenId: BigNumberish) => {
return Transaction.fromContractWrapper({
contractWrapper: this.contractWrapper,
method: "approve",
args: [await resolveAddress(operator), tokenId],
});
},
);
////// ERC721 Supply Extension //////
/**
* Get all NFTs
*
* @remarks Get all the data associated with every NFT in this contract.
*
* By default, returns the first 100 NFTs, use queryParams to fetch more.
*
* @example
* ```javascript
* const nfts = await contract.erc721.getAll();
* console.log(nfts);
* ```
* @param queryParams - optional filtering to only fetch a subset of results.
* @returns The NFT metadata for all NFTs queried.
* @twfeature ERC721Supply | ERC721Enumerable
*/
public async getAll(queryParams?: QueryAllParams) {
return assertEnabled(this.query, FEATURE_NFT_SUPPLY).all(queryParams);
}
/**
* Get all NFT owners
* @example
* ```javascript
* const owners = await contract.erc721.getAllOwners();
* console.log(owners);
* ```
* @returns an array of token ids and owners
* @twfeature ERC721Supply | ERC721Enumerable
*/
public async getAllOwners() {
return assertEnabled(this.query, FEATURE_NFT_SUPPLY).allOwners();
}
/**
* Get the total number of NFTs minted
* @remarks This returns the total number of NFTs minted in this contract, **not** the total supply of a given token.
* @example
* ```javascript
* const count = await contract.erc721.totalCount();
* console.log(count);
* ```
*
* @returns the total number of NFTs minted in this contract
* @public
*/
public async totalCount() {
return this.nextTokenIdToMint();
}
/**
* Get the total count NFTs minted in this contract
* @twfeature ERC721Supply | ERC721Enumerable
*/
public async totalCirculatingSupply() {
return assertEnabled(
this.query,
FEATURE_NFT_SUPPLY,
).totalCirculatingSupply();
}
////// ERC721 Enumerable Extension //////
/**
* Get all NFTs owned by a specific wallet
*
* @remarks Get all the data associated with the NFTs owned by a specific wallet.
*
* @example
* ```javascript
* // Address of the wallet to get the NFTs of
* const address = "{{wallet_address}}";
* const nfts = await contract.erc721.getOwned(address);
* console.log(nfts);
* ```
* @param walletAddress - the wallet address to query, defaults to the connected wallet
* @param queryParams - optional filtering to only fetch a subset of results.
* @returns The NFT metadata for all NFTs in the contract.
* @twfeature ERC721Supply | ERC721Enumerable
*/
public async getOwned(
walletAddress?: AddressOrEns,
queryParams?: QueryAllParams,
): Promise<NFT[] | NFTWithoutMetadata[]> {
if (walletAddress) {
walletAddress = await resolveAddress(walletAddress);
}
if (this.query?.owned) {
return this.query.owned.all(walletAddress, queryParams);
} else {
const [address, allOwners] = await Promise.all([
walletAddress || this.contractWrapper.getSignerAddress(),
this.getAllOwners(),
]);
let ownedTokens = (allOwners || []).filter(
(i) => address?.toLowerCase() === i.owner?.toLowerCase(),
);
if (queryParams) {
const start = queryParams?.start || 0;
const count = queryParams?.count || DEFAULT_QUERY_ALL_COUNT;
ownedTokens = ownedTokens.slice(start, start + count);
}
const loadMetadata = queryParams
? queryParams.loadMetadata !== false
: true;
return await Promise.all(
ownedTokens.map(async (i) => this.get(i.tokenId, loadMetadata)),
);
}
}
/**
* Get all token ids of NFTs owned by a specific wallet.
* @param walletAddress - the wallet address to query, defaults to the connected wallet
*/
public async getOwnedTokenIds(walletAddress?: AddressOrEns) {
if (walletAddress) {
walletAddress = await resolveAddress(walletAddress);
}
if (this.query?.owned) {
return this.query.owned.tokenIds(walletAddress);
} else {
const [address, allOwners] = await Promise.all([
walletAddress || this.contractWrapper.getSignerAddress(),
this.getAllOwners(),
]);
return (allOwners || [])
.filter((i) => address?.toLowerCase() === i.owner?.toLowerCase())
.map((i) => BigNumber.from(i.tokenId));
}
}
////// ERC721 Mintable Extension //////
/**
* Mint an NFT
*
* @remarks Mint an NFT to the connected wallet.
*
* @example
* ```javascript
* // Custom metadata of the NFT, note that you can fully customize this metadata with other properties.
* const metadata = {
* name: "Cool NFT",
* description: "This is a cool NFT",
* image: fs.readFileSync("path/to/image.png"), // This can be an image url or file
* };
*
* const tx = await contract.erc721.mint(metadata);
* const receipt = tx.receipt; // the transaction receipt
* const tokenId = tx.id; // the id of the NFT minted
* const nft = await tx.data(); // (optional) fetch details of minted NFT
* ```
* @twfeature ERC721Mintable
*/
mint = /* @__PURE__ */ buildTransactionFunction(
async (metadata: NFTMetadataOrUri) => {
return this.mintTo.prepare(
await this.contractWrapper.getSignerAddress(),
metadata,
);
},
);
/**
* Mint an NFT to a specific wallet
*
* @remarks Mint a unique NFT to a specified wallet.
*
* @example
* ```javascript
* // Address of the wallet you want to mint the NFT to
* const walletAddress = "{{wallet_address}}";
*
* // Custom metadata of the NFT, note that you can fully customize this metadata with other properties.
* const metadata = {
* name: "Cool NFT",
* description: "This is a cool NFT",
* image: fs.readFileSync("path/to/image.png"), // This can be an image url or file
* };
*
* const tx = await contract.erc721.mintTo(walletAddress, metadata);
* const receipt = tx.receipt; // the transaction receipt
* const tokenId = tx.id; // the id of the NFT minted
* const nft = await tx.data(); // (optional) fetch details of minted NFT
* ```
* @twfeature ERC721Mintable
*/
mintTo = /* @__PURE__ */ buildTransactionFunction(
async (receiver: AddressOrEns, metadata: NFTMetadataOrUri) => {
return assertEnabled(this.mintable, FEATURE_NFT_MINTABLE).to.prepare(
receiver,
metadata,
);
},
);
/**
* Construct a mint transaction without executing it.
* This is useful for estimating the gas cost of a mint transaction, overriding transaction options and having fine grained control over the transaction execution.
* @param receiver - Address you want to send the token to
* @param metadata - The metadata of the NFT you want to mint
*
* @deprecated Use `contract.erc721.mint.prepare(...args)` instead
* @twfeature ERC721Mintable
*/
public async getMintTransaction(
receiver: AddressOrEns,
metadata: NFTMetadataOrUri,
) {
return this.mintTo.prepare(receiver, metadata);
}
////// ERC721 Batch Mintable Extension //////
/**
* Mint many NFTs
*
* @remarks Mint many unique NFTs at once to the connected wallet
*
* @example
* ```typescript
* // Custom metadata of the NFTs you want to mint.
* const metadatas = [{
* name: "Cool NFT #1",
* description: "This is a cool NFT",
* image: fs.readFileSync("path/to/image.png"), // This can be an image url or file
* }, {
* name: "Cool NFT #2",
* description: "This is a cool NFT",
* image: fs.readFileSync("path/to/other/image.png"),
* }];
*
* const tx = await contract.erc721.mintBatch(metadatas);
* const receipt = tx[0].receipt; // same transaction receipt for all minted NFTs
* const firstTokenId = tx[0].id; // token id of the first minted NFT
* const firstNFT = await tx[0].data(); // (optional) fetch details of the first minted NFT
* ```
* @twfeature ERC721BatchMintable
*/
mintBatch = /* @__PURE__ */ buildTransactionFunction(
async (metadatas: NFTMetadataOrUri[]) => {
return this.mintBatchTo.prepare(
await this.contractWrapper.getSignerAddress(),
metadatas,
);
},
);
/**
* Mint many NFTs to a specific wallet
*
* @remarks Mint many unique NFTs at once to a specified wallet.
*
* @example
* ```typescript
* // Address of the wallet you want to mint the NFT to
* const walletAddress = "{{wallet_address}}";
*
* // Custom metadata of the NFTs you want to mint.
* const metadatas = [{
* name: "Cool NFT #1",
* description: "This is a cool NFT",
* image: fs.readFileSync("path/to/image.png"), // This can be an image url or file
* }, {
* name: "Cool NFT #2",
* description: "This is a cool NFT",
* image: fs.readFileSync("path/to/other/image.png"),
* }];
*
* const tx = await contract.erc721.mintBatchTo(walletAddress, metadatas);
* const receipt = tx[0].receipt; // same transaction receipt for all minted NFTs
* const firstTokenId = tx[0].id; // token id of the first minted NFT
* const firstNFT = await tx[0].data(); // (optional) fetch details of the first minted NFT
* ```
* @twfeature ERC721BatchMintable
*/
mintBatchTo = /* @__PURE__ */ buildTransactionFunction(
async (receiver: AddressOrEns, metadatas: NFTMetadataOrUri[]) => {
return assertEnabled(
this.mintable?.batch,
FEATURE_NFT_BATCH_MINTABLE,
).to.prepare(receiver, metadatas);
},
);
////// ERC721 Burnable Extension //////
/**
* Burn a single NFT
* @param tokenId - the token Id to burn
*
* @example
* ```javascript
* const result = await contract.erc721.burn(tokenId);
* ```
* @twfeature ERC721Burnable
*/
burn = /* @__PURE__ */ buildTransactionFunction(
async (tokenId: BigNumberish) => {
return assertEnabled(this.burnable, FEATURE_NFT_BURNABLE).token.prepare(
tokenId,
);
},
);
////// ERC721 Loyalty Card Extension //////
/**
* Cancel loyalty card NFTs
*
* @remarks Cancel loyalty card NFTs held by the connected wallet
*
* @example
* ```javascript
* // The token ID of the loyalty card you want to cancel
* const tokenId = 0;
*
* const result = await contract.erc721.cancel(tokenId);
* ```
* @twfeature ERC721LoyaltyCard
*/
cancel = /* @__PURE__ */ buildTransactionFunction(
async (tokenId: BigNumberish) => {
return assertEnabled(
this.loyaltyCard,
FEATURE_NFT_LOYALTY_CARD,
).cancel.prepare(tokenId);
},
);
/**
* Revoke loyalty card NFTs
*
* @remarks Revoke loyalty card NFTs held by some owner.
*
* @example
* ```javascript
* // The token ID of the loyalty card you want to revoke
* const tokenId = 0;
*
* const result = await contract.erc721.revoke(tokenId);
* ```
* @twfeature ERC721LoyaltyCard
*/
revoke = /* @__PURE__ */ buildTransactionFunction(
async (tokenId: BigNumberish) => {
return assertEnabled(
this.loyaltyCard,
FEATURE_NFT_LOYALTY_CARD,
).revoke.prepare(tokenId);
},
);
////// ERC721 LazyMint Extension //////
/**
* Lazy mint NFTs
*
* @remarks Create batch allows you to create a batch of many unique NFTs in one transaction.
*
* @example
* ```javascript
* // Custom metadata of the NFTs to create
* const metadatas = [{
* name: "Cool NFT",
* description: "This is a cool NFT",
* image: fs.readFileSync("path/to/image.png"), // This can be an image url or file
* }, {
* name: "Cool NFT",
* description: "This is a cool NFT",
* image: fs.readFileSync("path/to/image.png"),
* }];
*
* const results = await contract.erc721.lazyMint(metadatas); // uploads and creates the NFTs on chain
* const firstTokenId = results[0].id; // token id of the first created NFT
* const firstNFT = await results[0].data(); // (optional) fetch details of the first created NFT
* ```
*
* @param metadatas - The metadata to include in the batch.
* @param options - optional upload progress callback
* @twfeature ERC721LazyMintable
*/
lazyMint = /* @__PURE__ */ buildTransactionFunction(
async (
metadatas: NFTMetadataOrUri[],
options?: {
onProgress: (event: UploadProgressEvent) => void;
},
) => {
return assertEnabled(
this.lazyMintable,
FEATURE_NFT_LAZY_MINTABLE,
).lazyMint.prepare(metadatas, options);
},
);
////// ERC721 Metadata Extension //////
/**
* Update the metadata of an NFT
*
* @remarks Update the metadata of an NFT
*
* @example
* ```javascript
* // The token ID of the NFT whose metadata you want to update
* const tokenId = 0;
* // The new metadata
* const metadata = { name: "My NFT", description: "My NFT description""}
*
* await contract.erc721.update(tokenId, metadata);
* ```
* @twfeature ERC721UpdatableMetadata
*/
update = /* @__PURE__ */ buildTransactionFunction(
async (tokenId: BigNumberish, metadata: NFTMetadataOrUri) => {
return assertEnabled(
this.updatableMetadata,
FEATURE_NFT_UPDATABLE_METADATA,
).update.prepare(tokenId, metadata);
},
);
////// ERC721 Claimable Extension //////
/**
* Claim NFTs
*
* @remarks Let the specified wallet claim NFTs.
*
* @example
* ```javascript
* const quantity = 1; // how many unique NFTs you want to claim
*
* const tx = await contract.erc721.claim(quantity);
* const receipt = tx.receipt; // the transaction receipt
* const claimedTokenId = tx.id; // the id of the NFT claimed
* const claimedNFT = await tx.data(); // (optional) get the claimed NFT metadata
* ```
*
* @param quantity - Quantity of the tokens you want to claim
*
* @returns - an array of results containing the id of the token claimed, the transaction receipt and a promise to optionally fetch the nft metadata
* @twfeature ERC721ClaimCustom | ERC721ClaimPhasesV2 | ERC721ClaimPhasesV1 | ERC721ClaimConditionsV2 | ERC721ClaimConditionsV1 | ERC721ClaimZora
*/
claim = /* @__PURE__ */ buildTransactionFunction(
async (quantity: BigNumberish, options?: ClaimOptions) => {
return this.claimTo.prepare(
await this.contractWrapper.getSignerAddress(),
quantity,
options,
);
},
);
/**
* Claim NFTs to a specific wallet
*
* @remarks Let the specified wallet claim NFTs.
*
* @example
* ```javascript
* const address = "{{wallet_address}}"; // address of the wallet you want to claim the NFTs
* const quantity = 1; // how many unique NFTs you want to claim
*
* const tx = await contract.erc721.claimTo(address, quantity);
* const receipt = tx.receipt; // the transaction receipt
* const claimedTokenId = tx.id; // the id of the NFT claimed
* const claimedNFT = await tx.data(); // (optional) get the claimed NFT metadata
* ```
*
* @param destinationAddress - Address you want to send the token to
* @param quantity - Quantity of the tokens you want to claim
* @param options
* @returns - an array of results containing the id of the token claimed, the transaction receipt and a promise to optionally fetch the nft metadata
* @twfeature ERC721ClaimCustom | ERC721ClaimPhasesV2 | ERC721ClaimPhasesV1 | ERC721ClaimConditionsV2 | ERC721ClaimConditionsV1 | ERC721ClaimZora
*/
claimTo = /* @__PURE__ */ buildTransactionFunction(
async (
destinationAddress: AddressOrEns,
quantity: BigNumberish,
options?: ClaimOptions,
): Promise<Transaction<TransactionResultWithId<NFT>[]>> => {
const claimWithConditions = this.claimWithConditions;
const claim = this.claimCustom;
const claimZora = this.claimZora;
if (claimWithConditions) {
return claimWithConditions.to.prepare(
destinationAddress,
quantity,
options,
);
}
if (claim) {
return claim.to.prepare(destinationAddress, quantity, options);
}
if (claimZora) {
return claimZora.to.prepare(destinationAddress, quantity, options);
}
throw new ExtensionNotImplementedError(FEATURE_NFT_CLAIM_CUSTOM);
},
);
/**
* Construct a claim transaction without executing it.
* This is useful for estimating the gas cost of a claim transaction, overriding transaction options and having fine grained control over the transaction execution.
* @param destinationAddress
* @param quantity
* @param options
*
* @deprecated Use `contract.erc721.claim.prepare(...args)` instead
* @twfeature ERC721ClaimCustom | ERC721ClaimPhasesV2 | ERC721ClaimPhasesV1 | ERC721ClaimConditionsV2 | ERC721ClaimConditionsV1
*/
public async getClaimTransaction(
destinationAddress: AddressOrEns,
quantity: BigNumberish,
options?: ClaimOptions,
): Promise<Transaction> {
const claimWithConditions = this.claimWithConditions;
const claim = this.claimCustom;
if (claimWithConditions) {
return claimWithConditions.conditions.getClaimTransaction(
destinationAddress,
quantity,
options,
);
}
if (claim) {
return claim.getClaimTransaction(destinationAddress, quantity, options);
}
throw new ExtensionNotImplementedError(FEATURE_NFT_CLAIM_CUSTOM);
}
/**
* Get the claimed supply
*
* @remarks Get the number of claimed NFTs in this Drop.
*
* * @example
* ```javascript
* const claimedNFTCount = await contract.totalClaimedSupply();
* console.log(`NFTs claimed: ${claimedNFTCount}`);
* ```
* @returns the unclaimed supply
* @twfeature ERC721ClaimCustom | ERC721ClaimPhasesV2 | ERC721ClaimPhasesV1 | ERC721ClaimConditionsV2 | ERC721ClaimConditionsV1
*/
public async totalClaimedSupply(): Promise<BigNumber> {
const contract = this.contractWrapper;
if (hasFunction<SignatureDrop>("totalMinted", contract)) {
return (this.contractWrapper as ContractWrapper<SignatureDrop>).read(
"totalMinted",
[],
);
}
if (hasFunction<DropERC721>("nextTokenIdToClaim", contract)) {
return (this.contractWrapper as ContractWrapper<DropERC721>).read(
"nextTokenIdToClaim",
[],
);
}
throw new Error(
"No function found on contract to get total claimed supply",
);
}
/**
* Get the unclaimed supply
*
* @remarks Get the number of unclaimed NFTs in this Drop.
*
* * @example
* ```javascript
* const unclaimedNFTCount = await contract.totalUnclaimedSupply();
* console.log(`NFTs left to claim: ${unclaimedNFTCount}`);
* ```
* @returns the unclaimed supply
* @twfeature ERC721ClaimCustom | ERC721ClaimPhasesV2 | ERC721ClaimPhasesV1 | ERC721ClaimConditionsV2 | ERC721ClaimConditionsV1
*/
public async totalUnclaimedSupply(): Promise<BigNumber> {
const [nextTokenIdToMint, totalClaimedSupply] = await Promise.all([
this.nextTokenIdToMint(),
this.totalClaimedSupply(),
]);
return nextTokenIdToMint.sub(totalClaimedSupply);
}
/**
* Configure claim conditions
* @remarks Define who can claim NFTs in the collection, when and how many.
* @example
* ```javascript
* const presaleStartTime = new Date();
* const publicSaleStartTime = new Date(Date.now() + 60 * 60 * 24 * 1000);
* const claimConditions = [
* {
* startTime: presaleStartTime, // start the presale now
* maxClaimableSupply: 2, // limit how many mints for this presale
* price: 0.01, // presale price
* snapshot: ['0x...', '0x...'], // limit minting to only certain addresses
* },
* {
* startTime: publicSaleStartTime, // 24h after presale, start public sale
* price: 0.08, // public sale price
* }
* ]);
* await contract.erc721.claimConditions.set(claimConditions);
* ```
* @twfeature ERC721ClaimPhasesV2 | ERC721ClaimPhasesV1 | ERC721ClaimConditionsV2 | ERC721ClaimConditionsV1
*/
get claimConditions() {
return assertEnabled(
this.claimWithConditions,
FEATURE_NFT_CLAIM_CONDITIONS_V2,
).conditions;
}
////// ERC721 Tiered Drop Extension //////
/**
* Tiered Drop
* @remarks Drop lazy minted NFTs using a tiered drop mechanism.
* @twfeature ERC721TieredDrop
*/
get tieredDrop() {
return assertEnabled(this.tieredDropable, FEATURE_NFT_TIERED_DROP);
}
////// ERC721 SignatureMint Extension //////
/**
* Mint with signature
* @remarks Generate dynamic NFTs with your own signature, and let others mint them using that signature.
* @example
* ```javascript
* // see how to craft a payload to sign in the `contract.erc721.signature.generate()` documentation