From 9dca566aa65add8005229650b25e132bc3d1db35 Mon Sep 17 00:00:00 2001 From: Joaquim Verges Date: Sat, 25 Jun 2022 22:34:14 -0700 Subject: [PATCH 1/5] Multichain SDK - override chain for any contract --- docs/sdk.chainandaddress.md | 14 ++ docs/sdk.md | 1 + docs/sdk.thirdwebsdk.getcontract.md | 3 +- docs/sdk.thirdwebsdk.getcontractfromabi.md | 3 +- docs/sdk.thirdwebsdk.getedition.md | 4 +- docs/sdk.thirdwebsdk.geteditiondrop.md | 4 +- docs/sdk.thirdwebsdk.getmarketplace.md | 4 +- docs/sdk.thirdwebsdk.getmultiwrap.md | 4 +- docs/sdk.thirdwebsdk.getnftcollection.md | 4 +- docs/sdk.thirdwebsdk.getnftdrop.md | 4 +- docs/sdk.thirdwebsdk.getpack.md | 4 +- docs/sdk.thirdwebsdk.getsplit.md | 4 +- docs/sdk.thirdwebsdk.gettoken.md | 4 +- docs/sdk.thirdwebsdk.gettokendrop.md | 4 +- docs/sdk.thirdwebsdk.getvote.md | 4 +- docs/sdk.thirdwebsdk.md | 4 +- etc/sdk.api.md | 70 ++++++++-- src/core/classes/contract-analytics.ts | 29 ---- src/core/sdk.ts | 155 ++++++++++++++------- src/core/types.ts | 6 + test/edition.test.ts | 2 +- 21 files changed, 207 insertions(+), 124 deletions(-) create mode 100644 docs/sdk.chainandaddress.md delete mode 100644 src/core/classes/contract-analytics.ts diff --git a/docs/sdk.chainandaddress.md b/docs/sdk.chainandaddress.md new file mode 100644 index 000000000..dfae84f56 --- /dev/null +++ b/docs/sdk.chainandaddress.md @@ -0,0 +1,14 @@ + + +[Home](./index.md) > [@thirdweb-dev/sdk](./sdk.md) > [ChainAndAddress](./sdk.chainandaddress.md) + +## ChainAndAddress type + +Signature: + +```typescript +export declare type ChainAndAddress = { + chainId: ChainIdOrName; + address: string; +}; +``` diff --git a/docs/sdk.md b/docs/sdk.md index 9968611c1..38e573495 100644 --- a/docs/sdk.md +++ b/docs/sdk.md @@ -132,6 +132,7 @@ | [AirdropInput](./sdk.airdropinput.md) | Input model to pass a list of addresses + amount to transfer to each one | | [Amount](./sdk.amount.md) | Represents a currency amount already formatted. ie. "1" for 1 ether. | | [BufferOrStringWithName](./sdk.bufferorstringwithname.md) | | +| [ChainAndAddress](./sdk.chainandaddress.md) | | | [ClaimCondition](./sdk.claimcondition.md) | Represents a claim condition fetched from the SDK | | [ClaimConditionInput](./sdk.claimconditioninput.md) | Input model to create a claim condition with optional snapshot of wallets | | [ClaimConditionsForToken](./sdk.claimconditionsfortoken.md) | | diff --git a/docs/sdk.thirdwebsdk.getcontract.md b/docs/sdk.thirdwebsdk.getcontract.md index ed46e3c7a..a4fe43aaf 100644 --- a/docs/sdk.thirdwebsdk.getcontract.md +++ b/docs/sdk.thirdwebsdk.getcontract.md @@ -12,7 +12,7 @@ Get an instance of a Custom ThirdwebContract Signature: ```typescript -getContract(address: string): Promise>; +getContract(address: string, chain?: number): Promise>; ``` ## Parameters @@ -20,6 +20,7 @@ getContract(address: string): Promise(Optional) optional the chain (id or name) of the contract (defaults to the SDK chainId) | Returns: diff --git a/docs/sdk.thirdwebsdk.getcontractfromabi.md b/docs/sdk.thirdwebsdk.getcontractfromabi.md index f92059145..4f88977c1 100644 --- a/docs/sdk.thirdwebsdk.getcontractfromabi.md +++ b/docs/sdk.thirdwebsdk.getcontractfromabi.md @@ -12,7 +12,7 @@ Get an instance of a Custom contract from a json ABI Signature: ```typescript -getContractFromAbi(address: string, abi: ContractInterface): SmartContract; +getContractFromAbi(address: string, abi: ContractInterface, chain?: ChainIdOrName): SmartContract; ``` ## Parameters @@ -21,6 +21,7 @@ getContractFromAbi(address: string, abi: ContractInterface): SmartContract(Optional) optional the chain (id or name) of the contract (defaults to the SDK chainId) | Returns: diff --git a/docs/sdk.thirdwebsdk.getedition.md b/docs/sdk.thirdwebsdk.getedition.md index 39c558230..933d77a4b 100644 --- a/docs/sdk.thirdwebsdk.getedition.md +++ b/docs/sdk.thirdwebsdk.getedition.md @@ -9,7 +9,7 @@ Get an instance of an Edition contract Signature: ```typescript -getEdition(address: string): Edition; +getEdition(address: string): Promise; ``` ## Parameters @@ -20,7 +20,7 @@ getEdition(address: string): Edition; Returns: -[Edition](./sdk.edition.md) +Promise<[Edition](./sdk.edition.md)> the contract diff --git a/docs/sdk.thirdwebsdk.geteditiondrop.md b/docs/sdk.thirdwebsdk.geteditiondrop.md index 565be2607..d66967797 100644 --- a/docs/sdk.thirdwebsdk.geteditiondrop.md +++ b/docs/sdk.thirdwebsdk.geteditiondrop.md @@ -9,7 +9,7 @@ Get an instance of a Edition Drop contract Signature: ```typescript -getEditionDrop(address: string): EditionDrop; +getEditionDrop(address: string): Promise; ``` ## Parameters @@ -20,7 +20,7 @@ getEditionDrop(address: string): EditionDrop; Returns: -[EditionDrop](./sdk.editiondrop.md) +Promise<[EditionDrop](./sdk.editiondrop.md)> the contract diff --git a/docs/sdk.thirdwebsdk.getmarketplace.md b/docs/sdk.thirdwebsdk.getmarketplace.md index ba91735b8..ad84f2e71 100644 --- a/docs/sdk.thirdwebsdk.getmarketplace.md +++ b/docs/sdk.thirdwebsdk.getmarketplace.md @@ -9,7 +9,7 @@ Get an instance of a Marketplace contract Signature: ```typescript -getMarketplace(address: string): Marketplace; +getMarketplace(address: string): Promise; ``` ## Parameters @@ -20,7 +20,7 @@ getMarketplace(address: string): Marketplace; Returns: -[Marketplace](./sdk.marketplace.md) +Promise<[Marketplace](./sdk.marketplace.md)> the contract diff --git a/docs/sdk.thirdwebsdk.getmultiwrap.md b/docs/sdk.thirdwebsdk.getmultiwrap.md index 1d873b3a1..c948e6f07 100644 --- a/docs/sdk.thirdwebsdk.getmultiwrap.md +++ b/docs/sdk.thirdwebsdk.getmultiwrap.md @@ -12,7 +12,7 @@ Get an instance of a Multiwrap contract Signature: ```typescript -getMultiwrap(address: string): Multiwrap; +getMultiwrap(address: string): Promise; ``` ## Parameters @@ -23,7 +23,7 @@ getMultiwrap(address: string): Multiwrap; Returns: -[Multiwrap](./sdk.multiwrap.md) +Promise<[Multiwrap](./sdk.multiwrap.md)> the contract diff --git a/docs/sdk.thirdwebsdk.getnftcollection.md b/docs/sdk.thirdwebsdk.getnftcollection.md index 74d245ca0..4971cf410 100644 --- a/docs/sdk.thirdwebsdk.getnftcollection.md +++ b/docs/sdk.thirdwebsdk.getnftcollection.md @@ -9,7 +9,7 @@ Get an instance of a NFT Collection contract Signature: ```typescript -getNFTCollection(address: string): NFTCollection; +getNFTCollection(address: string): Promise; ``` ## Parameters @@ -20,7 +20,7 @@ getNFTCollection(address: string): NFTCollection; Returns: -[NFTCollection](./sdk.nftcollection.md) +Promise<[NFTCollection](./sdk.nftcollection.md)> the contract diff --git a/docs/sdk.thirdwebsdk.getnftdrop.md b/docs/sdk.thirdwebsdk.getnftdrop.md index 25feed37a..2daf31415 100644 --- a/docs/sdk.thirdwebsdk.getnftdrop.md +++ b/docs/sdk.thirdwebsdk.getnftdrop.md @@ -9,7 +9,7 @@ Get an instance of a Drop contract Signature: ```typescript -getNFTDrop(contractAddress: string): NFTDrop; +getNFTDrop(contractAddress: string): Promise; ``` ## Parameters @@ -20,7 +20,7 @@ getNFTDrop(contractAddress: string): NFTDrop; Returns: -[NFTDrop](./sdk.nftdrop.md) +Promise<[NFTDrop](./sdk.nftdrop.md)> the contract diff --git a/docs/sdk.thirdwebsdk.getpack.md b/docs/sdk.thirdwebsdk.getpack.md index e54ba18bb..6add753ea 100644 --- a/docs/sdk.thirdwebsdk.getpack.md +++ b/docs/sdk.thirdwebsdk.getpack.md @@ -9,7 +9,7 @@ Get an instance of a Pack contract Signature: ```typescript -getPack(address: string): Pack; +getPack(address: string): Promise; ``` ## Parameters @@ -20,7 +20,7 @@ getPack(address: string): Pack; Returns: -[Pack](./sdk.pack.md) +Promise<[Pack](./sdk.pack.md)> the contract diff --git a/docs/sdk.thirdwebsdk.getsplit.md b/docs/sdk.thirdwebsdk.getsplit.md index a30111057..29e09f963 100644 --- a/docs/sdk.thirdwebsdk.getsplit.md +++ b/docs/sdk.thirdwebsdk.getsplit.md @@ -9,7 +9,7 @@ Get an instance of a Splits contract Signature: ```typescript -getSplit(address: string): Split; +getSplit(address: string): Promise; ``` ## Parameters @@ -20,7 +20,7 @@ getSplit(address: string): Split; Returns: -[Split](./sdk.split.md) +Promise<[Split](./sdk.split.md)> the contract diff --git a/docs/sdk.thirdwebsdk.gettoken.md b/docs/sdk.thirdwebsdk.gettoken.md index decb10273..41d57c30c 100644 --- a/docs/sdk.thirdwebsdk.gettoken.md +++ b/docs/sdk.thirdwebsdk.gettoken.md @@ -9,7 +9,7 @@ Get an instance of a Token contract Signature: ```typescript -getToken(address: string): Token; +getToken(address: string): Promise; ``` ## Parameters @@ -20,7 +20,7 @@ getToken(address: string): Token; Returns: -[Token](./sdk.token.md) +Promise<[Token](./sdk.token.md)> the contract diff --git a/docs/sdk.thirdwebsdk.gettokendrop.md b/docs/sdk.thirdwebsdk.gettokendrop.md index d70ab189c..01fad0f48 100644 --- a/docs/sdk.thirdwebsdk.gettokendrop.md +++ b/docs/sdk.thirdwebsdk.gettokendrop.md @@ -9,7 +9,7 @@ Get an instance of a Token Drop contract Signature: ```typescript -getTokenDrop(address: string): TokenDrop; +getTokenDrop(address: string): Promise; ``` ## Parameters @@ -20,7 +20,7 @@ getTokenDrop(address: string): TokenDrop; Returns: -[TokenDrop](./sdk.tokendrop.md) +Promise<[TokenDrop](./sdk.tokendrop.md)> the contract diff --git a/docs/sdk.thirdwebsdk.getvote.md b/docs/sdk.thirdwebsdk.getvote.md index f0020d85d..2cac02d5e 100644 --- a/docs/sdk.thirdwebsdk.getvote.md +++ b/docs/sdk.thirdwebsdk.getvote.md @@ -9,7 +9,7 @@ Get an instance of a Vote contract Signature: ```typescript -getVote(address: string): Vote; +getVote(address: string): Promise; ``` ## Parameters @@ -20,7 +20,7 @@ getVote(address: string): Vote; Returns: -[Vote](./sdk.vote.md) +Promise<[Vote](./sdk.vote.md)> the contract diff --git a/docs/sdk.thirdwebsdk.md b/docs/sdk.thirdwebsdk.md index 7dad338f7..76effed71 100644 --- a/docs/sdk.thirdwebsdk.md +++ b/docs/sdk.thirdwebsdk.md @@ -35,8 +35,8 @@ export declare class ThirdwebSDK extends RPCConnectionHandler | [fromPrivateKey(privateKey, chain, options, storage)](./sdk.thirdwebsdk.fromprivatekey.md) | static | (BETA) Get an instance of the thirdweb SDK based on a private key. | | [fromSigner(signer, chain, options, storage)](./sdk.thirdwebsdk.fromsigner.md) | static | (BETA) Get an instance of the thirdweb SDK based on an existing ethers signer | | [getBalance(address)](./sdk.thirdwebsdk.getbalance.md) | | Get the native balance of a given address (wallet or contract) | -| [getContract(address)](./sdk.thirdwebsdk.getcontract.md) | | (BETA) Get an instance of a Custom ThirdwebContract | -| [getContractFromAbi(address, abi)](./sdk.thirdwebsdk.getcontractfromabi.md) | | (BETA) Get an instance of a Custom contract from a json ABI | +| [getContract(address, chain)](./sdk.thirdwebsdk.getcontract.md) | | (BETA) Get an instance of a Custom ThirdwebContract | +| [getContractFromAbi(address, abi, chain)](./sdk.thirdwebsdk.getcontractfromabi.md) | | (BETA) Get an instance of a Custom contract from a json ABI | | [getContractList(walletAddress)](./sdk.thirdwebsdk.getcontractlist.md) | | Return all the contracts deployed by the specified address | | [getEdition(address)](./sdk.thirdwebsdk.getedition.md) | | Get an instance of an Edition contract | | [getEditionDrop(address)](./sdk.thirdwebsdk.geteditiondrop.md) | | Get an instance of a Edition Drop contract | diff --git a/etc/sdk.api.md b/etc/sdk.api.md index e4ff30947..31b222eab 100644 --- a/etc/sdk.api.md +++ b/etc/sdk.api.md @@ -152,6 +152,12 @@ export type BufferOrStringWithName = { name?: string; }; +// @public (undocumented) +export type ChainAndAddress = { + chainId: ChainIdOrName; + address: string; +}; + // @public (undocumented) export enum ChainId { // (undocumented) @@ -5006,34 +5012,64 @@ export class ThirdwebSDK extends RPCConnectionHandler { static fromSigner(signer: Signer, chain: ChainIdOrName, options?: SDKOptions, storage?: IStorage): ThirdwebSDK; getBalance(address: string): Promise; // @internal (undocumented) - getBuiltInContract(address: string, contractType: TContractType): ContractForContractType; + getBuiltInContract(address: string, contractType: TContractType, chain?: ChainIdOrName): Promise<{ + readonly custom: typeof SmartContract; + readonly "nft-drop": typeof NFTDrop; + readonly "signature-drop": typeof SignatureDrop; + readonly "nft-collection": typeof NFTCollection; + readonly "edition-drop": typeof EditionDrop; + readonly edition: typeof Edition; + readonly "token-drop": typeof TokenDrop; + readonly token: typeof Token; + readonly vote: typeof Vote; + readonly split: typeof Split; + readonly marketplace: typeof Marketplace; + readonly pack: typeof Pack; + readonly multiwrap: typeof Multiwrap; + }[TContractType] extends infer T ? T extends { + readonly custom: typeof SmartContract; + readonly "nft-drop": typeof NFTDrop; + readonly "signature-drop": typeof SignatureDrop; + readonly "nft-collection": typeof NFTCollection; + readonly "edition-drop": typeof EditionDrop; + readonly edition: typeof Edition; + readonly "token-drop": typeof TokenDrop; + readonly token: typeof Token; + readonly vote: typeof Vote; + readonly split: typeof Split; + readonly marketplace: typeof Marketplace; + readonly pack: typeof Pack; + readonly multiwrap: typeof Multiwrap; + }[TContractType] ? T extends new (...args: any[]) => object ? object : any : never : never>; // @beta - getContract(address: string): Promise>; + getContract(address: string, chain?: number): Promise>; + // Warning: (ae-incompatible-release-tags) The symbol "getContractFromAbi" is marked as @beta, but its signature references "ChainIdOrName" which is marked as @internal + // // @beta - getContractFromAbi(address: string, abi: ContractInterface): SmartContract; + getContractFromAbi(address: string, abi: ContractInterface, chain?: ChainIdOrName): SmartContract; getContractList(walletAddress: string): Promise<{ address: string; contractType: "custom" | "token" | "split" | "edition" | "edition-drop" | "token-drop" | "vote" | "marketplace" | "pack" | "nft-drop" | "signature-drop" | "multiwrap" | "nft-collection"; metadata: () => Promise; }[]>; - getEdition(address: string): Edition; - getEditionDrop(address: string): EditionDrop; - getMarketplace(address: string): Marketplace; + getEdition(address: string): Promise; + getEditionDrop(address: string): Promise; + getMarketplace(address: string): Promise; // @beta - getMultiwrap(address: string): Multiwrap; - getNFTCollection(address: string): NFTCollection; - getNFTDrop(contractAddress: string): NFTDrop; - getPack(address: string): Pack; + getMultiwrap(address: string): Promise; + getNFTCollection(address: string): Promise; + getNFTDrop(contractAddress: string): Promise; + getPack(address: string): Promise; // Warning: (ae-forgotten-export) The symbol "ContractPublisher" needs to be exported by the entry point index.d.ts // // @internal (undocumented) getPublisher(): ContractPublisher; // @internal - getSignatureDrop(contractAddress: string): SignatureDrop; - getSplit(address: string): Split; - getToken(address: string): Token; - getTokenDrop(address: string): TokenDrop; - getVote(address: string): Vote; + getSignatureDrop(contractAddress: string): Promise; + getSplit(address: string): Promise; + getToken(address: string): Promise; + getTokenDrop(address: string): Promise; + getVote(address: string): Promise; // (undocumented) resolveContractType(contractAddress: string): Promise; storage: RemoteStorage; @@ -5649,6 +5685,10 @@ export class WrongListingTypeError extends Error { constructor(marketplaceContractAddress: string, listingId?: string, actualType?: string, expectedType?: string); } +// Warnings were encountered during analysis: +// +// dist/src/core/types.d.ts:48:5 - (ae-incompatible-release-tags) The symbol "chainId" is marked as @public, but its signature references "ChainIdOrName" which is marked as @internal + // (No @packageDocumentation comment for this package) ``` diff --git a/src/core/classes/contract-analytics.ts b/src/core/classes/contract-analytics.ts deleted file mode 100644 index fbd2463db..000000000 --- a/src/core/classes/contract-analytics.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { BaseContract, Event } from "ethers"; -import { ContractWrapper } from "./contract-wrapper"; - -export class ContractAnalytics { - private contractWrapper: ContractWrapper; - - constructor(contractWrapper: ContractWrapper) { - this.contractWrapper = contractWrapper; - } - - public async query( - eventName: keyof TContract["filters"] | string, - ): Promise { - const event = this.contractWrapper.readContract.interface.getEvent( - eventName as string, - ); - const filter = this.contractWrapper.readContract.filters[event.name]; - - // TODO limit the number of blocks queried - const fromBlock = 0; - const toBlock = - await this.contractWrapper.readContract.provider.getBlockNumber(); - return await this.contractWrapper.readContract.queryFilter( - filter(), - fromBlock, - toBlock, - ); - } -} diff --git a/src/core/sdk.ts b/src/core/sdk.ts index 6fcedaffb..e5c0201f4 100644 --- a/src/core/sdk.ts +++ b/src/core/sdk.ts @@ -42,6 +42,7 @@ import { Multiwrap } from "../contracts/multiwrap"; import { WalletAuthenticator } from "./auth/wallet-authenticator"; import { CurrencyValue } from "../types/index"; import { fetchCurrencyValue } from "../common/currency"; +import { ChainAndAddress } from "./types"; /** * The main entry point for the thirdweb SDK @@ -116,7 +117,7 @@ export class ThirdwebSDK extends RPCConnectionHandler { * the cache of contracts that we have already seen */ private contractCache = new Map< - string, + ChainAndAddress, ValidContractInstance | SmartContract >(); /** @@ -161,11 +162,19 @@ export class ThirdwebSDK extends RPCConnectionHandler { super(connection, options); this.storageHandler = storage; this.storage = new RemoteStorage(storage); - this.deployer = new ContractDeployer(connection, options, storage); - this.wallet = new UserWallet(connection, options); - this.auth = new WalletAuthenticator(connection, this.wallet, options); + this.deployer = new ContractDeployer( + this.getConnectionInfo(), + options, + storage, + ); + this.wallet = new UserWallet(this.getConnectionInfo(), options); + this.auth = new WalletAuthenticator( + this.getConnectionInfo(), + this.wallet, + options, + ); this._publisher = new ContractPublisher( - connection, + this.getConnectionInfo(), this.options, this.storageHandler, ); @@ -184,11 +193,11 @@ export class ThirdwebSDK extends RPCConnectionHandler { * @param contractAddress - the address of the deployed contract * @returns the contract */ - public getNFTDrop(contractAddress: string): NFTDrop { - return this.getBuiltInContract( + public async getNFTDrop(contractAddress: string): Promise { + return this.getBuiltInContract<"nft-drop">( contractAddress, NFTDrop.contractType, - ) as NFTDrop; + ); } /** @@ -197,11 +206,13 @@ export class ThirdwebSDK extends RPCConnectionHandler { * @returns the contract * @internal */ - public getSignatureDrop(contractAddress: string): SignatureDrop { - return this.getBuiltInContract( + public async getSignatureDrop( + contractAddress: string, + ): Promise { + return this.getBuiltInContract<"signature-drop">( contractAddress, SignatureDrop.contractType, - ) as SignatureDrop; + ); } /** @@ -209,11 +220,11 @@ export class ThirdwebSDK extends RPCConnectionHandler { * @param address - the address of the deployed contract * @returns the contract */ - public getNFTCollection(address: string): NFTCollection { - return this.getBuiltInContract( + public async getNFTCollection(address: string): Promise { + return this.getBuiltInContract<"nft-collection">( address, NFTCollection.contractType, - ) as NFTCollection; + ); } /** @@ -221,11 +232,11 @@ export class ThirdwebSDK extends RPCConnectionHandler { * @param address - the address of the deployed contract * @returns the contract */ - public getEditionDrop(address: string): EditionDrop { - return this.getBuiltInContract( + public async getEditionDrop(address: string): Promise { + return this.getBuiltInContract<"edition-drop">( address, EditionDrop.contractType, - ) as EditionDrop; + ); } /** @@ -233,8 +244,8 @@ export class ThirdwebSDK extends RPCConnectionHandler { * @param address - the address of the deployed contract * @returns the contract */ - public getEdition(address: string): Edition { - return this.getBuiltInContract(address, Edition.contractType) as Edition; + public async getEdition(address: string): Promise { + return this.getBuiltInContract<"edition">(address, Edition.contractType); } /** @@ -242,11 +253,11 @@ export class ThirdwebSDK extends RPCConnectionHandler { * @param address - the address of the deployed contract * @returns the contract */ - public getTokenDrop(address: string): TokenDrop { - return this.getBuiltInContract( + public async getTokenDrop(address: string): Promise { + return this.getBuiltInContract<"token-drop">( address, TokenDrop.contractType, - ) as TokenDrop; + ); } /** @@ -254,8 +265,8 @@ export class ThirdwebSDK extends RPCConnectionHandler { * @param address - the address of the deployed contract * @returns the contract */ - public getToken(address: string): Token { - return this.getBuiltInContract(address, Token.contractType) as Token; + public async getToken(address: string): Promise { + return this.getBuiltInContract<"token">(address, Token.contractType); } /** @@ -263,8 +274,8 @@ export class ThirdwebSDK extends RPCConnectionHandler { * @param address - the address of the deployed contract * @returns the contract */ - public getVote(address: string): Vote { - return this.getBuiltInContract(address, Vote.contractType) as Vote; + public async getVote(address: string): Promise { + return this.getBuiltInContract<"vote">(address, Vote.contractType); } /** @@ -272,8 +283,8 @@ export class ThirdwebSDK extends RPCConnectionHandler { * @param address - the address of the deployed contract * @returns the contract */ - public getSplit(address: string): Split { - return this.getBuiltInContract(address, Split.contractType) as Split; + public async getSplit(address: string): Promise { + return this.getBuiltInContract<"split">(address, Split.contractType); } /** @@ -281,11 +292,11 @@ export class ThirdwebSDK extends RPCConnectionHandler { * @param address - the address of the deployed contract * @returns the contract */ - public getMarketplace(address: string): Marketplace { - return this.getBuiltInContract( + public async getMarketplace(address: string): Promise { + return this.getBuiltInContract<"marketplace">( address, Marketplace.contractType, - ) as Marketplace; + ); } /** @@ -293,8 +304,8 @@ export class ThirdwebSDK extends RPCConnectionHandler { * @param address - the address of the deployed contract * @returns the contract */ - public getPack(address: string): Pack { - return this.getBuiltInContract(address, Pack.contractType) as Pack; + public async getPack(address: string): Promise { + return this.getBuiltInContract<"pack">(address, Pack.contractType); } /** @@ -303,30 +314,36 @@ export class ThirdwebSDK extends RPCConnectionHandler { * @returns the contract * @beta */ - public getMultiwrap(address: string): Multiwrap { - return this.getBuiltInContract( + public async getMultiwrap(address: string): Promise { + return this.getBuiltInContract<"multiwrap">( address, Multiwrap.contractType, - ) as Multiwrap; + ); } /** * * @internal * @param address - the address of the contract to instantiate - * @param contractType - optional, the type of contract to instantiate + * @param contractType - the type of contract to instantiate + * @param chain - optional the chain (id or name) of the contract (defaults to the SDK chainId) * @returns a promise that resolves with the contract instance */ - public getBuiltInContract( + public async getBuiltInContract< + TContractType extends ContractType = ContractType, + >( address: string, contractType: TContractType, - ): ContractForContractType { + chain: ChainIdOrName = this.getConnectionInfo().chainId, + ) { + const chainId = typeof chain === "string" ? chainNameToId[chain] : chain; // if we have a contract in the cache we will return it // we will do this **without** checking any contract type things for simplicity, this may have to change in the future? - if (this.contractCache.has(address)) { - return this.contractCache.get( + if (this.contractCache.has({ chainId, address })) { + return this.contractCache.get({ + chainId, address, - ) as ContractForContractType; + }) as ContractForContractType; } if (contractType === "custom") { @@ -335,11 +352,20 @@ export class ThirdwebSDK extends RPCConnectionHandler { ); } + let connectionInfo = this.getConnectionInfo(); + if (chainId !== this.getConnectionInfo().chainId) { + connectionInfo = { + chainId, + provider: undefined, + signer: connectionInfo.signer, + }; + } + const newContract = new KNOWN_CONTRACTS_MAP[ contractType as keyof typeof KNOWN_CONTRACTS_MAP - ](this.getConnectionInfo(), address, this.storageHandler, this.options); + ](connectionInfo, address, this.storageHandler, this.options); - this.contractCache.set(address, newContract); + this.contractCache.set({ chainId, address }, newContract); // return the new contract return newContract as ContractForContractType; @@ -397,7 +423,11 @@ export class ThirdwebSDK extends RPCConnectionHandler { ); } } else { - metadata = this.getBuiltInContract(address, contractType).metadata; + const builtInContract = await this.getBuiltInContract( + address, + contractType, + ); + metadata = builtInContract.metadata; } return { address, @@ -422,12 +452,17 @@ export class ThirdwebSDK extends RPCConnectionHandler { /** * Get an instance of a Custom ThirdwebContract * @param address - the address of the deployed contract + * @param chain - optional the chain (id or name) of the contract (defaults to the SDK chainId) * @returns the contract * @beta */ - public async getContract(address: string) { - if (this.contractCache.has(address)) { - return this.contractCache.get(address) as SmartContract; + public async getContract( + address: string, + chain: number = this.getConnectionInfo().chainId, + ) { + const chainId = typeof chain === "string" ? chainNameToId[chain] : chain; + if (this.contractCache.has({ chainId, address })) { + return this.contractCache.get({ chainId, address }) as SmartContract; } try { const publisher = this.getPublisher(); @@ -444,21 +479,35 @@ export class ThirdwebSDK extends RPCConnectionHandler { * Get an instance of a Custom contract from a json ABI * @param address - the address of the deployed contract * @param abi - the JSON abi + * @param chain - optional the chain (id or name) of the contract (defaults to the SDK chainId) * @returns the contract * @beta */ - public getContractFromAbi(address: string, abi: ContractInterface) { - if (this.contractCache.has(address)) { - return this.contractCache.get(address) as SmartContract; + public getContractFromAbi( + address: string, + abi: ContractInterface, + chain: ChainIdOrName = this.getConnectionInfo().chainId, + ) { + const chainId = typeof chain === "string" ? chainNameToId[chain] : chain; + if (this.contractCache.has({ chainId, address })) { + return this.contractCache.get({ chainId, address }) as SmartContract; + } + let connectionInfo = this.getConnectionInfo(); + if (chainId !== this.getConnectionInfo().chainId) { + connectionInfo = { + chainId, + provider: undefined, + signer: connectionInfo.signer, + }; } const contract = new SmartContract( - this.getConnectionInfo(), + connectionInfo, address, abi, this.storageHandler, this.options, ); - this.contractCache.set(address, contract); + this.contractCache.set({ chainId, address }, contract); return contract; } diff --git a/src/core/types.ts b/src/core/types.ts index 5c9a8a001..017d6b06e 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -1,5 +1,6 @@ import { BigNumber, BytesLike, CallOverrides, Signer, providers } from "ethers"; import type { CONTRACTS_MAP, KNOWN_CONTRACTS_MAP } from "../contracts/maps"; +import { ChainIdOrName } from "../constants/index"; // --- utility types extracted from from ts-toolbelt --- // @@ -77,6 +78,11 @@ export type TransactionResult = If< TransactionResultWithMetadata >; +export type ChainAndAddress = { + chainId: ChainIdOrName; + address: string; +}; + /** * Forward Request Message that's used for gasless transaction * @public diff --git a/test/edition.test.ts b/test/edition.test.ts index 641b32d3b..150cbc9c9 100644 --- a/test/edition.test.ts +++ b/test/edition.test.ts @@ -34,7 +34,7 @@ describe("Edition Contract", async () => { platform_fee_basis_points: 10, platform_fee_recipient: AddressZero, }); - bundleContract = sdk.getEdition(address); + bundleContract = await sdk.getEdition(address); }); it("gas cost", async () => { From 2feb764ef7bb715284c5cd39fe9baff9b1f08557 Mon Sep 17 00:00:00 2001 From: Joaquim Verges Date: Sun, 26 Jun 2022 18:22:25 -0700 Subject: [PATCH 2/5] multi chain registry and factory --- docs/sdk.thirdwebsdk.getcontract.md | 4 +- docs/sdk.thirdwebsdk.getcontractlist.md | 3 +- docs/sdk.thirdwebsdk.md | 4 +- docs/sdk.thirdwebsdk.resolvecontracttype.md | 3 +- etc/sdk.api.md | 18 +++- src/constants/urls.ts | 8 ++ src/core/classes/contract-deployer.ts | 109 +++++++++----------- src/core/classes/contract-wrapper.ts | 4 + src/core/classes/factory.ts | 9 +- src/core/classes/registry.ts | 14 +-- src/core/sdk.ts | 38 ++++--- 11 files changed, 119 insertions(+), 95 deletions(-) diff --git a/docs/sdk.thirdwebsdk.getcontract.md b/docs/sdk.thirdwebsdk.getcontract.md index a4fe43aaf..b29e0f299 100644 --- a/docs/sdk.thirdwebsdk.getcontract.md +++ b/docs/sdk.thirdwebsdk.getcontract.md @@ -12,7 +12,7 @@ Get an instance of a Custom ThirdwebContract Signature: ```typescript -getContract(address: string, chain?: number): Promise>; +getContract(address: string, chain?: ChainIdOrName): Promise>; ``` ## Parameters @@ -20,7 +20,7 @@ getContract(address: string, chain?: number): Promise(Optional) optional the chain (id or name) of the contract (defaults to the SDK chainId) | +| chain | ChainIdOrName | (Optional) optional the chain (id or name) of the contract (defaults to the SDK chainId) | Returns: diff --git a/docs/sdk.thirdwebsdk.getcontractlist.md b/docs/sdk.thirdwebsdk.getcontractlist.md index 97d738bb5..3cce045b9 100644 --- a/docs/sdk.thirdwebsdk.getcontractlist.md +++ b/docs/sdk.thirdwebsdk.getcontractlist.md @@ -9,7 +9,7 @@ Return all the contracts deployed by the specified address Signature: ```typescript -getContractList(walletAddress: string): Promise<{ +getContractList(walletAddress: string, chain?: ChainIdOrName): Promise<{ address: string; contractType: "custom" | "token" | "split" | "edition" | "edition-drop" | "token-drop" | "vote" | "marketplace" | "pack" | "nft-drop" | "signature-drop" | "multiwrap" | "nft-collection"; metadata: () => Promise; @@ -21,6 +21,7 @@ getContractList(walletAddress: string): Promise<{ | Parameter | Type | Description | | --- | --- | --- | | walletAddress | string | the deployed address | +| chain | ChainIdOrName | (Optional) the chain to fetch from contracts from | Returns: diff --git a/docs/sdk.thirdwebsdk.md b/docs/sdk.thirdwebsdk.md index 76effed71..ae289f956 100644 --- a/docs/sdk.thirdwebsdk.md +++ b/docs/sdk.thirdwebsdk.md @@ -37,7 +37,7 @@ export declare class ThirdwebSDK extends RPCConnectionHandler | [getBalance(address)](./sdk.thirdwebsdk.getbalance.md) | | Get the native balance of a given address (wallet or contract) | | [getContract(address, chain)](./sdk.thirdwebsdk.getcontract.md) | | (BETA) Get an instance of a Custom ThirdwebContract | | [getContractFromAbi(address, abi, chain)](./sdk.thirdwebsdk.getcontractfromabi.md) | | (BETA) Get an instance of a Custom contract from a json ABI | -| [getContractList(walletAddress)](./sdk.thirdwebsdk.getcontractlist.md) | | Return all the contracts deployed by the specified address | +| [getContractList(walletAddress, chain)](./sdk.thirdwebsdk.getcontractlist.md) | | Return all the contracts deployed by the specified address | | [getEdition(address)](./sdk.thirdwebsdk.getedition.md) | | Get an instance of an Edition contract | | [getEditionDrop(address)](./sdk.thirdwebsdk.geteditiondrop.md) | | Get an instance of a Edition Drop contract | | [getMarketplace(address)](./sdk.thirdwebsdk.getmarketplace.md) | | Get an instance of a Marketplace contract | @@ -49,5 +49,5 @@ export declare class ThirdwebSDK extends RPCConnectionHandler | [getToken(address)](./sdk.thirdwebsdk.gettoken.md) | | Get an instance of a Token contract | | [getTokenDrop(address)](./sdk.thirdwebsdk.gettokendrop.md) | | Get an instance of a Token Drop contract | | [getVote(address)](./sdk.thirdwebsdk.getvote.md) | | Get an instance of a Vote contract | -| [resolveContractType(contractAddress)](./sdk.thirdwebsdk.resolvecontracttype.md) | | | +| [resolveContractType(contractAddress, chain)](./sdk.thirdwebsdk.resolvecontracttype.md) | | | diff --git a/docs/sdk.thirdwebsdk.resolvecontracttype.md b/docs/sdk.thirdwebsdk.resolvecontracttype.md index d3ca71538..251baa2f7 100644 --- a/docs/sdk.thirdwebsdk.resolvecontracttype.md +++ b/docs/sdk.thirdwebsdk.resolvecontracttype.md @@ -7,7 +7,7 @@ Signature: ```typescript -resolveContractType(contractAddress: string): Promise; +resolveContractType(contractAddress: string, chain?: ChainIdOrName): Promise; ``` ## Parameters @@ -15,6 +15,7 @@ resolveContractType(contractAddress: string): Promise; | Parameter | Type | Description | | --- | --- | --- | | contractAddress | string | the address of the contract to attempt to resolve the contract type for | +| chain | ChainIdOrName | (Optional) optional the chain (id or name) of the contract (defaults to the SDK chainId) | Returns: diff --git a/etc/sdk.api.md b/etc/sdk.api.md index 31b222eab..8c821691d 100644 --- a/etc/sdk.api.md +++ b/etc/sdk.api.md @@ -610,7 +610,7 @@ export class ContractDeployer extends RPCConnectionHandler { // Warning: (ae-forgotten-export) The symbol "ContractRegistry" needs to be exported by the entry point index.d.ts // // @internal (undocumented) - getRegistry(): Promise; + getRegistry(chain?: ChainIdOrName): Promise; // (undocumented) updateSigner(signer: Signer | undefined): void; } @@ -5041,13 +5041,16 @@ export class ThirdwebSDK extends RPCConnectionHandler { readonly pack: typeof Pack; readonly multiwrap: typeof Multiwrap; }[TContractType] ? T extends new (...args: any[]) => object ? object : any : never : never>; + // Warning: (ae-incompatible-release-tags) The symbol "getContract" is marked as @beta, but its signature references "ChainIdOrName" which is marked as @internal + // // @beta - getContract(address: string, chain?: number): Promise>; + getContract(address: string, chain?: ChainIdOrName): Promise>; // Warning: (ae-incompatible-release-tags) The symbol "getContractFromAbi" is marked as @beta, but its signature references "ChainIdOrName" which is marked as @internal // // @beta getContractFromAbi(address: string, abi: ContractInterface, chain?: ChainIdOrName): SmartContract; - getContractList(walletAddress: string): Promise<{ + // Warning: (ae-incompatible-release-tags) The symbol "getContractList" is marked as @public, but its signature references "ChainIdOrName" which is marked as @internal + getContractList(walletAddress: string, chain?: ChainIdOrName): Promise<{ address: string; contractType: "custom" | "token" | "split" | "edition" | "edition-drop" | "token-drop" | "vote" | "marketplace" | "pack" | "nft-drop" | "signature-drop" | "multiwrap" | "nft-collection"; metadata: () => Promise; @@ -5070,12 +5073,19 @@ export class ThirdwebSDK extends RPCConnectionHandler { getToken(address: string): Promise; getTokenDrop(address: string): Promise; getVote(address: string): Promise; + // Warning: (ae-incompatible-release-tags) The symbol "resolveContractType" is marked as @public, but its signature references "ChainIdOrName" which is marked as @internal + // // (undocumented) - resolveContractType(contractAddress: string): Promise; + resolveContractType(contractAddress: string, chain?: ChainIdOrName): Promise; storage: RemoteStorage; wallet: UserWallet; } +// Warning: (ae-internal-missing-underscore) The name "toChainId" should be prefixed with an underscore because the declaration is marked as @internal +// +// @internal (undocumented) +export function toChainId(chain: ChainIdOrName): number; + // @public export class Token extends Erc20 { constructor(connection: ConnectionInfo, address: string, storage: IStorage, options?: SDKOptions, contractWrapper?: ContractWrapper); diff --git a/src/constants/urls.ts b/src/constants/urls.ts index dbc52f5da..8bc9b2dc6 100644 --- a/src/constants/urls.ts +++ b/src/constants/urls.ts @@ -92,6 +92,14 @@ export const defaultRPCMap: Record< [ChainId.Localhost]: "http://localhost:8545", }; +/** + * @internal + * @param chain + */ +export function toChainId(chain: ChainIdOrName) { + return typeof chain === "string" ? chainNameToId[chain] : chain; +} + /** * @internal * @param chainId diff --git a/src/core/classes/contract-deployer.ts b/src/core/classes/contract-deployer.ts index 1c5ba88db..62a510bd0 100644 --- a/src/core/classes/contract-deployer.ts +++ b/src/core/classes/contract-deployer.ts @@ -1,7 +1,6 @@ import { ConnectionInfo, ValidContractClass } from "../types"; import { z } from "zod"; import { ContractRegistry } from "./registry"; -import { getContractAddressByChainId } from "../../constants/addresses"; import { ContractFactory } from "./factory"; import { SDKOptions } from "../../schema/sdk-options"; import { IStorage } from "../interfaces"; @@ -29,22 +28,15 @@ import { import { TokenDrop } from "../../contracts/token-drop"; import { Multiwrap } from "../../contracts/multiwrap"; import { Signer } from "ethers"; +import { ChainIdOrName, toChainId } from "../../constants/index"; /** * Handles deploying new contracts * @public */ export class ContractDeployer extends RPCConnectionHandler { - /** - * @internal - * should never be accessed directly, use {@link ContractDeployer.getFactory} instead - */ - private _factory: Promise | undefined; - /** - * @internal - * should never be accessed directly, use {@link ContractDeployer.getRegistry} instead - */ - private _registry: Promise | undefined; + private registryCache = new Map(); + private factoryCache = new Map(); private storage: IStorage; constructor( @@ -346,64 +338,57 @@ export class ContractDeployer extends RPCConnectionHandler { /** * @internal */ - public async getRegistry(): Promise { - // if we already have a registry just return it back - if (this._registry) { - return this._registry; + public async getRegistry( + chain: ChainIdOrName = this.getConnectionInfo().chainId, + ): Promise { + const chainId = toChainId(chain); + if (this.registryCache.has(chainId)) { + return this.registryCache.get(chainId) as ContractRegistry; } - - // otherwise get the registry address for the active chain and get a new one - - // have to do it like this otherwise we run it over and over and over - // "this._registry" has to be assigned to the promise upfront. - return (this._registry = this.getProvider() - .getNetwork() - .then(async ({ chainId }) => { - const registryAddress = getContractAddressByChainId( - chainId, - "twRegistry", - ); - return new ContractRegistry( - registryAddress, - this.getConnectionInfo(), - this.options, - ); - })); + let connectionInfo = this.getConnectionInfo(); + if (chainId !== this.getConnectionInfo().chainId) { + connectionInfo = { + chainId, + provider: undefined, + signer: connectionInfo.signer, + }; + } + const registry = new ContractRegistry(connectionInfo, this.options); + this.registryCache.set(chainId, registry); + return registry; } - private async getFactory(): Promise { - // if we already have a factory just return it back - if (this._factory) { - return this._factory; + private async getFactory( + chain: ChainIdOrName = this.getConnectionInfo().chainId, + ): Promise { + const chainId = toChainId(chain); + if (this.factoryCache.has(chainId)) { + return this.factoryCache.get(chainId) as ContractFactory; } - - // otherwise get the factory address for the active chain and get a new one - - // have to do it like this otherwise we run it over and over and over - // "this._factory" has to be assigned to the promise upfront. - return (this._factory = this.getProvider() - .getNetwork() - .then(async ({ chainId }) => { - const factoryAddress = getContractAddressByChainId( - chainId, - "twFactory", - ); - return new ContractFactory( - factoryAddress, - this.getConnectionInfo(), - this.storage, - this.options, - ); - })); + let connectionInfo = this.getConnectionInfo(); + if (chainId !== this.getConnectionInfo().chainId) { + connectionInfo = { + chainId, + provider: undefined, + signer: connectionInfo.signer, + }; + } + const factory = new ContractFactory( + connectionInfo, + this.storage, + this.options, + ); + this.factoryCache.set(chainId, factory); + return factory; } public override updateSigner(signer: Signer | undefined) { super.updateSigner(signer); - this._factory?.then((factory) => { - factory.updateSigner(signer); - }); - this._registry?.then((registry) => { - registry.updateSigner(signer); - }); + for (const [, contract] of this.registryCache) { + contract.updateSigner(this.getSigner()); + } + for (const [, contract] of this.factoryCache) { + contract.updateSigner(this.getSigner()); + } } } diff --git a/src/core/classes/contract-wrapper.ts b/src/core/classes/contract-wrapper.ts index cc12a4f83..78555d0ae 100644 --- a/src/core/classes/contract-wrapper.ts +++ b/src/core/classes/contract-wrapper.ts @@ -82,6 +82,10 @@ export class ContractWrapper< ) as TContract; } + public getAddress(): string { + return this.readContract.address; + } + /** * @internal */ diff --git a/src/core/classes/factory.ts b/src/core/classes/factory.ts index a0740374e..59967a55c 100644 --- a/src/core/classes/factory.ts +++ b/src/core/classes/factory.ts @@ -19,6 +19,7 @@ import { CONTRACTS_MAP, REMOTE_CONTRACT_NAME } from "../../contracts/maps"; import { CONTRACT_ADDRESSES, + getContractAddressByChainId, OZ_DEFENDER_FORWARDER_ADDRESS, SUPPORTED_CHAIN_IDS, } from "../../constants"; @@ -33,12 +34,16 @@ export class ContractFactory extends ContractWrapper { private storage: IStorage; constructor( - factoryAddr: string, connection: ConnectionInfo, storage: IStorage, options?: SDKOptions, ) { - super(connection, factoryAddr, TWFactory__factory.abi, options); + super( + connection, + getContractAddressByChainId(connection.chainId, "twFactory"), + TWFactory__factory.abi, + options, + ); this.storage = storage; } diff --git a/src/core/classes/registry.ts b/src/core/classes/registry.ts index 9348ebc7f..35c9ebcbd 100644 --- a/src/core/classes/registry.ts +++ b/src/core/classes/registry.ts @@ -4,17 +4,19 @@ import { ConnectionInfo } from "../types"; import { ContractWrapper } from "./contract-wrapper"; import { constants, utils } from "ethers"; import { TransactionResult } from ".."; +import { getContractAddressByChainId } from "../../constants/index"; /** * @internal */ export class ContractRegistry extends ContractWrapper { - constructor( - registryAddress: string, - connection: ConnectionInfo, - options?: SDKOptions, - ) { - super(connection, registryAddress, TWRegistry__factory.abi, options); + constructor(connection: ConnectionInfo, options?: SDKOptions) { + super( + connection, + getContractAddressByChainId(connection.chainId, "twRegistry"), + TWRegistry__factory.abi, + options, + ); } public async getContractAddresses(walletAddress: string) { diff --git a/src/core/sdk.ts b/src/core/sdk.ts index e5c0201f4..2969c0ebd 100644 --- a/src/core/sdk.ts +++ b/src/core/sdk.ts @@ -24,6 +24,7 @@ import type { ContractType, ValidContractInstance, } from "./types"; +import { ChainAndAddress } from "./types"; import { IThirdwebContract__factory } from "contracts"; import { ContractDeployer } from "./classes/contract-deployer"; import { SmartContract } from "../contracts/smart-contract"; @@ -32,17 +33,17 @@ import { TokenDrop } from "../contracts/token-drop"; import { ContractPublisher } from "./classes/contract-publisher"; import { ContractMetadata } from "./classes"; import { - chainNameToId, ChainIdOrName, + chainNameToId, getProviderForChain, NATIVE_TOKEN_ADDRESS, + toChainId, } from "../constants"; import { UserWallet } from "./wallet/UserWallet"; import { Multiwrap } from "../contracts/multiwrap"; import { WalletAuthenticator } from "./auth/wallet-authenticator"; import { CurrencyValue } from "../types/index"; import { fetchCurrencyValue } from "../common/currency"; -import { ChainAndAddress } from "./types"; /** * The main entry point for the thirdweb SDK @@ -106,7 +107,7 @@ export class ThirdwebSDK extends RPCConnectionHandler { options: SDKOptions = {}, storage: IStorage = new IpfsStorage(), ): ThirdwebSDK { - const chainId = typeof chain === "string" ? chainNameToId[chain] : chain; + const chainId = toChainId(chain); const provider = getProviderForChain(chainId, options.chainIdToRPCUrlMap); const signer = new ethers.Wallet(privateKey, provider); return ThirdwebSDK.fromSigner(signer, chainId, options, storage); @@ -153,7 +154,7 @@ export class ThirdwebSDK extends RPCConnectionHandler { ) { // Throw helpful error for old usages of this constructor verifyInputs(chain); - const chainId = typeof chain === "string" ? chainNameToId[chain] : chain; + const chainId = toChainId(chain); const connection: ConnectionInfo = { chainId, signer: undefined, @@ -336,7 +337,7 @@ export class ThirdwebSDK extends RPCConnectionHandler { contractType: TContractType, chain: ChainIdOrName = this.getConnectionInfo().chainId, ) { - const chainId = typeof chain === "string" ? chainNameToId[chain] : chain; + const chainId = toChainId(chain); // if we have a contract in the cache we will return it // we will do this **without** checking any contract type things for simplicity, this may have to change in the future? if (this.contractCache.has({ chainId, address })) { @@ -373,15 +374,18 @@ export class ThirdwebSDK extends RPCConnectionHandler { /** * @param contractAddress - the address of the contract to attempt to resolve the contract type for + * @param chain - optional the chain (id or name) of the contract (defaults to the SDK chainId) * @returns the {@link ContractType} for the given contract address * @throws if the contract type cannot be determined (is not a valid thirdweb contract) */ public async resolveContractType( contractAddress: string, + chain: ChainIdOrName = this.getConnectionInfo().chainId, ): Promise { + const chainId = toChainId(chain); const contract = IThirdwebContract__factory.connect( contractAddress, - this.getSignerOrProvider(), + getProviderForChain(chainId, this.options.chainIdToRPCUrlMap), ); const remoteContractType = ethers.utils .toUtf8String(await contract.contractType()) @@ -399,24 +403,27 @@ export class ThirdwebSDK extends RPCConnectionHandler { /** * Return all the contracts deployed by the specified address * @param walletAddress - the deployed address + * @param chain - the chain to fetch from contracts from */ - public async getContractList(walletAddress: string) { - const addresses = await ( - await this.deployer.getRegistry() - ).getContractAddresses(walletAddress); + public async getContractList( + walletAddress: string, + chain: ChainIdOrName = this.getConnectionInfo().chainId, + ) { + const registry = await this.deployer.getRegistry(chain); + const addresses = await registry.getContractAddresses(walletAddress); const addressesWithContractTypes = await Promise.all( addresses.map(async (address) => { let contractType: ContractType = "custom"; try { - contractType = await this.resolveContractType(address); + contractType = await this.resolveContractType(address, chain); } catch (e) { // this going to happen frequently and be OK, we'll just catch it and ignore it } let metadata: ContractMetadata | undefined; if (contractType === "custom") { try { - metadata = (await this.getContract(address)).metadata; + metadata = (await this.getContract(address, chain)).metadata; } catch (e) { console.log( `Couldn't get contract metadata for custom contract: ${address}`, @@ -426,6 +433,7 @@ export class ThirdwebSDK extends RPCConnectionHandler { const builtInContract = await this.getBuiltInContract( address, contractType, + chain, ); metadata = builtInContract.metadata; } @@ -458,9 +466,9 @@ export class ThirdwebSDK extends RPCConnectionHandler { */ public async getContract( address: string, - chain: number = this.getConnectionInfo().chainId, + chain: ChainIdOrName = this.getConnectionInfo().chainId, ) { - const chainId = typeof chain === "string" ? chainNameToId[chain] : chain; + const chainId = toChainId(chain); if (this.contractCache.has({ chainId, address })) { return this.contractCache.get({ chainId, address }) as SmartContract; } @@ -488,7 +496,7 @@ export class ThirdwebSDK extends RPCConnectionHandler { abi: ContractInterface, chain: ChainIdOrName = this.getConnectionInfo().chainId, ) { - const chainId = typeof chain === "string" ? chainNameToId[chain] : chain; + const chainId = toChainId(chain); if (this.contractCache.has({ chainId, address })) { return this.contractCache.get({ chainId, address }) as SmartContract; } From bb66b0bec03d0989269fc6a0099eee365721caf6 Mon Sep 17 00:00:00 2001 From: Joaquim Verges Date: Sun, 26 Jun 2022 21:11:11 -0700 Subject: [PATCH 3/5] pass optional chain to sdk.getX() and fix signer RPC switch when using private keys --- docs/sdk.contractdeployer.deployedition.md | 3 +- .../sdk.contractdeployer.deployeditiondrop.md | 3 +- .../sdk.contractdeployer.deploymarketplace.md | 3 +- docs/sdk.contractdeployer.deploymultiwrap.md | 3 +- ...dk.contractdeployer.deploynftcollection.md | 3 +- docs/sdk.contractdeployer.deploynftdrop.md | 3 +- docs/sdk.contractdeployer.deploypack.md | 3 +- docs/sdk.contractdeployer.deploysplit.md | 3 +- docs/sdk.contractdeployer.deploytoken.md | 3 +- docs/sdk.contractdeployer.deploytokendrop.md | 3 +- docs/sdk.contractdeployer.deployvote.md | 3 +- docs/sdk.contractdeployer.md | 22 ++--- docs/sdk.thirdwebsdk.getedition.md | 3 +- docs/sdk.thirdwebsdk.geteditiondrop.md | 3 +- docs/sdk.thirdwebsdk.getmarketplace.md | 3 +- docs/sdk.thirdwebsdk.getmultiwrap.md | 3 +- docs/sdk.thirdwebsdk.getnftcollection.md | 3 +- docs/sdk.thirdwebsdk.getnftdrop.md | 3 +- docs/sdk.thirdwebsdk.getpack.md | 3 +- docs/sdk.thirdwebsdk.getsplit.md | 3 +- docs/sdk.thirdwebsdk.gettoken.md | 3 +- docs/sdk.thirdwebsdk.gettokendrop.md | 3 +- docs/sdk.thirdwebsdk.getvote.md | 3 +- docs/sdk.thirdwebsdk.md | 22 ++--- etc/sdk.api.md | 74 ++++++++++----- src/core/classes/contract-deployer.ts | 83 ++++++++++++++--- src/core/classes/rpc-connection-handler.ts | 12 ++- src/core/sdk.ts | 91 +++++++++++++++---- 28 files changed, 270 insertions(+), 100 deletions(-) diff --git a/docs/sdk.contractdeployer.deployedition.md b/docs/sdk.contractdeployer.deployedition.md index 3fcb93322..503582479 100644 --- a/docs/sdk.contractdeployer.deployedition.md +++ b/docs/sdk.contractdeployer.deployedition.md @@ -9,7 +9,7 @@ Deploys a new Edition contract Signature: ```typescript -deployEdition(metadata: NFTContractDeployMetadata): Promise; +deployEdition(metadata: NFTContractDeployMetadata, chain?: ChainIdOrName): Promise; ``` ## Parameters @@ -17,6 +17,7 @@ deployEdition(metadata: NFTContractDeployMetadata): Promise; | Parameter | Type | Description | | --- | --- | --- | | metadata | [NFTContractDeployMetadata](./sdk.nftcontractdeploymetadata.md) | the contract metadata | +| chain | ChainIdOrName | (Optional) the chain to deploy the contract to, defaults to the chain the SDK is connected to | Returns: diff --git a/docs/sdk.contractdeployer.deployeditiondrop.md b/docs/sdk.contractdeployer.deployeditiondrop.md index 2bd08c2ad..a44a1b54f 100644 --- a/docs/sdk.contractdeployer.deployeditiondrop.md +++ b/docs/sdk.contractdeployer.deployeditiondrop.md @@ -9,7 +9,7 @@ Deploys a new EditionDrop contract Signature: ```typescript -deployEditionDrop(metadata: NFTContractDeployMetadata): Promise; +deployEditionDrop(metadata: NFTContractDeployMetadata, chain?: ChainIdOrName): Promise; ``` ## Parameters @@ -17,6 +17,7 @@ deployEditionDrop(metadata: NFTContractDeployMetadata): Promise; | Parameter | Type | Description | | --- | --- | --- | | metadata | [NFTContractDeployMetadata](./sdk.nftcontractdeploymetadata.md) | the contract metadata | +| chain | ChainIdOrName | (Optional) the chain to deploy the contract to, defaults to the chain the SDK is connected to | Returns: diff --git a/docs/sdk.contractdeployer.deploymarketplace.md b/docs/sdk.contractdeployer.deploymarketplace.md index 259b46675..ff1668e85 100644 --- a/docs/sdk.contractdeployer.deploymarketplace.md +++ b/docs/sdk.contractdeployer.deploymarketplace.md @@ -9,7 +9,7 @@ Deploys a new Marketplace contract Signature: ```typescript -deployMarketplace(metadata: MarketplaceContractDeployMetadata): Promise; +deployMarketplace(metadata: MarketplaceContractDeployMetadata, chain?: ChainIdOrName): Promise; ``` ## Parameters @@ -17,6 +17,7 @@ deployMarketplace(metadata: MarketplaceContractDeployMetadata): Promise; | Parameter | Type | Description | | --- | --- | --- | | metadata | [MarketplaceContractDeployMetadata](./sdk.marketplacecontractdeploymetadata.md) | the contract metadata | +| chain | ChainIdOrName | (Optional) the chain to deploy the contract to, defaults to the chain the SDK is connected to | Returns: diff --git a/docs/sdk.contractdeployer.deploymultiwrap.md b/docs/sdk.contractdeployer.deploymultiwrap.md index 9e9a9d4bb..524fa1eea 100644 --- a/docs/sdk.contractdeployer.deploymultiwrap.md +++ b/docs/sdk.contractdeployer.deploymultiwrap.md @@ -12,7 +12,7 @@ Deploys a new Multiwrap contract Signature: ```typescript -deployMultiwrap(metadata: MultiwrapContractDeployMetadata): Promise; +deployMultiwrap(metadata: MultiwrapContractDeployMetadata, chain?: ChainIdOrName): Promise; ``` ## Parameters @@ -20,6 +20,7 @@ deployMultiwrap(metadata: MultiwrapContractDeployMetadata): Promise; | Parameter | Type | Description | | --- | --- | --- | | metadata | [MultiwrapContractDeployMetadata](./sdk.multiwrapcontractdeploymetadata.md) | the contract metadata | +| chain | ChainIdOrName | (Optional) the chain to deploy the contract to, defaults to the chain the SDK is connected to | Returns: diff --git a/docs/sdk.contractdeployer.deploynftcollection.md b/docs/sdk.contractdeployer.deploynftcollection.md index b26f215c1..9055ae7a6 100644 --- a/docs/sdk.contractdeployer.deploynftcollection.md +++ b/docs/sdk.contractdeployer.deploynftcollection.md @@ -9,7 +9,7 @@ Deploys an NFT Collection contract Signature: ```typescript -deployNFTCollection(metadata: NFTContractDeployMetadata): Promise; +deployNFTCollection(metadata: NFTContractDeployMetadata, chain?: ChainIdOrName): Promise; ``` ## Parameters @@ -17,6 +17,7 @@ deployNFTCollection(metadata: NFTContractDeployMetadata): Promise; | Parameter | Type | Description | | --- | --- | --- | | metadata | [NFTContractDeployMetadata](./sdk.nftcontractdeploymetadata.md) | the contract metadata | +| chain | ChainIdOrName | (Optional) the chain to deploy the contract to, defaults to the chain the SDK is connected to | Returns: diff --git a/docs/sdk.contractdeployer.deploynftdrop.md b/docs/sdk.contractdeployer.deploynftdrop.md index 264bf3230..b2f86b98f 100644 --- a/docs/sdk.contractdeployer.deploynftdrop.md +++ b/docs/sdk.contractdeployer.deploynftdrop.md @@ -9,7 +9,7 @@ Deploys a new NFTDrop contract Signature: ```typescript -deployNFTDrop(metadata: NFTContractDeployMetadata): Promise; +deployNFTDrop(metadata: NFTContractDeployMetadata, chain?: ChainIdOrName): Promise; ``` ## Parameters @@ -17,6 +17,7 @@ deployNFTDrop(metadata: NFTContractDeployMetadata): Promise; | Parameter | Type | Description | | --- | --- | --- | | metadata | [NFTContractDeployMetadata](./sdk.nftcontractdeploymetadata.md) | the contract metadata | +| chain | ChainIdOrName | (Optional) the chain to deploy the contract to, defaults to the chain the SDK is connected to | Returns: diff --git a/docs/sdk.contractdeployer.deploypack.md b/docs/sdk.contractdeployer.deploypack.md index 1c2d34634..bc93ff486 100644 --- a/docs/sdk.contractdeployer.deploypack.md +++ b/docs/sdk.contractdeployer.deploypack.md @@ -9,7 +9,7 @@ Deploys a new Pack contract Signature: ```typescript -deployPack(metadata: NFTContractDeployMetadata): Promise; +deployPack(metadata: NFTContractDeployMetadata, chain?: ChainIdOrName): Promise; ``` ## Parameters @@ -17,6 +17,7 @@ deployPack(metadata: NFTContractDeployMetadata): Promise; | Parameter | Type | Description | | --- | --- | --- | | metadata | [NFTContractDeployMetadata](./sdk.nftcontractdeploymetadata.md) | the contract metadata | +| chain | ChainIdOrName | (Optional) the chain to deploy the contract to, defaults to the chain the SDK is connected to | Returns: diff --git a/docs/sdk.contractdeployer.deploysplit.md b/docs/sdk.contractdeployer.deploysplit.md index 7ccccfdeb..c2595941b 100644 --- a/docs/sdk.contractdeployer.deploysplit.md +++ b/docs/sdk.contractdeployer.deploysplit.md @@ -9,7 +9,7 @@ Deploys a new Split contract Signature: ```typescript -deploySplit(metadata: SplitContractDeployMetadata): Promise; +deploySplit(metadata: SplitContractDeployMetadata, chain?: ChainIdOrName): Promise; ``` ## Parameters @@ -17,6 +17,7 @@ deploySplit(metadata: SplitContractDeployMetadata): Promise; | Parameter | Type | Description | | --- | --- | --- | | metadata | [SplitContractDeployMetadata](./sdk.splitcontractdeploymetadata.md) | the contract metadata | +| chain | ChainIdOrName | (Optional) the chain to deploy the contract to, defaults to the chain the SDK is connected to | Returns: diff --git a/docs/sdk.contractdeployer.deploytoken.md b/docs/sdk.contractdeployer.deploytoken.md index a79d18c66..af09c52ca 100644 --- a/docs/sdk.contractdeployer.deploytoken.md +++ b/docs/sdk.contractdeployer.deploytoken.md @@ -9,7 +9,7 @@ Deploys a new Token contract Signature: ```typescript -deployToken(metadata: TokenContractDeployMetadata): Promise; +deployToken(metadata: TokenContractDeployMetadata, chain?: ChainIdOrName): Promise; ``` ## Parameters @@ -17,6 +17,7 @@ deployToken(metadata: TokenContractDeployMetadata): Promise; | Parameter | Type | Description | | --- | --- | --- | | metadata | [TokenContractDeployMetadata](./sdk.tokencontractdeploymetadata.md) | the contract metadata | +| chain | ChainIdOrName | (Optional) the chain to deploy the contract to, defaults to the chain the SDK is connected to | Returns: diff --git a/docs/sdk.contractdeployer.deploytokendrop.md b/docs/sdk.contractdeployer.deploytokendrop.md index 24b0763f8..69fd16129 100644 --- a/docs/sdk.contractdeployer.deploytokendrop.md +++ b/docs/sdk.contractdeployer.deploytokendrop.md @@ -9,7 +9,7 @@ Deploys a new Token Drop contract Signature: ```typescript -deployTokenDrop(metadata: TokenContractDeployMetadata): Promise; +deployTokenDrop(metadata: TokenContractDeployMetadata, chain?: ChainIdOrName): Promise; ``` ## Parameters @@ -17,6 +17,7 @@ deployTokenDrop(metadata: TokenContractDeployMetadata): Promise; | Parameter | Type | Description | | --- | --- | --- | | metadata | [TokenContractDeployMetadata](./sdk.tokencontractdeploymetadata.md) | the contract metadata | +| chain | ChainIdOrName | (Optional) the chain to deploy the contract to, defaults to the chain the SDK is connected to | Returns: diff --git a/docs/sdk.contractdeployer.deployvote.md b/docs/sdk.contractdeployer.deployvote.md index def07770c..fdeff1ff1 100644 --- a/docs/sdk.contractdeployer.deployvote.md +++ b/docs/sdk.contractdeployer.deployvote.md @@ -9,7 +9,7 @@ Deploys a new Vote contract Signature: ```typescript -deployVote(metadata: VoteContractDeployMetadata): Promise; +deployVote(metadata: VoteContractDeployMetadata, chain?: ChainIdOrName): Promise; ``` ## Parameters @@ -17,6 +17,7 @@ deployVote(metadata: VoteContractDeployMetadata): Promise; | Parameter | Type | Description | | --- | --- | --- | | metadata | [VoteContractDeployMetadata](./sdk.votecontractdeploymetadata.md) | the contract metadata | +| chain | ChainIdOrName | (Optional) the chain to deploy the contract to, defaults to the chain the SDK is connected to | Returns: diff --git a/docs/sdk.contractdeployer.md b/docs/sdk.contractdeployer.md index e21c7e00d..fc6eafe3d 100644 --- a/docs/sdk.contractdeployer.md +++ b/docs/sdk.contractdeployer.md @@ -23,16 +23,16 @@ export declare class ContractDeployer extends RPCConnectionHandler | Method | Modifiers | Description | | --- | --- | --- | -| [deployEdition(metadata)](./sdk.contractdeployer.deployedition.md) | | Deploys a new Edition contract | -| [deployEditionDrop(metadata)](./sdk.contractdeployer.deployeditiondrop.md) | | Deploys a new EditionDrop contract | -| [deployMarketplace(metadata)](./sdk.contractdeployer.deploymarketplace.md) | | Deploys a new Marketplace contract | -| [deployMultiwrap(metadata)](./sdk.contractdeployer.deploymultiwrap.md) | | (BETA) Deploys a new Multiwrap contract | -| [deployNFTCollection(metadata)](./sdk.contractdeployer.deploynftcollection.md) | | Deploys an NFT Collection contract | -| [deployNFTDrop(metadata)](./sdk.contractdeployer.deploynftdrop.md) | | Deploys a new NFTDrop contract | -| [deployPack(metadata)](./sdk.contractdeployer.deploypack.md) | | Deploys a new Pack contract | -| [deploySplit(metadata)](./sdk.contractdeployer.deploysplit.md) | | Deploys a new Split contract | -| [deployToken(metadata)](./sdk.contractdeployer.deploytoken.md) | | Deploys a new Token contract | -| [deployTokenDrop(metadata)](./sdk.contractdeployer.deploytokendrop.md) | | Deploys a new Token Drop contract | -| [deployVote(metadata)](./sdk.contractdeployer.deployvote.md) | | Deploys a new Vote contract | +| [deployEdition(metadata, chain)](./sdk.contractdeployer.deployedition.md) | | Deploys a new Edition contract | +| [deployEditionDrop(metadata, chain)](./sdk.contractdeployer.deployeditiondrop.md) | | Deploys a new EditionDrop contract | +| [deployMarketplace(metadata, chain)](./sdk.contractdeployer.deploymarketplace.md) | | Deploys a new Marketplace contract | +| [deployMultiwrap(metadata, chain)](./sdk.contractdeployer.deploymultiwrap.md) | | (BETA) Deploys a new Multiwrap contract | +| [deployNFTCollection(metadata, chain)](./sdk.contractdeployer.deploynftcollection.md) | | Deploys an NFT Collection contract | +| [deployNFTDrop(metadata, chain)](./sdk.contractdeployer.deploynftdrop.md) | | Deploys a new NFTDrop contract | +| [deployPack(metadata, chain)](./sdk.contractdeployer.deploypack.md) | | Deploys a new Pack contract | +| [deploySplit(metadata, chain)](./sdk.contractdeployer.deploysplit.md) | | Deploys a new Split contract | +| [deployToken(metadata, chain)](./sdk.contractdeployer.deploytoken.md) | | Deploys a new Token contract | +| [deployTokenDrop(metadata, chain)](./sdk.contractdeployer.deploytokendrop.md) | | Deploys a new Token Drop contract | +| [deployVote(metadata, chain)](./sdk.contractdeployer.deployvote.md) | | Deploys a new Vote contract | | [updateSigner(signer)](./sdk.contractdeployer.updatesigner.md) | | | diff --git a/docs/sdk.thirdwebsdk.getedition.md b/docs/sdk.thirdwebsdk.getedition.md index 933d77a4b..dd9027424 100644 --- a/docs/sdk.thirdwebsdk.getedition.md +++ b/docs/sdk.thirdwebsdk.getedition.md @@ -9,7 +9,7 @@ Get an instance of an Edition contract Signature: ```typescript -getEdition(address: string): Promise; +getEdition(address: string, chain?: ChainIdOrName): Promise; ``` ## Parameters @@ -17,6 +17,7 @@ getEdition(address: string): Promise; | Parameter | Type | Description | | --- | --- | --- | | address | string | the address of the deployed contract | +| chain | ChainIdOrName | (Optional) optional, chain (id or name) of the contract (defaults to the chain the SDK is connected to) | Returns: diff --git a/docs/sdk.thirdwebsdk.geteditiondrop.md b/docs/sdk.thirdwebsdk.geteditiondrop.md index d66967797..df66f4bee 100644 --- a/docs/sdk.thirdwebsdk.geteditiondrop.md +++ b/docs/sdk.thirdwebsdk.geteditiondrop.md @@ -9,7 +9,7 @@ Get an instance of a Edition Drop contract Signature: ```typescript -getEditionDrop(address: string): Promise; +getEditionDrop(address: string, chain?: ChainIdOrName): Promise; ``` ## Parameters @@ -17,6 +17,7 @@ getEditionDrop(address: string): Promise; | Parameter | Type | Description | | --- | --- | --- | | address | string | the address of the deployed contract | +| chain | ChainIdOrName | (Optional) optional, chain (id or name) of the contract (defaults to the chain the SDK is connected to) | Returns: diff --git a/docs/sdk.thirdwebsdk.getmarketplace.md b/docs/sdk.thirdwebsdk.getmarketplace.md index ad84f2e71..6fba53f97 100644 --- a/docs/sdk.thirdwebsdk.getmarketplace.md +++ b/docs/sdk.thirdwebsdk.getmarketplace.md @@ -9,7 +9,7 @@ Get an instance of a Marketplace contract Signature: ```typescript -getMarketplace(address: string): Promise; +getMarketplace(address: string, chain?: ChainIdOrName): Promise; ``` ## Parameters @@ -17,6 +17,7 @@ getMarketplace(address: string): Promise; | Parameter | Type | Description | | --- | --- | --- | | address | string | the address of the deployed contract | +| chain | ChainIdOrName | (Optional) optional, chain (id or name) of the contract (defaults to the chain the SDK is connected to) | Returns: diff --git a/docs/sdk.thirdwebsdk.getmultiwrap.md b/docs/sdk.thirdwebsdk.getmultiwrap.md index c948e6f07..fc2862833 100644 --- a/docs/sdk.thirdwebsdk.getmultiwrap.md +++ b/docs/sdk.thirdwebsdk.getmultiwrap.md @@ -12,7 +12,7 @@ Get an instance of a Multiwrap contract Signature: ```typescript -getMultiwrap(address: string): Promise; +getMultiwrap(address: string, chain?: ChainIdOrName): Promise; ``` ## Parameters @@ -20,6 +20,7 @@ getMultiwrap(address: string): Promise; | Parameter | Type | Description | | --- | --- | --- | | address | string | the address of the deployed contract | +| chain | ChainIdOrName | (Optional) optional, chain (id or name) of the contract (defaults to the chain the SDK is connected to) | Returns: diff --git a/docs/sdk.thirdwebsdk.getnftcollection.md b/docs/sdk.thirdwebsdk.getnftcollection.md index 4971cf410..9d50588df 100644 --- a/docs/sdk.thirdwebsdk.getnftcollection.md +++ b/docs/sdk.thirdwebsdk.getnftcollection.md @@ -9,7 +9,7 @@ Get an instance of a NFT Collection contract Signature: ```typescript -getNFTCollection(address: string): Promise; +getNFTCollection(address: string, chain?: ChainIdOrName): Promise; ``` ## Parameters @@ -17,6 +17,7 @@ getNFTCollection(address: string): Promise; | Parameter | Type | Description | | --- | --- | --- | | address | string | the address of the deployed contract | +| chain | ChainIdOrName | (Optional) optional, chain (id or name) of the contract (defaults to the chain the SDK is connected to) | Returns: diff --git a/docs/sdk.thirdwebsdk.getnftdrop.md b/docs/sdk.thirdwebsdk.getnftdrop.md index 2daf31415..fc84ae946 100644 --- a/docs/sdk.thirdwebsdk.getnftdrop.md +++ b/docs/sdk.thirdwebsdk.getnftdrop.md @@ -9,7 +9,7 @@ Get an instance of a Drop contract Signature: ```typescript -getNFTDrop(contractAddress: string): Promise; +getNFTDrop(contractAddress: string, chain?: ChainIdOrName): Promise; ``` ## Parameters @@ -17,6 +17,7 @@ getNFTDrop(contractAddress: string): Promise; | Parameter | Type | Description | | --- | --- | --- | | contractAddress | string | the address of the deployed contract | +| chain | ChainIdOrName | (Optional) optional, chain (id or name) of the contract (defaults to the chain the SDK is connected to) | Returns: diff --git a/docs/sdk.thirdwebsdk.getpack.md b/docs/sdk.thirdwebsdk.getpack.md index 6add753ea..c302546a5 100644 --- a/docs/sdk.thirdwebsdk.getpack.md +++ b/docs/sdk.thirdwebsdk.getpack.md @@ -9,7 +9,7 @@ Get an instance of a Pack contract Signature: ```typescript -getPack(address: string): Promise; +getPack(address: string, chain?: ChainIdOrName): Promise; ``` ## Parameters @@ -17,6 +17,7 @@ getPack(address: string): Promise; | Parameter | Type | Description | | --- | --- | --- | | address | string | the address of the deployed contract | +| chain | ChainIdOrName | (Optional) optional, chain (id or name) of the contract (defaults to the chain the SDK is connected to) | Returns: diff --git a/docs/sdk.thirdwebsdk.getsplit.md b/docs/sdk.thirdwebsdk.getsplit.md index 29e09f963..b3c6d3c83 100644 --- a/docs/sdk.thirdwebsdk.getsplit.md +++ b/docs/sdk.thirdwebsdk.getsplit.md @@ -9,7 +9,7 @@ Get an instance of a Splits contract Signature: ```typescript -getSplit(address: string): Promise; +getSplit(address: string, chain?: ChainIdOrName): Promise; ``` ## Parameters @@ -17,6 +17,7 @@ getSplit(address: string): Promise; | Parameter | Type | Description | | --- | --- | --- | | address | string | the address of the deployed contract | +| chain | ChainIdOrName | (Optional) optional, chain (id or name) of the contract (defaults to the chain the SDK is connected to) | Returns: diff --git a/docs/sdk.thirdwebsdk.gettoken.md b/docs/sdk.thirdwebsdk.gettoken.md index 41d57c30c..7ab05b5a9 100644 --- a/docs/sdk.thirdwebsdk.gettoken.md +++ b/docs/sdk.thirdwebsdk.gettoken.md @@ -9,7 +9,7 @@ Get an instance of a Token contract Signature: ```typescript -getToken(address: string): Promise; +getToken(address: string, chain?: ChainIdOrName): Promise; ``` ## Parameters @@ -17,6 +17,7 @@ getToken(address: string): Promise; | Parameter | Type | Description | | --- | --- | --- | | address | string | the address of the deployed contract | +| chain | ChainIdOrName | (Optional) optional, chain (id or name) of the contract (defaults to the chain the SDK is connected to) | Returns: diff --git a/docs/sdk.thirdwebsdk.gettokendrop.md b/docs/sdk.thirdwebsdk.gettokendrop.md index 01fad0f48..cd8388a84 100644 --- a/docs/sdk.thirdwebsdk.gettokendrop.md +++ b/docs/sdk.thirdwebsdk.gettokendrop.md @@ -9,7 +9,7 @@ Get an instance of a Token Drop contract Signature: ```typescript -getTokenDrop(address: string): Promise; +getTokenDrop(address: string, chain?: ChainIdOrName): Promise; ``` ## Parameters @@ -17,6 +17,7 @@ getTokenDrop(address: string): Promise; | Parameter | Type | Description | | --- | --- | --- | | address | string | the address of the deployed contract | +| chain | ChainIdOrName | (Optional) optional, chain (id or name) of the contract (defaults to the chain the SDK is connected to) | Returns: diff --git a/docs/sdk.thirdwebsdk.getvote.md b/docs/sdk.thirdwebsdk.getvote.md index 2cac02d5e..40c7c89b7 100644 --- a/docs/sdk.thirdwebsdk.getvote.md +++ b/docs/sdk.thirdwebsdk.getvote.md @@ -9,7 +9,7 @@ Get an instance of a Vote contract Signature: ```typescript -getVote(address: string): Promise; +getVote(address: string, chain?: ChainIdOrName): Promise; ``` ## Parameters @@ -17,6 +17,7 @@ getVote(address: string): Promise; | Parameter | Type | Description | | --- | --- | --- | | address | string | the address of the deployed contract | +| chain | ChainIdOrName | (Optional) optional, chain (id or name) of the contract (defaults to the chain the SDK is connected to) | Returns: diff --git a/docs/sdk.thirdwebsdk.md b/docs/sdk.thirdwebsdk.md index ae289f956..e57548cb4 100644 --- a/docs/sdk.thirdwebsdk.md +++ b/docs/sdk.thirdwebsdk.md @@ -38,16 +38,16 @@ export declare class ThirdwebSDK extends RPCConnectionHandler | [getContract(address, chain)](./sdk.thirdwebsdk.getcontract.md) | | (BETA) Get an instance of a Custom ThirdwebContract | | [getContractFromAbi(address, abi, chain)](./sdk.thirdwebsdk.getcontractfromabi.md) | | (BETA) Get an instance of a Custom contract from a json ABI | | [getContractList(walletAddress, chain)](./sdk.thirdwebsdk.getcontractlist.md) | | Return all the contracts deployed by the specified address | -| [getEdition(address)](./sdk.thirdwebsdk.getedition.md) | | Get an instance of an Edition contract | -| [getEditionDrop(address)](./sdk.thirdwebsdk.geteditiondrop.md) | | Get an instance of a Edition Drop contract | -| [getMarketplace(address)](./sdk.thirdwebsdk.getmarketplace.md) | | Get an instance of a Marketplace contract | -| [getMultiwrap(address)](./sdk.thirdwebsdk.getmultiwrap.md) | | (BETA) Get an instance of a Multiwrap contract | -| [getNFTCollection(address)](./sdk.thirdwebsdk.getnftcollection.md) | | Get an instance of a NFT Collection contract | -| [getNFTDrop(contractAddress)](./sdk.thirdwebsdk.getnftdrop.md) | | Get an instance of a Drop contract | -| [getPack(address)](./sdk.thirdwebsdk.getpack.md) | | Get an instance of a Pack contract | -| [getSplit(address)](./sdk.thirdwebsdk.getsplit.md) | | Get an instance of a Splits contract | -| [getToken(address)](./sdk.thirdwebsdk.gettoken.md) | | Get an instance of a Token contract | -| [getTokenDrop(address)](./sdk.thirdwebsdk.gettokendrop.md) | | Get an instance of a Token Drop contract | -| [getVote(address)](./sdk.thirdwebsdk.getvote.md) | | Get an instance of a Vote contract | +| [getEdition(address, chain)](./sdk.thirdwebsdk.getedition.md) | | Get an instance of an Edition contract | +| [getEditionDrop(address, chain)](./sdk.thirdwebsdk.geteditiondrop.md) | | Get an instance of a Edition Drop contract | +| [getMarketplace(address, chain)](./sdk.thirdwebsdk.getmarketplace.md) | | Get an instance of a Marketplace contract | +| [getMultiwrap(address, chain)](./sdk.thirdwebsdk.getmultiwrap.md) | | (BETA) Get an instance of a Multiwrap contract | +| [getNFTCollection(address, chain)](./sdk.thirdwebsdk.getnftcollection.md) | | Get an instance of a NFT Collection contract | +| [getNFTDrop(contractAddress, chain)](./sdk.thirdwebsdk.getnftdrop.md) | | Get an instance of a Drop contract | +| [getPack(address, chain)](./sdk.thirdwebsdk.getpack.md) | | Get an instance of a Pack contract | +| [getSplit(address, chain)](./sdk.thirdwebsdk.getsplit.md) | | Get an instance of a Splits contract | +| [getToken(address, chain)](./sdk.thirdwebsdk.gettoken.md) | | Get an instance of a Token contract | +| [getTokenDrop(address, chain)](./sdk.thirdwebsdk.gettokendrop.md) | | Get an instance of a Token Drop contract | +| [getVote(address, chain)](./sdk.thirdwebsdk.getvote.md) | | Get an instance of a Vote contract | | [resolveContractType(contractAddress, chain)](./sdk.thirdwebsdk.resolvecontracttype.md) | | | diff --git a/etc/sdk.api.md b/etc/sdk.api.md index 8c821691d..259ea1b74 100644 --- a/etc/sdk.api.md +++ b/etc/sdk.api.md @@ -592,21 +592,33 @@ export const CONTRACT_ADDRESSES: Record(contractType: TContract["contractType"], contractMetadata: z.input): Promise; - deployEdition(metadata: NFTContractDeployMetadata): Promise; - deployEditionDrop(metadata: NFTContractDeployMetadata): Promise; - deployMarketplace(metadata: MarketplaceContractDeployMetadata): Promise; + deployBuiltInContract(contractType: TContract["contractType"], contractMetadata: z.input, chain?: ChainIdOrName): Promise; + // Warning: (ae-incompatible-release-tags) The symbol "deployEdition" is marked as @public, but its signature references "ChainIdOrName" which is marked as @internal + deployEdition(metadata: NFTContractDeployMetadata, chain?: ChainIdOrName): Promise; + // Warning: (ae-incompatible-release-tags) The symbol "deployEditionDrop" is marked as @public, but its signature references "ChainIdOrName" which is marked as @internal + deployEditionDrop(metadata: NFTContractDeployMetadata, chain?: ChainIdOrName): Promise; + // Warning: (ae-incompatible-release-tags) The symbol "deployMarketplace" is marked as @public, but its signature references "ChainIdOrName" which is marked as @internal + deployMarketplace(metadata: MarketplaceContractDeployMetadata, chain?: ChainIdOrName): Promise; + // Warning: (ae-incompatible-release-tags) The symbol "deployMultiwrap" is marked as @beta, but its signature references "ChainIdOrName" which is marked as @internal + // // @beta - deployMultiwrap(metadata: MultiwrapContractDeployMetadata): Promise; - deployNFTCollection(metadata: NFTContractDeployMetadata): Promise; - deployNFTDrop(metadata: NFTContractDeployMetadata): Promise; - deployPack(metadata: NFTContractDeployMetadata): Promise; + deployMultiwrap(metadata: MultiwrapContractDeployMetadata, chain?: ChainIdOrName): Promise; + // Warning: (ae-incompatible-release-tags) The symbol "deployNFTCollection" is marked as @public, but its signature references "ChainIdOrName" which is marked as @internal + deployNFTCollection(metadata: NFTContractDeployMetadata, chain?: ChainIdOrName): Promise; + // Warning: (ae-incompatible-release-tags) The symbol "deployNFTDrop" is marked as @public, but its signature references "ChainIdOrName" which is marked as @internal + deployNFTDrop(metadata: NFTContractDeployMetadata, chain?: ChainIdOrName): Promise; + // Warning: (ae-incompatible-release-tags) The symbol "deployPack" is marked as @public, but its signature references "ChainIdOrName" which is marked as @internal + deployPack(metadata: NFTContractDeployMetadata, chain?: ChainIdOrName): Promise; // @internal - deploySignatureDrop(metadata: NFTContractDeployMetadata): Promise; - deploySplit(metadata: SplitContractDeployMetadata): Promise; - deployToken(metadata: TokenContractDeployMetadata): Promise; - deployTokenDrop(metadata: TokenContractDeployMetadata): Promise; - deployVote(metadata: VoteContractDeployMetadata): Promise; + deploySignatureDrop(metadata: NFTContractDeployMetadata, chain?: ChainIdOrName): Promise; + // Warning: (ae-incompatible-release-tags) The symbol "deploySplit" is marked as @public, but its signature references "ChainIdOrName" which is marked as @internal + deploySplit(metadata: SplitContractDeployMetadata, chain?: ChainIdOrName): Promise; + // Warning: (ae-incompatible-release-tags) The symbol "deployToken" is marked as @public, but its signature references "ChainIdOrName" which is marked as @internal + deployToken(metadata: TokenContractDeployMetadata, chain?: ChainIdOrName): Promise; + // Warning: (ae-incompatible-release-tags) The symbol "deployTokenDrop" is marked as @public, but its signature references "ChainIdOrName" which is marked as @internal + deployTokenDrop(metadata: TokenContractDeployMetadata, chain?: ChainIdOrName): Promise; + // Warning: (ae-incompatible-release-tags) The symbol "deployVote" is marked as @public, but its signature references "ChainIdOrName" which is marked as @internal + deployVote(metadata: VoteContractDeployMetadata, chain?: ChainIdOrName): Promise; // Warning: (ae-forgotten-export) The symbol "ContractRegistry" needs to be exported by the entry point index.d.ts // // @internal (undocumented) @@ -5055,24 +5067,36 @@ export class ThirdwebSDK extends RPCConnectionHandler { contractType: "custom" | "token" | "split" | "edition" | "edition-drop" | "token-drop" | "vote" | "marketplace" | "pack" | "nft-drop" | "signature-drop" | "multiwrap" | "nft-collection"; metadata: () => Promise; }[]>; - getEdition(address: string): Promise; - getEditionDrop(address: string): Promise; - getMarketplace(address: string): Promise; + // Warning: (ae-incompatible-release-tags) The symbol "getEdition" is marked as @public, but its signature references "ChainIdOrName" which is marked as @internal + getEdition(address: string, chain?: ChainIdOrName): Promise; + // Warning: (ae-incompatible-release-tags) The symbol "getEditionDrop" is marked as @public, but its signature references "ChainIdOrName" which is marked as @internal + getEditionDrop(address: string, chain?: ChainIdOrName): Promise; + // Warning: (ae-incompatible-release-tags) The symbol "getMarketplace" is marked as @public, but its signature references "ChainIdOrName" which is marked as @internal + getMarketplace(address: string, chain?: ChainIdOrName): Promise; + // Warning: (ae-incompatible-release-tags) The symbol "getMultiwrap" is marked as @beta, but its signature references "ChainIdOrName" which is marked as @internal + // // @beta - getMultiwrap(address: string): Promise; - getNFTCollection(address: string): Promise; - getNFTDrop(contractAddress: string): Promise; - getPack(address: string): Promise; + getMultiwrap(address: string, chain?: ChainIdOrName): Promise; + // Warning: (ae-incompatible-release-tags) The symbol "getNFTCollection" is marked as @public, but its signature references "ChainIdOrName" which is marked as @internal + getNFTCollection(address: string, chain?: ChainIdOrName): Promise; + // Warning: (ae-incompatible-release-tags) The symbol "getNFTDrop" is marked as @public, but its signature references "ChainIdOrName" which is marked as @internal + getNFTDrop(contractAddress: string, chain?: ChainIdOrName): Promise; + // Warning: (ae-incompatible-release-tags) The symbol "getPack" is marked as @public, but its signature references "ChainIdOrName" which is marked as @internal + getPack(address: string, chain?: ChainIdOrName): Promise; // Warning: (ae-forgotten-export) The symbol "ContractPublisher" needs to be exported by the entry point index.d.ts // // @internal (undocumented) getPublisher(): ContractPublisher; // @internal - getSignatureDrop(contractAddress: string): Promise; - getSplit(address: string): Promise; - getToken(address: string): Promise; - getTokenDrop(address: string): Promise; - getVote(address: string): Promise; + getSignatureDrop(contractAddress: string, chain?: ChainIdOrName): Promise; + // Warning: (ae-incompatible-release-tags) The symbol "getSplit" is marked as @public, but its signature references "ChainIdOrName" which is marked as @internal + getSplit(address: string, chain?: ChainIdOrName): Promise; + // Warning: (ae-incompatible-release-tags) The symbol "getToken" is marked as @public, but its signature references "ChainIdOrName" which is marked as @internal + getToken(address: string, chain?: ChainIdOrName): Promise; + // Warning: (ae-incompatible-release-tags) The symbol "getTokenDrop" is marked as @public, but its signature references "ChainIdOrName" which is marked as @internal + getTokenDrop(address: string, chain?: ChainIdOrName): Promise; + // Warning: (ae-incompatible-release-tags) The symbol "getVote" is marked as @public, but its signature references "ChainIdOrName" which is marked as @internal + getVote(address: string, chain?: ChainIdOrName): Promise; // Warning: (ae-incompatible-release-tags) The symbol "resolveContractType" is marked as @public, but its signature references "ChainIdOrName" which is marked as @internal // // (undocumented) diff --git a/src/core/classes/contract-deployer.ts b/src/core/classes/contract-deployer.ts index 62a510bd0..114654261 100644 --- a/src/core/classes/contract-deployer.ts +++ b/src/core/classes/contract-deployer.ts @@ -61,14 +61,17 @@ export class ContractDeployer extends RPCConnectionHandler { * }); * ``` * @param metadata - the contract metadata + * @param chain - the chain to deploy the contract to, defaults to the chain the SDK is connected to * @returns the address of the deployed contract */ public async deployNFTCollection( metadata: NFTContractDeployMetadata, + chain: ChainIdOrName = this.getConnectionInfo().chainId, ): Promise { return await this.deployBuiltInContract( NFTCollection.contractType, metadata, + chain, ); } @@ -85,12 +88,18 @@ export class ContractDeployer extends RPCConnectionHandler { * }); * ``` * @param metadata - the contract metadata + * @param chain - the chain to deploy the contract to, defaults to the chain the SDK is connected to * @returns the address of the deployed contract */ public async deployNFTDrop( metadata: NFTContractDeployMetadata, + chain: ChainIdOrName = this.getConnectionInfo().chainId, ): Promise { - return await this.deployBuiltInContract(NFTDrop.contractType, metadata); + return await this.deployBuiltInContract( + NFTDrop.contractType, + metadata, + chain, + ); } /** @@ -106,15 +115,18 @@ export class ContractDeployer extends RPCConnectionHandler { * }); * ``` * @param metadata - the contract metadata + * @param chain - the chain to deploy the contract to, defaults to the chain the SDK is connected to * @returns the address of the deployed contract * @internal */ public async deploySignatureDrop( metadata: NFTContractDeployMetadata, + chain: ChainIdOrName = this.getConnectionInfo().chainId, ): Promise { return await this.deployBuiltInContract( SignatureDrop.contractType, metadata, + chain, ); } @@ -130,13 +142,19 @@ export class ContractDeployer extends RPCConnectionHandler { * }); * ``` * @param metadata - the contract metadata + * @param chain - the chain to deploy the contract to, defaults to the chain the SDK is connected to * @returns the address of the deployed contract * @beta */ public async deployMultiwrap( metadata: MultiwrapContractDeployMetadata, + chain: ChainIdOrName = this.getConnectionInfo().chainId, ): Promise { - return await this.deployBuiltInContract(Multiwrap.contractType, metadata); + return await this.deployBuiltInContract( + Multiwrap.contractType, + metadata, + chain, + ); } /** @@ -152,12 +170,18 @@ export class ContractDeployer extends RPCConnectionHandler { * }); * ``` * @param metadata - the contract metadata + * @param chain - the chain to deploy the contract to, defaults to the chain the SDK is connected to * @returns the address of the deployed contract */ public async deployEdition( metadata: NFTContractDeployMetadata, + chain: ChainIdOrName = this.getConnectionInfo().chainId, ): Promise { - return await this.deployBuiltInContract(Edition.contractType, metadata); + return await this.deployBuiltInContract( + Edition.contractType, + metadata, + chain, + ); } /** @@ -173,13 +197,18 @@ export class ContractDeployer extends RPCConnectionHandler { * }); * ``` * @param metadata - the contract metadata + * @param chain - the chain to deploy the contract to, defaults to the chain the SDK is connected to * @returns the address of the deployed contract */ public async deployEditionDrop( metadata: NFTContractDeployMetadata, + chain: ChainIdOrName = this.getConnectionInfo().chainId, ): Promise { - const parsed = EditionDrop.schema.deploy.parse(metadata); - return await this.deployBuiltInContract(EditionDrop.contractType, parsed); + return await this.deployBuiltInContract( + EditionDrop.contractType, + metadata, + chain, + ); } /** @@ -195,12 +224,18 @@ export class ContractDeployer extends RPCConnectionHandler { * }); * ``` * @param metadata - the contract metadata + * @param chain - the chain to deploy the contract to, defaults to the chain the SDK is connected to * @returns the address of the deployed contract */ public async deployToken( metadata: TokenContractDeployMetadata, + chain: ChainIdOrName = this.getConnectionInfo().chainId, ): Promise { - return await this.deployBuiltInContract(Token.contractType, metadata); + return await this.deployBuiltInContract( + Token.contractType, + metadata, + chain, + ); } /** @@ -216,12 +251,18 @@ export class ContractDeployer extends RPCConnectionHandler { * }); * ``` * @param metadata - the contract metadata + * @param chain - the chain to deploy the contract to, defaults to the chain the SDK is connected to * @returns the address of the deployed contract */ public async deployTokenDrop( metadata: TokenContractDeployMetadata, + chain: ChainIdOrName = this.getConnectionInfo().chainId, ): Promise { - return await this.deployBuiltInContract(TokenDrop.contractType, metadata); + return await this.deployBuiltInContract( + TokenDrop.contractType, + metadata, + chain, + ); } /** @@ -237,12 +278,18 @@ export class ContractDeployer extends RPCConnectionHandler { * }); * ``` * @param metadata - the contract metadata + * @param chain - the chain to deploy the contract to, defaults to the chain the SDK is connected to * @returns the address of the deployed contract */ public async deployMarketplace( metadata: MarketplaceContractDeployMetadata, + chain: ChainIdOrName = this.getConnectionInfo().chainId, ): Promise { - return await this.deployBuiltInContract(Marketplace.contractType, metadata); + return await this.deployBuiltInContract( + Marketplace.contractType, + metadata, + chain, + ); } /** @@ -258,12 +305,14 @@ export class ContractDeployer extends RPCConnectionHandler { * }); * ``` * @param metadata - the contract metadata + * @param chain - the chain to deploy the contract to, defaults to the chain the SDK is connected to * @returns the address of the deployed contract */ public async deployPack( metadata: NFTContractDeployMetadata, + chain: ChainIdOrName = this.getConnectionInfo().chainId, ): Promise { - return await this.deployBuiltInContract(Pack.contractType, metadata); + return await this.deployBuiltInContract(Pack.contractType, metadata, chain); } /** @@ -289,12 +338,18 @@ export class ContractDeployer extends RPCConnectionHandler { * }); * ``` * @param metadata - the contract metadata + * @param chain - the chain to deploy the contract to, defaults to the chain the SDK is connected to * @returns the address of the deployed contract */ public async deploySplit( metadata: SplitContractDeployMetadata, + chain: ChainIdOrName = this.getConnectionInfo().chainId, ): Promise { - return await this.deployBuiltInContract(Split.contractType, metadata); + return await this.deployBuiltInContract( + Split.contractType, + metadata, + chain, + ); } /** @@ -311,12 +366,14 @@ export class ContractDeployer extends RPCConnectionHandler { * }); * ``` * @param metadata - the contract metadata + * @param chain - the chain to deploy the contract to, defaults to the chain the SDK is connected to * @returns the address of the deployed contract */ public async deployVote( metadata: VoteContractDeployMetadata, + chain: ChainIdOrName = this.getConnectionInfo().chainId, ): Promise { - return await this.deployBuiltInContract(Vote.contractType, metadata); + return await this.deployBuiltInContract(Vote.contractType, metadata, chain); } /** @@ -325,13 +382,15 @@ export class ContractDeployer extends RPCConnectionHandler { * @internal * @param contractType - the type of contract to deploy * @param contractMetadata - the metadata to deploy the contract with + * @param chain - the chain to deploy the contract to, defaults to the chain the SDK is connected to * @returns a promise of the address of the newly deployed contract */ public async deployBuiltInContract( contractType: TContract["contractType"], contractMetadata: z.input, + chain: ChainIdOrName = this.getConnectionInfo().chainId, ): Promise { - const factory = await this.getFactory(); + const factory = await this.getFactory(chain); return await factory.deploy(contractType, contractMetadata); } diff --git a/src/core/classes/rpc-connection-handler.ts b/src/core/classes/rpc-connection-handler.ts index 610e31fc6..b40f91c18 100644 --- a/src/core/classes/rpc-connection-handler.ts +++ b/src/core/classes/rpc-connection-handler.ts @@ -35,7 +35,7 @@ export class RPCConnectionHandler extends EventEmitter { connection.chainId, this.options.chainIdToRPCUrlMap, ); - this.signer = connection.signer; + this.signer = this.maybeConnectSigner(connection.signer); } /** @@ -45,12 +45,12 @@ export class RPCConnectionHandler extends EventEmitter { * @internal */ public updateSigner(signer: Signer | undefined) { - this.signer = signer; // TODO (rpc) - make sure we don't need to do this for type of signers if (this.chainId === ChainId.Hardhat) { // For hardhat tests - the provider inside the signer is enhanced for tests, need to use it as the provider this.provider = signer?.provider || this.provider; } + this.signer = this.maybeConnectSigner(signer); } /** * @@ -96,4 +96,12 @@ export class RPCConnectionHandler extends EventEmitter { provider: this.getProvider(), }; } + + private maybeConnectSigner(signer: Signer | undefined) { + try { + return signer?.connect(this.provider); + } catch (e) { + return signer; + } + } } diff --git a/src/core/sdk.ts b/src/core/sdk.ts index 2969c0ebd..20b89ca30 100644 --- a/src/core/sdk.ts +++ b/src/core/sdk.ts @@ -192,133 +192,190 @@ export class ThirdwebSDK extends RPCConnectionHandler { /** * Get an instance of a Drop contract * @param contractAddress - the address of the deployed contract + * @param chain - optional, chain (id or name) of the contract (defaults to the chain the SDK is connected to) * @returns the contract */ - public async getNFTDrop(contractAddress: string): Promise { + public async getNFTDrop( + contractAddress: string, + chain: ChainIdOrName = this.getConnectionInfo().chainId, + ): Promise { return this.getBuiltInContract<"nft-drop">( contractAddress, NFTDrop.contractType, + chain, ); } /** * Get an instance of a SignatureDrop contract * @param contractAddress - the address of the deployed contract + * @param chain - optional, chain (id or name) of the contract (defaults to the chain the SDK is connected to) * @returns the contract * @internal */ public async getSignatureDrop( contractAddress: string, + chain: ChainIdOrName = this.getConnectionInfo().chainId, ): Promise { return this.getBuiltInContract<"signature-drop">( contractAddress, SignatureDrop.contractType, + chain, ); } /** * Get an instance of a NFT Collection contract * @param address - the address of the deployed contract + * @param chain - optional, chain (id or name) of the contract (defaults to the chain the SDK is connected to) * @returns the contract */ - public async getNFTCollection(address: string): Promise { + public async getNFTCollection( + address: string, + chain: ChainIdOrName = this.getConnectionInfo().chainId, + ): Promise { return this.getBuiltInContract<"nft-collection">( address, NFTCollection.contractType, + chain, ); } /** * Get an instance of a Edition Drop contract * @param address - the address of the deployed contract + * @param chain - optional, chain (id or name) of the contract (defaults to the chain the SDK is connected to) * @returns the contract */ - public async getEditionDrop(address: string): Promise { + public async getEditionDrop( + address: string, + chain: ChainIdOrName = this.getConnectionInfo().chainId, + ): Promise { return this.getBuiltInContract<"edition-drop">( address, EditionDrop.contractType, + chain, ); } /** * Get an instance of an Edition contract * @param address - the address of the deployed contract + * @param chain - optional, chain (id or name) of the contract (defaults to the chain the SDK is connected to) * @returns the contract */ - public async getEdition(address: string): Promise { - return this.getBuiltInContract<"edition">(address, Edition.contractType); + public async getEdition( + address: string, + chain: ChainIdOrName = this.getConnectionInfo().chainId, + ): Promise { + return this.getBuiltInContract<"edition">( + address, + Edition.contractType, + chain, + ); } /** * Get an instance of a Token Drop contract * @param address - the address of the deployed contract + * @param chain - optional, chain (id or name) of the contract (defaults to the chain the SDK is connected to) * @returns the contract */ - public async getTokenDrop(address: string): Promise { + public async getTokenDrop( + address: string, + chain: ChainIdOrName = this.getConnectionInfo().chainId, + ): Promise { return this.getBuiltInContract<"token-drop">( address, TokenDrop.contractType, + chain, ); } /** * Get an instance of a Token contract * @param address - the address of the deployed contract + * @param chain - optional, chain (id or name) of the contract (defaults to the chain the SDK is connected to) * @returns the contract */ - public async getToken(address: string): Promise { - return this.getBuiltInContract<"token">(address, Token.contractType); + public async getToken( + address: string, + chain: ChainIdOrName = this.getConnectionInfo().chainId, + ): Promise { + return this.getBuiltInContract<"token">(address, Token.contractType, chain); } /** * Get an instance of a Vote contract * @param address - the address of the deployed contract + * @param chain - optional, chain (id or name) of the contract (defaults to the chain the SDK is connected to) * @returns the contract */ - public async getVote(address: string): Promise { - return this.getBuiltInContract<"vote">(address, Vote.contractType); + public async getVote( + address: string, + chain: ChainIdOrName = this.getConnectionInfo().chainId, + ): Promise { + return this.getBuiltInContract<"vote">(address, Vote.contractType, chain); } /** * Get an instance of a Splits contract * @param address - the address of the deployed contract + * @param chain - optional, chain (id or name) of the contract (defaults to the chain the SDK is connected to) * @returns the contract */ - public async getSplit(address: string): Promise { - return this.getBuiltInContract<"split">(address, Split.contractType); + public async getSplit( + address: string, + chain: ChainIdOrName = this.getConnectionInfo().chainId, + ): Promise { + return this.getBuiltInContract<"split">(address, Split.contractType, chain); } /** * Get an instance of a Marketplace contract * @param address - the address of the deployed contract + * @param chain - optional, chain (id or name) of the contract (defaults to the chain the SDK is connected to) * @returns the contract */ - public async getMarketplace(address: string): Promise { + public async getMarketplace( + address: string, + chain: ChainIdOrName = this.getConnectionInfo().chainId, + ): Promise { return this.getBuiltInContract<"marketplace">( address, Marketplace.contractType, + chain, ); } /** * Get an instance of a Pack contract * @param address - the address of the deployed contract + * @param chain - optional, chain (id or name) of the contract (defaults to the chain the SDK is connected to) * @returns the contract */ - public async getPack(address: string): Promise { - return this.getBuiltInContract<"pack">(address, Pack.contractType); + public async getPack( + address: string, + chain: ChainIdOrName = this.getConnectionInfo().chainId, + ): Promise { + return this.getBuiltInContract<"pack">(address, Pack.contractType, chain); } /** * Get an instance of a Multiwrap contract * @param address - the address of the deployed contract + * @param chain - optional, chain (id or name) of the contract (defaults to the chain the SDK is connected to) * @returns the contract * @beta */ - public async getMultiwrap(address: string): Promise { + public async getMultiwrap( + address: string, + chain: ChainIdOrName = this.getConnectionInfo().chainId, + ): Promise { return this.getBuiltInContract<"multiwrap">( address, Multiwrap.contractType, + chain, ); } @@ -327,7 +384,7 @@ export class ThirdwebSDK extends RPCConnectionHandler { * @internal * @param address - the address of the contract to instantiate * @param contractType - the type of contract to instantiate - * @param chain - optional the chain (id or name) of the contract (defaults to the SDK chainId) + * @param chain - optional, chain (id or name) of the contract (defaults to the chain the SDK is connected to) * @returns a promise that resolves with the contract instance */ public async getBuiltInContract< From dce9ac2b6f0f6aa900a09199caf28b4eb5516e57 Mon Sep 17 00:00:00 2001 From: Joaquim Verges Date: Sun, 26 Jun 2022 21:58:49 -0700 Subject: [PATCH 4/5] fix all the tests --- test/auth.test.ts | 23 ++-- test/edition-drop.test.ts | 208 +++++++++++++++---------------- test/edition.test.ts | 68 +++++----- test/events.test.ts | 44 +------ test/gasless.test.ts | 41 ------ test/marketplace.test.ts | 38 +++--- test/multiwrap.test.ts | 10 +- test/nft-drop.test.ts | 2 +- test/nft.test.ts | 8 +- test/pack.test.ts | 32 +++-- test/recursive.test.ts | 2 + test/registry.test.ts | 6 +- test/roles.test.ts | 32 ++--- test/royalty.test.ts | 26 ++-- test/sigdroptest.ts | 4 +- test/signature-mint-1155.test.ts | 6 +- test/signature-mint-20.test.ts | 6 +- test/signature-mint-721.test.ts | 6 +- test/split.test.ts | 2 +- test/token-drop.test.ts | 3 +- test/token.test.ts | 2 +- test/volume.test.ts | 95 -------------- test/vote.test.ts | 19 ++- test/wallet.test.ts | 2 +- 24 files changed, 255 insertions(+), 430 deletions(-) delete mode 100644 test/gasless.test.ts delete mode 100644 test/volume.test.ts diff --git a/test/auth.test.ts b/test/auth.test.ts index 3eaa89094..edf9e024a 100644 --- a/test/auth.test.ts +++ b/test/auth.test.ts @@ -1,4 +1,4 @@ -import { signers } from "./before-setup"; +import { expectError, signers } from "./before-setup"; import { expect } from "chai"; import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; import { ChainId, ThirdwebSDK } from "../src"; @@ -50,7 +50,8 @@ describe("Wallet Authentication", async () => { sdk.auth.verify("test.thirdweb.com", payload); expect.fail(); } catch (err) { - expect(err.message).to.equal( + expectError( + err, "Expected domain 'test.thirdweb.com' does not match domain on payload 'thirdweb.com'", ); } @@ -66,7 +67,7 @@ describe("Wallet Authentication", async () => { sdk.auth.verify(domain, payload); expect.fail(); } catch (err) { - expect(err.message).to.equal("Login request has expired"); + expectError(err, "Login request has expired"); } }); @@ -82,9 +83,7 @@ describe("Wallet Authentication", async () => { }); expect.fail(); } catch (err) { - expect(err.message).to.equal( - "Chain ID '137' does not match payload chain ID '1'", - ); + expectError(err, "Chain ID '137' does not match payload chain ID '1'"); } }); @@ -97,7 +96,7 @@ describe("Wallet Authentication", async () => { sdk.auth.verify(domain, payload); expect.fail(); } catch (err) { - expect(err.message).to.contain("does not match payload address"); + expectError(err, "does not match payload address"); } }); @@ -121,7 +120,8 @@ describe("Wallet Authentication", async () => { await sdk.auth.authenticate("test.thirdweb.com", token); expect.fail(); } catch (err) { - expect(err.message).to.contain( + expectError( + err, "Expected token to be for the domain 'test.thirdweb.com', but found token with domain 'thirdweb.com'", ); } @@ -139,7 +139,7 @@ describe("Wallet Authentication", async () => { await sdk.auth.authenticate(domain, token); expect.fail(); } catch (err) { - expect(err.message).to.contain("This token is invalid before"); + expectError(err, "This token is invalid before"); } }); @@ -155,7 +155,7 @@ describe("Wallet Authentication", async () => { await sdk.auth.authenticate(domain, token); expect.fail(); } catch (err) { - expect(err.message).to.contain("This token expired"); + expectError(err, "This token expired"); } }); @@ -170,7 +170,8 @@ describe("Wallet Authentication", async () => { await sdk.auth.authenticate(domain, token); expect.fail(); } catch (err) { - expect(err.message).to.contain( + expectError( + err, `Expected the connected wallet address '${signerWallet.address}' to match the token issuer address '${adminWallet.address}'`, ); } diff --git a/test/edition-drop.test.ts b/test/edition-drop.test.ts index b6501f3bb..15a528a95 100644 --- a/test/edition-drop.test.ts +++ b/test/edition-drop.test.ts @@ -16,7 +16,7 @@ const deepEqualInAnyOrder = require("deep-equal-in-any-order"); use(deepEqualInAnyOrder); describe("Edition Drop Contract", async () => { - let bdContract: EditionDrop; + let editionDrop: EditionDrop; let adminWallet: SignerWithAddress, samWallet: SignerWithAddress, abbyWallet: SignerWithAddress, @@ -43,11 +43,11 @@ describe("Edition Drop Contract", async () => { platform_fee_basis_points: 10, platform_fee_recipient: adminWallet.address, }); - bdContract = sdk.getEditionDrop(address); + editionDrop = await sdk.getEditionDrop(address); }); it("should estimate gas cost", async () => { - const cost = await bdContract.estimator.gasCostOf("lazyMint", [ + const cost = await editionDrop.estimator.gasCostOf("lazyMint", [ 1000, "mock://12398172398172389/0", ]); @@ -55,26 +55,26 @@ describe("Edition Drop Contract", async () => { }); it("should allow you to set claim conditions", async () => { - await bdContract.createBatch([ + await editionDrop.createBatch([ { name: "test", description: "test" }, { name: "test", description: "test" }, ]); - await bdContract.claimConditions.set(BigNumber.from("0"), [{}]); - const conditions = await bdContract.claimConditions.getAll(0); + await editionDrop.claimConditions.set(BigNumber.from("0"), [{}]); + const conditions = await editionDrop.claimConditions.getAll(0); assert.lengthOf(conditions, 1); }); it("should get all", async () => { - await bdContract.createBatch([ + await editionDrop.createBatch([ { name: "test", description: "test" }, { name: "test", description: "test" }, ]); - const all = await bdContract.getAll(); + const all = await editionDrop.getAll(); expect(all.length).to.eq(2); }); it("allow all addresses in the merkle tree to claim", async () => { - await bdContract.createBatch([ + await editionDrop.createBatch([ { name: "test", description: "test", @@ -92,7 +92,7 @@ describe("Edition Drop Contract", async () => { ]; const members = testWallets.map((w) => w.address); - await bdContract.claimConditions.set("0", [ + await editionDrop.claimConditions.set("0", [ { maxQuantity: 1000, snapshot: members, @@ -101,18 +101,18 @@ describe("Edition Drop Contract", async () => { for (const member of testWallets) { await sdk.wallet.connect(member); - await bdContract.claim("0", 1); + await editionDrop.claim("0", 1); } - const bundle = await bdContract.get("0"); + const bundle = await editionDrop.get("0"); assert(bundle.supply.toNumber() === testWallets.length); - const claimers = await bdContract.history.getAllClaimerAddresses("0"); + const claimers = await editionDrop.history.getAllClaimerAddresses("0"); expect(claimers.length).to.eq(testWallets.length); expect(claimers).to.include(bobWallet.address); }); it("allow all addresses in the merkle tree to claim using useSnapshot", async () => { - await bdContract.createBatch([ + await editionDrop.createBatch([ { name: "test", description: "test", @@ -128,7 +128,7 @@ describe("Edition Drop Contract", async () => { w3, ]; const members = testWallets.map((w) => w.address); - await bdContract.claimConditions.set("0", [ + await editionDrop.claimConditions.set("0", [ { maxQuantity: 1000, snapshot: members, @@ -139,14 +139,14 @@ describe("Edition Drop Contract", async () => { for (const member of testWallets) { try { sdk.wallet.connect(member); - await bdContract.claim("0", 1); + await editionDrop.claim("0", 1); } catch (e) { if (member !== w4) { throw e; } } } - const bundle = await bdContract.get("0"); + const bundle = await editionDrop.get("0"); assert(bundle.supply.toNumber() === testWallets.length - 1); }); @@ -168,7 +168,7 @@ describe("Edition Drop Contract", async () => { name: "test 4", }, ]; - const result = await bdContract.createBatch(tokens); + const result = await editionDrop.createBatch(tokens); assert.lengthOf(result, tokens.length); for (const token of tokens) { const found = result.find( @@ -185,7 +185,7 @@ describe("Edition Drop Contract", async () => { name: "test 6", }, ]; - const moreResult = await bdContract.createBatch(moreTokens); + const moreResult = await editionDrop.createBatch(moreTokens); assert.lengthOf(moreResult, moreTokens.length); for (const token of moreTokens) { const found = moreResult.find( @@ -196,10 +196,10 @@ describe("Edition Drop Contract", async () => { }); it("should allow setting max claims per wallet", async () => { - await bdContract.createBatch([ + await editionDrop.createBatch([ { name: "name", description: "description" }, ]); - await bdContract.claimConditions.set(0, [ + await editionDrop.claimConditions.set(0, [ { snapshot: [ { address: w1.address, maxClaimable: 2 }, @@ -208,17 +208,17 @@ describe("Edition Drop Contract", async () => { }, ]); await sdk.wallet.connect(w1); - await bdContract.claim(0, 2); + await editionDrop.claim(0, 2); try { await sdk.wallet.connect(w2); - await bdContract.claim(0, 2); + await editionDrop.claim(0, 2); } catch (e) { expectError(e, "invalid quantity proof"); } }); it("should allow a default claim condition to be used to claim", async () => { - await bdContract.createBatch([ + await editionDrop.createBatch([ { name: "test 0", }, @@ -230,12 +230,12 @@ describe("Edition Drop Contract", async () => { }, ]); - await bdContract.claimConditions.set("0", [{}]); - await bdContract.claim("0", 1); + await editionDrop.claimConditions.set("0", [{}]); + await editionDrop.claim("0", 1); }); it("should return addresses of all the claimers", async () => { - await bdContract.createBatch([ + await editionDrop.createBatch([ { name: "test 0", }, @@ -244,12 +244,12 @@ describe("Edition Drop Contract", async () => { }, ]); - await bdContract.claimConditions.set("0", [{}]); - await bdContract.claimConditions.set("1", [{}]); - await bdContract.claim("0", 1); + await editionDrop.claimConditions.set("0", [{}]); + await editionDrop.claimConditions.set("1", [{}]); + await editionDrop.claim("0", 1); await sdk.wallet.connect(samWallet); - await bdContract.claim("0", 1); + await editionDrop.claim("0", 1); // TODO some asserts // const claimers = await bdContract.getAllClaimerAddresses("0"); @@ -259,52 +259,52 @@ describe("Edition Drop Contract", async () => { // ]); await sdk.wallet.connect(w1); - await bdContract.claim("1", 1); + await editionDrop.claim("1", 1); await sdk.wallet.connect(w2); - await bdContract.claim("1", 1); + await editionDrop.claim("1", 1); - const ownedW1 = await bdContract.getOwned(w1.address); + const ownedW1 = await editionDrop.getOwned(w1.address); assert(ownedW1.length === 1); - const ownedW2 = await bdContract.getOwned(w2.address); + const ownedW2 = await editionDrop.getOwned(w2.address); assert(ownedW2.length === 1); }); it("should return the correct status if a token can be claimed", async () => { - await bdContract.claimConditions.set("0", [ + await editionDrop.claimConditions.set("0", [ { snapshot: [w1.address], }, ]); await sdk.wallet.connect(w1); - const canClaimW1 = await bdContract.claimConditions.canClaim("0", 1); + const canClaimW1 = await editionDrop.claimConditions.canClaim("0", 1); assert.isTrue(canClaimW1, "w1 should be able to claim"); await sdk.wallet.connect(w2); - const canClaimW2 = await bdContract.claimConditions.canClaim("0", 1); + const canClaimW2 = await editionDrop.claimConditions.canClaim("0", 1); assert.isFalse(canClaimW2, "w2 should not be able to claim"); }); it("Platform fees", async () => { - const fees = await bdContract.platformFees.get(); + const fees = await editionDrop.platformFees.get(); expect(fees.platform_fee_recipient).to.eq(adminWallet.address); expect(fees.platform_fee_basis_points).to.eq(10); - await bdContract.platformFees.set({ + await editionDrop.platformFees.set({ platform_fee_recipient: samWallet.address, platform_fee_basis_points: 500, }); - const fees2 = await bdContract.platformFees.get(); + const fees2 = await editionDrop.platformFees.get(); expect(fees2.platform_fee_recipient).to.eq(samWallet.address); expect(fees2.platform_fee_basis_points).to.eq(500); }); it("should allow custom overrides", async () => { - bdContract.interceptor.overrideNextTransaction(() => ({ + editionDrop.interceptor.overrideNextTransaction(() => ({ nonce: 5000, })); try { - await bdContract.createBatch([ + await editionDrop.createBatch([ { name: "test", description: "test", @@ -316,24 +316,24 @@ describe("Edition Drop Contract", async () => { }); it("canClaim: 1 address", async () => { - await bdContract.claimConditions.set("0", [ + await editionDrop.claimConditions.set("0", [ { snapshot: [w1.address], }, ]); assert.isTrue( - await bdContract.claimConditions.canClaim("0", 1, w1.address), + await editionDrop.claimConditions.canClaim("0", 1, w1.address), "can claim", ); assert.isFalse( - await bdContract.claimConditions.canClaim("0", 1, w2.address), + await editionDrop.claimConditions.canClaim("0", 1, w2.address), "!can claim", ); }); it("canClaim: 3 address", async () => { - await bdContract.claimConditions.set("0", [ + await editionDrop.claimConditions.set("0", [ { snapshot: [ w1.address.toUpperCase().replace("0X", "0x"), @@ -344,40 +344,40 @@ describe("Edition Drop Contract", async () => { ]); assert.isTrue( - await bdContract.claimConditions.canClaim("0", 1, w1.address), + await editionDrop.claimConditions.canClaim("0", 1, w1.address), "can claim", ); assert.isTrue( - await bdContract.claimConditions.canClaim("0", 1, w2.address), + await editionDrop.claimConditions.canClaim("0", 1, w2.address), "can claim", ); assert.isTrue( - await bdContract.claimConditions.canClaim("0", 1, w3.address), + await editionDrop.claimConditions.canClaim("0", 1, w3.address), "can claim", ); assert.isFalse( - await bdContract.claimConditions.canClaim("0", 1, bobWallet.address), + await editionDrop.claimConditions.canClaim("0", 1, bobWallet.address), "!can claim", ); }); it("should work when the token has a price", async () => { - await bdContract.createBatch([ + await editionDrop.createBatch([ { name: "test", description: "test", }, ]); - await bdContract.claimConditions.set("0", [ + await editionDrop.claimConditions.set("0", [ { price: 1, }, ]); - await bdContract.claim("0", 1); + await editionDrop.claim("0", 1); }); it("should set multiple claim conditions at once", async () => { - await bdContract.createBatch([ + await editionDrop.createBatch([ { name: "test1", description: "test1", @@ -387,7 +387,7 @@ describe("Edition Drop Contract", async () => { description: "test2", }, ]); - await bdContract.claimConditions.setBatch([ + await editionDrop.claimConditions.setBatch([ { tokenId: 0, claimConditions: [ @@ -406,9 +406,9 @@ describe("Edition Drop Contract", async () => { ], }, ]); - await bdContract.claim("0", 2); + await editionDrop.claim("0", 2); try { - await bdContract.claim("1", 2); + await editionDrop.claim("1", 2); } catch (e) { expectError(e, "exceed max mint supply"); } @@ -416,7 +416,7 @@ describe("Edition Drop Contract", async () => { describe("eligibility", () => { beforeEach(async () => { - await bdContract.createBatch([ + await editionDrop.createBatch([ { name: "test", description: "test", @@ -426,7 +426,7 @@ describe("Edition Drop Contract", async () => { it("should return false if there isn't an active claim condition", async () => { const reasons = - await bdContract.claimConditions.getClaimIneligibilityReasons( + await editionDrop.claimConditions.getClaimIneligibilityReasons( "0", "0", bobWallet.address, @@ -434,7 +434,7 @@ describe("Edition Drop Contract", async () => { expect(reasons).to.include(ClaimEligibility.NoClaimConditionSet); assert.lengthOf(reasons, 1); - const canClaim = await bdContract.claimConditions.canClaim( + const canClaim = await editionDrop.claimConditions.canClaim( "0", "1", w1.address, @@ -443,30 +443,30 @@ describe("Edition Drop Contract", async () => { }); it("set claim condition in the future should not be claimable now", async () => { - await bdContract.claimConditions.set(0, [ + await editionDrop.claimConditions.set(0, [ { startTime: new Date(Date.now() + 60 * 60 * 24 * 1000), }, ]); - const canClaim = await bdContract.claimConditions.canClaim(0, 1); + const canClaim = await editionDrop.claimConditions.canClaim(0, 1); expect(canClaim).to.eq(false); }); it("should check for the total supply", async () => { - await bdContract.claimConditions.set("0", [ + await editionDrop.claimConditions.set("0", [ { maxQuantity: 1, }, ]); const reasons = - await bdContract.claimConditions.getClaimIneligibilityReasons( + await editionDrop.claimConditions.getClaimIneligibilityReasons( "0", "2", w1.address, ); expect(reasons).to.include(ClaimEligibility.NotEnoughSupply); - const canClaim = await bdContract.claimConditions.canClaim( + const canClaim = await editionDrop.claimConditions.canClaim( "0", "2", w1.address, @@ -475,7 +475,7 @@ describe("Edition Drop Contract", async () => { }); it("should check if an address has valid merkle proofs", async () => { - await bdContract.claimConditions.set("0", [ + await editionDrop.claimConditions.set("0", [ { maxQuantity: 1, snapshot: [w2.address, adminWallet.address], @@ -483,13 +483,13 @@ describe("Edition Drop Contract", async () => { ]); const reasons = - await bdContract.claimConditions.getClaimIneligibilityReasons( + await editionDrop.claimConditions.getClaimIneligibilityReasons( "0", "1", w1.address, ); expect(reasons).to.include(ClaimEligibility.AddressNotAllowed); - const canClaim = await bdContract.claimConditions.canClaim( + const canClaim = await editionDrop.claimConditions.canClaim( "0", "1", w1.address, @@ -498,17 +498,17 @@ describe("Edition Drop Contract", async () => { }); it("should check if its been long enough since the last claim", async () => { - await bdContract.claimConditions.set("0", [ + await editionDrop.claimConditions.set("0", [ { maxQuantity: 10, waitInSeconds: 24 * 60 * 60, }, ]); await sdk.wallet.connect(bobWallet); - await bdContract.claim("0", 1); + await editionDrop.claim("0", 1); const reasons = - await bdContract.claimConditions.getClaimIneligibilityReasons( + await editionDrop.claimConditions.getClaimIneligibilityReasons( "0", "1", bobWallet.address, @@ -517,7 +517,7 @@ describe("Edition Drop Contract", async () => { expect(reasons).to.include( ClaimEligibility.WaitBeforeNextClaimTransaction, ); - const canClaim = await bdContract.claimConditions.canClaim( + const canClaim = await editionDrop.claimConditions.canClaim( "0", "1", bobWallet.address, @@ -526,7 +526,7 @@ describe("Edition Drop Contract", async () => { }); it("should check if an address has enough native currency", async () => { - await bdContract.claimConditions.set("0", [ + await editionDrop.claimConditions.set("0", [ { maxQuantity: 10, price: "1000000000000000", @@ -536,14 +536,14 @@ describe("Edition Drop Contract", async () => { await sdk.wallet.connect(bobWallet); const reasons = - await bdContract.claimConditions.getClaimIneligibilityReasons( + await editionDrop.claimConditions.getClaimIneligibilityReasons( "0", "1", bobWallet.address, ); expect(reasons).to.include(ClaimEligibility.NotEnoughTokens); - const canClaim = await bdContract.claimConditions.canClaim( + const canClaim = await editionDrop.claimConditions.canClaim( "0", "1", w1.address, @@ -552,7 +552,7 @@ describe("Edition Drop Contract", async () => { }); it("should check if an address has enough erc20 currency", async () => { - const currency = sdk.getToken( + const currency = await sdk.getToken( await sdk.deployer.deployBuiltInContract(Token.contractType, { name: "test", symbol: "test", @@ -560,7 +560,7 @@ describe("Edition Drop Contract", async () => { }), ); - await bdContract.claimConditions.set("0", [ + await editionDrop.claimConditions.set("0", [ { maxQuantity: 10, price: "1000000000000000", @@ -570,14 +570,14 @@ describe("Edition Drop Contract", async () => { await sdk.wallet.connect(bobWallet); const reasons = - await bdContract.claimConditions.getClaimIneligibilityReasons( + await editionDrop.claimConditions.getClaimIneligibilityReasons( "0", "1", bobWallet.address, ); expect(reasons).to.include(ClaimEligibility.NotEnoughTokens); - const canClaim = await bdContract.claimConditions.canClaim( + const canClaim = await editionDrop.claimConditions.canClaim( "0", "1", w1.address, @@ -586,7 +586,7 @@ describe("Edition Drop Contract", async () => { }); it("should return nothing if the claim is eligible", async () => { - await bdContract.claimConditions.set("0", [ + await editionDrop.claimConditions.set("0", [ { maxQuantity: 10, price: "100", @@ -596,14 +596,14 @@ describe("Edition Drop Contract", async () => { ]); const reasons = - await bdContract.claimConditions.getClaimIneligibilityReasons( + await editionDrop.claimConditions.getClaimIneligibilityReasons( "0", "1", w1.address, ); assert.lengthOf(reasons, 0); - const canClaim = await bdContract.claimConditions.canClaim( + const canClaim = await editionDrop.claimConditions.canClaim( "0", "1", w1.address, @@ -612,85 +612,85 @@ describe("Edition Drop Contract", async () => { }); }); it("should allow you to update claim conditions", async () => { - await bdContract.createBatch([ + await editionDrop.createBatch([ { name: "test", description: "test" }, { name: "test", description: "test" }, ]); - await bdContract.claimConditions.set(BigNumber.from("0"), [{}]); - await bdContract.claimConditions.update(BigNumber.from("0"), 0, {}); - const conditions = await bdContract.claimConditions.getAll(0); + await editionDrop.claimConditions.set(BigNumber.from("0"), [{}]); + await editionDrop.claimConditions.update(BigNumber.from("0"), 0, {}); + const conditions = await editionDrop.claimConditions.getAll(0); assert.lengthOf(conditions, 1); }); it("should return snapshot data on claim conditions", async () => { - await bdContract.createBatch([ + await editionDrop.createBatch([ { name: "test", description: "test" }, { name: "test", description: "test" }, ]); - await bdContract.claimConditions.set(0, [ + await editionDrop.claimConditions.set(0, [ { snapshot: [samWallet.address], }, ]); - const conditions = await bdContract.claimConditions.getAll(0); + const conditions = await editionDrop.claimConditions.getAll(0); assert.lengthOf(conditions, 1); invariant(conditions[0].snapshot); expect(conditions[0].snapshot[0].address).to.eq(samWallet.address); }); it("should be able to use claim as function expected", async () => { - await bdContract.createBatch([ + await editionDrop.createBatch([ { name: "test", }, ]); - await bdContract.claimConditions.set("0", [{}]); - await bdContract.claim("0", 1); - assert((await bdContract.getOwned()).length > 0); + await editionDrop.claimConditions.set("0", [{}]); + await editionDrop.claim("0", 1); + assert((await editionDrop.getOwned()).length > 0); }); it("should be able to use claimTo function as expected", async () => { - await bdContract.createBatch([ + await editionDrop.createBatch([ { name: "test", }, ]); - await bdContract.claimConditions.set("0", [{}]); - await bdContract.claimTo(samWallet.address, "0", 3); - assert((await bdContract.getOwned(samWallet.address)).length === 1); + await editionDrop.claimConditions.set("0", [{}]); + await editionDrop.claimTo(samWallet.address, "0", 3); + assert((await editionDrop.getOwned(samWallet.address)).length === 1); assert( - (await bdContract.getOwned(samWallet.address))[0].owner === + (await editionDrop.getOwned(samWallet.address))[0].owner === samWallet.address, ); assert( ( - await bdContract.getOwned(samWallet.address) + await editionDrop.getOwned(samWallet.address) )[0].quantityOwned.toNumber() === 3, ); }); describe("setting merkle claim conditions", () => { it("should not overwrite existing merkle keys in the metadata", async () => { - await bdContract.createBatch([ + await editionDrop.createBatch([ { name: "test", description: "test" }, { name: "test", description: "test" }, ]); - await bdContract.claimConditions.set("1", [ + await editionDrop.claimConditions.set("1", [ { snapshot: [w1.address, w2.address, bobWallet.address], }, ]); - await bdContract.claimConditions.set("2", [ + await editionDrop.claimConditions.set("2", [ { snapshot: [w3.address, w1.address, w2.address, adminWallet.address], }, ]); - const metadata = await bdContract.metadata.get(); + const metadata = await editionDrop.metadata.get(); const merkle: { [key: string]: string } = metadata.merkle; assert.lengthOf(Object.keys(merkle), 2); }); diff --git a/test/edition.test.ts b/test/edition.test.ts index 150cbc9c9..fd024dd46 100644 --- a/test/edition.test.ts +++ b/test/edition.test.ts @@ -9,7 +9,7 @@ import { ethers } from "ethers"; global.fetch = require("cross-fetch"); describe("Edition Contract", async () => { - let bundleContract: Edition; + let editionContract: Edition; // let nftContract: NFTContract; // let currencyContract: CurrencyContract; @@ -34,11 +34,11 @@ describe("Edition Contract", async () => { platform_fee_basis_points: 10, platform_fee_recipient: AddressZero, }); - bundleContract = await sdk.getEdition(address); + editionContract = await sdk.getEdition(address); }); it("gas cost", async () => { - const cost = await bundleContract.estimator.gasCostOf("mintTo", [ + const cost = await editionContract.estimator.gasCostOf("mintTo", [ adminWallet.address, ethers.constants.MaxUint256, "mock://12398172398172389/0", @@ -55,15 +55,15 @@ describe("Edition Contract", async () => { supply: 10, }); } - await bundleContract.mintBatch(nfts); - const total = await bundleContract.getTotalCount(); + await editionContract.mintBatch(nfts); + const total = await editionContract.getTotalCount(); expect(total.toNumber()).to.eq(100); - const page1 = await bundleContract.getAll({ + const page1 = await editionContract.getAll({ count: 2, start: 0, }); expect(page1).to.be.an("array").length(2); - const page2 = await bundleContract.getAll({ + const page2 = await editionContract.getAll({ count: 2, start: 20, }); @@ -73,7 +73,7 @@ describe("Edition Contract", async () => { }); it("mint additional suply", async () => { - const tx = await bundleContract.mintToSelf({ + const tx = await editionContract.mintToSelf({ metadata: { name: "Bundle 1", description: "Bundle 1", @@ -81,10 +81,10 @@ describe("Edition Contract", async () => { }, supply: 10, }); - const nft = await bundleContract.get(tx.id); + const nft = await editionContract.get(tx.id); expect(nft.supply.toNumber()).to.eq(10); - await bundleContract.mintAdditionalSupply(tx.id, 10); - const nft2 = await bundleContract.get(tx.id); + await editionContract.mintAdditionalSupply(tx.id, 10); + const nft2 = await editionContract.get(tx.id); expect(nft2.supply.toNumber()).to.eq(20); }); @@ -92,11 +92,11 @@ describe("Edition Contract", async () => { const uri = await storage.uploadMetadata({ name: "Test1", }); - const tx = await bundleContract.mintToSelf({ + const tx = await editionContract.mintToSelf({ metadata: uri, supply: 10, }); - const nft = await bundleContract.get(tx.id); + const nft = await editionContract.get(tx.id); assert.isNotNull(nft); assert.equal(nft.metadata.name, "Test1"); }); @@ -105,19 +105,19 @@ describe("Edition Contract", async () => { const uri = await storage.uploadMetadata({ name: "Test1", }); - await bundleContract.mintBatch([ + await editionContract.mintBatch([ { metadata: uri, supply: 10, }, ]); - const nft = await bundleContract.get("0"); + const nft = await editionContract.get("0"); assert.isNotNull(nft); assert.equal(nft.metadata.name, "Test1"); }); it("should return all owned collection tokens", async () => { - await bundleContract.mintToSelf({ + await editionContract.mintToSelf({ metadata: { name: "Bundle 1", description: "Bundle 1", @@ -125,29 +125,29 @@ describe("Edition Contract", async () => { }, supply: 100, }); - const nfts = await bundleContract.getOwned(adminWallet.address); + const nfts = await editionContract.getOwned(adminWallet.address); expect(nfts).to.be.an("array").length(1); expect(nfts[0].metadata.image).to.be.equal("fake://myownfakeipfs"); expect(nfts[0].owner).to.be.equal(adminWallet.address); expect(nfts[0].quantityOwned.toNumber()).to.be.equal(100); expect(nfts[0].supply.toNumber()).to.be.equal(100); - const bobsNfts = await bundleContract.getOwned(bobWallet.address); + const bobsNfts = await editionContract.getOwned(bobWallet.address); expect(bobsNfts) .to.be.an("array") .length(0, "Bob should not have any nfts"); - await bundleContract.transfer(bobWallet.address, 0, 20); - const adminNft = await bundleContract.getOwned(adminWallet.address); + await editionContract.transfer(bobWallet.address, 0, 20); + const adminNft = await editionContract.getOwned(adminWallet.address); expect(adminNft[0].quantityOwned.toNumber()).to.be.equal(80); - const bobsNftsAfterTransfer = await bundleContract.getOwned( + const bobsNftsAfterTransfer = await editionContract.getOwned( bobWallet.address, ); expect(bobsNftsAfterTransfer[0].quantityOwned.toNumber()).to.be.equal(20); }); it("should airdrop edition tokens to different wallets", async () => { - await bundleContract.mintToSelf({ + await editionContract.mintToSelf({ metadata: { name: "Bundle 1", description: "Bundle 1", @@ -166,16 +166,16 @@ describe("Edition Contract", async () => { }, ]; - await bundleContract.airdrop(0, addresses); + await editionContract.airdrop(0, addresses); - const samOwned = await bundleContract.getOwned(samWallet.address); - const bobOwned = await bundleContract.getOwned(bobWallet.address); + const samOwned = await editionContract.getOwned(samWallet.address); + const bobOwned = await editionContract.getOwned(bobWallet.address); expect(samOwned[0].quantityOwned.toNumber()).to.be.equal(5); expect(bobOwned[0].quantityOwned.toNumber()).to.be.equal(3); }); it("should fail airdrop because not enough NFTs owned", async () => { - await bundleContract.mintToSelf({ + await editionContract.mintToSelf({ metadata: { name: "Bundle 1", description: "Bundle 1", @@ -195,7 +195,7 @@ describe("Edition Contract", async () => { ]; try { - await bundleContract.airdrop(0, addresses); + await editionContract.airdrop(0, addresses); } catch (e) { expectError(e, "The caller owns"); } @@ -203,17 +203,17 @@ describe("Edition Contract", async () => { // TODO: This test should move to the royalty suite it("updates the bps in both the metadata and on-chain", async () => { - const currentBps = (await bundleContract.royalties.getDefaultRoyaltyInfo()) + const currentBps = (await editionContract.royalties.getDefaultRoyaltyInfo()) .seller_fee_basis_points; assert.equal(currentBps, 1000); - const cMetadata = await bundleContract.metadata.get(); + const cMetadata = await editionContract.metadata.get(); assert.equal(cMetadata.seller_fee_basis_points, 1000); const testBPS = 100; - await bundleContract.royalties.setDefaultRoyaltyInfo({ + await editionContract.royalties.setDefaultRoyaltyInfo({ seller_fee_basis_points: testBPS, }); - const newMetadata = await bundleContract.metadata.get(); + const newMetadata = await editionContract.metadata.get(); assert.equal( newMetadata.seller_fee_basis_points, @@ -221,14 +221,14 @@ describe("Edition Contract", async () => { "Fetching the BPS from the metadata should return 100", ); assert.equal( - (await bundleContract.royalties.getDefaultRoyaltyInfo()) + (await editionContract.royalties.getDefaultRoyaltyInfo()) .seller_fee_basis_points, testBPS, "Fetching the BPS with the tx should return 100", ); }); it("should correctly upload nft metadata", async () => { - await bundleContract.mintBatch([ + await editionContract.mintBatch([ { metadata: { name: "Test0", @@ -244,7 +244,7 @@ describe("Edition Contract", async () => { supply: 5, }, ]); - const nfts = await bundleContract.getAll(); + const nfts = await editionContract.getAll(); expect(nfts).to.be.an("array").length(2); let i = 0; nfts.forEach((nft) => { diff --git a/test/events.test.ts b/test/events.test.ts index 4f1c01d10..0bea60cd9 100644 --- a/test/events.test.ts +++ b/test/events.test.ts @@ -1,14 +1,7 @@ -import { ethers, Wallet } from "ethers"; +import { ethers } from "ethers"; import { sdk, signers } from "./before-setup"; -import { EventType } from "../src/constants/events"; import { expect } from "chai"; -import { - ContractEvent, - NFTDrop, - ThirdwebSDK, - NFTCollection, - ChainId, -} from "../src"; +import { ContractEvent, NFTCollection, NFTDrop } from "../src"; import { AddressZero } from "@ethersproject/constants"; import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; @@ -17,16 +10,14 @@ global.fetch = require("cross-fetch"); describe("Events", async () => { let dropContract: NFTDrop; let nftContract: NFTCollection; - let adminWallet: SignerWithAddress, - samWallet: SignerWithAddress, - bobWallet: SignerWithAddress; + let adminWallet: SignerWithAddress, samWallet: SignerWithAddress; before(() => { - [adminWallet, samWallet, bobWallet] = signers; + [adminWallet, samWallet] = signers; }); beforeEach(async () => { - dropContract = sdk.getNFTDrop( + dropContract = await sdk.getNFTDrop( await sdk.deployer.deployBuiltInContract(NFTDrop.contractType, { name: `Testing drop from SDK`, description: "Test contract from tests", @@ -40,7 +31,7 @@ describe("Events", async () => { }), ); - nftContract = sdk.getNFTCollection( + nftContract = await sdk.getNFTCollection( await sdk.deployer.deployBuiltInContract(NFTCollection.contractType, { name: "NFT Contract", description: "Test NFT contract from tests", @@ -88,29 +79,6 @@ describe("Events", async () => { expect(events.map((e) => e.eventName)).to.include("TokensLazyMinted"); }); - // TODO - it.skip("should emit Signature events", async () => { - const RPC_URL = "https://rpc-mumbai.maticvigil.com/"; - const provider = ethers.getDefaultProvider(RPC_URL); - const wallet = Wallet.createRandom().connect(provider); - const esdk = ThirdwebSDK.fromSigner(wallet, ChainId.Hardhat, { - gasless: { - openzeppelin: { - relayerUrl: "https://google.com", // TODO test relayer url? - }, - }, - }); - sdk.on(EventType.Transaction, (event) => { - console.log(event); - }); - sdk.on(EventType.Signature, (event) => { - console.log(event); - }); - await esdk - .getNFTDrop(dropContract.getAddress()) - .setApprovalForAll(ethers.constants.AddressZero, true); - }); - it("should return single event", async () => { await nftContract.mintToSelf({ name: "Test1", diff --git a/test/gasless.test.ts b/test/gasless.test.ts deleted file mode 100644 index ad72a7630..000000000 --- a/test/gasless.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { ethers, Wallet } from "ethers"; -import { ChainId, EditionDrop, ThirdwebSDK } from "../src"; - -const RPC_URL = "https://rpc-mumbai.maticvigil.com/"; - -global.fetch = require("cross-fetch"); - -describe("Gasless Forwarder", async () => { - let bundleDropContract: EditionDrop; - - it.skip("should use sdk with biconomy", async () => { - const BUNDLE_DROP_ADDRESS = "0xEBed8e37a32660dbCeeeC19cCBb952b7d214f008"; - const provider = ethers.getDefaultProvider(RPC_URL); - const wallet = Wallet.createRandom().connect(provider); - const sdk = ThirdwebSDK.fromSigner(wallet, ChainId.Hardhat, { - gasless: { - biconomy: { - apiKey: process.env.BICONOMY_API_KEY as string, - apiId: process.env.BICONOMY_API_ID as string, - }, - }, - }); - const bundleDrop = sdk.getEditionDrop(BUNDLE_DROP_ADDRESS); - await bundleDrop.claim("0", 1, []); - }); - - it.skip("should use sdk with openzeppelin defender", async () => { - const BUNDLE_DROP_ADDRESS = "0x41c1f16fAd38381727b327b26F282C7798ee0655"; - const provider = ethers.getDefaultProvider(RPC_URL); - const wallet = Wallet.createRandom().connect(provider); - const sdk = new ThirdwebSDK(wallet, { - gasless: { - openzeppelin: { - relayerUrl: process.env.OZ_DEFENDER_RELAYER_URL as string, - }, - }, - }); - const bundleDrop = sdk.getBundleDropContract(BUNDLE_DROP_ADDRESS); - await bundleDrop.claim("0", 1, []); - }); -}); diff --git a/test/marketplace.test.ts b/test/marketplace.test.ts index 156dfc123..bffa434b8 100644 --- a/test/marketplace.test.ts +++ b/test/marketplace.test.ts @@ -33,7 +33,7 @@ let tokenAddress = NATIVE_TOKEN_ADDRESS; describe("Marketplace Contract", async () => { let marketplaceContract: Marketplace; let dummyNftContract: NFTCollection; - let dummyBundleContract: Edition; + let dummyEditionContract: Edition; let customTokenContract: Token; let adminWallet: SignerWithAddress, @@ -51,13 +51,13 @@ describe("Marketplace Contract", async () => { await sdk.wallet.connect(adminWallet); - marketplaceContract = sdk.getMarketplace( + marketplaceContract = await sdk.getMarketplace( await sdk.deployer.deployBuiltInContract(Marketplace.contractType, { name: "Test Marketplace", seller_fee_basis_points: 0, }), ); - dummyNftContract = sdk.getNFTCollection( + dummyNftContract = await sdk.getNFTCollection( await sdk.deployer.deployBuiltInContract(NFTCollection.contractType, { name: "TEST NFT", seller_fee_basis_points: 200, @@ -79,14 +79,14 @@ describe("Marketplace Contract", async () => { name: "Test 4", }, ]); - dummyBundleContract = sdk.getEdition( + dummyEditionContract = await sdk.getEdition( await sdk.deployer.deployBuiltInContract(Edition.contractType, { - name: "TEST BUNDLE", + name: "TEST EDITION", seller_fee_basis_points: 100, primary_sale_recipient: adminWallet.address, }), ); - await dummyBundleContract.mintBatch([ + await dummyEditionContract.mintBatch([ { metadata: { name: "Test 0", @@ -101,7 +101,7 @@ describe("Marketplace Contract", async () => { }, ]); - customTokenContract = sdk.getToken( + customTokenContract = await sdk.getToken( await sdk.deployer.deployBuiltInContract(Token.contractType, { name: "Test", symbol: "TEST", @@ -191,7 +191,7 @@ describe("Marketplace Contract", async () => { it("should list direct listings with 1155s", async () => { const listingId = await createDirectListing( - dummyBundleContract.getAddress(), + dummyEditionContract.getAddress(), 0, 10, ); @@ -217,10 +217,10 @@ describe("Marketplace Contract", async () => { it("should be able to restrict listing", async () => { await marketplaceContract.allowListingFromSpecificAssetOnly( - dummyBundleContract.getAddress(), + dummyEditionContract.getAddress(), ); const listingId = await createDirectListing( - dummyBundleContract.getAddress(), + dummyEditionContract.getAddress(), 0, 10, ); @@ -239,15 +239,15 @@ describe("Marketplace Contract", async () => { await createDirectListing(dummyNftContract.getAddress(), 0); await createAuctionListing(dummyNftContract.getAddress(), 1); - await createDirectListing(dummyBundleContract.getAddress(), 0, 10); - await createAuctionListing(dummyBundleContract.getAddress(), 0, 10); + await createDirectListing(dummyEditionContract.getAddress(), 0, 10); + await createAuctionListing(dummyEditionContract.getAddress(), 0, 10); - await dummyBundleContract.transfer(samWallet.address, "0", 10); - await dummyBundleContract.transfer(samWallet.address, "1", 10); + await dummyEditionContract.transfer(samWallet.address, "0", 10); + await dummyEditionContract.transfer(samWallet.address, "1", 10); await sdk.wallet.connect(samWallet); - await createDirectListing(dummyBundleContract.getAddress(), 0, 10); - await createAuctionListing(dummyBundleContract.getAddress(), 1, 10); + await createDirectListing(dummyEditionContract.getAddress(), 0, 10); + await createAuctionListing(dummyEditionContract.getAddress(), 1, 10); }); it("should paginate properly", async () => { @@ -267,7 +267,7 @@ describe("Marketplace Contract", async () => { it("should filter asset contract properly", async () => { const listings = await marketplaceContract.getAllListings({ - tokenContract: dummyBundleContract.getAddress(), + tokenContract: dummyEditionContract.getAddress(), }); assert.equal(listings.length, 4, "filter doesn't work"); }); @@ -712,7 +712,7 @@ describe("Marketplace Contract", async () => { it("should allow an auction buyout", async () => { const id = ( await marketplaceContract.auction.createListing({ - assetContractAddress: dummyBundleContract.getAddress(), + assetContractAddress: dummyEditionContract.getAddress(), buyoutPricePerToken: 0.8, currencyContractAddress: tokenAddress, // to start tomorrow so we can update it @@ -726,7 +726,7 @@ describe("Marketplace Contract", async () => { await sdk.wallet.connect(bobWallet); await marketplaceContract.buyoutListing(id); - const balance = await dummyBundleContract.balanceOf( + const balance = await dummyEditionContract.balanceOf( bobWallet.address, "1", ); diff --git a/test/multiwrap.test.ts b/test/multiwrap.test.ts index 993f8be8b..d9d6965c2 100644 --- a/test/multiwrap.test.ts +++ b/test/multiwrap.test.ts @@ -27,9 +27,9 @@ describe("Multiwrap Contract", async () => { image: "https://pbs.twimg.com/profile_images/1433508973215367176/XBCfBn3g_400x400.jpg", }); - multiwrapContract = sdk.getMultiwrap(address); + multiwrapContract = await sdk.getMultiwrap(address); - nftContract = sdk.getNFTCollection( + nftContract = await sdk.getNFTCollection( await sdk.deployer.deployBuiltInContract(NFTCollection.contractType, { name: "TEST NFT", seller_fee_basis_points: 200, @@ -55,7 +55,7 @@ describe("Multiwrap Contract", async () => { // TODO should this be done inside wrap() ? might result in a ton of different transactions :/ await nftContract.setApprovalForAll(multiwrapContract.getAddress(), true); - editionContract = sdk.getEdition( + editionContract = await sdk.getEdition( await sdk.deployer.deployBuiltInContract(Edition.contractType, { name: "TEST BUNDLE", seller_fee_basis_points: 100, @@ -82,7 +82,7 @@ describe("Multiwrap Contract", async () => { true, ); - tokenContract = sdk.getToken( + tokenContract = await sdk.getToken( await sdk.deployer.deployBuiltInContract(Token.contractType, { name: "Test", symbol: "TEST", @@ -106,7 +106,7 @@ describe("Multiwrap Contract", async () => { await tokenContract.setAllowance(multiwrapContract.getAddress(), 1000); - tokenContract2 = sdk.getToken( + tokenContract2 = await sdk.getToken( await sdk.deployer.deployBuiltInContract(Token.contractType, { name: "Test2", symbol: "TEST2", diff --git a/test/nft-drop.test.ts b/test/nft-drop.test.ts index 17bf50845..aaebdd10d 100644 --- a/test/nft-drop.test.ts +++ b/test/nft-drop.test.ts @@ -37,7 +37,7 @@ describe("NFT Drop Contract", async () => { platform_fee_basis_points: 10, platform_fee_recipient: AddressZero, }); - dropContract = sdk.getNFTDrop(address); + dropContract = await sdk.getNFTDrop(address); }); it("should lazy mint with URI", async () => { diff --git a/test/nft.test.ts b/test/nft.test.ts index 7cc795f65..345b2cc9a 100644 --- a/test/nft.test.ts +++ b/test/nft.test.ts @@ -9,12 +9,10 @@ global.fetch = require("cross-fetch"); describe("NFT Contract", async () => { type NewType = NFTCollection; let nftContract: NewType; - let adminWallet: SignerWithAddress, - samWallet: SignerWithAddress, - bobWallet: SignerWithAddress; + let adminWallet: SignerWithAddress, samWallet: SignerWithAddress; before(() => { - [adminWallet, samWallet, bobWallet] = signers; + [adminWallet, samWallet] = signers; }); beforeEach(async () => { @@ -33,7 +31,7 @@ describe("NFT Contract", async () => { platform_fee_recipient: AddressZero, }, ); - nftContract = sdk.getNFTCollection(address); + nftContract = await sdk.getNFTCollection(address); }); it("should return nfts even if some are burned", async () => { diff --git a/test/pack.test.ts b/test/pack.test.ts index f5b67a5c9..7f683129c 100644 --- a/test/pack.test.ts +++ b/test/pack.test.ts @@ -9,17 +9,15 @@ global.fetch = require("cross-fetch"); describe("Pack Contract", async () => { let packContract: Pack; - let bundleContract: Edition; + let editionContract: Edition; - let adminWallet: SignerWithAddress, - samWallet: SignerWithAddress, - bobWallet: SignerWithAddress; + let adminWallet: SignerWithAddress, samWallet: SignerWithAddress; before(() => { - [adminWallet, samWallet, bobWallet] = signers; + [adminWallet, samWallet] = signers; }); - const createBundles = async () => { + const mintEditions = async () => { const batch: EditionMetadataInput[] = []; for (let i = 0; i < 5; i++) { batch.push({ @@ -30,19 +28,19 @@ describe("Pack Contract", async () => { }); } - await bundleContract.mintBatch(batch); + await editionContract.mintBatch(batch); }; beforeEach(async () => { sdk.wallet.connect(adminWallet); - packContract = sdk.getPack( + packContract = await sdk.getPack( await sdk.deployer.deployBuiltInContract(Pack.contractType, { name: "Pack Contract", seller_fee_basis_points: 1000, }), ); - bundleContract = sdk.getEdition( + editionContract = await sdk.getEdition( await sdk.deployer.deployBuiltInContract(Edition.contractType, { name: "NFT Contract", seller_fee_basis_points: 1000, @@ -50,27 +48,27 @@ describe("Pack Contract", async () => { }), ); - await bundleContract.setApprovalForAll(packContract.getAddress(), true); - await createBundles(); + await editionContract.setApprovalForAll(packContract.getAddress(), true); + await mintEditions(); }); const createPacks = async () => { const packOne = await packContract.create({ erc1155Rewards: [ { - contractAddress: bundleContract.getAddress(), + contractAddress: editionContract.getAddress(), tokenId: "0", quantityPerReward: 1, totalRewards: 50, }, { - contractAddress: bundleContract.getAddress(), + contractAddress: editionContract.getAddress(), tokenId: "1", quantityPerReward: 1, totalRewards: 50, }, { - contractAddress: bundleContract.getAddress(), + contractAddress: editionContract.getAddress(), tokenId: "2", quantityPerReward: 1, totalRewards: 50, @@ -84,19 +82,19 @@ describe("Pack Contract", async () => { const packTwo = await packContract.create({ erc1155Rewards: [ { - contractAddress: bundleContract.getAddress(), + contractAddress: editionContract.getAddress(), tokenId: "0", quantityPerReward: 1, totalRewards: 50, }, { - contractAddress: bundleContract.getAddress(), + contractAddress: editionContract.getAddress(), tokenId: "1", quantityPerReward: 1, totalRewards: 50, }, { - contractAddress: bundleContract.getAddress(), + contractAddress: editionContract.getAddress(), tokenId: "2", quantityPerReward: 1, totalRewards: 50, diff --git a/test/recursive.test.ts b/test/recursive.test.ts index 0342a050f..b8ded176e 100644 --- a/test/recursive.test.ts +++ b/test/recursive.test.ts @@ -4,6 +4,8 @@ import { IpfsStorage, JsonObject } from "../src"; const ipfsGatewayUrl = "https://ipfs.thirdweb.com/ipfs/"; const storage = new IpfsStorage(ipfsGatewayUrl); +global.fetch = require("cross-fetch"); + describe("Recursive Testing", async () => { let json: JsonObject; beforeEach(async () => { diff --git a/test/registry.test.ts b/test/registry.test.ts index c2d811a5e..4d62be0e9 100644 --- a/test/registry.test.ts +++ b/test/registry.test.ts @@ -6,14 +6,12 @@ import { ContractRegistry } from "../src/core/classes/registry"; describe("Contract Registry", () => { let registry: ContractRegistry; - let adminWallet: SignerWithAddress, - samWallet: SignerWithAddress, - bobWallet: SignerWithAddress; + let adminWallet: SignerWithAddress; let address: string; before(async () => { - [adminWallet, samWallet, bobWallet] = signers; + [adminWallet] = signers; }); it("should allow adding and removing contracts", async () => { diff --git a/test/roles.test.ts b/test/roles.test.ts index e92ca0d6c..c91b5b2e1 100644 --- a/test/roles.test.ts +++ b/test/roles.test.ts @@ -8,7 +8,7 @@ import { AddressZero } from "@ethersproject/constants"; global.fetch = require("cross-fetch"); describe("Roles Contract", async () => { - let bundleContract: Edition; + let editionContract: Edition; let adminWallet: SignerWithAddress, samWallet: SignerWithAddress, @@ -21,7 +21,7 @@ describe("Roles Contract", async () => { beforeEach(async () => { sdk.wallet.connect(adminWallet); - bundleContract = sdk.getEdition( + editionContract = await sdk.getEdition( await sdk.deployer.deployBuiltInContract(Edition.contractType, { name: "NFT Contract", primary_sale_recipient: adminWallet.address, @@ -34,7 +34,7 @@ describe("Roles Contract", async () => { /** * This wallet owns only one token in the collection (that contains 6 tokens) */ - const roles = await bundleContract.roles.get("admin"); + const roles = await editionContract.roles.get("admin"); assert.include( roles, adminWallet.address, @@ -52,7 +52,7 @@ describe("Roles Contract", async () => { */ it("should override current roles in the contract", async () => { - await bundleContract.roles.setAll({ + await editionContract.roles.setAll({ admin: [adminWallet.address], minter: [ "0x553C5E856801b5876e80D32a192086b2035286C1", @@ -61,7 +61,7 @@ describe("Roles Contract", async () => { transfer: ["0x553C5E856801b5876e80D32a192086b2035286C1"], }); - const newRoles = await bundleContract.roles.getAll(); + const newRoles = await editionContract.roles.getAll(); assert.isTrue( newRoles.admin.length === 1 && newRoles.admin.includes(adminWallet.address), @@ -82,7 +82,7 @@ describe("Roles Contract", async () => { }); it("Replace all roles - confirm that all roles were replaced (not just added)", async () => { - await bundleContract.roles.setAll({ + await editionContract.roles.setAll({ admin: [ adminWallet.address, "0x553C5E856801b5876e80D32a192086b2035286C1", @@ -93,7 +93,7 @@ describe("Roles Contract", async () => { ], transfer: ["0xf16851cb58F3b3881e6bdAD21f57144E9aCf602E"], }); - const newRoles = await bundleContract.roles.getAll(); + const newRoles = await editionContract.roles.getAll(); assert.isTrue( newRoles.admin.length === 2 && newRoles.admin.includes(adminWallet.address) && @@ -115,39 +115,39 @@ describe("Roles Contract", async () => { }); it("Make collection non-transferable", async () => { - const oldRoles = await bundleContract.roles.getAll(); - await bundleContract.roles.setAll({ + const oldRoles = await editionContract.roles.getAll(); + await editionContract.roles.setAll({ admin: [...oldRoles.admin], minter: [...oldRoles.minter], transfer: [], }); - const newRoles = await bundleContract.roles.getAll(); + const newRoles = await editionContract.roles.getAll(); assert.isTrue(newRoles.admin.length === oldRoles.admin.length); assert.isTrue(newRoles.minter.length === oldRoles.minter.length); assert.isTrue(newRoles.transfer.length === 0); }); it("Make collection transferable", async () => { - const oldRoles = await bundleContract.roles.getAll(); - await bundleContract.roles.setAll({ + const oldRoles = await editionContract.roles.getAll(); + await editionContract.roles.setAll({ admin: [...oldRoles.admin], minter: [...oldRoles.minter], transfer: [AddressZero], }); - const newRoles = await bundleContract.roles.getAll(); + const newRoles = await editionContract.roles.getAll(); assert.isTrue(newRoles.admin.length === oldRoles.admin.length); assert.isTrue(newRoles.minter.length === oldRoles.minter.length); assert.isTrue(newRoles.transfer.includes(AddressZero)); }); it("Make collection non-transferable with some wallets being able to transfer", async () => { - const oldRoles = await bundleContract.roles.getAll(); - await bundleContract.roles.setAll({ + const oldRoles = await editionContract.roles.getAll(); + await editionContract.roles.setAll({ admin: [...oldRoles.admin], minter: [...oldRoles.minter], transfer: [bobWallet.address, samWallet.address], }); - const newRoles = await bundleContract.roles.getAll(); + const newRoles = await editionContract.roles.getAll(); assert.isTrue(newRoles.admin.length === oldRoles.admin.length); assert.isTrue(newRoles.minter.length === oldRoles.minter.length); assert.isTrue( diff --git a/test/royalty.test.ts b/test/royalty.test.ts index 2e6907679..3de34d591 100644 --- a/test/royalty.test.ts +++ b/test/royalty.test.ts @@ -2,25 +2,23 @@ import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; import { Edition } from "../src/index"; import { sdk, signers } from "./before-setup"; -import { assert, expect } from "chai"; +import { expect } from "chai"; global.fetch = require("cross-fetch"); describe("Royalties", async () => { - let bundleContract: Edition; + let editionContract: Edition; - let adminWallet: SignerWithAddress, - samWallet: SignerWithAddress, - bobWallet: SignerWithAddress; + let adminWallet: SignerWithAddress, samWallet: SignerWithAddress; before(() => { - [adminWallet, samWallet, bobWallet] = signers; + [adminWallet, samWallet] = signers; }); beforeEach(async () => { sdk.wallet.connect(adminWallet); - bundleContract = sdk.getEdition( + editionContract = await sdk.getEdition( await sdk.deployer.deployBuiltInContract(Edition.contractType, { name: "NFT Contract", primary_sale_recipient: adminWallet.address, @@ -29,7 +27,7 @@ describe("Royalties", async () => { }), ); - await bundleContract.mintToSelf({ + await editionContract.mintToSelf({ metadata: { name: "Cool NFT", }, @@ -38,33 +36,33 @@ describe("Royalties", async () => { }); it("should return default royalty", async () => { - const info = await bundleContract.royalties.getDefaultRoyaltyInfo(); + const info = await editionContract.royalties.getDefaultRoyaltyInfo(); expect(info.fee_recipient).to.eq(adminWallet.address); expect(info.seller_fee_basis_points).to.eq(1000); }); it("should set default royalty", async () => { - await bundleContract.royalties.setDefaultRoyaltyInfo({ + await editionContract.royalties.setDefaultRoyaltyInfo({ fee_recipient: samWallet.address, seller_fee_basis_points: 500, }); - const info = await bundleContract.royalties.getDefaultRoyaltyInfo(); + const info = await editionContract.royalties.getDefaultRoyaltyInfo(); expect(info.fee_recipient).to.eq(samWallet.address); expect(info.seller_fee_basis_points).to.eq(500); }); it("should return per token royalty", async () => { - const info = await bundleContract.royalties.getTokenRoyaltyInfo("0"); + const info = await editionContract.royalties.getTokenRoyaltyInfo("0"); expect(info.fee_recipient).to.eq(adminWallet.address); expect(info.seller_fee_basis_points).to.eq(1000); }); it("should set per token royalty", async () => { - await bundleContract.royalties.setTokenRoyaltyInfo("0", { + await editionContract.royalties.setTokenRoyaltyInfo("0", { fee_recipient: samWallet.address, seller_fee_basis_points: 500, }); - const info = await bundleContract.royalties.getTokenRoyaltyInfo("0"); + const info = await editionContract.royalties.getTokenRoyaltyInfo("0"); expect(info.fee_recipient).to.eq(samWallet.address); expect(info.seller_fee_basis_points).to.eq(500); }); diff --git a/test/sigdroptest.ts b/test/sigdroptest.ts index e6e33ffa4..06c3279b2 100644 --- a/test/sigdroptest.ts +++ b/test/sigdroptest.ts @@ -39,7 +39,7 @@ describe("Signature drop tests", async () => { beforeEach(async () => { sdk.wallet.connect(adminWallet); - signatureDropContract = sdk.getSignatureDrop( + signatureDropContract = await sdk.getSignatureDrop( await sdk.deployer.deployBuiltInContract(SignatureDrop.contractType, { name: "OUCH VOUCH", symbol: "VOUCH", @@ -58,7 +58,7 @@ describe("Signature drop tests", async () => { to: samWallet.address, }; - customTokenContract = sdk.getToken( + customTokenContract = await sdk.getToken( await sdk.deployer.deployBuiltInContract(Token.contractType, { name: "Test", symbol: "TEST", diff --git a/test/signature-mint-1155.test.ts b/test/signature-mint-1155.test.ts index 50fe0c1bd..298694d6d 100644 --- a/test/signature-mint-1155.test.ts +++ b/test/signature-mint-1155.test.ts @@ -1,6 +1,6 @@ import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; import { assert, expect } from "chai"; -import { BigNumber, ethers } from "ethers"; +import { BigNumber } from "ethers"; import { Edition, Token } from "../src"; import { sdk, signers, storage } from "./before-setup"; import { @@ -27,7 +27,7 @@ describe("Edition sig minting", async () => { beforeEach(async () => { sdk.wallet.connect(adminWallet); - editionContract = sdk.getEdition( + editionContract = await sdk.getEdition( await sdk.deployer.deployBuiltInContract(Edition.contractType, { name: "OUCH VOUCH", symbol: "VOUCH", @@ -46,7 +46,7 @@ describe("Edition sig minting", async () => { to: samWallet.address, }; - customTokenContract = sdk.getToken( + customTokenContract = await sdk.getToken( await sdk.deployer.deployBuiltInContract(Token.contractType, { name: "Test", symbol: "TEST", diff --git a/test/signature-mint-20.test.ts b/test/signature-mint-20.test.ts index ae59645bd..e7bd8c754 100644 --- a/test/signature-mint-20.test.ts +++ b/test/signature-mint-20.test.ts @@ -1,6 +1,6 @@ import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; import { assert, expect } from "chai"; -import { BigNumber, ethers } from "ethers"; +import { BigNumber } from "ethers"; import { PayloadToSign20, SignedPayload20, Token } from "../src"; import { sdk, signers } from "./before-setup"; import { NATIVE_TOKEN_ADDRESS } from "../src/constants/currency"; @@ -23,7 +23,7 @@ describe("Token sig minting", async () => { beforeEach(async () => { sdk.wallet.connect(adminWallet); - contract = sdk.getToken( + contract = await sdk.getToken( await sdk.deployer.deployToken({ name: "Token sigmint", symbol: "TSIG", @@ -39,7 +39,7 @@ describe("Token sig minting", async () => { primarySaleRecipient: adminWallet.address, }; - customTokenContract = sdk.getToken( + customTokenContract = await sdk.getToken( await sdk.deployer.deployToken({ name: "Test", symbol: "TEST", diff --git a/test/signature-mint-721.test.ts b/test/signature-mint-721.test.ts index bbaef6583..d564c14bd 100644 --- a/test/signature-mint-721.test.ts +++ b/test/signature-mint-721.test.ts @@ -1,6 +1,6 @@ import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; import { assert, expect } from "chai"; -import { BigNumber, ethers } from "ethers"; +import { BigNumber } from "ethers"; import { NFTCollection, Token } from "../src"; import { sdk, signers, storage } from "./before-setup"; import { @@ -27,7 +27,7 @@ describe("NFT sig minting", async () => { beforeEach(async () => { sdk.wallet.connect(adminWallet); - nftContract = sdk.getNFTCollection( + nftContract = await sdk.getNFTCollection( await sdk.deployer.deployBuiltInContract(NFTCollection.contractType, { name: "OUCH VOUCH", symbol: "VOUCH", @@ -47,7 +47,7 @@ describe("NFT sig minting", async () => { mintStartTime: new Date(), }; - customTokenContract = sdk.getToken( + customTokenContract = await sdk.getToken( await sdk.deployer.deployBuiltInContract(Token.contractType, { name: "Test", symbol: "TEST", diff --git a/test/split.test.ts b/test/split.test.ts index dd83a2172..173e12440 100644 --- a/test/split.test.ts +++ b/test/split.test.ts @@ -39,7 +39,7 @@ describe("Splits Contract", async () => { ], }, ); - splitsContract = sdk.getSplit(address); + splitsContract = await sdk.getSplit(address); }); it("should fetch contract balance", async () => { diff --git a/test/token-drop.test.ts b/test/token-drop.test.ts index 9a5c824bc..2cba19d09 100644 --- a/test/token-drop.test.ts +++ b/test/token-drop.test.ts @@ -39,7 +39,7 @@ describe("Token Drop Contract", async () => { platform_fee_recipient: AddressZero, }, ); - dropContract = sdk.getTokenDrop(address); + dropContract = await sdk.getTokenDrop(address); }); it("should allow a snapshot to be set", async () => { @@ -342,6 +342,7 @@ describe("Token Drop Contract", async () => { }, ]); const active = await dropContract.claimConditions.getActive(); + expect(active.maxQuantity).to.eq("10.8"); }); it("should check if its been long enough since the last claim", async () => { diff --git a/test/token.test.ts b/test/token.test.ts index f88b37eeb..cfc1622cd 100644 --- a/test/token.test.ts +++ b/test/token.test.ts @@ -31,7 +31,7 @@ describe("Token Contract", async () => { primary_sale_recipient: adminWallet.address, }, ); - currencyContract = sdk.getToken(address); + currencyContract = await sdk.getToken(address); }); it("should mint tokens", async () => { diff --git a/test/volume.test.ts b/test/volume.test.ts deleted file mode 100644 index f2a9a921c..000000000 --- a/test/volume.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; -import { - BundleDropContract, - NATIVE_TOKEN_ADDRESS, - ThirdwebSDK, -} from "../src/index"; -import { appContract, registryAddress, signers } from "./before-setup"; -import { ethers } from "hardhat"; -import { assert } from "chai"; - -global.fetch = require("cross-fetch"); - -describe("Bundle Contract (aka Collection Contract)", async () => { - let bundleDropContract: BundleDropContract; - - let adminWallet: SignerWithAddress; - let testSigners: SignerWithAddress[]; - - it.skip("should be able to claim using 15000 addresses", async () => { - [adminWallet] = signers; - testSigners = []; - console.time("wallet"); - for (let i = 0; i < 15000; i++) { - testSigners.push(new ethers.Wallet.createRandom()); - } - console.timeEnd("wallet"); - const token = await appContract.deployCurrencyContract({ - name: "Test Token", - symbol: "TST", - }); - - console.log("testSigners", testSigners.length); - const allowList = []; - testSigners.forEach((signer) => { - try { - allowList.push(signer.address); - } catch (e) { - console.log(signer); - } - }); - bundleDropContract = await appContract.deployBundleDropContract({ - name: "test", - description: "test", - primarySaleRecipientAddress: "0x0000000000000000000000000000000000000000", - }); - await bundleDropContract.lazyMintBatch([{ name: "test" }]); - - console.log("bundleDropContract", bundleDropContract.address); - - const factory = bundleDropContract.getClaimConditionFactory(); - const claimPhase = factory.newClaimPhase({ - startTime: new Date(), - maxQuantity: 30000, - maxQuantityPerTransaction: 1, - }); - claimPhase.setPrice(ethers.utils.parseEther("0.01"), NATIVE_TOKEN_ADDRESS); - await claimPhase.setSnapshot(allowList); - - await bundleDropContract.setClaimCondition("0", factory); - const sdk = new ThirdwebSDK(adminWallet, { - ipfsGatewayUrl: "https://ipfs.thirdweb.com/ipfs/", - registryContractAddress: registryAddress, - maxGasPriceInGwei: 10000, - }); - let error = false; - await sdk - .getBundleDropContract(bundleDropContract.address) - .claim(0, 1) - .catch((e) => { - error = true; - }); - assert.equal(error, true); - for (let i = 0; i < testSigners.length; i++) { - assert(adminWallet.address !== testSigners[i].address); - const signer = testSigners[i].connect(ethers.provider); - await adminWallet.sendTransaction({ - from: adminWallet.address, - to: signer.address, - value: ethers.utils.parseEther("0.02"), - }); - assert((await signer.getBalance()).gt(0)); - const testSdk = new ThirdwebSDK(signer, { - ipfsGatewayUrl: "https://ipfs.thirdweb.com/ipfs/", - registryContractAddress: registryAddress, - maxGasPriceInGwei: 10000, - }); - await testSdk - .getBundleDropContract(bundleDropContract.address) - .claim(0, 1); - console.log("claimed", i); - } - - console.log("claimed successfully for all"); - }); -}); diff --git a/test/vote.test.ts b/test/vote.test.ts index fa1b2f935..fc78eabda 100644 --- a/test/vote.test.ts +++ b/test/vote.test.ts @@ -1,9 +1,9 @@ -import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; -import { assert } from "chai"; -import { ethers } from "ethers"; -import { ethers as hardhatEthers } from "hardhat"; -import { sdk, signers } from "./before-setup"; -import { Token, Vote } from "../src"; +import {SignerWithAddress} from "@nomiclabs/hardhat-ethers/signers"; +import {assert} from "chai"; +import {ethers} from "ethers"; +import {ethers as hardhatEthers} from "hardhat"; +import {sdk, signers} from "./before-setup"; +import {Token, Vote} from "../src"; global.fetch = require("cross-fetch"); @@ -11,9 +11,6 @@ describe("Vote Contract", async () => { let voteContract: Vote; let currencyContract: Token; - const voteStartWaitTimeInSeconds = 0; - const voteWaitTimeInSeconds = 5; - let adminWallet: SignerWithAddress, samWallet: SignerWithAddress, bobWallet: SignerWithAddress; @@ -33,7 +30,7 @@ describe("Vote Contract", async () => { primary_sale_recipient: adminWallet.address, }, ); - currencyContract = sdk.getToken(tokenContractAddress); + currencyContract = await sdk.getToken(tokenContractAddress); const voteContractAddress = await sdk.deployer.deployBuiltInContract( Vote.contractType, { @@ -43,7 +40,7 @@ describe("Vote Contract", async () => { proposal_token_threshold: ethers.utils.parseUnits("1", 18), }, ); - voteContract = sdk.getVote(voteContractAddress); + voteContract = await .getVote(voteContractAddress); // step 1: mint 1000 governance tokens to my wallet await currencyContract.mintTo(samWallet.address, "100"); diff --git a/test/wallet.test.ts b/test/wallet.test.ts index 6725db8a8..f272b4d1d 100644 --- a/test/wallet.test.ts +++ b/test/wallet.test.ts @@ -29,7 +29,7 @@ describe("Wallet", async () => { name: "My Token", primary_sale_recipient: adminWallet.address, }); - await sdk.getToken(tokenAddr).mintToSelf(100); + await (await sdk.getToken(tokenAddr)).mintToSelf(100); const oldBalance = await sdk.wallet.balance(tokenAddr); expect(oldBalance.displayValue).to.eq("100.0"); From 798ddf60732380ca00d90e1aa8bf92a649adcdfd Mon Sep 17 00:00:00 2001 From: Joaquim Verges Date: Sun, 26 Jun 2022 22:47:58 -0700 Subject: [PATCH 5/5] fix vote test --- src/common/feature-detection.ts | 8 ++++++++ test/vote.test.ts | 28 +++++++--------------------- 2 files changed, 15 insertions(+), 21 deletions(-) diff --git a/src/common/feature-detection.ts b/src/common/feature-detection.ts index dae12e182..7ffa81795 100644 --- a/src/common/feature-detection.ts +++ b/src/common/feature-detection.ts @@ -314,6 +314,14 @@ export async function fetchSourceFilesFromMetadata( return await Promise.all( Object.entries(publishedMetadata.metadata.sources).map( async ([path, info]) => { + // standard metadata can contain either the full source inline + if ((info as any).content) { + return { + filename: path, + source: (info as any).content, + }; + } + // or a URL to it const urls = (info as any).urls as string[]; const ipfsLink = urls.find((url) => url.includes("ipfs")); if (ipfsLink) { diff --git a/test/vote.test.ts b/test/vote.test.ts index fc78eabda..85970b08f 100644 --- a/test/vote.test.ts +++ b/test/vote.test.ts @@ -1,9 +1,9 @@ -import {SignerWithAddress} from "@nomiclabs/hardhat-ethers/signers"; -import {assert} from "chai"; -import {ethers} from "ethers"; -import {ethers as hardhatEthers} from "hardhat"; -import {sdk, signers} from "./before-setup"; -import {Token, Vote} from "../src"; +import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; +import { assert } from "chai"; +import { ethers } from "ethers"; +import { ethers as hardhatEthers } from "hardhat"; +import { sdk, signers } from "./before-setup"; +import { Token, Vote } from "../src"; global.fetch = require("cross-fetch"); @@ -40,7 +40,7 @@ describe("Vote Contract", async () => { proposal_token_threshold: ethers.utils.parseUnits("1", 18), }, ); - voteContract = await .getVote(voteContractAddress); + voteContract = await sdk.getVote(voteContractAddress); // step 1: mint 1000 governance tokens to my wallet await currencyContract.mintTo(samWallet.address, "100"); @@ -108,20 +108,6 @@ describe("Vote Contract", async () => { await voteContract.execute(proposalId.toString()); }); - it.skip("", async () => { - const blockTimes = []; - const provider = ethers.getDefaultProvider(); - - const latest = await provider.getBlock("latest"); - for (let i = 0; i <= 10; i++) { - const current = await provider.getBlock(latest.number - i); - const previous = await provider.getBlock(latest.number - i - 1); - const diff = current.timestamp - previous.timestamp; - blockTimes.push(diff); - } - - const sum = blockTimes.reduce((result, a) => result + a, 0); - }); it("should permit a proposal to be passed if it receives the right votes", async () => { await sdk.wallet.connect(samWallet);