Compare commits

..
Author SHA1 Message Date
github-actions[bot]GitHubgithub-actions[bot] <github-actions[bot]@users.noreply.github.com>
603e24f1e2 Version Packages (#873)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2023-04-06 17:18:37 -07:00
YashandGitHub c9027fced0 [SDK] transaction count for any-evm deploy (#878) 2023-04-07 00:01:26 +00:00
Joaquim VergesandGitHub ac8fa0b345 [SDK] Fix resolving proxy implementation addreses with leading 0s (#882) 2023-04-06 23:26:13 +00:00
iketwandGitHub 81a32b4dd2 [React] change major change to patch (#881) 2023-04-06 20:40:03 +00:00
ciaranightingaleandGitHub bd0bb4fed7 fix portal links in README (#880) 2023-04-06 17:35:45 +00:00
iketwandGitHub b616dca7eb [Wallets] Rename base wallets (#868) 2023-04-06 17:12:13 +00:00
59434aac4f [react] add style prop on ConnectWallet and Web3Button (#879)
Co-authored-by: Nacho Iacovino <[email protected]>
2023-04-06 16:47:07 +00:00
iketwandGitHub cef16471f4 [CLI] Update min ruby version to 2.7.6 for React Native templates (#877) 2023-04-06 15:19:08 +00:00
Nacho IacovinoandGitHub 0db0cc7564 [React] Fix useContractEvents cache not storing individual events (#876) 2023-04-06 14:09:43 +00:00
229a47413e Fix build error in vite when connecting safe (#859)
Co-authored-by: Jonas Daniels <[email protected]>
2023-04-05 22:05:47 +00:00
b75bcef55b [SDK] any evm deploy setup (#756)
Co-authored-by: Jonas Daniels <[email protected]>
Co-authored-by: Joaquim Verges <[email protected]>
2023-04-05 21:38:00 +00:00
Nacho IacovinoandGitHub 2545a440dc Rename Wallet Connect to WalletConnect (#872) 2023-04-05 19:41:58 +00:00
58 changed files with 1612 additions and 2464 deletions
+7
View File
@@ -1,5 +1,12 @@
# @thirdweb-dev/auth
## 3.0.14
### Patch Changes
- Updated dependencies [[`b616dca7`](https://github.com/thirdweb-dev/js/commit/b616dca7eb861cd1d2adba3f3d1fe9c3b50f259e), [`2545a440`](https://github.com/thirdweb-dev/js/commit/2545a440dc272690cacbc23023f7b0a68f390c6e), [`229a4741`](https://github.com/thirdweb-dev/js/commit/229a47413e422952ad946b8c09af32cc1fcdc7f0)]:
- @thirdweb-dev/wallets@0.2.15
## 3.0.13
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@thirdweb-dev/auth",
"version": "3.0.13",
"version": "3.0.14",
"main": "dist/thirdweb-dev-auth.cjs.js",
"module": "dist/thirdweb-dev-auth.esm.js",
"browser": {
+9
View File
@@ -1,5 +1,14 @@
# thirdweb
## 0.10.11
### Patch Changes
- [#877](https://github.com/thirdweb-dev/js/pull/877) [`cef16471`](https://github.com/thirdweb-dev/js/commit/cef16471f4493d7c2c1897a81ffebf84a743716e) Thanks [@iketw](https://github.com/iketw)! - [CLI] Update min ruby version supported to 2.7.6 for React Native templates
- Updated dependencies [[`ac8fa0b3`](https://github.com/thirdweb-dev/js/commit/ac8fa0b34545a2bc0b489a0551d476a9f560e851), [`b75bcef5`](https://github.com/thirdweb-dev/js/commit/b75bcef55bfdedc260b5b62bb4aff10a7d5c47b6), [`c9027fce`](https://github.com/thirdweb-dev/js/commit/c9027fced0fffbf757bf0080bc4a49f5464df647)]:
- @thirdweb-dev/sdk@3.10.10
## 0.10.10
### Patch Changes
+1 -1
View File
@@ -63,7 +63,7 @@ Deploying published contracts give deployers access to automatic SDKs to integra
npx thirdweb@latest detect
```
As you're developing your contracts, you may want to implement [Extensions](https://portal.thirdweb.com/contractkit) to unlock functionality on the SDKs (ie. nft minting with automatic upload to IPFS) and the dashboard (ie. generated UI to manage permissions). This command will show what extensions were detected on your contract, unlocking the corresponding functionality on the SDKs and dashboard.
As you're developing your contracts, you may want to implement [Extensions](https://portal.thirdweb.com/solidity/extensions) to unlock functionality on the SDKs (ie. nft minting with automatic upload to IPFS) and the dashboard (ie. generated UI to manage permissions). This command will show what extensions were detected on your contract, unlocking the corresponding functionality on the SDKs and dashboard.
---
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "thirdweb",
"main": "dist/cli/index.js",
"version": "0.10.10",
"version": "0.10.11",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/cli",
"author": "thirdweb eng <[email protected]>",
"license": "Apache-2.0",
@@ -2,7 +2,7 @@
import { runCommand } from "./run-command";
import chalk from "chalk";
export const SUPPORTED_RUBY_VERSION = "2.7.5";
export const SUPPORTED_RUBY_VERSION = "2.7.6";
/**
* Checks if the current ruby version is supported by the project.
@@ -1,51 +0,0 @@
/* eslint-disable import/no-extraneous-dependencies */
import { runCommand } from "./run-command";
import fs from "fs";
import path from "path";
/**
* Checks if the current ruby version is supported by the project.
*
* @returns A Promise that resolves once the ruby version is checked. True if it changed, false otherwise.
*/
export function setRubyVersion(root: string): Promise<boolean> {
/**
* Return a Promise that resolves once the installation is finished.
*/
return new Promise(async (resolve, reject) => {
try {
await runCommand("ruby", ["-v"], false, (dataBfr) => {
const data = String(dataBfr);
const systemVersion = data.split(" ")[1];
let rubyVersionFile = path.join(root, ".ruby-version");
let rubyProjectVersionString = "";
try {
rubyProjectVersionString = String(fs.readFileSync(rubyVersionFile));
} catch (error) {
rubyVersionFile = path.join(root, "_ruby-version");
rubyProjectVersionString = String(fs.readFileSync(rubyVersionFile));
}
try {
if (systemVersion.includes(rubyProjectVersionString)) {
// same version, no need to update
resolve(false);
} else {
const systemVersionWithoutPatch = systemVersion.split("p")[0];
fs.writeFileSync(rubyVersionFile, systemVersionWithoutPatch);
resolve(true);
}
} catch (e) {
console.log(
"Failed to update ruby version. Please, set your ruby version to a minimum of 2.6 and try again.",
);
console.log();
}
});
} catch (error) {
reject(error);
}
});
}
+6
View File
@@ -1,5 +1,11 @@
# @thirdweb-dev/contracts-js
## 1.3.3
### Patch Changes
- [#756](https://github.com/thirdweb-dev/js/pull/756) [`b75bcef5`](https://github.com/thirdweb-dev/js/commit/b75bcef55bfdedc260b5b62bb4aff10a7d5c47b6) Thanks [@kumaryash90](https://github.com/kumaryash90)! - Any EVM deploy flow with Create2 factory
## 1.3.2
### Patch Changes
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@thirdweb-dev/contracts-js",
"version": "1.3.2",
"version": "1.3.3",
"main": "dist/thirdweb-dev-contracts-js.cjs.js",
"module": "dist/thirdweb-dev-contracts-js.esm.js",
"browser": {
@@ -10,7 +10,7 @@
"license": "Apache-2.0",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/contracts-js",
"dependencies": {
"@thirdweb-dev/contracts": "3.4.4"
"@thirdweb-dev/contracts": "3.4.6-1"
},
"devDependencies": {
"@babel/preset-env": "^7.18.10",
+10
View File
@@ -1,5 +1,15 @@
# @thirdweb-dev/react-core
## 3.11.7
### Patch Changes
- [#876](https://github.com/thirdweb-dev/js/pull/876) [`0db0cc75`](https://github.com/thirdweb-dev/js/commit/0db0cc756436dba8f9df0cf8678b87c009acc283) Thanks [@nachoiacovino](https://github.com/nachoiacovino)! - Fix useContractEvents cache not storing individual events
- Updated dependencies [[`ac8fa0b3`](https://github.com/thirdweb-dev/js/commit/ac8fa0b34545a2bc0b489a0551d476a9f560e851), [`b616dca7`](https://github.com/thirdweb-dev/js/commit/b616dca7eb861cd1d2adba3f3d1fe9c3b50f259e), [`2545a440`](https://github.com/thirdweb-dev/js/commit/2545a440dc272690cacbc23023f7b0a68f390c6e), [`b75bcef5`](https://github.com/thirdweb-dev/js/commit/b75bcef55bfdedc260b5b62bb4aff10a7d5c47b6), [`229a4741`](https://github.com/thirdweb-dev/js/commit/229a47413e422952ad946b8c09af32cc1fcdc7f0), [`c9027fce`](https://github.com/thirdweb-dev/js/commit/c9027fced0fffbf757bf0080bc4a49f5464df647)]:
- @thirdweb-dev/sdk@3.10.10
- @thirdweb-dev/wallets@0.2.15
## 3.11.6
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@thirdweb-dev/react-core",
"version": "3.11.6",
"version": "3.11.7",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react-core",
"author": "thirdweb eng <[email protected]>",
"license": "Apache-2.0",
+4 -4
View File
@@ -1,5 +1,5 @@
import type {
AbstractBrowserWallet,
AbstractClientWallet,
Chain,
DAppMetaData,
} from "@thirdweb-dev/wallets";
@@ -15,16 +15,16 @@ export type WalletOptions = {
dappMetadata?: DAppMetaData;
} & ExtraCoreWalletOptions;
export type WalletInstance = InstanceType<typeof AbstractBrowserWallet>;
export type WalletInstance = InstanceType<typeof AbstractClientWallet>;
export type WalletClass<I extends WalletInstance = WalletInstance> = {
id: string;
new (options: WalletOptions): I;
meta: (typeof AbstractBrowserWallet)["meta"];
meta: (typeof AbstractClientWallet)["meta"];
};
export type Wallet<I extends WalletInstance = WalletInstance> = {
id: string;
meta: (typeof AbstractBrowserWallet)["meta"];
meta: (typeof AbstractClientWallet)["meta"];
create: (options: WalletOptions) => I;
};
@@ -427,11 +427,11 @@ export function useContractEvents(
() =>
createCacheKeyWithNetwork(
eventName
? cacheKeys.contract.events.getAllEvents(contractAddress)
: cacheKeys.contract.events.getEvents(
? cacheKeys.contract.events.getEvents(
contractAddress,
eventName as string,
),
)
: cacheKeys.contract.events.getAllEvents(contractAddress),
activeChainId,
),
[activeChainId, contractAddress, eventName],
@@ -1,5 +1,7 @@
# @thirdweb-dev/react-native-compat
## 0.2.7
## 0.2.6
## 0.2.5
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@thirdweb-dev/react-native-compat",
"description": "Shims for Thirdweb in React Native Projects",
"version": "0.2.6",
"version": "0.2.7",
"author": "thirdweb eng <[email protected]>",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react-native-compat",
"license": "Apache-2.0",
+9
View File
@@ -1,5 +1,14 @@
# @thirdweb-dev/react-native
## 0.2.7
### Patch Changes
- Updated dependencies [[`ac8fa0b3`](https://github.com/thirdweb-dev/js/commit/ac8fa0b34545a2bc0b489a0551d476a9f560e851), [`b616dca7`](https://github.com/thirdweb-dev/js/commit/b616dca7eb861cd1d2adba3f3d1fe9c3b50f259e), [`2545a440`](https://github.com/thirdweb-dev/js/commit/2545a440dc272690cacbc23023f7b0a68f390c6e), [`b75bcef5`](https://github.com/thirdweb-dev/js/commit/b75bcef55bfdedc260b5b62bb4aff10a7d5c47b6), [`229a4741`](https://github.com/thirdweb-dev/js/commit/229a47413e422952ad946b8c09af32cc1fcdc7f0), [`c9027fce`](https://github.com/thirdweb-dev/js/commit/c9027fced0fffbf757bf0080bc4a49f5464df647), [`0db0cc75`](https://github.com/thirdweb-dev/js/commit/0db0cc756436dba8f9df0cf8678b87c009acc283)]:
- @thirdweb-dev/sdk@3.10.10
- @thirdweb-dev/wallets@0.2.15
- @thirdweb-dev/react-core@3.11.7
## 0.2.6
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@thirdweb-dev/react-native",
"version": "0.2.6",
"version": "0.2.7",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react-native",
"author": "thirdweb eng <[email protected]>",
"license": "Apache-2.0",
@@ -4,7 +4,7 @@ import type {
CoinbaseWalletConnectorOptions,
} from "../connectors/coinbase-wallet";
import {
AbstractBrowserWallet,
AbstractClientWallet,
TWConnector,
WagmiAdapter,
WalletOptions,
@@ -16,7 +16,7 @@ import {
type CoinbaseWalletOptions = Omit<WalletOptions<CoinbaseWalletConnectorOptions>,"walletStorage">;
export class CoinbaseWallet extends AbstractBrowserWallet<CoinbaseWalletConnectorOptions> {
export class CoinbaseWallet extends AbstractClientWallet<CoinbaseWalletConnectorOptions> {
static meta = {
id: "coinbase",
name: "Coinbase Wallet",
+13
View File
@@ -1,5 +1,18 @@
# @thirdweb-dev/react
## 3.11.7
### Patch Changes
- [#859](https://github.com/thirdweb-dev/js/pull/859) [`229a4741`](https://github.com/thirdweb-dev/js/commit/229a47413e422952ad946b8c09af32cc1fcdc7f0) Thanks [@MananTank](https://github.com/MananTank)! - Fix Error when connecting to Safe in Vite
- [#879](https://github.com/thirdweb-dev/js/pull/879) [`59434aac`](https://github.com/thirdweb-dev/js/commit/59434aac4f1ca6d16a212c5379cf29fd346baf26) Thanks [@MananTank](https://github.com/MananTank)! - [react] add style prop on ConnectWallet and Web3Button
- Updated dependencies [[`ac8fa0b3`](https://github.com/thirdweb-dev/js/commit/ac8fa0b34545a2bc0b489a0551d476a9f560e851), [`b616dca7`](https://github.com/thirdweb-dev/js/commit/b616dca7eb861cd1d2adba3f3d1fe9c3b50f259e), [`2545a440`](https://github.com/thirdweb-dev/js/commit/2545a440dc272690cacbc23023f7b0a68f390c6e), [`b75bcef5`](https://github.com/thirdweb-dev/js/commit/b75bcef55bfdedc260b5b62bb4aff10a7d5c47b6), [`229a4741`](https://github.com/thirdweb-dev/js/commit/229a47413e422952ad946b8c09af32cc1fcdc7f0), [`c9027fce`](https://github.com/thirdweb-dev/js/commit/c9027fced0fffbf757bf0080bc4a49f5464df647), [`0db0cc75`](https://github.com/thirdweb-dev/js/commit/0db0cc756436dba8f9df0cf8678b87c009acc283)]:
- @thirdweb-dev/sdk@3.10.10
- @thirdweb-dev/wallets@0.2.15
- @thirdweb-dev/react-core@3.11.7
## 3.11.6
### Patch Changes
+2 -2
View File
@@ -143,7 +143,7 @@ Each [extension](https://portal.thirdweb.com/extensions) you implement in your s
These hooks make it easy to interact with your smart contracts by implementing the complex logic for you under the hood.
For example, if your smart contract implements [ERC721Supply](https://portal.thirdweb.com/contractkit/interfaces/erc721supply#unlocked-features), you unlock the ability to [view all NFTs](https://portal.thirdweb.com/sdk/interacting-with-contracts/erc721supply#get-all-minted-nfts) on that contract using the SDK; which fetches all of your NFT metadata and the current owner of each NFT in parallel. In the React SDK, that is available using `useNFTs`:
For example, if your smart contract implements [ERC721Supply](https://portal.thirdweb.com/solidity/extensions/erc721supply), you unlock the ability to [view all NFTs](https://portal.thirdweb.com/sdk/interacting-with-contracts/erc721supply#get-all-minted-nfts) on that contract using the SDK; which fetches all of your NFT metadata and the current owner of each NFT in parallel. In the React SDK, that is available using `useNFTs`:
```jsx
import { useContract, useNFTs } from "@thirdweb-dev/react";
@@ -154,7 +154,7 @@ export default function Home() {
}
```
If we want to mint an NFT and our contract implements [ERC721Mintable](https://portal.thirdweb.com/contractkit/interfaces/erc721mintable#unlocked-features), we can use the [`useMintNFT`](https://portal.thirdweb.com/sdk/interacting-with-contracts/erc721mintable) hook to mint an NFT from the connected wallet; handling all of the logic of uploading and pinning the metadata to IPFS for us behind the scenes.
If we want to mint an NFT and our contract implements [ERC721Mintable](https://portal.thirdweb.com/solidity/extensions/erc721mintable), we can use the [`useMintNFT`](https://portal.thirdweb.com/sdk/interacting-with-contracts/erc721mintable) hook to mint an NFT from the connected wallet; handling all of the logic of uploading and pinning the metadata to IPFS for us behind the scenes.
```jsx
import { useContract, useNFTs, useMintNFT } from "@thirdweb-dev/react";
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@thirdweb-dev/react",
"version": "3.11.6",
"version": "3.11.7",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react",
"author": "thirdweb eng <[email protected]>",
"license": "Apache-2.0",
@@ -42,6 +42,7 @@ interface Web3ButtonProps<TActionFn extends ActionFn> {
action: TActionFn;
type?: "button" | "submit" | "reset";
theme?: "dark" | "light";
style?: React.CSSProperties;
}
/**
@@ -77,6 +78,7 @@ export const Web3Button = <TAction extends ActionFn>({
className,
type,
theme,
style,
}: PropsWithChildren<Web3ButtonProps<TAction>>) => {
const address = useAddress();
const sdkChainId = useSDKChainId();
@@ -125,6 +127,7 @@ export const Web3Button = <TAction extends ActionFn>({
if (!address) {
return (
<ConnectWallet
style={style}
theme={theme}
className={`${className || ""} ${TW_WEB3BUTTON}--connect-wallet`}
/>
@@ -161,7 +164,7 @@ export const Web3Button = <TAction extends ActionFn>({
type={type}
className={`${className || ""} ${TW_WEB3BUTTON}--switch-network`}
onClick={handleSwitchChain}
style={btnStyle}
style={{ ...btnStyle, ...style }}
data-is-loading={confirmStatus === "waiting"}
data-theme={theme}
>
@@ -206,7 +209,7 @@ export const Web3Button = <TAction extends ActionFn>({
type={type}
className={`${className || ""} ${TW_WEB3BUTTON}`}
disabled
style={btnStyle}
style={{ ...btnStyle, ...style }}
data-is-loading
data-theme={theme}
>
@@ -224,7 +227,7 @@ export const Web3Button = <TAction extends ActionFn>({
className={`${className || ""} ${TW_WEB3BUTTON}`}
onClick={() => actionMutation.mutate()}
disabled={isDisabled}
style={btnStyle}
style={{ ...btnStyle, ...style }}
data-is-loading="false"
data-theme={theme}
>
@@ -36,6 +36,7 @@ type ConnectWalletProps = {
loginOptions?: LoginOptions;
loginOptional?: boolean;
};
style?: React.CSSProperties;
};
const TW_CONNECT_WALLET = "tw-connect-wallet";
@@ -105,6 +106,7 @@ export const ConnectWallet: React.FC<ConnectWalletProps> = (props) => {
onClick={signIn}
data-theme={theme}
className={`${TW_CONNECT_WALLET}--sign-in`}
style={props.style}
>
<Flex
alignItems="center"
@@ -134,6 +136,7 @@ export const ConnectWallet: React.FC<ConnectWalletProps> = (props) => {
type="button"
style={{
minWidth: "140px",
...props.style,
}}
aria-label={
connectionStatus === "connecting" ? "Connecting" : btnTitle
@@ -149,6 +152,7 @@ export const ConnectWallet: React.FC<ConnectWalletProps> = (props) => {
<ConnectedWalletDetails
dropdownPosition={props.dropdownPosition}
theme={theme}
style={props.style}
onDisconnect={() => {
if (authConfig?.authUrl) {
logout();
@@ -50,6 +50,7 @@ export const ConnectedWalletDetails: React.FC<{
dropdownPosition?: DropDownPosition;
onDisconnect: () => void;
theme: "dark" | "light";
style?: React.CSSProperties;
}> = (props) => {
const disconnect = useDisconnect();
const chains = useSupportedChains();
@@ -108,6 +109,7 @@ export const ConnectedWalletDetails: React.FC<{
type="button"
className={TW_CONNECTED_WALLET}
data-theme={props.theme}
style={props.style}
>
<ChainIcon
chain={chain}
+13
View File
@@ -1,5 +1,18 @@
# @thirdweb-dev/sdk
## 3.10.10
### Patch Changes
- [#882](https://github.com/thirdweb-dev/js/pull/882) [`ac8fa0b3`](https://github.com/thirdweb-dev/js/commit/ac8fa0b34545a2bc0b489a0551d476a9f560e851) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - Fix resolving proxy implementation addreses with leading 0s
- [#756](https://github.com/thirdweb-dev/js/pull/756) [`b75bcef5`](https://github.com/thirdweb-dev/js/commit/b75bcef55bfdedc260b5b62bb4aff10a7d5c47b6) Thanks [@kumaryash90](https://github.com/kumaryash90)! - Any EVM deploy flow with Create2 factory
- [#878](https://github.com/thirdweb-dev/js/pull/878) [`c9027fce`](https://github.com/thirdweb-dev/js/commit/c9027fced0fffbf757bf0080bc4a49f5464df647) Thanks [@kumaryash90](https://github.com/kumaryash90)! - Util function for any-evm deployment status
- Updated dependencies [[`b75bcef5`](https://github.com/thirdweb-dev/js/commit/b75bcef55bfdedc260b5b62bb4aff10a7d5c47b6)]:
- @thirdweb-dev/contracts-js@1.3.3
## 3.10.9
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@thirdweb-dev/sdk",
"version": "3.10.9",
"version": "3.10.10",
"description": "The main thirdweb SDK.",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/sdk",
"license": "Apache-2.0",
File diff suppressed because one or more lines are too long
@@ -0,0 +1,771 @@
import invariant from "tiny-invariant";
import { BigNumber, BytesLike, ethers, providers, Signer } from "ethers";
import { bytecode as WETHBytecode } from "./WETH9";
import {
DeploymentInfo,
KeylessDeploymentInfo,
KeylessTransaction,
} from "../types/any-evm/deploy-data";
import {
CloneFactory,
EOAForwarder,
Forwarder,
INFRA_CONTRACTS_MAP,
NativeTokenWrapper,
} from "./infra-data";
import { ThirdwebSDK } from "../core/sdk";
import { InfraContractType } from "../core";
import {
extractConstructorParamsFromAbi,
fetchPreDeployMetadata,
} from "./feature-detection";
import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { getNativeTokenByChainId } from "../constants";
import { PreDeployMetadataFetched } from "../schema";
import { toWei } from "./currency";
import { DeployOptions } from "../types";
//
// =============================
// ======== CONSTANTS ==========
// =============================
//
const THIRDWEB_DEPLOYER = "0xdd99b75f095d0c4d5112aCe938e4e6ed962fb024";
export const CREATE2_FACTORY_BYTECODE =
"0x604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3";
export const SIGNATURE = {
v: 27,
r: "0x2222222222222222222222222222222222222222222222222222222222222222",
s: "0x2222222222222222222222222222222222222222222222222222222222222222",
};
export const COMMON_FACTORY = "0x4e59b44847b379578588920cA78FbF26c0B4956C"; // for pre-eip-155 supporting chains
export const DEPLOYER_BYTECODE =
"0x60806040526040516107f33803806107f383398101604081905261002291610359565b805160005b818110156100c157828181518110610041576100416104c9565b6020026020010151600001516001600160a01b03163b600014156100af576100ad838281518110610074576100746104c9565b602002602001015160200151848381518110610092576100926104c9565b6020026020010151604001516100c960201b6100091760201c565b505b806100b9816104df565b915050610027565b505050610557565b606061011183836040518060400160405280601e81526020017f416464726573733a206c6f772d6c6576656c2063616c6c206661696c6564000081525061011860201b60201c565b9392505050565b6060610127848460008561012f565b949350505050565b6060824710156101955760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b60648201526084015b60405180910390fd5b6001600160a01b0385163b6101ec5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640161018c565b600080866001600160a01b031685876040516102089190610508565b60006040518083038185875af1925050503d8060008114610245576040519150601f19603f3d011682016040523d82523d6000602084013e61024a565b606091505b50909250905061025b828286610266565b979650505050505050565b60608315610275575081610111565b8251156102855782518084602001fd5b8160405162461bcd60e51b815260040161018c9190610524565b634e487b7160e01b600052604160045260246000fd5b604051606081016001600160401b03811182821017156102d7576102d761029f565b60405290565b604051601f8201601f191681016001600160401b03811182821017156103055761030561029f565b604052919050565b80516001600160a01b038116811461032457600080fd5b919050565b60005b8381101561034457818101518382015260200161032c565b83811115610353576000848401525b50505050565b6000602080838503121561036c57600080fd5b82516001600160401b038082111561038357600080fd5b818501915085601f83011261039757600080fd5b8151818111156103a9576103a961029f565b8060051b6103b88582016102dd565b91825283810185019185810190898411156103d257600080fd5b86860192505b838310156104bc578251858111156103f05760008081fd5b86016060601f19828d0381018213156104095760008081fd5b6104116102b5565b61041c8b850161030d565b8152604061042b81860161030d565b828d01529284015192898411156104425760008081fd5b83850194508e603f86011261045957600093508384fd5b8b85015193508984111561046f5761046f61029f565b61047f8c84601f870116016102dd565b92508383528e818587010111156104965760008081fd5b6104a5848d8501838801610329565b8101919091528452505091860191908601906103d8565b9998505050505050505050565b634e487b7160e01b600052603260045260246000fd5b600060001982141561050157634e487b7160e01b600052601160045260246000fd5b5060010190565b6000825161051a818460208701610329565b9190910192915050565b6020815260008251806020840152610543816040850160208701610329565b601f01601f19169190910160400192915050565b61028d806105666000396000f3fe6080604052600080fd5b606061004b83836040518060400160405280601e81526020017f416464726573733a206c6f772d6c6576656c2063616c6c206661696c65640000815250610052565b9392505050565b60606100618484600085610069565b949350505050565b6060824710156100cf5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b60648201526084015b60405180910390fd5b6001600160a01b0385163b6101265760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016100c6565b600080866001600160a01b031685876040516101429190610208565b60006040518083038185875af1925050503d806000811461017f576040519150601f19603f3d011682016040523d82523d6000602084013e610184565b606091505b509150915061019482828661019f565b979650505050505050565b606083156101ae57508161004b565b8251156101be5782518084602001fd5b8160405162461bcd60e51b81526004016100c69190610224565b60005b838110156101f35781810151838201526020016101db565b83811115610202576000848401525b50505050565b6000825161021a8184602087016101d8565b9190910192915050565b60208152600082518060208401526102438160408501602087016101d8565b601f01601f1916919091016040019291505056fea26469706673582212200b524eb8ceaafe6c603273ee859fddbc2d6f1b7860c3d853dcf6f129f9d9371364736f6c634300080c0033";
export const DEPLOYER_ABI = [
{
inputs: [
{
components: [
{
internalType: "address",
name: "predictedAddress",
type: "address",
},
{
internalType: "address",
name: "to",
type: "address",
},
{
internalType: "bytes",
name: "data",
type: "bytes",
},
],
internalType: "struct IDeployer.Transaction[]",
name: "transactions",
type: "tuple[]",
},
],
stateMutability: "payable",
type: "constructor",
},
];
//
// ==================================
// ======== View Functions ==========
// ==================================
//
/**
* Check if a contract exists at the given address
*
* @internal
* @param address
* @param provider
*/
export async function isContractDeployed(
address: string,
provider: providers.Provider,
): Promise<boolean> {
const code = await provider.getCode(address);
return code !== "0x";
}
/**
* Check if a chain enforces EIP-155 transactions
* Ref: https://eips.ethereum.org/EIPS/eip-155
*
* @internal
* @param provider
*/
export async function isEIP155Enforced(
provider: providers.Provider,
): Promise<boolean> {
try {
// TODO: Find a better way to check this.
// Send a random transaction of legacy type (pre-eip-155).
// It will fail. Parse the error message to check whether eip-155 is enforced.
await provider.sendTransaction(
"0xf8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffafffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222",
);
} catch (e: any) {
if (
e.toString().toLowerCase().includes("eip-155") ||
e.message?.toString().toLowerCase().includes("eip-155") ||
e.data?.message?.toString().toLowerCase().includes("eip-155")
) {
return true;
}
return false;
}
return false;
}
/**
* Get the CREATE2 Factory address for a network
* Source code of the factory:
* https://github.com/Arachnid/deterministic-deployment-proxy/blob/master/source/deterministic-deployment-proxy.yul
*
* @internal
* @param provider
*/
export async function getCreate2FactoryAddress(
provider: providers.Provider,
): Promise<string> {
const commonFactoryExists = await isContractDeployed(
COMMON_FACTORY,
provider,
);
if (commonFactoryExists) {
return COMMON_FACTORY;
}
const enforceEip155 = await isEIP155Enforced(provider);
const chainId = enforceEip155 ? (await provider.getNetwork()).chainId : 0;
const deploymentInfo = getCreate2FactoryDeploymentInfo(chainId);
return deploymentInfo.deployment;
}
/**
* Generate salt for deployment with Create2
* Note: Salt component is generated by appending `tw` (thirdweb) to the bytecode
*
* @internal
* @param bytecode: Creation bytecode of the contract to deploy
*/
export function getSaltHash(bytecode: string): string {
const bytecodeHash = ethers.utils.id(bytecode);
const salt = `tw.${bytecodeHash}`;
const saltHash = ethers.utils.id(salt);
return saltHash;
}
/**
*
* Construct init-bytecode, packed with salthash.
* This hex data is intended to be sent to the CREATE2 factory address
*
* @internal
* @param bytecode: Creation bytecode of the contract to deploy
* @param encodedArgs: Abi-encoded constructor params
*/
export function getInitBytecodeWithSalt(
bytecode: string,
encodedArgs: BytesLike,
): string {
const saltHash = getSaltHash(bytecode);
const initBytecodeWithSalt = ethers.utils.solidityPack(
["bytes32", "bytes", "bytes"],
[saltHash, bytecode, encodedArgs],
);
return initBytecodeWithSalt;
}
/**
* Pre-compute a contract's deployment address for a CREATE2 deployment.
*
* @public
* @param bytecode: Creation bytecode of the contract to deploy
* @param encodedArgs: Abi-encoded constructor params
* @param create2FactoryAddress
*/
export function computeDeploymentAddress(
bytecode: string,
encodedArgs: BytesLike,
create2FactoryAddress: string,
): string {
const saltHash = getSaltHash(bytecode);
// 1. create init bytecode hash with contract's bytecode and encoded args
const initBytecode = ethers.utils.solidityPack(
["bytes", "bytes"],
[bytecode, encodedArgs],
);
// 2. abi-encode pack the deployer address, salt, and bytecode hash
const deployInfoPacked = ethers.utils.solidityPack(
["bytes1", "address", "bytes32", "bytes32"],
[
"0xff",
create2FactoryAddress,
saltHash,
ethers.utils.solidityKeccak256(["bytes"], [initBytecode]),
],
);
// 3. hash the packed deploy info
const hashedDeployInfo = ethers.utils.solidityKeccak256(
["bytes"],
[deployInfoPacked],
);
// 4. return last 20 bytes (40 characters) of the hash -- this is the predicted address
return `0x${hashedDeployInfo.slice(26)}`;
}
/**
*
* @internal
* @param provider
* @param storage
* @param create2Factory
*/
export async function computeEOAForwarderAddress(
provider: providers.Provider,
storage: ThirdwebStorage,
create2Factory?: string,
): Promise<string> {
if (!create2Factory) {
create2Factory = await getCreate2FactoryAddress(provider);
}
return await computeAddressInfra(
EOAForwarder.contractType,
provider,
storage,
create2Factory,
);
}
/**
*
* @internal
* @param provider
* @param storage
* @param create2Factory
*/
export async function computeForwarderAddress(
provider: providers.Provider,
storage: ThirdwebStorage,
create2Factory?: string,
): Promise<string> {
if (!create2Factory) {
create2Factory = await getCreate2FactoryAddress(provider);
}
return await computeAddressInfra(
Forwarder.contractType,
provider,
storage,
create2Factory,
);
}
/**
*
* @internal
* @param provider
* @param storage
* @param create2Factory
*/
export async function computeCloneFactoryAddress(
provider: providers.Provider,
storage: ThirdwebStorage,
create2Factory?: string,
): Promise<string> {
if (!create2Factory) {
create2Factory = await getCreate2FactoryAddress(provider);
}
return await computeAddressInfra(
CloneFactory.contractType,
provider,
storage,
create2Factory,
);
}
/**
*
* @internal
* @param provider
* @param storage
* @param create2Factory
*/
export async function computeNativeTokenAddress(
provider: providers.Provider,
storage: ThirdwebStorage,
create2Factory?: string,
): Promise<string> {
if (!create2Factory) {
create2Factory = await getCreate2FactoryAddress(provider);
}
return await computeAddressInfra(
NativeTokenWrapper.contractType,
provider,
storage,
create2Factory,
);
}
//
// ==============================================
// ======== Create / Send Transactions ==========
// ==============================================
//
/**
* Generate a transaction to be sent with a keyless signer.
*
* @public
* @param transaction: Unsigned transaction object
* @param signature: Signature bytes
*/
export function getKeylessTxn(
transaction: ethers.UnsignedTransaction,
signature: string,
): KeylessTransaction {
// 1. Create serialized txn string
const digest = ethers.utils.arrayify(
ethers.utils.keccak256(ethers.utils.serializeTransaction(transaction)),
);
// 2. Determine signer address from custom signature + txn
const signer = ethers.utils.recoverAddress(digest, signature);
// 3. Create the signed serialized txn string.
// To be sent directly to the chain using a provider.
const signedSerializedTx = ethers.utils.serializeTransaction(
transaction,
signature,
);
return {
signer: signer,
transaction: signedSerializedTx,
};
}
/**
* Deploy Nick's Create2 factory on a given network.
* Deployment is keyless. Signer is needed to fund the keyless signer address.
* Ref: https://github.com/Arachnid/deterministic-deployment-proxy
*
* @public
* @param signer
*/
export async function deployCreate2Factory(
signer: Signer,
options?: DeployOptions,
): Promise<string> {
invariant(signer.provider, "No provider");
const commonFactoryExists = await isContractDeployed(
COMMON_FACTORY,
signer.provider,
);
if (commonFactoryExists) {
return COMMON_FACTORY;
}
const enforceEip155 = await isEIP155Enforced(signer.provider);
const networkId = (await signer.provider.getNetwork()).chainId;
const chainId = enforceEip155 ? networkId : 0;
console.debug(`ChainId ${networkId} enforces EIP155: ${enforceEip155}`);
const deploymentInfo = getCreate2FactoryDeploymentInfo(chainId);
const factoryExists = await isContractDeployed(
deploymentInfo.deployment,
signer.provider,
);
// deploy community factory if not already deployed
if (!factoryExists) {
// send balance to the keyless signer
if (
(await signer.provider.getBalance(deploymentInfo.signer)).lt(
toWei("0.01"),
)
) {
await signer.sendTransaction({
to: deploymentInfo.signer,
value: toWei("0.01"),
});
}
// deploy
try {
console.debug(
`deploying CREATE2 factory at: ${deploymentInfo.deployment}`,
);
options?.notifier?.("deploying", "create2Factory");
await signer.provider.sendTransaction(deploymentInfo.transaction);
options?.notifier?.("deployed", "create2Factory");
} catch (err) {
throw new Error(`Couldn't deploy CREATE2 factory: ${err}`);
}
}
return deploymentInfo.deployment;
}
/**
* Deploy a contract at a deterministic address, using Create2 method
* Address depends on the Create2 factory address.
*
* @public
*
* @param singer
* @param bytecode
* @param encodedArgs
* @param create2FactoryAddress
*/
export async function deployContractDeterministic(
signer: Signer,
bytecode: string,
encodedArgs: BytesLike,
create2FactoryAddress: string,
options?: DeployOptions,
predictedAddress?: string,
gasLimit: number = 7000000,
) {
// Check if the implementation contract is already deployed
const code = predictedAddress
? await signer.provider?.getCode(predictedAddress)
: "0x";
if (code === "0x") {
console.debug(
`deploying contract via create2 factory at: ${predictedAddress}`,
);
const initBytecodeWithSalt = getInitBytecodeWithSalt(bytecode, encodedArgs);
let tx: ethers.PopulatedTransaction = {
to: create2FactoryAddress,
data: initBytecodeWithSalt,
};
try {
await signer.estimateGas(tx);
} catch (e) {
console.debug("error estimating gas while deploying prebuilt: ", e);
tx.gasLimit = BigNumber.from(gasLimit);
}
options?.notifier?.("deploying", "implementation");
await (await signer.sendTransaction(tx)).wait();
options?.notifier?.("deployed", "implementation");
}
}
/**
*
* Returns txn data for keyless deploys as well as signer deploys.
* Also provides a list of infra contracts to deploy.
*
* @internal
*
* @param metadataUri
* @param storage
* @param provider
* @param create2Factory
*/
export async function getDeploymentInfo(
metadataUri: string,
storage: ThirdwebStorage,
provider: providers.Provider,
create2Factory?: string,
): Promise<DeploymentInfo> {
const compilerMetadata = await fetchPreDeployMetadata(metadataUri, storage);
if (!create2Factory) {
create2Factory = await getCreate2FactoryAddress(provider);
}
// 1. Get abi-encoded args and list of infra contracts required based on constructor params
const { encodedArgs, infraContracts } =
await encodeConstructorParamsForImplementation(
compilerMetadata,
provider,
storage,
create2Factory,
);
// 2. Compute the CREATE2 address
const predictedAddress = computeDeploymentAddress(
compilerMetadata.bytecode,
encodedArgs,
create2Factory,
);
// 3. Add TWStatelessFactory and Forwarder to the list of infra contracts --
// these must be deployed regardless of constructor params of implementation contract
infraContracts.push(CloneFactory.contractType);
infraContracts.push(Forwarder.contractType);
return {
bytecode: compilerMetadata.bytecode,
encodedArgs: encodedArgs,
predictedAddress: predictedAddress,
infraContractsToDeploy: infraContracts,
};
}
/**
* Deploy Infra contracts with a signer.
* The serialized txn data and addresses are precomputed for infra contracts.
*
* @internal
*
* @param signer: Signer of infra deployment txns
* @param provider
* @param storage
* @param create2Factory
* @param contractTypes: List of infra contracts to deploy
*/
export async function deployInfraWithSigner(
signer: Signer,
provider: providers.Provider,
storage: ThirdwebStorage,
create2Factory: string,
contractTypes: InfraContractType[],
options?: DeployOptions,
) {
const txns = [];
for (let contractType of contractTypes as InfraContractType[]) {
const infraContractAddress = await computeAddressInfra(
contractType,
provider,
storage,
create2Factory,
);
if (contractType === NativeTokenWrapper.contractType) {
const code = await provider.getCode(infraContractAddress);
if (code === "0x") {
const initCode = getInitBytecodeWithSalt(WETHBytecode, []);
txns.push({
predictedAddress: infraContractAddress,
to: create2Factory,
data: initCode,
});
}
continue;
}
const uri = await fetchPublishedContractURI(
INFRA_CONTRACTS_MAP[contractType].name,
);
const infraContractMetadata = await fetchPreDeployMetadata(uri, storage);
const code = await provider.getCode(infraContractAddress);
if (code === "0x") {
const encodedArgs = (
await encodeConstructorParamsForImplementation(
infraContractMetadata,
provider,
storage,
create2Factory,
)
).encodedArgs;
// get init bytecode
const initBytecodeWithSalt = getInitBytecodeWithSalt(
infraContractMetadata.bytecode,
encodedArgs,
);
txns.push({
predictedAddress: infraContractAddress,
to: create2Factory,
data: initBytecodeWithSalt,
});
}
}
// Call/deploy the throaway-deployer only if there are any contracts to deploy
if (txns.length > 0) {
txns.forEach((tx) =>
console.debug(`deploying infra contract at: ${tx.predictedAddress}`),
);
options?.notifier?.("deploying", "infra");
// Using the deployer contract, send the deploy transactions to common factory with a signer
const deployer = new ethers.ContractFactory(DEPLOYER_ABI, DEPLOYER_BYTECODE)
.connect(signer)
.deploy(txns);
await (await deployer).deployed();
options?.notifier?.("deployed", "infra");
}
}
//
// ==============================================
// ======== Other helper functions ==============
// ==============================================
//
/**
*
* @public
* @param transaction: Unsigned transaction object
* @param signature: Signature bytes
*/
export function getCreate2FactoryDeploymentInfo(
chainId: number,
): KeylessDeploymentInfo {
const signature = ethers.utils.joinSignature(SIGNATURE);
const deploymentTransaction = getKeylessTxn(
{
gasPrice: 100 * 10 ** 9,
gasLimit: 100000,
nonce: 0,
data: CREATE2_FACTORY_BYTECODE,
chainId: chainId,
},
signature,
);
const create2FactoryAddress = ethers.utils.getContractAddress({
from: deploymentTransaction.signer,
nonce: 0,
});
return {
...deploymentTransaction,
deployment: create2FactoryAddress,
};
}
async function fetchPublishedContractURI(
contractName: string,
): Promise<string> {
// fetch the publish URI from the ContractPublisher contract
const publishedContract = await new ThirdwebSDK("polygon")
.getPublisher()
.getVersion(THIRDWEB_DEPLOYER, contractName);
if (!publishedContract) {
throw new Error(
`No published contract found for ${contractName} at version by '${THIRDWEB_DEPLOYER}'`,
);
}
return publishedContract?.metadataUri;
}
export async function computeAddressInfra(
contractType: InfraContractType,
provider: providers.Provider,
storage: ThirdwebStorage,
create2Factory: string,
): Promise<string> {
const contract = INFRA_CONTRACTS_MAP[contractType];
if (contract.contractType === NativeTokenWrapper.contractType) {
const address = computeDeploymentAddress(WETHBytecode, [], create2Factory);
return address;
} else {
let uri = await fetchPublishedContractURI(contract.name);
const metadata = await fetchPreDeployMetadata(uri, storage);
const encodedArgs = (
await encodeConstructorParamsForImplementation(
metadata,
provider,
storage,
create2Factory,
)
).encodedArgs;
const address = computeDeploymentAddress(
metadata.bytecode,
encodedArgs,
create2Factory,
);
return address;
}
}
/**
* @internal
*
* Determine constructor params required by an implementation contract.
* Return abi-encoded params.
*/
async function encodeConstructorParamsForImplementation(
compilerMetadata: PreDeployMetadataFetched,
provider: providers.Provider,
storage: ThirdwebStorage,
create2Factory: string,
) {
const chainId = (await provider.getNetwork()).chainId;
const infraContracts: InfraContractType[] = [];
const constructorParams = extractConstructorParamsFromAbi(
compilerMetadata.abi,
);
const constructorParamTypes = constructorParams.map((p) => p.type);
const constructorParamValues = await Promise.all(
constructorParams.map(async (p) => {
if (p.name && p.name.includes("nativeTokenWrapper")) {
let nativeTokenWrapperAddress =
getNativeTokenByChainId(chainId).wrapped.address;
if (nativeTokenWrapperAddress === ethers.constants.AddressZero) {
nativeTokenWrapperAddress = await computeNativeTokenAddress(
provider,
storage,
create2Factory,
);
infraContracts.push(NativeTokenWrapper.contractType);
}
return nativeTokenWrapperAddress;
} else if (p.name && p.name.includes("trustedForwarder")) {
if (
compilerMetadata.analytics?.contract_name &&
compilerMetadata.analytics.contract_name === "Pack"
) {
infraContracts.push(EOAForwarder.contractType);
const eoaForwarderAddress = await computeEOAForwarderAddress(
provider,
storage,
create2Factory,
);
return eoaForwarderAddress;
}
infraContracts.push(Forwarder.contractType);
const forwarderAddress = await computeForwarderAddress(
provider,
storage,
create2Factory,
);
return forwarderAddress;
} else {
return "";
}
}),
);
const encodedArgs = ethers.utils.defaultAbiCoder.encode(
constructorParamTypes,
constructorParamValues,
);
return { encodedArgs, infraContracts };
}
+20 -5
View File
@@ -18,8 +18,11 @@ import {
PrebuiltContractType,
DeploySchemaForPrebuiltContractType,
} from "../core";
import { BigNumber, Signer } from "ethers";
import { BigNumber, providers, Signer } from "ethers";
import { z } from "zod";
import { SUPPORTED_CHAIN_IDS } from "../constants";
import { computeForwarderAddress } from "./any-evm-utils";
import { ThirdwebStorage } from "@thirdweb-dev/storage";
/**
*
@@ -36,13 +39,25 @@ export async function getDeployArguments<
metadata: z.input<DeploySchemaForPrebuiltContractType<TContractType>>,
contractURI: string,
signer: Signer,
storage: ThirdwebStorage,
): Promise<any[]> {
const chainId = await signer.getChainId();
const signerAddress = await signer.getAddress();
let trustedForwarders =
contractType === PackInitializer.contractType
? []
: getDefaultTrustedForwarders(chainId);
const chainEnum = SUPPORTED_CHAIN_IDS.find((c) => c === chainId);
let trustedForwarders;
if (!chainEnum) {
const forwarder = await computeForwarderAddress(
signer.provider as providers.Provider,
storage,
);
trustedForwarders = [forwarder];
} else {
trustedForwarders =
contractType === PackInitializer.contractType
? []
: getDefaultTrustedForwarders(chainId);
}
// override default forwarders if custom ones are passed in
if (metadata.trusted_forwarders && metadata.trusted_forwarders.length > 0) {
trustedForwarders = metadata.trusted_forwarders;
@@ -26,6 +26,7 @@ import { ThirdwebStorage } from "@thirdweb-dev/storage";
import bs58 from "bs58";
import { BaseContract, BigNumber, ethers } from "ethers";
import { z } from "zod";
import { isAddress } from "ethers/lib/utils";
/**
* @internal
@@ -316,7 +317,13 @@ export async function resolveContractUriFromAddress(
address: string,
provider: ethers.providers.Provider,
): Promise<string | undefined> {
const bytecode = await provider.getCode(address);
let bytecode;
try {
bytecode = await provider.getCode(address);
} catch (e) {
throw new Error(`Failed to get bytecode for address ${address}: ${e}`);
}
if (bytecode === "0x") {
const chain = await provider.getNetwork();
throw new Error(
@@ -345,8 +352,11 @@ export async function resolveContractUriFromAddress(
"0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc",
),
);
const implementationAddress = ethers.utils.hexStripZeros(proxyStorage);
if (implementationAddress !== "0x") {
const implementationAddress = `0x${proxyStorage.slice(-40)}`;
if (
isAddress(implementationAddress) &&
implementationAddress !== ethers.constants.AddressZero
) {
return await resolveContractUriFromAddress(
implementationAddress,
provider,
+29
View File
@@ -0,0 +1,29 @@
export const CloneFactory = {
name: "TWCloneFactory" as const,
contractType: "cloneFactory" as const,
};
export const NativeTokenWrapper = {
name: "WETH9" as const,
contractType: "nativeTokenWrapper" as const,
};
export const Forwarder = {
name: "Forwarder" as const,
contractType: "forwarder" as const,
};
export const EOAForwarder = {
name: "ForwarderEOAOnly" as const,
contractType: "eoaForwarder" as const,
};
/**
* @internal
*/
export const INFRA_CONTRACTS_MAP = {
[NativeTokenWrapper.contractType]: NativeTokenWrapper,
[Forwarder.contractType]: Forwarder,
[EOAForwarder.contractType]: EOAForwarder,
[CloneFactory.contractType]: CloneFactory,
} as const;
@@ -4,17 +4,23 @@ import {
fetchExtendedReleaseMetadata,
fetchPreDeployMetadata,
} from "../../common";
import {
computeAddressInfra,
computeCloneFactoryAddress,
deployContractDeterministic,
deployInfraWithSigner,
getCreate2FactoryAddress,
getDeploymentInfo,
isContractDeployed,
} from "../../common/any-evm-utils";
import { deployCreate2Factory } from "../../common/any-evm-utils";
import { getDeployArguments } from "../../common/deploy";
import { resolveAddress } from "../../common/ens";
import {
buildDeployTransactionFunction,
buildTransactionFunction,
} from "../../common/transactions";
import {
EventType,
getContractAddressByChainId,
getNativeTokenByChainId,
} from "../../constants";
import { EventType, getContractAddressByChainId } from "../../constants";
import {
EditionDropInitializer,
EditionInitializer,
@@ -49,7 +55,6 @@ import {
} from "../../types";
import { ThirdwebSDK } from "../sdk";
import {
ContractType,
DeploySchemaForPrebuiltContractType,
NetworkInput,
PrebuiltContractType,
@@ -69,6 +74,7 @@ import {
import { EventEmitter } from "eventemitter3";
import invariant from "tiny-invariant";
import { z } from "zod";
import { DeploymentTransaction } from "../../types/any-evm/deploy-data";
const THIRDWEB_DEPLOYER = "0xdd99b75f095d0c4d5112aCe938e4e6ed962fb024";
@@ -90,6 +96,7 @@ export class ContractDeployer extends RPCConnectionHandler {
private storage: ThirdwebStorage;
private events: EventEmitter<DeployEvents>;
private deployMetadataCache: Record<string, any> = {};
private transactionListener = (event: any) => {
if (event.status === "submitted") {
this.events.emit("contractDeployed", {
@@ -516,52 +523,20 @@ export class ContractDeployer extends RPCConnectionHandler {
parsedMetadata,
contractURI,
signer,
this.storage,
);
const activeChainId = (await this.getProvider().getNetwork()).chainId;
// fetch the publish URI from the ContractPublisher contract
const publishedContract = await this.fetchPublishedContractFromPolygon(
THIRDWEB_DEPLOYER,
contractName,
version,
);
// fetch the deploy metadata from the publish URI
const deployMeta = await this.fetchAndCacheDeployMetadata(
publishedContract.metadataUri,
);
let implementationAddress = deployMeta.extendedMetadata
?.factoryDeploymentData?.implementationAddresses?.[
activeChainId
] as AddressOrEns;
if (implementationAddress) {
// implementation exists on the current chain, continue with normal flow
return this.deployContractFromUri.prepare(
publishedContract.metadataUri,
constructorParams,
);
} else {
// implementation does NOT exist on chain, deploy the implementation first, then deploy a proxy
implementationAddress = await this.deployContractFromUri(
publishedContract.metadataUri,
this.getConstructorParamsForImplementation(
contractType,
activeChainId,
),
{
forceDirectDeploy: true,
},
);
const resolvedImplementationAddress = await resolveAddress(
implementationAddress,
);
return this.deployProxy.prepare(
resolvedImplementationAddress,
deployMeta.compilerMetadata.abi,
"initialize",
constructorParams,
);
}
return this.deployContractFromUri.prepare(
publishedContract.metadataUri,
constructorParams,
);
},
);
@@ -788,22 +763,8 @@ export class ContractDeployer extends RPCConnectionHandler {
extendedMetadata.isDeployableViaFactory) &&
!forceDirectDeploy
) {
console.log("Deploying directly...");
const chainId = (await this.getProvider().getNetwork()).chainId;
invariant(
extendedMetadata.factoryDeploymentData.implementationAddresses,
"implementationAddresses is required",
);
const implementationAddress = extendedMetadata.factoryDeploymentData
.implementationAddresses[chainId] as AddressOrEns;
const resolvedImplementationAddress = await resolveAddress(
implementationAddress,
);
invariant(
resolvedImplementationAddress,
`implementationAddress not found for chainId '${chainId}'`,
);
invariant(
extendedMetadata.factoryDeploymentData
.implementationInitializerFunction,
@@ -819,36 +780,108 @@ export class ContractDeployer extends RPCConnectionHandler {
constructorParamValues,
);
if (extendedMetadata.isDeployableViaFactory) {
// deploy via a factory (prioritise factory)
invariant(
extendedMetadata.factoryDeploymentData.factoryAddresses,
"isDeployableViaFactory is true so factoryAddresses is required",
let implementationAddress = extendedMetadata.factoryDeploymentData
.implementationAddresses[chainId] as AddressOrEns;
if (implementationAddress) {
const resolvedImplementationAddress = await resolveAddress(
implementationAddress,
);
const factoryAddress = extendedMetadata.factoryDeploymentData
.factoryAddresses[chainId] as AddressOrEns;
invariant(
factoryAddress,
`isDeployableViaFactory is true and factoryAddress not found for chainId '${chainId}'`,
resolvedImplementationAddress,
`implementationAddress not found for chainId '${chainId}'`,
);
const resolvedFactoryAddress = await resolveAddress(factoryAddress);
return (await this.deployViaFactory.prepare(
resolvedFactoryAddress,
if (extendedMetadata.isDeployableViaFactory) {
// deploy via a factory (prioritise factory)
invariant(
extendedMetadata.factoryDeploymentData.factoryAddresses,
"isDeployableViaFactory is true so factoryAddresses is required",
);
const factoryAddress = extendedMetadata.factoryDeploymentData
.factoryAddresses[chainId] as AddressOrEns;
invariant(
factoryAddress,
`isDeployableViaFactory is true and factoryAddress not found for chainId '${chainId}'`,
);
const resolvedFactoryAddress = await resolveAddress(factoryAddress);
return (await this.deployViaFactory.prepare(
resolvedFactoryAddress,
resolvedImplementationAddress,
compilerMetadata.abi,
extendedMetadata.factoryDeploymentData
.implementationInitializerFunction,
paramValues,
)) as unknown as DeployTransaction;
} else if (extendedMetadata.isDeployableViaProxy) {
// deploy a proxy directly
return await this.deployProxy.prepare(
resolvedImplementationAddress,
compilerMetadata.abi,
extendedMetadata.factoryDeploymentData
.implementationInitializerFunction,
paramValues,
);
}
} else {
// any evm deployment flow -- with signer
// 1. Deploy CREATE2 factory (if not already exists)
const create2Factory = await deployCreate2Factory(signer, options);
// 2. get deployment info for any evm
const deploymentInfo = await getDeploymentInfo(
publishMetadataUri,
this.storage,
this.getProvider(),
create2Factory,
);
implementationAddress = deploymentInfo.predictedAddress;
// 3. deploy infra
await deployInfraWithSigner(
signer,
this.getProvider(),
this.storage,
create2Factory,
deploymentInfo.infraContractsToDeploy,
options,
);
// 4. deploy implementation contract
await deployContractDeterministic(
signer,
deploymentInfo.bytecode,
deploymentInfo.encodedArgs,
create2Factory,
options,
deploymentInfo.predictedAddress,
);
const resolvedImplementationAddress = await resolveAddress(
implementationAddress,
);
// 5. deploy proxy with TWStatelessFactory (Clone factory) and return address
const cloneFactory = await computeCloneFactoryAddress(
this.getProvider(),
this.storage,
create2Factory,
);
options?.notifier?.("deploying", "proxy");
const proxyDeployTransaction = (await this.deployViaFactory.prepare(
cloneFactory,
resolvedImplementationAddress,
compilerMetadata.abi,
extendedMetadata.factoryDeploymentData
.implementationInitializerFunction,
paramValues,
)) as unknown as DeployTransaction;
} else if (extendedMetadata.isDeployableViaProxy) {
// deploy a proxy directly
return await this.deployProxy.prepare(
resolvedImplementationAddress,
compilerMetadata.abi,
extendedMetadata.factoryDeploymentData
.implementationInitializerFunction,
paramValues,
);
options?.notifier?.("deployed", "proxy");
return proxyDeployTransaction;
}
}
@@ -901,6 +934,105 @@ export class ContractDeployer extends RPCConnectionHandler {
},
);
/**
* @public
* @param publishMetadataUri
* @param options
*/
public async getTransactionsForDeploy(
publishMetadataUri: string,
options?: DeployOptions,
): Promise<DeploymentTransaction[]> {
let transactions: DeploymentTransaction[] = [];
const provider = this.getProvider();
invariant(provider, "A provider is required");
const { extendedMetadata } = await this.fetchAndCacheDeployMetadata(
publishMetadataUri,
);
const forceDirectDeploy = options?.forceDirectDeploy || false;
if (
extendedMetadata &&
extendedMetadata.factoryDeploymentData &&
(extendedMetadata.isDeployableViaProxy ||
extendedMetadata.isDeployableViaFactory) &&
!forceDirectDeploy
) {
const chainId = (await this.getProvider().getNetwork()).chainId;
let implementationAddress = extendedMetadata.factoryDeploymentData
.implementationAddresses[chainId] as AddressOrEns;
if (!implementationAddress) {
const create2FactoryAddress = await getCreate2FactoryAddress(
this.getProvider(),
);
transactions.push({
contractType: "create2Factory",
addresses: [create2FactoryAddress],
});
const deploymentInfo = await getDeploymentInfo(
publishMetadataUri,
this.storage,
this.getProvider(),
create2FactoryAddress,
);
implementationAddress = deploymentInfo.predictedAddress;
transactions.push({
contractType: "implementation",
addresses: [implementationAddress],
});
const infraAddresses = await Promise.all(
deploymentInfo.infraContractsToDeploy.map((contract) => {
return computeAddressInfra(
contract,
this.getProvider(),
this.storage,
create2FactoryAddress,
);
}),
);
transactions.push({
contractType: "infra",
addresses: [...infraAddresses],
});
transactions = (
await Promise.all(
transactions.map(async (tx) => {
const addresses = (
await Promise.all(
tx.addresses.map(async (address) => {
const isDeployed = await isContractDeployed(
address,
provider,
);
return isDeployed ? null : address;
}),
)
).filter(Boolean);
return addresses.length > 0 ? tx : null;
}),
)
).filter(Boolean) as DeploymentTransaction[];
}
transactions.push({
contractType: "proxy",
addresses: [],
});
} else {
transactions.push({
contractType: "custom",
addresses: [],
});
}
return transactions;
}
/**
* Listen to all deploy transactions from this deployer
* @param listener the listener to add
@@ -970,27 +1102,6 @@ export class ContractDeployer extends RPCConnectionHandler {
return publishedContract;
}
private getConstructorParamsForImplementation(
contractType: ContractType,
chainId: number,
) {
switch (contractType) {
case MarketplaceInitializer.contractType:
case MultiwrapInitializer.contractType:
const nativeTokenWrapperAddress =
getNativeTokenByChainId(chainId)?.wrapped?.address ||
ethers.constants.AddressZero;
return [nativeTokenWrapperAddress];
case PackInitializer.contractType:
const addr =
getNativeTokenByChainId(chainId).wrapped.address ||
ethers.constants.AddressZero;
return [addr, ethers.constants.AddressZero];
default:
return [];
}
}
private hasLocalFactory() {
// eslint-disable-next-line turbo/no-undeclared-env-vars
return process.env.factoryAddress !== undefined;
@@ -121,6 +121,7 @@ export class ContractFactory extends ContractWrapper<TWFactory> {
metadata,
contractURI,
signer,
this.storage,
);
const encodedFunc = Contract.getInterface(ABI).encodeFunctionData(
+4
View File
@@ -1,3 +1,4 @@
import { INFRA_CONTRACTS_MAP } from "../common/infra-data";
import type { CONTRACTS_MAP, PREBUILT_CONTRACTS_MAP } from "../contracts";
import type { SmartContract } from "../contracts/smart-contract";
import type { Chain, ChainSlug, ChainId } from "@thirdweb-dev/chains";
@@ -34,6 +35,9 @@ export type ContractsMap = typeof CONTRACTS_MAP;
export type PrebuiltContractType = keyof PrebuiltContractsMap;
export type ContractType = keyof ContractsMap;
export type InfraContractsMap = typeof INFRA_CONTRACTS_MAP;
export type InfraContractType = keyof InfraContractsMap;
export type ValidContractInstance =
| Awaited<ReturnType<ContractsMap[keyof PrebuiltContractsMap]["initialize"]>>
| SmartContract;
@@ -0,0 +1,37 @@
import { InfraContractType } from "../../core";
export type PrecomputedDeploymentData = {
predictedAddress: string;
bytecode: string;
encodedArgs: any;
};
export type DeploymentInfo = {
bytecode: string;
encodedArgs: any;
predictedAddress: string;
infraContractsToDeploy: InfraContractType[];
};
export type KeylessTransaction = {
signer: string;
transaction: string;
};
export type KeylessDeploymentInfo = {
signer: string;
transaction: string;
deployment: string;
};
export type DeployedContractType =
| "proxy"
| "infra"
| "implementation"
| "create2Factory"
| "custom";
export type DeploymentTransaction = {
contractType: DeployedContractType;
addresses: string[];
};
@@ -2,9 +2,14 @@ import {
FullPublishMetadata,
PreDeployMetadataFetched,
} from "../../schema/contracts/custom";
import { DeployedContractType } from "../any-evm/deploy-data";
export type DeployOptions = {
forceDirectDeploy?: boolean;
notifier?: (
status: "deploying" | "deployed",
contractType: DeployedContractType,
) => void;
};
export type DeployMetadata = {
@@ -0,0 +1,79 @@
import { NATIVE_TOKEN_ADDRESS, ThirdwebSDK } from "../../src/evm";
import { SmartContract } from "../../src/evm/contracts/smart-contract";
import { signers } from "./before-setup";
import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers";
import { expect, assert } from "chai";
describe("Any EVM Keyless Deploy", async () => {
let contract: SmartContract;
let sdk: ThirdwebSDK;
let adminWallet: SignerWithAddress;
let claimerWallet: SignerWithAddress;
let notificationCounter: number;
let transactionCount: number;
async function deployTieredDrop() {
const mockPublisher = process.env.contractPublisherAddress;
process.env.contractPublisherAddress =
"0x664244560eBa21Bf82d7150C791bE1AbcD5B4cd7";
const walletAddress = await sdk.wallet.getAddress();
// This needs to match the published contract for the currently used ABI
const publishUri =
"ipfs://QmXu9ezFNgXBX1juLZ7kwdf5KpTD1x9GPHnk14QB2NpUvK/0";
console.log(
"transactions: ",
await sdk.deployer.getTransactionsForDeploy(publishUri),
);
transactionCount = (await sdk.deployer.getTransactionsForDeploy(publishUri))
.length;
const address = await sdk.deployer.deployContractFromUri(
publishUri,
[
walletAddress, // defaultAdmin
"Tiered Drop #1", // name
"TD", // symbol
"ipfs://QmUj5kNz7Xe5AEhV2YvHiCKfMSL5YZpD4E18QLLYEsGBcd/0", // contractUri
[], // trustedForwarders
walletAddress, // saleRecipient
walletAddress, // royaltyRecipient
0, // royaltyBps
],
{
forceDirectDeploy: false,
notifier(status, contractType) {
notificationCounter += 1;
},
},
);
process.env.contractPublisherAddress = mockPublisher;
const tieredDrop = await sdk.getContract(address);
return tieredDrop;
}
before(async () => {
[adminWallet, claimerWallet] = signers;
sdk = new ThirdwebSDK(adminWallet);
});
beforeEach(() => {
sdk.updateSignerOrProvider(adminWallet);
});
it("correct count of logs and transactions", async () => {
notificationCounter = 0;
transactionCount = 0;
contract = await deployTieredDrop();
expect(notificationCounter).to.equal(8);
expect(transactionCount).to.equal(4);
notificationCounter = 0;
transactionCount = 0;
contract = await deployTieredDrop();
expect(notificationCounter).to.equal(2);
expect(transactionCount).to.equal(1);
});
});
+9
View File
@@ -1,5 +1,14 @@
# @thirdweb-dev/unity-js-bridge
## 0.2.25
### Patch Changes
- Updated dependencies [[`ac8fa0b3`](https://github.com/thirdweb-dev/js/commit/ac8fa0b34545a2bc0b489a0551d476a9f560e851), [`b616dca7`](https://github.com/thirdweb-dev/js/commit/b616dca7eb861cd1d2adba3f3d1fe9c3b50f259e), [`2545a440`](https://github.com/thirdweb-dev/js/commit/2545a440dc272690cacbc23023f7b0a68f390c6e), [`b75bcef5`](https://github.com/thirdweb-dev/js/commit/b75bcef55bfdedc260b5b62bb4aff10a7d5c47b6), [`229a4741`](https://github.com/thirdweb-dev/js/commit/229a47413e422952ad946b8c09af32cc1fcdc7f0), [`c9027fce`](https://github.com/thirdweb-dev/js/commit/c9027fced0fffbf757bf0080bc4a49f5464df647)]:
- @thirdweb-dev/sdk@3.10.10
- @thirdweb-dev/wallets@0.2.15
- @thirdweb-dev/auth@3.0.14
## 0.2.24
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@thirdweb-dev/unity-js-bridge",
"version": "0.2.24",
"version": "0.2.25",
"main": "dist/thirdweb-unity-bridge.js",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/unity-js-bridge",
"license": "Apache-2.0",
@@ -4,7 +4,7 @@ import { CoinbasePayIntegration, FundWalletOptions } from "@thirdweb-dev/pay";
import { ThirdwebSDK, ChainIdOrName } from "@thirdweb-dev/sdk";
import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { DAppMetaData } from "@thirdweb-dev/wallets";
import type { AbstractBrowserWallet } from "@thirdweb-dev/wallets/evm/wallets/base";
import type { AbstractClientWallet } from "@thirdweb-dev/wallets/evm/wallets/base";
import { CoinbaseWallet } from "@thirdweb-dev/wallets/evm/wallets/coinbase-wallet";
import { DeviceBrowserWallet } from "@thirdweb-dev/wallets/evm/wallets/device-wallet";
import { EthersWallet } from "@thirdweb-dev/wallets/evm/wallets/ethers";
@@ -74,8 +74,8 @@ interface TWBridge {
const w = window;
class ThirdwebBridge implements TWBridge {
private walletMap: Map<string, AbstractBrowserWallet> = new Map();
private activeWallet: AbstractBrowserWallet | undefined;
private walletMap: Map<string, AbstractClientWallet> = new Map();
private activeWallet: AbstractClientWallet | undefined;
private initializedChain: ChainIdOrName | undefined;
private activeSDK: ThirdwebSDK | undefined;
private auth: ThirdwebAuth | undefined;
@@ -116,7 +116,7 @@ class ThirdwebBridge implements TWBridge {
sdkOptions.thirdwebApiKey = sdkOptions.thirdwebApiKey || API_KEY;
this.activeSDK = new ThirdwebSDK(chain, sdkOptions, storage);
for (let possibleWallet of WALLETS) {
let walletInstance: AbstractBrowserWallet;
let walletInstance: AbstractClientWallet;
const dappMetadata: DAppMetaData = {
name: sdkOptions.wallet?.appName || "thirdweb powered game",
url: sdkOptions.wallet?.appUrl || "https://thirdweb.com",
+13
View File
@@ -1,5 +1,18 @@
# @thirdweb-dev/wallets
## 0.2.15
### Patch Changes
- [#868](https://github.com/thirdweb-dev/js/pull/868) [`b616dca7`](https://github.com/thirdweb-dev/js/commit/b616dca7eb861cd1d2adba3f3d1fe9c3b50f259e) Thanks [@iketw](https://github.com/iketw)! - - Updates base wallet classes names
- Makes InjectedWallet params optional
- Removes connector storage constructor param from Injected and MetaMask wallets
- [#872](https://github.com/thirdweb-dev/js/pull/872) [`2545a440`](https://github.com/thirdweb-dev/js/commit/2545a440dc272690cacbc23023f7b0a68f390c6e) Thanks [@nachoiacovino](https://github.com/nachoiacovino)! - Rename Wallet Connect to WalletConnect
- [#859](https://github.com/thirdweb-dev/js/pull/859) [`229a4741`](https://github.com/thirdweb-dev/js/commit/229a47413e422952ad946b8c09af32cc1fcdc7f0) Thanks [@MananTank](https://github.com/MananTank)! - Fix Error when connecting to Safe in Vite
## 0.2.14
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@thirdweb-dev/wallets",
"version": "0.2.14",
"version": "0.2.15",
"main": "dist/thirdweb-dev-wallets.cjs.js",
"module": "dist/thirdweb-dev-wallets.esm.js",
"types": "dist/thirdweb-dev-wallets.cjs.d.ts",
@@ -3,7 +3,13 @@ import { AbstractWallet } from "../../wallets/abstract";
import type { SafeConnectionArgs } from "./types";
import { ethers } from "ethers";
import type { Signer } from "ethers";
import { AbstractBrowserWallet } from "../../wallets/base";
import { AbstractClientWallet } from "../../wallets/base";
import {
SafeService,
SafeEthersSigner,
} from "@safe-global/safe-ethers-adapters";
import safeCoreSdk from "@safe-global/safe-core-sdk";
import safeEthersLib from "@safe-global/safe-ethers-lib";
// excerpt from https://docs.gnosis-safe.io/backend/available-services
const CHAIN_ID_TO_GNOSIS_SERVER_URL = {
@@ -37,7 +43,7 @@ export class SafeConnector extends TWConnector<SafeConnectionArgs> {
public previousConnector?: AbstractWallet;
// private options: SafeOptions;
private safeSigner?: Signer;
personalWallet?: AbstractBrowserWallet;
personalWallet?: AbstractClientWallet;
constructor() {
super();
@@ -88,23 +94,17 @@ export class SafeConnector extends TWConnector<SafeConnectionArgs> {
throw new Error("Chain not supported");
}
const [safeEthersAdapters, safeCoreSdk, safeEthersLib] = await Promise.all([
import("@safe-global/safe-ethers-adapters"),
import("@safe-global/safe-core-sdk"),
import("@safe-global/safe-ethers-lib"),
]);
const ethAdapter = new safeEthersLib.default({
const ethAdapter = new safeEthersLib({
ethers,
signerOrProvider: signer,
});
const safe = await safeCoreSdk.default.create({
const safe = await safeCoreSdk.create({
ethAdapter: ethAdapter as any,
safeAddress,
});
const service = new safeEthersAdapters.SafeService(serverUrl);
const safeSigner = new safeEthersAdapters.SafeEthersSigner(
const service = new SafeService(serverUrl);
const safeSigner = new SafeEthersSigner(
safe as any,
service,
signer.provider,
@@ -1,8 +1,8 @@
import type { AbstractBrowserWallet } from "../../wallets/base";
import type { AbstractClientWallet } from "../../wallets/base";
import type { Chain } from "@thirdweb-dev/chains";
export interface SafeConnectionArgs {
safeAddress: string;
personalWallet: AbstractBrowserWallet;
personalWallet: AbstractClientWallet;
chain: Pick<Chain, "chainId" | "rpc">;
}
+3 -3
View File
@@ -10,8 +10,8 @@ export {
UserRejectedRequestError,
} from "../lib/wagmi-core";
export type { EVMWallet } from "./interfaces";
export type { ConnectParams, TWConnector } from "./interfaces/tw-connector";
export { WagmiAdapter } from "./interfaces/tw-connector";
export type { ConnectParams } from "./interfaces/tw-connector";
export { TWConnector, WagmiAdapter } from "./interfaces/tw-connector";
export type {
AbstractWallet,
WalletData,
@@ -21,7 +21,7 @@ export type {
export * from "./wallets/paper-wallet";
// just the types
export type { WalletOptions } from "./wallets/base";
export { AbstractBrowserWallet } from "./wallets/base";
export { AbstractClientWallet } from "./wallets/base";
export * from "./wallets/coinbase-wallet";
export * from "./wallets/device-wallet";
export * from "./wallets/injected";
+2 -2
View File
@@ -17,7 +17,7 @@ export type WalletMeta = {
iconURL: string;
};
export abstract class AbstractBrowserWallet<
export abstract class AbstractClientWallet<
TAdditionalOpts extends Record<string, any> = {},
TConnectParams extends Record<string, any> = {},
> extends AbstractWallet {
@@ -28,7 +28,7 @@ export abstract class AbstractBrowserWallet<
protected options?: WalletOptions<TAdditionalOpts>;
static meta: WalletMeta;
getMeta() {
return (this.constructor as typeof AbstractBrowserWallet).meta;
return (this.constructor as typeof AbstractClientWallet).meta;
}
constructor(walletId: string, options?: WalletOptions<TAdditionalOpts>) {
@@ -1,6 +1,6 @@
import type { CoinbaseWalletConnector } from "../connectors/coinbase-wallet";
import { TWConnector, WagmiAdapter } from "../interfaces/tw-connector";
import { AbstractBrowserWallet, WalletOptions } from "./base";
import { AbstractClientWallet, WalletOptions } from "./base";
import { Buffer } from "buffer";
if (typeof window !== "undefined") {
@@ -10,7 +10,7 @@ if (typeof window !== "undefined") {
export type CoinbaseWalletOptions = WalletOptions<{ headlessMode?: boolean }>;
export class CoinbaseWallet extends AbstractBrowserWallet {
export class CoinbaseWallet extends AbstractClientWallet {
connector?: TWConnector;
coinbaseConnector?: CoinbaseWalletConnector;
static meta = {
@@ -1,7 +1,7 @@
import { AsyncStorage, createAsyncLocalStorage } from "../../core";
import { TWConnector } from "../interfaces/tw-connector";
import { AbstractWallet } from "./abstract";
import { AbstractBrowserWallet, WalletOptions } from "./base";
import { AbstractClientWallet, WalletOptions } from "./base";
import { Chain, defaultChains, Ethereum } from "@thirdweb-dev/chains";
import { ethers } from "ethers";
@@ -19,7 +19,7 @@ export type DeviceWalletConnectionArgs = {
const STORAGE_KEY_DATA = "data";
const STORAGE_KEY_ADDR = "address";
export class DeviceBrowserWallet extends AbstractBrowserWallet<
export class DeviceBrowserWallet extends AbstractClientWallet<
DeviceWalletOptions,
DeviceWalletConnectionArgs
> {
+4 -8
View File
@@ -1,20 +1,16 @@
import { AsyncStorage, createAsyncLocalStorage } from "../../core/AsyncStorage";
import { TWConnector, WagmiAdapter } from "../interfaces/tw-connector";
import { AbstractBrowserWallet, WalletOptions } from "./base";
import { AbstractClientWallet, WalletOptions } from "./base";
export class InjectedWallet extends AbstractBrowserWallet {
export class InjectedWallet extends AbstractClientWallet {
connector?: TWConnector;
connectorStorage: AsyncStorage;
static id = "injected" as const;
public get walletName() {
return "Injected Wallet";
}
constructor(options: WalletOptions<{ connectorStorage?: AsyncStorage }>) {
constructor(options?: WalletOptions) {
super(InjectedWallet.id, options);
this.connectorStorage =
options.connectorStorage || createAsyncLocalStorage("connector");
}
protected async getConnector(): Promise<TWConnector> {
@@ -24,7 +20,7 @@ export class InjectedWallet extends AbstractBrowserWallet {
this.connector = new WagmiAdapter(
new InjectedConnector({
chains: this.chains,
connectorStorage: this.connectorStorage,
connectorStorage: this.walletStorage,
options: {
shimDisconnect: true,
},
+4 -12
View File
@@ -1,14 +1,9 @@
import { AsyncStorage, createAsyncLocalStorage } from "../../core/AsyncStorage";
import type { WalletConnectV1Connector as WalletConnectV1ConnectorType } from "../connectors/wallet-connect-v1";
import { TWConnector, WagmiAdapter } from "../interfaces/tw-connector";
import { assertWindowEthereum } from "../utils/assertWindowEthereum";
import { AbstractBrowserWallet, WalletOptions } from "./base";
import { AbstractClientWallet, WalletOptions } from "./base";
type MetamaskAdditionalOptions = {
/**
* Storage interface to store whether metamask is connected or disconnected.
*/
connectorStorage?: AsyncStorage;
/**
* Whether to display the Wallet Connect QR code Modal for connecting to MetaMask on mobile if MetaMask is not injected.
*/
@@ -23,9 +18,8 @@ type ConnectWithQrCodeArgs = {
onConnected: (accountAddress: string) => void;
};
export class MetaMaskWallet extends AbstractBrowserWallet<MetamaskAdditionalOptions> {
export class MetaMaskWallet extends AbstractClientWallet<MetamaskAdditionalOptions> {
connector?: TWConnector;
connectorStorage: AsyncStorage;
walletConnectConnector?: WalletConnectV1ConnectorType;
isInjected: boolean;
@@ -43,8 +37,6 @@ export class MetaMaskWallet extends AbstractBrowserWallet<MetamaskAdditionalOpti
constructor(options: MetamaskWalletOptions) {
super(MetaMaskWallet.id, options);
this.connectorStorage =
options.connectorStorage || createAsyncLocalStorage("connector");
if (assertWindowEthereum(globalThis.window)) {
this.isInjected = !!globalThis.window.ethereum?.isMetaMask;
@@ -63,7 +55,7 @@ export class MetaMaskWallet extends AbstractBrowserWallet<MetamaskAdditionalOpti
const { MetaMaskConnector } = await import("../connectors/metamask");
const metamaskConnector = new MetaMaskConnector({
chains: this.chains,
connectorStorage: this.connectorStorage,
connectorStorage: this.walletStorage,
options: {
shimDisconnect: true,
},
@@ -77,7 +69,7 @@ export class MetaMaskWallet extends AbstractBrowserWallet<MetamaskAdditionalOpti
const walletConnectConnector = new WalletConnectV1Connector({
chains: this.chains,
storage: this.connectorStorage,
storage: this.walletStorage,
options: {
clientMeta: {
name: this.dappMetadata.name,
@@ -3,13 +3,13 @@ import {
PaperWalletAdditionalOptions,
} from "../connectors/paper/types";
import { TWConnector } from "../interfaces/tw-connector";
import { AbstractBrowserWallet, WalletOptions } from "./base";
import { AbstractClientWallet, WalletOptions } from "./base";
import type { Chain } from "@thirdweb-dev/chains";
import type { PaperWalletConnector } from "../connectors/paper";
export type PaperWalletOptions = WalletOptions<PaperWalletAdditionalOptions>;
export class PaperWallet extends AbstractBrowserWallet<
export class PaperWallet extends AbstractClientWallet<
PaperWalletAdditionalOptions,
PaperWalletConnectionArgs
> {
+3 -3
View File
@@ -1,7 +1,7 @@
import { ConnectParams, TWConnector } from "../interfaces/tw-connector";
import { AbstractBrowserWallet, WalletOptions } from "./base";
import { AbstractClientWallet, WalletOptions } from "./base";
import type { Chain } from "@thirdweb-dev/chains";
import { SafeConnectionArgs } from "../connectors/safe/types";
import type { SafeConnectionArgs } from "../connectors/safe/types";
import type { SafeConnector as SafeConnectorType } from "../connectors/safe";
export { SafeSupportedChainsSet } from "../connectors/safe";
@@ -10,7 +10,7 @@ export { SafeSupportedChainsSet } from "../connectors/safe";
export type { SafeConnectionArgs } from "../connectors/safe/types";
export type SafeWalletOptions = WalletOptions<{}>;
export class SafeWallet extends AbstractBrowserWallet<{}, SafeConnectionArgs> {
export class SafeWallet extends AbstractClientWallet<{}, SafeConnectionArgs> {
connector?: SafeConnectorType;
static meta = {
@@ -2,13 +2,13 @@ import type { ConnectorData } from "../../lib/wagmi-core";
import type { WalletConnectV1Connector } from "../connectors/wallet-connect-v1";
import type WalletConnectProvider from "../connectors/wallet-connect-v1/walletconnect-legacy-provider";
import { TWConnector, WagmiAdapter } from "../interfaces/tw-connector";
import { AbstractBrowserWallet, WalletOptions } from "./base";
import { AbstractClientWallet, WalletOptions } from "./base";
export type WalletConnectV1Options = {
qrcode?: boolean;
} & Omit<ConstructorParameters<typeof WalletConnectProvider>[0], "clientMeta">;
export class WalletConnectV1 extends AbstractBrowserWallet<WalletConnectV1Options> {
export class WalletConnectV1 extends AbstractClientWallet<WalletConnectV1Options> {
#walletConnectConnector?: WalletConnectV1Connector;
#provider?: WalletConnectProvider;
@@ -17,7 +17,7 @@ export class WalletConnectV1 extends AbstractBrowserWallet<WalletConnectV1Option
static id = "walletConnectV1";
static meta = {
name: "Wallet Connect",
name: "WalletConnect",
iconURL:
"ipfs://QmX58KPRaTC9JYZ7KriuBzeoEaV2P9eZcA3qbFnTHZazKw/wallet-connect.svg",
};
@@ -1,7 +1,7 @@
import type { ConnectorData } from "../../lib/wagmi-core";
import type { WalletConnectConnector } from "../connectors/wallet-connect";
import { TWConnector, WagmiAdapter } from "../interfaces/tw-connector";
import { AbstractBrowserWallet, WalletOptions } from "./base";
import { AbstractClientWallet, WalletOptions } from "./base";
import type WalletConnectProvider from "@walletconnect/ethereum-provider";
import { TW_WC_PROJECT_ID } from "../constants/wc";
@@ -10,7 +10,7 @@ export type WalletConnectOptions = {
qrcode?: boolean;
};
export class WalletConnect extends AbstractBrowserWallet<WalletConnectOptions> {
export class WalletConnect extends AbstractClientWallet<WalletConnectOptions> {
#walletConnectConnector?: WalletConnectConnector;
#provider?: WalletConnectProvider;
@@ -19,7 +19,7 @@ export class WalletConnect extends AbstractBrowserWallet<WalletConnectOptions> {
static id = "walletConnect";
static meta = {
name: "Wallet Connect",
name: "WalletConnect",
iconURL:
"ipfs://QmX58KPRaTC9JYZ7KriuBzeoEaV2P9eZcA3qbFnTHZazKw/wallet-connect.svg",
};
@@ -1,36 +0,0 @@
diff --git a/node_modules/@walletconnect/legacy-types/dist/cjs/jsonrpc.d.ts b/node_modules/@walletconnect/legacy-types/dist/cjs/jsonrpc.d.ts
index 7c2f8f0..0cca28c 100644
--- a/node_modules/@walletconnect/legacy-types/dist/cjs/jsonrpc.d.ts
+++ b/node_modules/@walletconnect/legacy-types/dist/cjs/jsonrpc.d.ts
@@ -1,4 +1,4 @@
-import { IClientMeta, IConnector } from "./protocol";
+import { IClientMeta, IConnector, IWalletConnectSession } from "./protocol";
import { IEvents } from "./events";
import { IQRCodeModal, IQRCodeModalOptions } from "./qrcode";
export interface IRpcConnection extends IEvents {
@@ -68,6 +68,7 @@ export interface IWCRpcConnectionOptions {
signingMethods?: string[];
qrcodeModalOptions?: IQRCodeModalOptions;
clientMeta?: IClientMeta;
+ session?: IWalletConnectSession;
}
export interface IWCEthRpcConnectionOptions extends IWCRpcConnectionOptions {
rpc?: IRPCMap;
diff --git a/node_modules/@walletconnect/legacy-types/dist/esm/jsonrpc.d.ts b/node_modules/@walletconnect/legacy-types/dist/esm/jsonrpc.d.ts
index 7c2f8f0..0cca28c 100644
--- a/node_modules/@walletconnect/legacy-types/dist/esm/jsonrpc.d.ts
+++ b/node_modules/@walletconnect/legacy-types/dist/esm/jsonrpc.d.ts
@@ -1,4 +1,4 @@
-import { IClientMeta, IConnector } from "./protocol";
+import { IClientMeta, IConnector, IWalletConnectSession } from "./protocol";
import { IEvents } from "./events";
import { IQRCodeModal, IQRCodeModalOptions } from "./qrcode";
export interface IRpcConnection extends IEvents {
@@ -68,6 +68,7 @@ export interface IWCRpcConnectionOptions {
signingMethods?: string[];
qrcodeModalOptions?: IQRCodeModalOptions;
clientMeta?: IClientMeta;
+ session?: IWalletConnectSession;
}
export interface IWCEthRpcConnectionOptions extends IWCRpcConnectionOptions {
rpc?: IRPCMap;
+103 -2183
View File
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -18,7 +18,8 @@
"@playwright/test": "1.31.2",
"@vitejs/plugin-react": "^2",
"serve": "^14.0.1",
"vite": "^3"
"vite": "^3",
"vite-plugin-node-polyfills": "^0.7.0"
},
"repository": "https://github.com/thirdweb-dev/js/tree/main/test/e2e/vite-3"
}
+7 -1
View File
@@ -1,9 +1,15 @@
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
import { nodePolyfills } from "vite-plugin-node-polyfills";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
plugins: [
react(),
nodePolyfills({
global: true,
}),
],
define: {
"process.env": {},
},