Compare commits

..
24 changed files with 377 additions and 93 deletions
+6
View File
@@ -1,5 +1,11 @@
# @thirdweb-dev/auth
## 2.0.31
### Patch Changes
- [#397](https://github.com/thirdweb-dev/js/pull/397) [`72589ec`](https://github.com/thirdweb-dev/js/commit/72589ec234d86939b67b0ca8b3b789f2e9c54cc2) Thanks [@adam-maj](https://github.com/adam-maj)! - Call user callback in getUser
## 2.0.30
## 2.0.29
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@thirdweb-dev/auth",
"version": "2.0.30",
"version": "2.0.31",
"exports": {
"./next": {
"module": "./next/dist/thirdweb-dev-auth-next.esm.js",
+7 -1
View File
@@ -70,7 +70,13 @@ export function ThirdwebAuth(cfg: ThirdwebAuthConfig) {
if (token) {
try {
const address = await sdk.auth.authenticate(domain, token);
user = { address };
let data = {};
if (ctx.callbacks?.user) {
data = await ctx.callbacks.user(address);
}
user = { ...data, address };
} catch {
// No-op
}
+7 -1
View File
@@ -70,7 +70,13 @@ export function ThirdwebAuth(cfg: ThirdwebAuthConfig) {
if (token) {
try {
const address = await sdk.auth.authenticate(domain, token);
user = { address };
let data = {};
if (ctx.callbacks?.user) {
data = await ctx.callbacks.user(address);
}
user = { ...data, address };
} catch {
// No-op
}
+7
View File
@@ -1,5 +1,12 @@
# thirdweb
## 0.8.17
### Patch Changes
- Updated dependencies [[`15514f1`](https://github.com/thirdweb-dev/js/commit/15514f190a844d809ae5b1edb580aab46a682485), [`7c0744a`](https://github.com/thirdweb-dev/js/commit/7c0744a006e78987ad8b271b2c64f4bac7759510), [`f8bceec`](https://github.com/thirdweb-dev/js/commit/f8bceec10c60b30dc3d6f45926e2a9e018202578), [`887af24`](https://github.com/thirdweb-dev/js/commit/887af24450e316c2ea390cd49c0563cebe793c0f), [`96bd92e`](https://github.com/thirdweb-dev/js/commit/96bd92e724ec7d880d23348071b26ab8c21dd868)]:
- @thirdweb-dev/sdk@3.6.1
## 0.8.16
### Patch Changes
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "thirdweb",
"main": "dist/cli/index.js",
"version": "0.8.16",
"version": "0.8.17",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/cli",
"author": "thirdweb eng <[email protected]>",
"license": "Apache-2.0",
+8
View File
@@ -1,5 +1,13 @@
# @thirdweb-dev/react
## 3.6.1
### Patch Changes
- [#392](https://github.com/thirdweb-dev/js/pull/392) [`846022e`](https://github.com/thirdweb-dev/js/commit/846022e2cfb12b846aae029b85899fb72fd2c9ad) Thanks [@nachoiacovino](https://github.com/nachoiacovino)! - Fix unlimited price for useActiveClaimConditionForWallet
- [#388](https://github.com/thirdweb-dev/js/pull/388) [`7c0744a`](https://github.com/thirdweb-dev/js/commit/7c0744a006e78987ad8b271b2c64f4bac7759510) Thanks [@adam-maj](https://github.com/adam-maj)! - Add support for total supply and pagination on get all
## 3.6.0
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@thirdweb-dev/react",
"version": "3.6.0",
"version": "3.6.1",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react",
"author": "thirdweb eng <[email protected]>",
"license": "Apache-2.0",
@@ -19,7 +19,7 @@ import {
convertToReadableQuantity,
fetchCurrencyMetadata,
} from "@thirdweb-dev/sdk";
import { BigNumberish, utils } from "ethers";
import { BigNumberish, constants, utils } from "ethers";
import invariant from "tiny-invariant";
/**
@@ -411,7 +411,9 @@ export function useActiveClaimConditionForWallet(
);
const normalizedPrize = price
? utils.parseUnits(price, currencyMetadata.decimals)
? price === "unlimited"
? constants.MaxUint256
: utils.parseUnits(price, currencyMetadata.decimals)
: null;
const priceWithOverride =
+12 -4
View File
@@ -4,17 +4,22 @@ import {
RequiredParam,
} from "../../../core/query-utils/required-param";
import { useQuery } from "@tanstack/react-query";
import { QueryAllParams } from "@thirdweb-dev/sdk";
import type { NFTCollection, NFTDrop } from "@thirdweb-dev/sdk/solana";
export function nftGetAllQuery(
program: RequiredParam<NFTCollection | NFTDrop>,
queryParams?: QueryAllParams,
) {
return {
queryKey: createSOLProgramQueryKey(program, ["getAll"] as const),
queryKey: createSOLProgramQueryKey(program, [
"getAll",
queryParams,
] as const),
queryFn: async () => {
requiredParamInvariant(program, "program is required");
return await program.getAll();
return program.getAll(queryParams);
},
enabled: !!program,
};
@@ -40,6 +45,9 @@ export function nftGetAllQuery(
*
* @public
*/
export function useNFTs(program: RequiredParam<NFTCollection | NFTDrop>) {
return useQuery(nftGetAllQuery(program));
export function useNFTs(
program: RequiredParam<NFTCollection | NFTDrop>,
queryParams?: QueryAllParams,
) {
return useQuery(nftGetAllQuery(program, queryParams));
}
@@ -0,0 +1,47 @@
import { createSOLProgramQueryKey } from "../../../core/query-utils/query-key";
import {
requiredParamInvariant,
RequiredParam,
} from "../../../core/query-utils/required-param";
import { useQuery } from "@tanstack/react-query";
import type { NFTCollection, NFTDrop } from "@thirdweb-dev/sdk/solana";
export function nftTotalSupplyQuery(
program: RequiredParam<NFTCollection | NFTDrop>,
) {
return {
queryKey: createSOLProgramQueryKey(program, ["supply"] as const),
queryFn: async () => {
requiredParamInvariant(program, "program is required");
return program.totalSupply();
},
enabled: !!program,
};
}
/**
* Get the totaly supply of NFTs on the program
* @param program - The NFT program to get the total supply of
*
* @example
* ```jsx
* import { useProgram, useTotalSupply } from "@thirdweb-dev/react/solana";
*
* export default function Component() {
* const { program } = useProgram("{{program_address}}");
* const { data: supply, isLoading } = useTotalSupply(program);
*
* return (
* <pre>{JSON.stringify(supply)}</pre>
* )
* }
* ```
*
* @public
*/
export function useTotalSupply(
program: RequiredParam<NFTCollection | NFTDrop>,
) {
return useQuery(nftTotalSupplyQuery(program));
}
+1
View File
@@ -18,6 +18,7 @@ export * from "./hooks/nft/useRoyaltySettings";
export * from "./hooks/nft/useUpdateRoyaltySettings";
export * from "./hooks/nft/useCreators";
export * from "./hooks/nft/useUpdateCreators";
export * from "./hooks/nft/useTotalSupply";
// NFT Collection
export * from "./hooks/nft/collection/useMintNFT";
+14
View File
@@ -1,5 +1,19 @@
# @thirdweb-dev/sdk
## 3.6.1
### Patch Changes
- [#398](https://github.com/thirdweb-dev/js/pull/398) [`15514f1`](https://github.com/thirdweb-dev/js/commit/15514f190a844d809ae5b1edb580aab46a682485) Thanks [@jnsdls](https://github.com/jnsdls)! - [EVM] - add `defaultValue` to constructorParams schema for releases
- [#388](https://github.com/thirdweb-dev/js/pull/388) [`7c0744a`](https://github.com/thirdweb-dev/js/commit/7c0744a006e78987ad8b271b2c64f4bac7759510) Thanks [@adam-maj](https://github.com/adam-maj)! - Add support for total supply and pagination on get all
- [#395](https://github.com/thirdweb-dev/js/pull/395) [`f8bceec`](https://github.com/thirdweb-dev/js/commit/f8bceec10c60b30dc3d6f45926e2a9e018202578) Thanks [@jnsdls](https://github.com/jnsdls)! - [Solana] - fix claim condition reset to native token from custom
- [#399](https://github.com/thirdweb-dev/js/pull/399) [`887af24`](https://github.com/thirdweb-dev/js/commit/887af24450e316c2ea390cd49c0563cebe793c0f) Thanks [@jnsdls](https://github.com/jnsdls)! - [EVM] - fix custom error handling for null-ish error values
- [#390](https://github.com/thirdweb-dev/js/pull/390) [`96bd92e`](https://github.com/thirdweb-dev/js/commit/96bd92e724ec7d880d23348071b26ab8c21dd868) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - [SDK] Expose `getAllDetectedFeatures(ABI)` helper function
## 3.6.0
### Minor Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@thirdweb-dev/sdk",
"version": "3.6.0",
"version": "3.6.1",
"description": "The main thirdweb SDK.",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/sdk",
"license": "Apache-2.0",
+16 -10
View File
@@ -1,19 +1,25 @@
import { z } from "zod";
/**
* @internal
*/
export const DEFAULT_QUERY_ALL_COUNT = 100;
export const QueryAllParamsSchema = z
.object({
start: z.number().default(0),
count: z.number().default(DEFAULT_QUERY_ALL_COUNT),
})
.default({
start: 0,
count: DEFAULT_QUERY_ALL_COUNT,
});
/**
* Pagination Parameters
* @public
*/
export interface QueryAllParams {
/**
* the index to start from (default: 0)
*/
start?: number;
/**
* how many items to return (default: 100)
*/
count?: number;
}
export type QueryAllParams = Exclude<
z.input<typeof QueryAllParamsSchema>,
undefined
>;
+5 -2
View File
@@ -459,9 +459,12 @@ function parseMessageParts(regex: RegExp, raw: string): string {
* @param message
*/
export function includesErrorMessage(err: any, message: string): boolean {
if (!err) {
return false;
}
return (
(err && err.toString().includes(message)) ||
(err.message && err.message.toString().includes(message)) ||
(err.error && err.error.toString().includes(message))
(err && err.message && err.message.toString().includes(message)) ||
(err && err.error && err.error.toString().includes(message))
);
}
@@ -525,7 +525,7 @@ export async function fetchExtendedReleaseMetadata(
* @returns the nested struct of all features and whether they're detected in the abi
*/
export function detectFeatures(
abi: z.input<typeof AbiSchema>,
abi: Abi,
features: Record<string, Feature> = SUPPORTED_FEATURES,
): Record<string, FeatureWithEnabled> {
const results: Record<string, FeatureWithEnabled> = {};
@@ -542,6 +542,51 @@ export function detectFeatures(
return results;
}
function extractFeatures(
input: Record<string, FeatureWithEnabled>,
enabledExtensions: FeatureWithEnabled[],
) {
if (!input) {
return;
}
for (const extensionKey in input) {
const extension = input[extensionKey];
// if extension is enabled, then add it to enabledFeatures
if (extension.enabled) {
enabledExtensions.push(extension);
}
// recurse
extractFeatures(
extension.features,
enabledExtensions,
);
}
}
/**
* Return all the detected features in the abi
* @param abi - parsed array of abi entries
* @returns array of all detected extensions with full information on each feature
* @public
*/
export function getAllDetectedFeatures(abi: Abi): FeatureWithEnabled[] {
const features: FeatureWithEnabled[] = [];
extractFeatures(detectFeatures(abi), features);
return features;
}
/**
* Return all the detected features names in the abi
* @param abi - parsed array of abi entries
* @returns array of all detected features names
* @public
*/
export function getAllDetectedFeatureNames(abi: Abi): string[] {
const features: FeatureWithEnabled[] = [];
extractFeatures(detectFeatures(abi), features);
return features.map((f) => f.name);
}
/**
* Checks whether the given ABI supports a given feature
* @internal
@@ -162,6 +162,7 @@ export const ExtraPublishMetadataSchemaInput = z
.object({
displayName: z.string().optional(),
description: z.string().optional(),
defaultValue: z.string().optional(),
})
.catchall(z.any()),
)
@@ -194,7 +194,12 @@ export class ClaimConditions {
const data = {
...(wallet && { wallet }),
...(tokenMint && { tokenMint }),
...(tokenMint
? { tokenMint }
: // if passing currencyAddress explcitly as null we need to honor that!
parsed.currencyAddress === null
? { tokenMint: null }
: {}),
...(price && { price }),
...(goLiveDate && { goLiveDate }),
...(sellerFeeBasisPoints && { sellerFeeBasisPoints }),
@@ -1,6 +1,6 @@
import {
QueryAllParams,
DEFAULT_QUERY_ALL_COUNT,
QueryAllParamsSchema,
} from "../../../core/schema/QueryParams";
import { NFT } from "../../../core/schema/nft";
import {
@@ -121,13 +121,73 @@ export class NFTHelper {
}
}
async supplyOf(nftAddress: string): Promise<number> {
let originalEdition;
const originalEditionAccount = await this.metaplex
.rpc()
.getAccount(findMasterEditionV2Pda(new PublicKey(nftAddress)));
if (originalEditionAccount.exists) {
originalEdition = toNftOriginalEdition(
toOriginalEditionAccount(originalEditionAccount),
);
} else {
return 0;
}
// Add one to supply to account for the master edition
return originalEdition.supply.toNumber() + 1;
}
async totalSupply(collectionAddress: string): Promise<number> {
const metadataAddresses = await this.getAllMetadataAddresses(
collectionAddress,
);
return metadataAddresses.length;
}
async getAll(
collectionAddress: string,
queryParams?: QueryAllParams,
): Promise<NFT[]> {
const { start, count } = QueryAllParamsSchema.parse(queryParams);
const metadataAddresses = await this.getAllMetadataAddresses(
collectionAddress,
);
// Metaplex GmaBuilder has a weird thing where they always start at 1 not 0
// so we workaround it by adding an extra address, and shifting the count to get the actual count we want
const fixedMetadataAddresses = (
start === 0 ? [PublicKey.default] : []
).concat(metadataAddresses);
const metadataInfos = await GmaBuilder.make(
this.metaplex,
fixedMetadataAddresses,
).getBetween(start, start === 0 ? count + 1 : start + count);
// Parse each account into a metadata account
const metadataParsed: Metadata<JsonMetadata<string>>[] = [];
for (const metadataInfo of metadataInfos) {
if (metadataInfo.exists) {
try {
metadataParsed.push(toMetadata(toMetadataAccount(metadataInfo)));
} catch (error) {
// no-op
}
}
}
// Finally, fetch the metadata + mint for each in parallel
const nfts = await Promise.all(
metadataParsed.map((m) => this.toNFTMetadata(m)),
);
return nfts;
}
private async getAllMetadataAddresses(collectionAddress: string) {
const collectionKey = new PublicKey(collectionAddress);
const start = queryParams?.start || 0;
const count = queryParams?.count || DEFAULT_QUERY_ALL_COUNT;
// TODO cache signatures <> transactions mapping in memory so pagination doesn't re-request this everytime
const allSignatures: ConfirmedSignatureInfo[] = [];
@@ -205,52 +265,7 @@ export class NFTHelper {
}
}
// Metaplex GmaBuilder has a weird thing where they always start at 1 not 0
// so we workaround it by adding an extra address, and shifting the count to get the actual count we want
const fixedMetadataAddresses = (
start === 0 ? [PublicKey.default] : []
).concat(metadataAddresses);
const metadataInfos = await GmaBuilder.make(
this.metaplex,
fixedMetadataAddresses,
).getBetween(start, start === 0 ? count + 1 : start + count);
// parse each account into a metadata account
const metadataParsed: Metadata<JsonMetadata<string>>[] = [];
for (const metadataInfo of metadataInfos) {
if (metadataInfo.exists) {
try {
metadataParsed.push(toMetadata(toMetadataAccount(metadataInfo)));
} catch (error) {
// ignore
}
}
}
// finally fetch the metadta + mint for each in parallel
const nfts = await Promise.all(
metadataParsed.map((m) => this.toNFTMetadata(m)),
);
return nfts;
}
async supplyOf(nftAddress: string): Promise<number> {
let originalEdition;
const originalEditionAccount = await this.metaplex
.rpc()
.getAccount(findMasterEditionV2Pda(new PublicKey(nftAddress)));
if (originalEditionAccount.exists) {
originalEdition = toNftOriginalEdition(
toOriginalEditionAccount(originalEditionAccount),
);
} else {
return 0;
}
// Add one to supply to account for the master edition
return originalEdition.supply.toNumber() + 1;
return metadataAddresses;
}
async toNFTMetadata(
@@ -140,6 +140,18 @@ export class NFTCollection {
return this.nft.getAll(this.publicKey.toBase58(), queryParams);
}
/**
* Get the total number of nfts minted on this program
* @returns the total number of NFTs minted on this program
*
* ```jsx
* const totalSupply = await program.totalSupply();
* ```
*/
async totalSupply(): Promise<number> {
return this.nft.totalSupply(this.publicKey.toBase58());
}
/**
* Get the NFT balance of the connected wallet
* @returns the NFT balance
+55 -15
View File
@@ -1,3 +1,7 @@
import {
QueryAllParams,
QueryAllParamsSchema,
} from "../../core/schema/QueryParams";
import {
CommonNFTInput,
NFT,
@@ -166,22 +170,37 @@ export class NFTDrop {
* console.log(nfts[0].metadata.name);
* ```
*/
async getAll(): Promise<NFT[]> {
// TODO: Add pagination to get NFT functions
async getAll(queryParams?: QueryAllParams): Promise<NFT[]> {
const parsedQueryParams = QueryAllParamsSchema.parse(queryParams);
const info = await this.getCandyMachine();
const claimed = await this.getAllClaimed();
return await Promise.all(
info.items.map(async (item) => {
// Check if the NFT has been claimed
// TODO: This only checks name/uri which is potentially not unique
const claimedNFT = claimed.find(
// First, get all the claimed NFTs within the query params range
const claimedNfts = await this.getAllClaimed(parsedQueryParams);
const totalClaimed = await this.totalClaimedSupply();
// Then filter out all claimed NFTs from items to leave only unclaimed remaining
const unclaimedItems: CandyMachineItem[] = [];
info.items.forEach((item) => {
const isClaimed =
claimedNfts.filter(
(nft) =>
nft.metadata.name === item.name && nft.metadata.uri === item.uri,
);
if (claimedNFT) {
return claimedNFT;
}
// not claimed yet, return a unclaimed NFT with just the metadata
).length > 0;
if (!isClaimed) {
unclaimedItems.push(item);
}
});
// Only fill the remaining count left over after claimed NFTs with unclaimed NFTs
const startIndex = Math.max(0, parsedQueryParams.start - totalClaimed);
const endIndex = Math.max(
0,
startIndex + parsedQueryParams.count - claimedNfts.length,
);
const unclaimedNfts = await Promise.all(
unclaimedItems.slice(startIndex, endIndex).map(async (item) => {
const metadata: NFTMetadata = await this.storage.downloadJSON(item.uri);
return {
metadata: {
@@ -195,6 +214,9 @@ export class NFTDrop {
} as NFT;
}),
);
// Always return claimed NFTs first, and then fill remaining query count with unclaimed NFTs
return [...claimedNfts, ...unclaimedNfts];
}
/**
@@ -208,11 +230,14 @@ export class NFTDrop {
* console.log(nfts[0].name)
* ```
*/
async getAllClaimed(): Promise<NFT[]> {
async getAllClaimed(queryParams?: QueryAllParams): Promise<NFT[]> {
// using getAll from collection here because candy machin findAllMinted doesn't return anything
const candy = await this.getCandyMachine();
invariant(candy.collectionMintAddress, "Collection mint address not found");
return await this.nft.getAll(candy.collectionMintAddress.toBase58());
return await this.nft.getAll(
candy.collectionMintAddress.toBase58(),
queryParams,
);
}
/**
@@ -268,6 +293,21 @@ export class NFTDrop {
return this.nft.ownerOf(nftAddress);
}
/**
* Get the total minted supply of this drop
* @returns the total supply
*
* @example
* ```jsx
* // Get the total number of NFTs that have been minted on this drop
* const supply = await program.totalSupply();
* ```
*/
async totalSupply(): Promise<number> {
const info = await this.getCandyMachine();
return info.itemsLoaded.toNumber();
}
/**
* Get the total unclaimed supply of this drop
* @returns the total supply
+15 -3
View File
@@ -1,6 +1,5 @@
import {
ChainId,
isFeatureEnabled,
ChainId, getAllDetectedFeatureNames, isFeatureEnabled,
resolveContractUriFromAddress,
ThirdwebSDK,
} from "../../src/evm";
@@ -8,7 +7,7 @@ import { implementations, signers } from "./before-setup";
import { AddressZero } from "@ethersproject/constants";
import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers";
import {
DropERC721__factory,
DropERC721__factory, DropERC721_V3__factory,
TokenERC721__factory,
} from "@thirdweb-dev/contracts-js";
import { ThirdwebStorage } from "@thirdweb-dev/storage";
@@ -94,6 +93,19 @@ describe("Publishing", async () => {
);
});
it("should extract all features", async () => {
const tokenFeatures = getAllDetectedFeatureNames(TokenERC721__factory.abi);
expect(
tokenFeatures
).to.contain("ERC721Enumerable");
expect(
getAllDetectedFeatureNames(DropERC721__factory.abi)
).to.contain("ERC721ClaimPhasesV2");
expect(
getAllDetectedFeatureNames(DropERC721_V3__factory.abi)
).to.contain("ERC721ClaimPhasesV1");
});
it("should update bio", async () => {
const address = adminWallet.address;
const publisher = sdk.getPublisher();
+40
View File
@@ -152,4 +152,44 @@ describe("NFTDrop", async () => {
royalty = await drop.getRoyalty();
expect(royalty).to.equal(100);
});
it("Should get all correctly", async () => {
const address = await sdk.deployer.createNftDrop({
name: "NFT Drop #1",
totalSupply: 5,
});
const contract = await sdk.getNFTDrop(address);
await contract.lazyMint([
{ name: "NFT #1", description: "This is the #1 NFT" },
{ name: "NFT #2", description: "This is the #2 NFT" },
{ name: "NFT #3", description: "This is the #3 NFT" },
{ name: "NFT #4", description: "This is the #4 NFT" },
{ name: "NFT #5", description: "This is the #5 NFT" },
]);
let all = await contract.getAll();
expect(all.length).to.equal(5);
expect(all[0].metadata.name).to.equal("NFT #1");
expect(all.filter((nft) => nft.supply > 0).length).to.equal(0);
await contract.claimConditions.set({
price: 0,
maxClaimable: 5,
});
await contract.claim(2);
all = await contract.getAll();
expect(all.length).to.equal(5);
expect(all[0].supply).to.equal(1);
expect(all[1].supply).to.equal(1);
expect(all[2].supply).to.equal(0);
all = await contract.getAll({ start: 2, count: 3 });
expect(all.length).to.equal(3);
expect(all.filter((nft) => nft.supply > 0).length).to.equal(0);
all = await contract.getAll({ start: 0, count: 3 });
expect(all.filter((nft) => nft.supply > 0).length).to.equal(2);
});
});