Compare commits

..
Author SHA1 Message Date
github-actions[bot]andgithub-actions[bot] f3fb440fb5 Version Packages (#1793)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2023-10-22 14:33:11 -07:00
Manan Tank 2307f11ab3 [wallets, react] Add OKX wallet (#1826) 2023-10-22 18:47:23 +00:00
Kien Ngo d8d48a9516 [SDK] Perf improvement for erc-1155-signature-mintable (#1824) 2023-10-21 22:29:55 +00:00
Winston Yeo 5ffbcfc302 [wallets, react] expose onAuthSuccess callback in paperWallet (#1815) 2023-10-21 01:03:06 +00:00
Joaquim Verges d27a3dee83 [SmartWallet] implement multidimensional nonces for smart wallets (#1821) 2023-10-20 23:28:08 +00:00
iketw 7080ff29fc [RN] Allow custom fontFamily (#1820) 2023-10-20 20:39:39 +00:00
iketw 638afd8e08 [RN] i18n strings (#1819) 2023-10-20 19:04:13 +00:00
iketw 947e3345ef [RN] i18n more strings and fix fontFamily (#1818) 2023-10-20 18:04:29 +00:00
iketw ea51a50bfc [RN] Update weights (#1817) 2023-10-20 16:10:07 +00:00
iketw c6f59e1b01 [RN] Makes locale optional (#1816) 2023-10-20 15:46:57 +00:00
Kien Ngo 6d1eabe9f9 [SDK] Some more small improvements (#1813) 2023-10-20 04:46:50 +00:00
Adam Majmudar c238fde877 [Auth] Update to call uuidv4 to generate jti (#1812) 2023-10-20 02:14:42 +00:00
Adam Majmudar 548601981f [Auth] Expose buildJWT (#1811) 2023-10-20 01:00:05 +00:00
iketw 05481aa8c0 [RN]i18n Extract more strings (#1810) 2023-10-20 00:19:25 +00:00
iketw 1cc26e43e5 [RN] Enable localization for the RN SDK (#1799) 2023-10-19 23:54:19 +00:00
Adam Majmudar 99d7ec06ec [Auth] Add fastify extension, onToken callback, & secure option (#1801) 2023-10-19 23:34:32 +00:00
Manan Tankandikethirdweb ff996646b2 [React, RN, Wallets, SDK, Storage] typedoc generation (#1787)
Co-authored-by: ikethirdweb <[email protected]>
2023-10-19 20:11:21 +00:00
iketw 01260009be [RN] Pass custom fontfamily to textinput placeholders (#1807) 2023-10-19 19:16:08 +00:00
iketw 7dea0975ec [RN] Update README (#1804) 2023-10-19 15:11:22 +00:00
iketw a63f5dc7cb [RN] Improve UI and theming (#1803) 2023-10-19 15:07:15 +00:00
Joaquim Verges fd7a9f0998 [SmartWallet] expose new send/execute smart wallet functions (#1800) 2023-10-19 05:37:01 +00:00
Manan Tank 246b0d4aac [react] Fix wrong Icon size of few icons in Firefox in ConnectWallet (#1797) 2023-10-18 23:31:50 +00:00
Kien Ngo 42ba15f2c0 Improve performance for /prebuilt-implementations (#1795) 2023-10-18 22:30:30 +00:00
Adam Majmudar aa9f48d136 [Wallets] Add AsyncWallet (#1790) 2023-10-18 18:48:31 +00:00
Adam Majmudar 64138642e8 Manually write GCP KMS signer with full configuration (#1789) 2023-10-18 18:38:48 +00:00
Joaquim Verges 223008b1f7 [SDK] fix marketplace tests (#1791) 2023-10-18 06:01:10 +00:00
154 changed files with 3502 additions and 1081 deletions
+3 -1
View File
@@ -20,4 +20,6 @@ playwright-report/
.env/
# Artifacts
packages/cli/artifacts/
packages/cli/artifacts/
typedoc
+17
View File
@@ -1,5 +1,22 @@
# @thirdweb-dev/auth
## 4.1.0
### Minor Changes
- [#1801](https://github.com/thirdweb-dev/js/pull/1801) [`99d7ec06`](https://github.com/thirdweb-dev/js/commit/99d7ec06ec4f31308627edc87d3122c21a884b5a) Thanks [@adam-maj](https://github.com/adam-maj)! - Add support for fastify
### Patch Changes
- [#1812](https://github.com/thirdweb-dev/js/pull/1812) [`c238fde8`](https://github.com/thirdweb-dev/js/commit/c238fde8777fd14b39837117e2d3fda1dd301029) Thanks [@adam-maj](https://github.com/adam-maj)! - Update to call uuidv4 to generate jti
- [#1811](https://github.com/thirdweb-dev/js/pull/1811) [`54860198`](https://github.com/thirdweb-dev/js/commit/548601981f6dd8706d7a9bd4ca48e4abc7723a1d) Thanks [@adam-maj](https://github.com/adam-maj)! - Expose buildJWT function
- [#1812](https://github.com/thirdweb-dev/js/pull/1812) [`c238fde8`](https://github.com/thirdweb-dev/js/commit/c238fde8777fd14b39837117e2d3fda1dd301029) Thanks [@adam-maj](https://github.com/adam-maj)! - Update to use uuidv4 for default jti
- Updated dependencies [[`5ffbcfc3`](https://github.com/thirdweb-dev/js/commit/5ffbcfc302f74167768b196d93a328f979344036), [`d27a3dee`](https://github.com/thirdweb-dev/js/commit/d27a3dee8398d5707d2d1343c428abf8e03f67e3), [`ff996646`](https://github.com/thirdweb-dev/js/commit/ff996646b228d4d095eea04b05004dd26fc7e522), [`aa9f48d1`](https://github.com/thirdweb-dev/js/commit/aa9f48d1361194fc81146da530c95a3409bd0799), [`fd7a9f09`](https://github.com/thirdweb-dev/js/commit/fd7a9f09989e39b02a93d9dfd01cc7378e6ead53), [`2307f11a`](https://github.com/thirdweb-dev/js/commit/2307f11ab311aa4a775edd23e777d10f8015ce86), [`64138642`](https://github.com/thirdweb-dev/js/commit/64138642e84d8b56b254762eca613d443cca292b)]:
- @thirdweb-dev/wallets@2.0.8
## 4.0.7
### Patch Changes
+7
View File
@@ -0,0 +1,7 @@
{
"main": "dist/thirdweb-dev-auth-fastify.cjs.js",
"module": "dist/thirdweb-dev-auth-fastify.esm.js",
"browser": {
"./dist/thirdweb-dev-auth-fastify.esm.js": "./dist/thirdweb-dev-auth-fastify.browser.esm.js"
}
}
+16 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@thirdweb-dev/auth",
"version": "4.0.7",
"version": "4.1.0",
"main": "dist/thirdweb-dev-auth.cjs.js",
"module": "dist/thirdweb-dev-auth.esm.js",
"browser": {
@@ -35,6 +35,13 @@
},
"default": "./express/dist/thirdweb-dev-auth-express.cjs.js"
},
"./fastify": {
"module": {
"browser": "./fastify/dist/thirdweb-dev-auth-fastify.browser.esm.js",
"default": "./fastify/dist/thirdweb-dev-auth-fastify.esm.js"
},
"default": "./fastify/dist/thirdweb-dev-auth-fastify.cjs.js"
},
"./next-auth": {
"module": {
"browser": "./next-auth/dist/thirdweb-dev-auth-next-auth.browser.esm.js",
@@ -63,6 +70,7 @@
"express/index.ts",
"next/index.ts",
"next-auth/index.ts",
"fastify/index.ts",
"evm/index.ts"
],
"exports": {
@@ -101,6 +109,7 @@
"eslint-plugin-tsdoc": "^0.2.16",
"ethers": "^5.7.2",
"express": "^4.18.1",
"fastify": "^4.24.2",
"mocha": "^10.2.0",
"next": "^12.3.4",
"next-auth": "^4.22.3",
@@ -111,6 +120,7 @@
"cookie-parser": "^1.4.6",
"ethers": "^5",
"express": "^4",
"fastify": "^4.24.2",
"next": "^12 || ^13",
"next-auth": "^4"
},
@@ -124,6 +134,9 @@
"express": {
"optional": true
},
"fastify": {
"optional": true
},
"next": {
"optional": true
},
@@ -132,8 +145,10 @@
}
},
"dependencies": {
"@fastify/cookie": "^9.1.0",
"@thirdweb-dev/wallets": "workspace:*",
"cookie": "^0.5.0",
"fastify-type-provider-zod": "^1.1.9",
"uuid": "^9.0.1",
"zod": "^3.22.3"
}
+4 -1
View File
@@ -38,7 +38,10 @@ function base64decode(data: string): string {
/**
* Build JWT token based on the authentication payload
*/
async function buildJWT({ wallet, payload }: BuildJwtParams): Promise<string> {
export async function buildJWT({
wallet,
payload,
}: BuildJwtParams): Promise<string> {
const payloadData = AuthenticationPayloadDataSchema.parse(payload);
const message = JSON.stringify(payloadData);
+1
View File
@@ -3,6 +3,7 @@ export { ThirdwebAuth } from "./auth";
// Export individual auth functions
export {
buildJWT,
generateJWT,
parseJWT,
refreshJWT,
@@ -9,7 +9,7 @@ export const AuthenticationPayloadDataSchema = z.object({
exp: RawDateSchema,
nbf: RawDateSchema,
iat: RawDateSchema,
jti: z.string().default(uuidv4()),
jti: z.string().default(() => uuidv4()),
ctx: JsonSchema.optional(),
});
+1 -1
View File
@@ -44,7 +44,7 @@ export const LoginPayloadDataSchema = z.object({
uri: z.string().optional(),
version: z.string().default("1"),
chain_id: z.string().optional(),
nonce: z.string().default(uuidv4()),
nonce: z.string().default(() => uuidv4()),
issued_at: z
.date()
.default(new Date())
+1 -1
View File
@@ -2,7 +2,7 @@ import {
THIRDWEB_AUTH_ACTIVE_ACCOUNT_COOKIE,
THIRDWEB_AUTH_TOKEN_COOKIE_PREFIX,
} from "../../constants";
import { Json } from "../../core/schema";
import { Json } from "../../core";
import { ThirdwebAuthContext, ThirdwebAuthUser } from "../types";
import { Request } from "express";
+8 -4
View File
@@ -2,7 +2,7 @@ import {
THIRDWEB_AUTH_ACTIVE_ACCOUNT_COOKIE,
THIRDWEB_AUTH_TOKEN_COOKIE_PREFIX,
} from "../../constants";
import { GenerateOptions } from "../../core";
import { GenerateOptionsWithOptionalDomain } from "../../core";
import { LoginPayloadBodySchema, ThirdwebAuthContext } from "../types";
import { serialize } from "cookie";
import { Request, Response } from "express";
@@ -41,7 +41,7 @@ export default async function handler(
? new Date(Date.now() + 1000 * ctx.authOptions.tokenDurationInSeconds)
: undefined;
const generateOptions: GenerateOptions = {
const generateOptions: GenerateOptionsWithOptionalDomain = {
verifyOptions: {
statement: ctx.authOptions?.statement,
uri: ctx.authOptions?.uri,
@@ -68,6 +68,10 @@ export default async function handler(
}
}
if (ctx.callbacks?.onToken) {
await ctx.callbacks.onToken(token, req);
}
const {
payload: { exp },
} = ctx.auth.parseToken(token);
@@ -84,7 +88,7 @@ export default async function handler(
sameSite: ctx.cookieOptions?.sameSite || "none",
expires: new Date(exp * 1000),
httpOnly: true,
secure: true,
secure: ctx.cookieOptions?.secure || true,
},
),
serialize(THIRDWEB_AUTH_ACTIVE_ACCOUNT_COOKIE, payload.payload.address, {
@@ -93,7 +97,7 @@ export default async function handler(
sameSite: ctx.cookieOptions?.sameSite || "none",
expires: new Date(exp * 1000),
httpOnly: true,
secure: true,
secure: ctx.cookieOptions?.secure || true,
}),
]);
+1 -1
View File
@@ -37,7 +37,7 @@ export default async function handler(
sameSite: ctx.cookieOptions?.sameSite || "none",
expires: new Date(Date.now() + 5 * 1000),
httpOnly: true,
secure: true,
secure: ctx.cookieOptions?.secure || true,
}),
);
@@ -55,7 +55,7 @@ export default async function handler(
sameSite: ctx.cookieOptions?.sameSite || "none",
expires: cookieExpiration,
httpOnly: true,
secure: true,
secure: ctx.cookieOptions?.secure || true,
}),
]);
+2 -2
View File
@@ -53,7 +53,7 @@ export default async function handler(
sameSite: ctx.cookieOptions?.sameSite || "none",
expires: new Date(refreshedPayload.payload.exp * 1000),
httpOnly: true,
secure: true,
secure: ctx.cookieOptions?.secure || true,
},
),
serialize(THIRDWEB_AUTH_ACTIVE_ACCOUNT_COOKIE, user.address, {
@@ -62,7 +62,7 @@ export default async function handler(
sameSite: ctx.cookieOptions?.sameSite || "none",
expires: new Date(refreshedPayload.payload.exp * 1000),
httpOnly: true,
secure: true,
secure: ctx.cookieOptions?.secure || true,
}),
]);
}
+10 -6
View File
@@ -52,17 +52,21 @@ export type ThirdwebAuthConfig<
domain?: string;
path?: string;
sameSite?: "lax" | "strict" | "none";
secure?: boolean;
};
callbacks?: {
onLogin?:
| ((address: string, req?: Request) => void | TSession)
| ((address: string, req?: Request) => Promise<void | TSession>);
| ((address: string, req: Request) => void | TSession)
| ((address: string, req: Request) => Promise<void | TSession>);
onToken?:
| ((token: string, req: Request) => void)
| ((token: string, req: Request) => Promise<void>);
onUser?:
| ((user: User<TSession>, req?: Request) => void | TData)
| ((user: User<TSession>, req?: Request) => Promise<void | TData>);
| ((user: User<TSession>, req: Request) => void | TData)
| ((user: User<TSession>, req: Request) => Promise<void | TData>);
onLogout?:
| ((user: User, req?: Request) => void)
| ((user: User, req?: Request) => Promise<void>);
| ((user: User, req: Request) => void)
| ((user: User, req: Request) => Promise<void>);
};
};
+91
View File
@@ -0,0 +1,91 @@
import {
THIRDWEB_AUTH_ACTIVE_ACCOUNT_COOKIE,
THIRDWEB_AUTH_TOKEN_COOKIE_PREFIX,
} from "../../constants";
import { Json } from "../../core";
import { ThirdwebAuthContext, ThirdwebAuthUser } from "../types";
import { FastifyRequest } from "fastify";
export function getCookie(
req: FastifyRequest,
cookie: string,
): string | undefined {
return req.cookies[cookie];
}
export function getActiveCookie(req: FastifyRequest): string | undefined {
if (!req.cookies) {
return undefined;
}
const activeAccount = getCookie(req, THIRDWEB_AUTH_ACTIVE_ACCOUNT_COOKIE);
if (activeAccount) {
return `${THIRDWEB_AUTH_TOKEN_COOKIE_PREFIX}_${activeAccount}`;
}
// If active account is not present, then use the old default
return THIRDWEB_AUTH_TOKEN_COOKIE_PREFIX;
}
/**
* @internal
* @param req
* @returns
*/
export function getToken(req: FastifyRequest): string | undefined {
if (req.headers.authorization) {
const authorizationHeader = req.headers.authorization.split(" ");
if (authorizationHeader?.length === 2) {
return authorizationHeader[1];
}
}
if (!req.cookies) {
return undefined;
}
const activeCookie = getActiveCookie(req);
if (!activeCookie) {
return undefined;
}
return getCookie(req, activeCookie);
}
export async function getUser<
TData extends Json = Json,
TSession extends Json = Json,
>(
req: FastifyRequest,
ctx: ThirdwebAuthContext<TData, TSession>,
): Promise<ThirdwebAuthUser<TData, TSession> | null> {
const token = getToken(req);
if (!token) {
return null;
}
let authenticatedUser: ThirdwebAuthUser<TData, TSession>;
try {
authenticatedUser = await ctx.auth.authenticate<TSession>(token, {
validateTokenId: async (tokenId: string) => {
if (ctx.authOptions?.validateTokenId) {
await ctx.authOptions?.validateTokenId(tokenId);
}
},
});
} catch (err) {
return null;
}
if (!ctx.callbacks?.onUser) {
return authenticatedUser;
}
const data = await ctx.callbacks.onUser(authenticatedUser, req);
if (!data) {
return authenticatedUser;
}
return { ...authenticatedUser, data: data };
}
+81
View File
@@ -0,0 +1,81 @@
import { FastifyInstance, FastifyPluginOptions, FastifyRequest } from "fastify";
import { Json, ThirdwebAuth as ThirdwebAuthSDK } from "../core";
import fastifyCookie, { FastifyCookie } from "@fastify/cookie";
import { payloadHandler } from "./routes/payload";
import { loginHandler } from "./routes/login";
import { userHandler } from "./routes/user";
import { logoutHandler } from "./routes/logout";
import { switchAccountHandler } from "./routes/switch-account";
import {
ZodTypeProvider,
serializerCompiler,
validatorCompiler,
} from "fastify-type-provider-zod";
import { getUser } from "./helpers/user";
import {
ThirdwebAuthConfig,
ThirdwebAuthContext,
ThirdwebAuthUser,
} from "./types";
export * from "./types";
export { getToken } from "./helpers/user";
type ThirdwebAuthReturnType<
TData extends Json = Json,
TSession extends Json = Json,
> = {
authRouter: (
fastify: FastifyInstance,
opts: FastifyPluginOptions,
done: (err?: Error | undefined) => void,
) => void;
authMiddleware: FastifyCookie;
getUser: (
req: FastifyRequest,
) => Promise<ThirdwebAuthUser<TData, TSession> | null>;
};
export function ThirdwebAuth<
TData extends Json = Json,
TSession extends Json = Json,
>(
cfg: ThirdwebAuthConfig<TData, TSession>,
): ThirdwebAuthReturnType<TData, TSession> {
const ctx = {
...cfg,
auth: new ThirdwebAuthSDK(cfg.wallet, cfg.domain),
};
const authRouter = async (
fastify: FastifyInstance,
_opts: FastifyPluginOptions,
done: (err?: Error | undefined) => void,
) => {
// Setup plugin to use zod as a type provider
fastify.setValidatorCompiler(validatorCompiler);
fastify.setSerializerCompiler(serializerCompiler);
const plugin = fastify.withTypeProvider<ZodTypeProvider>();
// Register the fastify cookie middleware with this plugin
await plugin.register(fastifyCookie);
// Register individual auth endpoints
payloadHandler(plugin, ctx as ThirdwebAuthContext);
loginHandler(plugin, ctx as ThirdwebAuthContext);
logoutHandler(plugin, ctx as ThirdwebAuthContext);
userHandler(plugin, ctx as ThirdwebAuthContext);
switchAccountHandler(plugin, ctx as ThirdwebAuthContext);
// Mark plugin creation as complete
done();
};
return {
authRouter,
authMiddleware: fastifyCookie,
getUser: (req: FastifyRequest) => {
return getUser<TData, TSession>(req, ctx);
},
};
}
+110
View File
@@ -0,0 +1,110 @@
import {
FastifyInstanceWithZod,
LoginPayloadBodySchema,
ThirdwebAuthContext,
} from "../types";
import { GenerateOptionsWithOptionalDomain } from "../../core";
import {
THIRDWEB_AUTH_ACTIVE_ACCOUNT_COOKIE,
THIRDWEB_AUTH_TOKEN_COOKIE_PREFIX,
} from "../../constants";
import { z } from "zod";
export const loginHandler = (
fastify: FastifyInstanceWithZod,
ctx: ThirdwebAuthContext,
) => {
fastify.route<{
Body: z.infer<typeof LoginPayloadBodySchema>;
}>({
method: "POST",
url: "/login",
schema: {
body: LoginPayloadBodySchema,
response: {
200: z.any(),
},
},
handler: async (req, res) => {
const validateNonce = async (nonce: string) => {
if (ctx.authOptions?.validateNonce) {
await ctx.authOptions?.validateNonce(nonce);
}
};
const getSession = async (address: string) => {
if (ctx.callbacks?.onLogin) {
return ctx.callbacks.onLogin(address, req);
}
};
const expirationTime = ctx.authOptions?.tokenDurationInSeconds
? new Date(Date.now() + 1000 * ctx.authOptions.tokenDurationInSeconds)
: undefined;
const generateOptions: GenerateOptionsWithOptionalDomain = {
verifyOptions: {
statement: ctx.authOptions?.statement,
uri: ctx.authOptions?.uri,
version: ctx.authOptions?.version,
chainId: ctx.authOptions?.chainId,
validateNonce,
resources: ctx.authOptions?.resources,
},
expirationTime,
session: getSession,
};
let token: string;
try {
// Generate an access token with the SDK using the signed payload
token = await ctx.auth.generate(req.body.payload, generateOptions);
} catch (err: any) {
if (err.message) {
return res.status(400).send({ error: err.message });
} else if (typeof err === "string") {
return res.status(400).send({ error: err });
} else {
return res.status(400).send({ error: "Invalid login payload" });
}
}
if (ctx.callbacks?.onToken) {
await ctx.callbacks.onToken(token, req);
}
const {
payload: { exp },
} = ctx.auth.parseToken(token);
// Securely set httpOnly cookie on request to prevent XSS on frontend
// And set path to / to enable thirdweb_auth_token usage on all endpoints
res.setCookie(
`${THIRDWEB_AUTH_TOKEN_COOKIE_PREFIX}_${req.body.payload.payload.address}`,
token,
{
domain: ctx.cookieOptions?.domain,
path: ctx.cookieOptions?.path || "/",
sameSite: ctx.cookieOptions?.sameSite || "none",
expires: new Date(exp * 1000),
httpOnly: true,
secure: ctx.cookieOptions?.secure || true,
},
);
res.setCookie(
THIRDWEB_AUTH_ACTIVE_ACCOUNT_COOKIE,
req.body.payload.payload.address,
{
domain: ctx.cookieOptions?.domain,
path: ctx.cookieOptions?.path || "/",
sameSite: ctx.cookieOptions?.sameSite || "none",
expires: new Date(exp * 1000),
httpOnly: true,
secure: ctx.cookieOptions?.secure || true,
},
);
return res.status(200).send({ success: true });
},
});
};
@@ -0,0 +1,52 @@
import { z } from "zod";
import { getActiveCookie, getUser } from "../helpers/user";
import {
ErrorResponseSchema,
FastifyInstanceWithZod,
ThirdwebAuthContext,
} from "../types";
export const logoutHandler = (
fastify: FastifyInstanceWithZod,
ctx: ThirdwebAuthContext,
) => {
fastify.route({
method: "POST",
url: "/logout",
schema: {
response: {
200: z.object({
message: z.string(),
}),
400: ErrorResponseSchema,
},
},
handler: async (req, res) => {
const activeCookie = getActiveCookie(req);
if (!activeCookie) {
return res.status(400).send({
error: "No logged in user to logout.",
});
}
if (ctx.callbacks?.onLogout) {
const user = await getUser(req, ctx);
if (user) {
await ctx.callbacks.onLogout(user, req);
}
}
// Set the access token to 'none' and expire in 5 seconds
res.setCookie(activeCookie, "", {
domain: ctx.cookieOptions?.domain,
path: ctx.cookieOptions?.path || "/",
sameSite: ctx.cookieOptions?.sameSite || "none",
expires: new Date(Date.now() + 5 * 1000),
httpOnly: true,
secure: ctx.cookieOptions?.secure || true,
});
return res.status(200).send({ message: "Successfully logged out" });
},
});
};
@@ -0,0 +1,41 @@
import {
FastifyInstanceWithZod,
PayloadBodySchema,
ThirdwebAuthContext,
} from "../types";
import { z } from "zod";
export const payloadHandler = (
fastify: FastifyInstanceWithZod,
ctx: ThirdwebAuthContext,
) => {
fastify.route<{
Body: z.infer<typeof PayloadBodySchema>;
}>({
method: "POST",
url: "/payload",
schema: {
body: PayloadBodySchema,
response: {
200: z.any(),
},
},
handler: async (req, res) => {
const payload = await ctx.auth.payload({
address: req.body.address,
statement: ctx.authOptions?.statement,
uri: ctx.authOptions?.uri,
version: ctx.authOptions?.version,
chainId: req.body.chainId || ctx.authOptions?.chainId,
resources: ctx.authOptions?.resources,
expirationTime: ctx.authOptions?.loginPayloadDurationInSeconds
? new Date(
Date.now() + 1000 * ctx.authOptions.loginPayloadDurationInSeconds,
)
: undefined,
});
return res.status(200).send({ payload });
},
});
};
@@ -0,0 +1,68 @@
import {
ActiveBodySchema,
ErrorResponseSchema,
FastifyInstanceWithZod,
ThirdwebAuthContext,
} from "../types";
import {
THIRDWEB_AUTH_ACTIVE_ACCOUNT_COOKIE,
THIRDWEB_AUTH_DEFAULT_TOKEN_DURATION_IN_SECONDS,
THIRDWEB_AUTH_TOKEN_COOKIE_PREFIX,
} from "../../constants";
import { getCookie } from "../helpers/user";
import { z } from "zod";
export const switchAccountHandler = (
fastify: FastifyInstanceWithZod,
ctx: ThirdwebAuthContext,
) => {
fastify.route<{
Body: z.infer<typeof ActiveBodySchema>;
}>({
method: "POST",
url: "/switch-account",
schema: {
body: ActiveBodySchema,
response: {
200: z.any(),
400: ErrorResponseSchema,
},
},
handler: async (req, res) => {
let cookieExpiration: Date;
const cookie = getCookie(
req,
`${THIRDWEB_AUTH_TOKEN_COOKIE_PREFIX}_${req.body.address}`,
);
if (cookie) {
// If the new account is already logged in, get the expiration time from the cookie
const {
payload: { exp },
} = ctx.auth.parseToken(cookie);
cookieExpiration = new Date(exp * 1000);
} else if (ctx.authOptions?.tokenDurationInSeconds) {
// Otherwise, if we have a token duration in seconds, set it to that
cookieExpiration = new Date(
Date.now() + 1000 * ctx.authOptions.tokenDurationInSeconds,
);
} else {
// Otherwise, just default to 24 hours
cookieExpiration = new Date(
Date.now() + 1000 * THIRDWEB_AUTH_DEFAULT_TOKEN_DURATION_IN_SECONDS,
);
}
res.setCookie(THIRDWEB_AUTH_ACTIVE_ACCOUNT_COOKIE, req.body.address, {
domain: ctx.cookieOptions?.domain,
path: ctx.cookieOptions?.path || "/",
sameSite: ctx.cookieOptions?.sameSite || "none",
expires: cookieExpiration,
httpOnly: true,
secure: ctx.cookieOptions?.secure || true,
});
return res.status(200).send();
},
});
};
+80
View File
@@ -0,0 +1,80 @@
import { getToken, getUser } from "../helpers/user";
import { FastifyInstanceWithZod, ThirdwebAuthContext } from "../types";
import {
THIRDWEB_AUTH_ACTIVE_ACCOUNT_COOKIE,
THIRDWEB_AUTH_DEFAULT_REFRESH_INTERVAL_IN_SECONDS,
THIRDWEB_AUTH_TOKEN_COOKIE_PREFIX,
} from "../../constants";
import { z } from "zod";
export const userHandler = (
fastify: FastifyInstanceWithZod,
ctx: ThirdwebAuthContext,
) => {
fastify.route({
method: "GET",
url: "/user",
schema: {
response: {
200: z.any(),
},
},
handler: async (req, res) => {
const user = await getUser(req, ctx);
// Importantly, make sure the user was actually logged in before refreshing
if (user) {
const token = getToken(req);
if (token) {
const payload = ctx.auth.parseToken(token);
const refreshDate = ctx.authOptions?.refreshIntervalInSeconds
? new Date(
payload.payload.iat * 1000 +
ctx.authOptions.refreshIntervalInSeconds * 1000,
)
: new Date(
payload.payload.iat * 1000 +
THIRDWEB_AUTH_DEFAULT_REFRESH_INTERVAL_IN_SECONDS * 1000,
);
if (new Date() > refreshDate) {
const expirationTime = ctx.authOptions?.tokenDurationInSeconds
? new Date(
Date.now() + 1000 * ctx.authOptions.tokenDurationInSeconds,
)
: undefined;
const refreshedToken = await ctx.auth.refresh(
token,
expirationTime,
);
const refreshedPayload = ctx.auth.parseToken(refreshedToken);
res.setCookie(
`${THIRDWEB_AUTH_TOKEN_COOKIE_PREFIX}_${user.address}`,
refreshedToken,
{
domain: ctx.cookieOptions?.domain,
path: ctx.cookieOptions?.path || "/",
sameSite: ctx.cookieOptions?.sameSite || "none",
expires: new Date(refreshedPayload.payload.exp * 1000),
httpOnly: true,
secure: ctx.cookieOptions?.secure || true,
},
);
res.setCookie(THIRDWEB_AUTH_ACTIVE_ACCOUNT_COOKIE, user.address, {
domain: ctx.cookieOptions?.domain,
path: ctx.cookieOptions?.path || "/",
sameSite: ctx.cookieOptions?.sameSite || "none",
expires: new Date(refreshedPayload.payload.exp * 1000),
httpOnly: true,
secure: ctx.cookieOptions?.secure || true,
});
}
}
}
return res.status(200).send(user);
},
});
};
+94
View File
@@ -0,0 +1,94 @@
import { GenericAuthWallet } from "@thirdweb-dev/wallets";
import { Json, LoginPayloadOutputSchema, ThirdwebAuth, User } from "../../core";
import {
FastifyBaseLogger,
FastifyInstance,
FastifyRequest,
RawServerDefault,
} from "fastify";
import { z } from "zod";
import { IncomingMessage, ServerResponse } from "http";
import { ZodTypeProvider } from "fastify-type-provider-zod";
export const PayloadBodySchema = z.object({
address: z.string(),
chainId: z.string().optional(),
});
export const ActiveBodySchema = z.object({
address: z.string(),
});
export const LoginPayloadBodySchema = z.object({
payload: LoginPayloadOutputSchema,
});
export const ErrorResponseSchema = z.object({
error: z.string(),
});
export type ThirdwebAuthUser<
TData extends Json = Json,
TSession extends Json = Json,
> = User<TSession> & {
data?: TData;
};
export type ThirdwebAuthConfig<
TData extends Json = Json,
TSession extends Json = Json,
> = {
domain: string;
wallet: GenericAuthWallet;
authOptions?: {
statement?: string;
uri?: string;
version?: string;
chainId?: string;
resources?: string[];
validateNonce?:
| ((nonce: string) => void)
| ((nonce: string) => Promise<void>);
validateTokenId?:
| ((tokenId: string) => void)
| ((tokenId: string) => Promise<void>);
loginPayloadDurationInSeconds?: number;
tokenDurationInSeconds?: number;
refreshIntervalInSeconds?: number;
};
cookieOptions?: {
domain?: string;
path?: string;
sameSite?: "lax" | "strict" | "none";
secure?: boolean;
};
callbacks?: {
onLogin?:
| ((address: string, req: FastifyRequest) => void | TSession)
| ((address: string, req: FastifyRequest) => Promise<void | TSession>);
onToken?:
| ((token: string, req: FastifyRequest) => void)
| ((token: string, req: FastifyRequest) => Promise<void>);
onUser?:
| ((user: User<TSession>, req: FastifyRequest) => void | TData)
| ((user: User<TSession>, req: FastifyRequest) => Promise<void | TData>);
onLogout?:
| ((user: User, req: FastifyRequest) => void)
| ((user: User, req: FastifyRequest) => Promise<void>);
};
};
export type ThirdwebAuthContext<
TData extends Json = Json,
TSession extends Json = Json,
> = Omit<Omit<ThirdwebAuthConfig<TData, TSession>, "wallet">, "domain"> & {
auth: ThirdwebAuth;
};
export type FastifyInstanceWithZod = FastifyInstance<
RawServerDefault,
IncomingMessage,
ServerResponse<IncomingMessage>,
FastifyBaseLogger,
ZodTypeProvider
>;
+1 -1
View File
@@ -2,7 +2,7 @@ import {
THIRDWEB_AUTH_ACTIVE_ACCOUNT_COOKIE,
THIRDWEB_AUTH_TOKEN_COOKIE_PREFIX,
} from "../../constants";
import { Json } from "../../core/schema";
import { Json } from "../../core";
import { ThirdwebAuthContext, ThirdwebAuthUser } from "../types";
import { GetServerSidePropsContext, NextApiRequest } from "next";
import { NextRequest } from "next/server";
+8 -4
View File
@@ -2,7 +2,7 @@ import {
THIRDWEB_AUTH_ACTIVE_ACCOUNT_COOKIE,
THIRDWEB_AUTH_TOKEN_COOKIE_PREFIX,
} from "../../constants";
import { GenerateOptions } from "../../core";
import { GenerateOptionsWithOptionalDomain } from "../../core";
import { LoginPayloadBodySchema, ThirdwebAuthContext } from "../types";
import { serialize } from "cookie";
import { NextApiRequest, NextApiResponse } from "next";
@@ -41,7 +41,7 @@ export default async function handler(
? new Date(Date.now() + 1000 * ctx.authOptions.tokenDurationInSeconds)
: undefined;
const generateOptions: GenerateOptions = {
const generateOptions: GenerateOptionsWithOptionalDomain = {
verifyOptions: {
statement: ctx.authOptions?.statement,
uri: ctx.authOptions?.uri,
@@ -68,6 +68,10 @@ export default async function handler(
}
}
if (ctx.callbacks?.onToken) {
await ctx.callbacks.onToken(token, req);
}
const {
payload: { exp },
} = ctx.auth.parseToken(token);
@@ -84,7 +88,7 @@ export default async function handler(
sameSite: ctx.cookieOptions?.sameSite || "none",
expires: new Date(exp * 1000),
httpOnly: true,
secure: true,
secure: ctx.cookieOptions?.secure || true,
},
),
serialize(THIRDWEB_AUTH_ACTIVE_ACCOUNT_COOKIE, payload.payload.address, {
@@ -93,7 +97,7 @@ export default async function handler(
sameSite: ctx.cookieOptions?.sameSite || "none",
expires: new Date(exp * 1000),
httpOnly: true,
secure: true,
secure: ctx.cookieOptions?.secure || true,
}),
]);
+1 -1
View File
@@ -37,7 +37,7 @@ export default async function handler(
sameSite: ctx.cookieOptions?.sameSite || "none",
expires: new Date(Date.now() + 5 * 1000),
httpOnly: true,
secure: true,
secure: ctx.cookieOptions?.secure || true,
}),
);
@@ -55,7 +55,7 @@ export default async function handler(
sameSite: ctx.cookieOptions?.sameSite || "none",
expires: cookieExpiration,
httpOnly: true,
secure: true,
secure: ctx.cookieOptions?.secure || true,
}),
]);
+2 -2
View File
@@ -53,7 +53,7 @@ export default async function handler(
sameSite: ctx.cookieOptions?.sameSite || "none",
expires: new Date(refreshedPayload.payload.exp * 1000),
httpOnly: true,
secure: true,
secure: ctx.cookieOptions?.secure || true,
},
),
serialize(THIRDWEB_AUTH_ACTIVE_ACCOUNT_COOKIE, user.address, {
@@ -62,7 +62,7 @@ export default async function handler(
sameSite: ctx.cookieOptions?.sameSite || "none",
expires: new Date(refreshedPayload.payload.exp * 1000),
httpOnly: true,
secure: true,
secure: ctx.cookieOptions?.secure || true,
}),
]);
}
+10 -6
View File
@@ -62,23 +62,27 @@ export type ThirdwebAuthConfig<
domain?: string;
path?: string;
sameSite?: "lax" | "strict" | "none";
secure?: boolean;
};
callbacks?: {
onLogin?:
| ((address: string, req?: NextApiRequest) => void | TSession)
| ((address: string, req?: NextApiRequest) => Promise<void | TSession>);
| ((address: string, req: NextApiRequest) => void | TSession)
| ((address: string, req: NextApiRequest) => Promise<void | TSession>);
onToken?:
| ((token: string, req: NextApiRequest) => void)
| ((token: string, req: NextApiRequest) => Promise<void>);
onUser?:
| (<TRequestType extends RequestType = RequestType>(
user: User<TSession>,
req?: TRequestType,
req: TRequestType,
) => void | TData)
| (<TRequestType extends RequestType = RequestType>(
user: User<TSession>,
req?: TRequestType,
req: TRequestType,
) => Promise<void | TData>);
onLogout?:
| ((user: User, req?: NextApiRequest) => void)
| ((user: User, req?: NextApiRequest) => Promise<void>);
| ((user: User, req: NextApiRequest) => void)
| ((user: User, req: NextApiRequest) => Promise<void>);
};
};
+10
View File
@@ -1,5 +1,15 @@
# thirdweb
## 0.13.8
### Patch Changes
- Updated dependencies [[`5ffbcfc3`](https://github.com/thirdweb-dev/js/commit/5ffbcfc302f74167768b196d93a328f979344036), [`42ba15f2`](https://github.com/thirdweb-dev/js/commit/42ba15f2c0e77e23e62650119dfaaa5c0dbe4481), [`d27a3dee`](https://github.com/thirdweb-dev/js/commit/d27a3dee8398d5707d2d1343c428abf8e03f67e3), [`c238fde8`](https://github.com/thirdweb-dev/js/commit/c238fde8777fd14b39837117e2d3fda1dd301029), [`99d7ec06`](https://github.com/thirdweb-dev/js/commit/99d7ec06ec4f31308627edc87d3122c21a884b5a), [`ff996646`](https://github.com/thirdweb-dev/js/commit/ff996646b228d4d095eea04b05004dd26fc7e522), [`d8d48a95`](https://github.com/thirdweb-dev/js/commit/d8d48a9516fc8fdd173fbb91a858fe7ec0725ddd), [`aa9f48d1`](https://github.com/thirdweb-dev/js/commit/aa9f48d1361194fc81146da530c95a3409bd0799), [`fd7a9f09`](https://github.com/thirdweb-dev/js/commit/fd7a9f09989e39b02a93d9dfd01cc7378e6ead53), [`fd7a9f09`](https://github.com/thirdweb-dev/js/commit/fd7a9f09989e39b02a93d9dfd01cc7378e6ead53), [`2307f11a`](https://github.com/thirdweb-dev/js/commit/2307f11ab311aa4a775edd23e777d10f8015ce86), [`54860198`](https://github.com/thirdweb-dev/js/commit/548601981f6dd8706d7a9bd4ca48e4abc7723a1d), [`64138642`](https://github.com/thirdweb-dev/js/commit/64138642e84d8b56b254762eca613d443cca292b), [`6d1eabe9`](https://github.com/thirdweb-dev/js/commit/6d1eabe9f9818ee2a79ce5bf6aa74417dbfd0558), [`c238fde8`](https://github.com/thirdweb-dev/js/commit/c238fde8777fd14b39837117e2d3fda1dd301029)]:
- @thirdweb-dev/wallets@2.0.8
- @thirdweb-dev/sdk@4.0.7
- @thirdweb-dev/auth@4.1.0
- @thirdweb-dev/storage@2.0.1
## 0.13.7
### Patch Changes
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "thirdweb",
"main": "dist/cli/index.js",
"version": "0.13.7",
"version": "0.13.8",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/cli",
"author": "thirdweb eng <[email protected]>",
"license": "Apache-2.0",
+12
View File
@@ -1,5 +1,17 @@
# @thirdweb-dev/react-core
## 4.0.8
### Patch Changes
- [#1787](https://github.com/thirdweb-dev/js/pull/1787) [`ff996646`](https://github.com/thirdweb-dev/js/commit/ff996646b228d4d095eea04b05004dd26fc7e522) Thanks [@MananTank](https://github.com/MananTank)! - Enable typedoc for packages
- Updated dependencies [[`5ffbcfc3`](https://github.com/thirdweb-dev/js/commit/5ffbcfc302f74167768b196d93a328f979344036), [`42ba15f2`](https://github.com/thirdweb-dev/js/commit/42ba15f2c0e77e23e62650119dfaaa5c0dbe4481), [`d27a3dee`](https://github.com/thirdweb-dev/js/commit/d27a3dee8398d5707d2d1343c428abf8e03f67e3), [`c238fde8`](https://github.com/thirdweb-dev/js/commit/c238fde8777fd14b39837117e2d3fda1dd301029), [`99d7ec06`](https://github.com/thirdweb-dev/js/commit/99d7ec06ec4f31308627edc87d3122c21a884b5a), [`ff996646`](https://github.com/thirdweb-dev/js/commit/ff996646b228d4d095eea04b05004dd26fc7e522), [`d8d48a95`](https://github.com/thirdweb-dev/js/commit/d8d48a9516fc8fdd173fbb91a858fe7ec0725ddd), [`aa9f48d1`](https://github.com/thirdweb-dev/js/commit/aa9f48d1361194fc81146da530c95a3409bd0799), [`fd7a9f09`](https://github.com/thirdweb-dev/js/commit/fd7a9f09989e39b02a93d9dfd01cc7378e6ead53), [`fd7a9f09`](https://github.com/thirdweb-dev/js/commit/fd7a9f09989e39b02a93d9dfd01cc7378e6ead53), [`2307f11a`](https://github.com/thirdweb-dev/js/commit/2307f11ab311aa4a775edd23e777d10f8015ce86), [`54860198`](https://github.com/thirdweb-dev/js/commit/548601981f6dd8706d7a9bd4ca48e4abc7723a1d), [`64138642`](https://github.com/thirdweb-dev/js/commit/64138642e84d8b56b254762eca613d443cca292b), [`6d1eabe9`](https://github.com/thirdweb-dev/js/commit/6d1eabe9f9818ee2a79ce5bf6aa74417dbfd0558), [`c238fde8`](https://github.com/thirdweb-dev/js/commit/c238fde8777fd14b39837117e2d3fda1dd301029)]:
- @thirdweb-dev/wallets@2.0.8
- @thirdweb-dev/sdk@4.0.7
- @thirdweb-dev/auth@4.1.0
- @thirdweb-dev/storage@2.0.1
## 4.0.7
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@thirdweb-dev/react-core",
"version": "4.0.7",
"version": "4.0.8",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react-core",
"author": "thirdweb eng <[email protected]>",
"license": "Apache-2.0",
@@ -1,2 +1,3 @@
/** @internal */
// eslint-disable-next-line turbo/no-undeclared-env-vars, better-tree-shaking/no-top-level-side-effects
export const __DEV__ = process.env.NODE_ENV !== "production";
@@ -8,6 +8,7 @@ import type {
LocalWallet,
MagicLink,
MetaMaskWallet,
OKXWallet,
PaperWallet,
PhantomWallet,
RainbowWallet,
@@ -37,6 +38,7 @@ type WalletIdToWalletTypeMap = {
walletConnect: WalletConnect;
phantom: PhantomWallet;
walletConnectV1: WalletConnect;
okx: OKXWallet;
};
/**
@@ -1,5 +1,7 @@
# @thirdweb-dev/react-native-compat
## 0.3.13
## 0.3.12
## 0.3.11
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@thirdweb-dev/react-native-compat",
"description": "Shims for Thirdweb in React Native Projects",
"version": "0.3.12",
"version": "0.3.13",
"author": "thirdweb eng <[email protected]>",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react-native-compat",
"license": "Apache-2.0",
+4
View File
@@ -1,6 +1,10 @@
module.exports = {
root: true,
extends: ["thirdweb"],
plugins: ["i18next"],
rules: {
"i18next/no-literal-string": 2,
},
settings: {
// https://github.com/facebook/react-native/issues/28549
"import/ignore": ["react-native"],
+28
View File
@@ -1,5 +1,33 @@
# @thirdweb-dev/react-native
## 0.3.13
### Patch Changes
- [#1803](https://github.com/thirdweb-dev/js/pull/1803) [`a63f5dc7`](https://github.com/thirdweb-dev/js/commit/a63f5dc7cb173bcb4dc5d17ccb0936411f9973e6) Thanks [@iketw](https://github.com/iketw)! - React Native UI/theme improvements
- [#1787](https://github.com/thirdweb-dev/js/pull/1787) [`ff996646`](https://github.com/thirdweb-dev/js/commit/ff996646b228d4d095eea04b05004dd26fc7e522) Thanks [@MananTank](https://github.com/MananTank)! - Enable typedoc for packages
- [#1799](https://github.com/thirdweb-dev/js/pull/1799) [`1cc26e43`](https://github.com/thirdweb-dev/js/commit/1cc26e43e533440abdb5c9df24ccd2ace671f413) Thanks [@iketw](https://github.com/iketw)! - Adds localization for the React Native SDK
You can now pass a Locale object to the ThirdwebProvider with your translations:
```javascript
import { ThirdwebProvicer, en } from @thirdweb-dev/react-native;
<ThirdwebProvider locale={{
...your-translated-strings
}}>
<App />
</ThirdwebProvider>
```
- Updated dependencies [[`5ffbcfc3`](https://github.com/thirdweb-dev/js/commit/5ffbcfc302f74167768b196d93a328f979344036), [`42ba15f2`](https://github.com/thirdweb-dev/js/commit/42ba15f2c0e77e23e62650119dfaaa5c0dbe4481), [`d27a3dee`](https://github.com/thirdweb-dev/js/commit/d27a3dee8398d5707d2d1343c428abf8e03f67e3), [`ff996646`](https://github.com/thirdweb-dev/js/commit/ff996646b228d4d095eea04b05004dd26fc7e522), [`d8d48a95`](https://github.com/thirdweb-dev/js/commit/d8d48a9516fc8fdd173fbb91a858fe7ec0725ddd), [`aa9f48d1`](https://github.com/thirdweb-dev/js/commit/aa9f48d1361194fc81146da530c95a3409bd0799), [`fd7a9f09`](https://github.com/thirdweb-dev/js/commit/fd7a9f09989e39b02a93d9dfd01cc7378e6ead53), [`fd7a9f09`](https://github.com/thirdweb-dev/js/commit/fd7a9f09989e39b02a93d9dfd01cc7378e6ead53), [`2307f11a`](https://github.com/thirdweb-dev/js/commit/2307f11ab311aa4a775edd23e777d10f8015ce86), [`64138642`](https://github.com/thirdweb-dev/js/commit/64138642e84d8b56b254762eca613d443cca292b), [`6d1eabe9`](https://github.com/thirdweb-dev/js/commit/6d1eabe9f9818ee2a79ce5bf6aa74417dbfd0558)]:
- @thirdweb-dev/[email protected]
- @thirdweb-dev/[email protected]
- @thirdweb-dev/[email protected]
- @thirdweb-dev/[email protected]
## 0.3.12
### Patch Changes
+7 -4
View File
@@ -10,13 +10,16 @@
<a href="https://discord.gg/thirdweb"><img alt="Join our Discord!" src="https://img.shields.io/discord/834227967404146718.svg?color=7289da&label=discord&logo=discord&style=flat"/></a>
</p>
<p align="center"><strong>Powering react-native dapps.</strong></p>
<br />
<p><strong>Powering react-native dapps.</strong></p>
## 👷🚧 Alpha 🚧👷
The go to librarly for seamless Web3 integration in React Native apps.
<br />
## Getting Started
Head over to the [documentation](https://portal.thirdweb.com/react-native) to learn more
Try it out by running:
`npx thirdweb create --template react-native-typescript-starter`
or head over to the [documentation](https://portal.thirdweb.com/react-native) to learn more
+11 -7
View File
@@ -1,6 +1,6 @@
{
"name": "@thirdweb-dev/react-native",
"version": "0.3.12",
"version": "0.3.13",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react-native",
"author": "thirdweb eng <[email protected]>",
"license": "Apache-2.0",
@@ -16,7 +16,8 @@
"fix": "eslint src/ --fix",
"clean": "rm -rf dist/",
"build": "tsc",
"push": "yalc push"
"push": "yalc push",
"typedoc": "rimraf typedoc && node ./scripts/typedoc.js"
},
"keywords": [
"react-native",
@@ -65,6 +66,7 @@
"eslint": "^8.45.0",
"eslint-config-prettier": "^8.9.0",
"eslint-config-thirdweb": "workspace:*",
"eslint-plugin-i18next": "^6.0.3",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-inclusive-language": "^2.2.0",
"eslint-plugin-prettier": "^5.0.0",
@@ -79,18 +81,20 @@
"react-native-mmkv": "2.5.1",
"react-native-safe-area-context": "4.5.3",
"react-native-webview": "12.1.0",
"rimraf": "^3.0.2",
"typedoc": "^0.25.2",
"typescript": "^5.1.6"
},
"optionalDependencies": {
"amazon-cognito-identity-js": "^6.3.3",
"react-native-aes-gcm-crypto": "^0.2.2",
"react-native-camera": "^4.2.1",
"react-native-device-info": "10.6.0",
"react-native-safe-area-context": "4.5.3",
"react-native-webview": "12.1.0",
"amazon-cognito-identity-js": "^6.3.3",
"react-native-inappbrowser-reborn": "^3.7.0",
"react-native-quick-base64": "^2.0.7",
"react-native-quick-crypto": "^0.6.1",
"react-native-aes-gcm-crypto": "^0.2.2",
"react-native-inappbrowser-reborn": "^3.7.0"
"react-native-safe-area-context": "4.5.3",
"react-native-webview": "12.1.0"
},
"peerDependencies": {
"ethers": ">=5.5.1 <6",
+38
View File
@@ -0,0 +1,38 @@
// eslint-disable-next-line @typescript-eslint/no-var-requires
const TypeDoc = require("typedoc");
async function main() {
// Application.bootstrap also exists, which will not load plugins
// Also accepts an array of option readers if you want to disable
// TypeDoc's tsconfig.json/package.json/typedoc.json option readers
const app = await TypeDoc.Application.bootstrapWithPlugins({
entryPoints: ["src/index.ts"],
excludeInternal: true,
externalPattern: [
"**/node_modules/**",
"**/packages/sdk/**",
"**/packages/wallets/**",
"**/packages/chains/**",
],
exclude: [
"**/node_modules/**",
"**/packages/sdk/**",
"**/packages/wallets/**",
"**/packages/chains/**",
],
});
const project = await app.convert();
if (project) {
// Project may not have converted correctly
const outputDir = "typedoc/";
// Rendered docs
await app.generateDocs(project, outputDir);
// Alternatively generate JSON output
await app.generateJson(project, outputDir + "/documentation.json");
}
}
main();
@@ -1,12 +1,12 @@
import Svg, { Path } from "react-native-svg";
import { IconStyleProp } from "./types";
const CloseIcon = ({ width, height }: IconStyleProp) => {
const CloseIcon = ({ width, height, color }: IconStyleProp) => {
return (
<Svg width={width} height={height} viewBox="0 0 14 14" fill="none">
<Path
d="M13.3002 0.70998C13.2077 0.617276 13.0978 0.543728 12.9768 0.493547C12.8559 0.443366 12.7262 0.417535 12.5952 0.417535C12.4643 0.417535 12.3346 0.443366 12.2136 0.493547C12.0926 0.543728 11.9827 0.617276 11.8902 0.70998L7.00022 5.58998L2.11022 0.699979C2.01764 0.607397 1.90773 0.533957 1.78677 0.483852C1.6658 0.433747 1.53615 0.407959 1.40522 0.407959C1.27429 0.407959 1.14464 0.433747 1.02368 0.483852C0.902716 0.533957 0.792805 0.607397 0.700223 0.699979C0.607642 0.792561 0.534202 0.902472 0.484097 1.02344C0.433992 1.1444 0.408203 1.27405 0.408203 1.40498C0.408203 1.53591 0.433992 1.66556 0.484097 1.78652C0.534202 1.90749 0.607642 2.0174 0.700223 2.10998L5.59022 6.99998L0.700223 11.89C0.607642 11.9826 0.534202 12.0925 0.484097 12.2134C0.433992 12.3344 0.408203 12.464 0.408203 12.595C0.408203 12.7259 0.433992 12.8556 0.484097 12.9765C0.534202 13.0975 0.607642 13.2074 0.700223 13.3C0.792805 13.3926 0.902716 13.466 1.02368 13.5161C1.14464 13.5662 1.27429 13.592 1.40522 13.592C1.53615 13.592 1.6658 13.5662 1.78677 13.5161C1.90773 13.466 2.01764 13.3926 2.11022 13.3L7.00022 8.40998L11.8902 13.3C11.9828 13.3926 12.0927 13.466 12.2137 13.5161C12.3346 13.5662 12.4643 13.592 12.5952 13.592C12.7262 13.592 12.8558 13.5662 12.9768 13.5161C13.0977 13.466 13.2076 13.3926 13.3002 13.3C13.3928 13.2074 13.4662 13.0975 13.5163 12.9765C13.5665 12.8556 13.5922 12.7259 13.5922 12.595C13.5922 12.464 13.5665 12.3344 13.5163 12.2134C13.4662 12.0925 13.3928 11.9826 13.3002 11.89L8.41022 6.99998L13.3002 2.10998C13.6802 1.72998 13.6802 1.08998 13.3002 0.70998Z"
fill="#646D7A"
fill={color}
/>
</Svg>
);
@@ -14,7 +14,7 @@ import { ConnectWalletButton } from "./ConnectWalletFlow/ConnectWalletButton";
import { ConnectWalletButtonProps } from "./ConnectWalletFlow/ConnectWalletButton";
import BaseButton from "./base/BaseButton";
import Text from "./base/Text";
import { useUIContext } from "../providers/ui-context-provider";
import { useLocale, useUIContext } from "../providers/ui-context-provider";
import { ThemeProvider } from "../styles/ThemeProvider";
import { SupportedTokens, defaultTokens } from "./SendFunds/defaultTokens";
@@ -81,6 +81,7 @@ export const ConnectWallet = ({
privacyPolicyUrl,
supportedTokens,
}: ConnectWalletProps) => {
const l = useLocale();
const fadeAnim = useRef(new Animated.Value(0)).current;
const address = useAddress();
const isNetworkMismatch = useNetworkMismatch();
@@ -142,7 +143,7 @@ export const ConnectWallet = ({
<ActivityIndicator size="small" color="buttonTextColor" />
) : (
<Text variant="bodyLarge" color="buttonTextColor">
Switch Network
{l.common.switch_network}
</Text>
)}
</BaseButton>
@@ -13,9 +13,11 @@ import { WalletIcon } from "../base/WalletIcon";
import WalletConnectIcon from "../../assets/wallet-connect";
import QrCodeIcon from "../../assets/qr-code";
import { QRCodeScan } from "./QRCodeScan";
import { useLocale } from "../../providers/ui-context-provider";
const ConnectAppField = () => {
const theme = useTheme();
const l = useLocale();
const [showWCInput, setShowWCInput] = useState(false);
const [wcUri, setWCUri] = useState<string | undefined>();
const [appMeta, setAppMeta] = useState<{ name: string; iconUrl: string }>();
@@ -130,6 +132,10 @@ const ConnectAppField = () => {
placeholder: "wc://...",
placeholderTextColor: theme.colors.textSecondary,
numberOfLines: 1,
style: {
color: theme.colors.textPrimary,
fontFamily: theme.textVariants.defaults.fontFamily,
},
}}
containerProps={{
flex: 1,
@@ -177,7 +183,7 @@ const ConnectAppField = () => {
)}
<View style={styles.exportWalletInfo}>
<Text variant="bodySmall" numberOfLines={1}>
{appMeta ? appMeta.name : "Connect app"}
{appMeta ? appMeta.name : l.common.connect_app}
</Text>
</View>
</>
@@ -29,6 +29,7 @@ import { SendButton } from "../SendFunds/SendButton";
import { SupportedTokens } from "../SendFunds/defaultTokens";
import { ActiveDot } from "../base";
import { EmbeddedWallet } from "../../wallets/wallets/embedded/EmbeddedWallet";
import { useLocale } from "../../providers/ui-context-provider";
const MODAL_HEIGHT = Dimensions.get("window").height * 0.7;
const DEVICE_WIDTH = Dimensions.get("window").width;
@@ -50,6 +51,7 @@ export const ConnectWalletDetailsModal = ({
supportedTokens: SupportedTokens;
displayBalanceToken?: Record<number, string>;
}) => {
const l = useLocale();
const [isExportModalVisible, setIsExportModalVisible] = useState(false);
const activeWallet = useWallet();
const chain = useChain();
@@ -137,11 +139,15 @@ export const ConnectWalletDetailsModal = ({
return (
<>
<View style={styles.currentNetwork}>
<Text variant="bodySmallSecondary">Additional Actions</Text>
<Text variant="bodySmallSecondary">
{l.connect_wallet_details.additional_actions}
</Text>
</View>
<BaseButton
backgroundColor="background"
borderColor="border"
borderRadius="lg"
borderWidth={0.5}
mb="sm"
justifyContent="space-between"
style={styles.exportWallet}
@@ -150,7 +156,9 @@ export const ConnectWalletDetailsModal = ({
<>
<PocketWalletIcon width={16} height={16} />
<View style={styles.exportWalletInfo}>
<Text variant="bodySmall">Backup wallet</Text>
<Text variant="bodySmall">
{l.connect_wallet_details.backup_wallet}
</Text>
</View>
</>
<RightArrowIcon height={10} width={10} />
@@ -159,6 +167,8 @@ export const ConnectWalletDetailsModal = ({
<BaseButton
backgroundColor="background"
borderColor="border"
borderRadius="lg"
borderWidth={0.5}
mb="sm"
justifyContent="space-between"
style={styles.exportWallet}
@@ -167,7 +177,9 @@ export const ConnectWalletDetailsModal = ({
<>
<PocketWalletIcon width={16} height={16} />
<View style={styles.exportWalletInfo}>
<Text variant="bodySmall">Import wallet</Text>
<Text variant="bodySmall">
{l.connect_wallet_details.import_wallet}
</Text>
</View>
</>
<RightArrowIcon height={10} width={10} />
@@ -181,9 +193,7 @@ export const ConnectWalletDetailsModal = ({
{activeWallet?.walletId === LocalWallet.id ? (
<Text variant="error" textAlign="left" mb="sm">
{
"This is a temporary guest wallet. Download a backup if you don't want to lose access to it."
}
{l.local_wallet.this_is_a_temporary_wallet}
</Text>
) : null}
</>
@@ -197,6 +207,7 @@ export const ConnectWalletDetailsModal = ({
onExportLocalWalletPress,
onWalletImported,
smartWallet,
l,
]);
return (
@@ -230,7 +241,7 @@ export const ConnectWalletDetailsModal = ({
<Box flexDirection="row" alignItems="center">
<ActiveDot width={10} height={10} />
<Text variant="bodySmallSecondary" ml="xxs">
Connected to a Smart Wallet
{l.connect_wallet_details.connected_to_smart_wallet}
</Text>
</Box>
{isSmartWalletDeployed ? (
@@ -256,13 +267,15 @@ export const ConnectWalletDetailsModal = ({
<ReceiveButton />
</Box>
<View style={styles.currentNetwork}>
<Text variant="bodySmallSecondary">Current Network</Text>
<Text variant="bodySmallSecondary">
{l.connect_wallet_details.current_network}
</Text>
</View>
<NetworkButton chain={chain} enableSwitchModal={true} />
{!hideTestnetFaucet && chain?.testnet && chain?.faucets?.length ? (
<IconTextButton
mt="xs"
text="Request Testnet Funds"
text={l.connect_wallet_details.request_testnet_funds}
icon={<MoneyIcon height={16} width={16} />}
onPress={() => {
if (chain?.faucets?.[0]) {
@@ -274,7 +287,7 @@ export const ConnectWalletDetailsModal = ({
{chain?.explorers && chain?.explorers?.[0] && (
<IconTextButton
mt="xs"
text="View Transaction History"
text={l.connect_wallet_details.view_transaction_history}
icon={<TransactionIcon height={16} width={16} />}
onPress={() => {
Linking.openURL(
@@ -323,8 +336,6 @@ const styles = StyleSheet.create({
alignContent: "center",
alignItems: "center",
justifyContent: "flex-start",
borderRadius: 12,
borderWidth: 0.5,
paddingHorizontal: 10,
paddingVertical: 12,
minWidth: 200,
@@ -336,5 +347,6 @@ const styles = StyleSheet.create({
alignItems: "flex-start",
justifyContent: "flex-start",
marginBottom: 8,
marginTop: 12,
},
});
@@ -18,6 +18,7 @@ import { usePersonalWalletAddress } from "../../wallets/hooks/usePersonalWalletA
import { shortenWalletAddress } from "../../utils/addresses";
import { LocalWallet } from "../../wallets/wallets/LocalWallet";
import { TWModal } from "../base/modal/TWModal";
import { useLocale } from "../../providers/ui-context-provider";
export type ExportLocalWalletModalProps = {
isVisible: boolean;
@@ -28,6 +29,7 @@ export const ExportLocalWalletModal = ({
isVisible,
onClose,
}: ExportLocalWalletModalProps) => {
const l = useLocale();
const [password, setPassword] = useState<string | undefined>();
const [error, setError] = useState<string | undefined>();
const [isExporting, setIsExporting] = useState<boolean>(false);
@@ -151,15 +153,13 @@ export const ExportLocalWalletModal = ({
>
<ModalHeaderTextClose
onClose={onCloseInternal}
headerText="Backup your Wallet"
headerText={l.local_wallet.backup_your_wallet}
/>
<Text variant="subHeader" mt="md" textAlign="left">
{
"This will download a JSON file containing your wallet information onto your device encrypted with the password."
}
{l.local_wallet.this_will_download_json}
</Text>
<Text variant="bodySmall" textAlign="left" mt="lg" mb="xxs">
Wallet Address
{l.local_wallet.wallet_address}
</Text>
<Text variant="bodySmallSecondary">
{shortenWalletAddress(
@@ -167,7 +167,7 @@ export const ExportLocalWalletModal = ({
)}
</Text>
<Text variant="bodySmall" textAlign="left" mt="lg" mb="xxs">
Password
{l.common.password}
</Text>
<PasswordInput onChangeText={onChangeText} />
<Text variant="bodySmall" color="red" mt="xs" textAlign="left">
@@ -183,7 +183,7 @@ export const ExportLocalWalletModal = ({
<ActivityIndicator size="small" color="buttonTextColor" />
) : (
<Text variant="bodySmall" color="black">
Backup
{l.connect_wallet_details.backup}
</Text>
)}
</BaseButton>
@@ -7,9 +7,10 @@ import {
CLOSE_MODAL_STATE,
WalletConnectSessionProposalModal,
} from "../../utils/modalTypes";
import { useModalState } from "../../providers/ui-context-provider";
import { useLocale, useModalState } from "../../providers/ui-context-provider";
export const SessionProposalModal = () => {
const l = useLocale();
const { modalState, setModalState } = useModalState();
const { data: proposalData } =
modalState as WalletConnectSessionProposalModal;
@@ -27,7 +28,7 @@ export const SessionProposalModal = () => {
borderRadius="md"
p="lg"
>
<Text variant="bodyLarge">Connect to App</Text>
<Text variant="bodyLarge">{l.connect_wallet_details.connect_to_app}</Text>
<Text variant="bodyLarge">{proposalData.proposer.metadata.name}</Text>
<Box flexDirection="row" justifyContent="space-evenly" mt="lg">
<BaseButton
@@ -44,7 +45,7 @@ export const SessionProposalModal = () => {
onClose();
}}
>
<Text variant="bodySmall">Reject</Text>
<Text variant="bodySmall">{l.common.reject}</Text>
</BaseButton>
<BaseButton
alignContent="center"
@@ -67,7 +68,7 @@ export const SessionProposalModal = () => {
}}
>
<Text variant="bodySmall" color="black">
Approve
{l.common.approve}
</Text>
</BaseButton>
</Box>
@@ -6,7 +6,7 @@ import {
EIP155_SIGNING_METHODS,
IWalletConnectReceiver,
} from "@thirdweb-dev/wallets";
import { useModalState } from "../../providers/ui-context-provider";
import { useLocale, useModalState } from "../../providers/ui-context-provider";
import {
CLOSE_MODAL_STATE,
WalletConnectSessionRequestModal,
@@ -30,6 +30,7 @@ const getTitle = (method: string) => {
const MODAL_HEIGHT = Dimensions.get("window").height * 0.7;
export const SessionRequestModal = () => {
const l = useLocale();
const { modalState, setModalState } = useModalState();
const { data: requestData } = modalState as WalletConnectSessionRequestModal;
const [approvingRequest, setApprovingRequest] = useState(false);
@@ -60,7 +61,7 @@ export const SessionRequestModal = () => {
case EIP155_SIGNING_METHODS.SWITCH_CHAIN:
return (
<Text variant="bodySmall" textAlign="left">
{`Switch to ${
{`${l.connect_wallet_details.switch_to} ${
requestData.params[0].chainId === chain?.chainId
? chain?.slug
: requestData.params[0].chainId
@@ -85,17 +86,17 @@ export const SessionRequestModal = () => {
return (
<Box>
<Text variant="bodySmall" textAlign="left">
{`from: ${shortenWalletAddress(from)}`}
{`${l.common.from}: ${shortenWalletAddress(from)}`}
</Text>
<Text variant="bodySmall" textAlign="left" mt="sm">
{`to: ${shortenWalletAddress(to)}`}
{`${l.common.to}: ${shortenWalletAddress(to)}`}
</Text>
</Box>
);
default:
throw new Error(`Method not implemented: ${requestData.method}`);
}
}, [chain?.chainId, chain?.slug, requestData]);
}, [chain?.chainId, chain?.slug, requestData, l]);
return (
<Box
@@ -129,7 +130,7 @@ export const SessionRequestModal = () => {
onClose();
}}
>
<Text variant="bodySmall">Reject</Text>
<Text variant="bodySmall">{l.common.reject}</Text>
</BaseButton>
<BaseButton
alignContent="center"
@@ -148,7 +149,7 @@ export const SessionRequestModal = () => {
<ActivityIndicator size="small" />
) : (
<Text variant="bodySmall" color="black">
Approve
{l.common.approve}
</Text>
)}
</BaseButton>
@@ -14,13 +14,14 @@ import RightArrowIcon from "../../assets/right-arrow";
import ConnectAppField from "./ConnectAppField";
import DisconnectIcon from "../../assets/disconnect";
import { IconTextButton } from "../base/IconTextButton";
import { useGlobalTheme } from "../../providers/ui-context-provider";
import { useGlobalTheme, useLocale } from "../../providers/ui-context-provider";
export const SmartWalletAdditionalActions = ({
onExportPress,
}: {
onExportPress: () => void;
}) => {
const l = useLocale();
const { setConnectedWallet } = useWalletContext();
const [smartWallet, setSmartWallet] = useSmartWallet();
const [smartWalletAddress, setSmartWalletAddress] = useState<string>("");
@@ -64,8 +65,8 @@ export const SmartWalletAdditionalActions = ({
mt="xs"
text={
showSmartWallet
? "Switch to Smart Wallet"
: "Switch to Personal Wallet"
? l.smart_wallet.switch_to_smart
: l.smart_wallet.switch_to_personal
}
icon={
<DisconnectIcon
@@ -85,6 +86,8 @@ export const SmartWalletAdditionalActions = ({
<BaseButton
backgroundColor="background"
borderColor="border"
borderRadius="lg"
borderWidth={0.5}
mb="sm"
mt="xs"
justifyContent="space-between"
@@ -96,8 +99,8 @@ export const SmartWalletAdditionalActions = ({
<View style={styles.exportWalletInfo}>
<Text variant="bodySmall">
{wallet?.walletId === walletIds.localWallet
? "Backup personal wallet"
: "Backup wallet"}
? l.connect_wallet_details.backup_personal_wallet
: l.connect_wallet_details.backup_wallet}
</Text>
</View>
</>
@@ -108,9 +111,7 @@ export const SmartWalletAdditionalActions = ({
/>
</BaseButton>
<Text variant="error" textAlign="left" mb="sm">
{
"This is a temporary guest wallet. Download a backup if you don't want to loose access to it."
}
{l.local_wallet.this_is_a_temporary_wallet}
</Text>
</>
) : null}
@@ -141,8 +142,6 @@ const styles = StyleSheet.create({
alignContent: "center",
alignItems: "center",
justifyContent: "flex-start",
borderRadius: 12,
borderWidth: 0.5,
paddingHorizontal: 10,
paddingVertical: 12,
minWidth: 200,
@@ -11,6 +11,7 @@ import { TextBalance } from "../base/TextBalance";
import { SupportedTokens } from "../SendFunds/defaultTokens";
import { SMART_WALLET_ICON } from "../../assets/svgs";
import { ImageSvgUri } from "../base";
import { useLocale } from "../../providers/ui-context-provider";
export type ConnectWalletDetailsProps = {
address?: string;
@@ -45,6 +46,7 @@ export const WalletDetailsButton = ({
supportedTokens,
displayBalanceToken,
}: ConnectWalletDetailsProps) => {
const l = useLocale();
const activeWallet = useWallet();
const [isModalVisible, setIsModalVisible] = useState(false);
const ensQuery = useENS();
@@ -100,7 +102,7 @@ export const WalletDetailsButton = ({
<Box ml="md" justifyContent="center" alignItems="flex-start">
{activeWallet?.walletId === LocalWallet.id ? (
<Text variant="bodySmall" color="red">
Guest
{l.connect_wallet_details.guest}
</Text>
) : ens ? (
<Text variant="bodySmall">{ens}</Text>
@@ -9,7 +9,10 @@ import { ChooseWalletContent } from "./ChooseWalletContent";
import { BaseButton, ImageSvgUri, WalletButton } from "../../base";
import { ActivityIndicator, Linking } from "react-native";
import { useTheme } from "@shopify/restyle";
import { useGlobalTheme } from "../../../providers/ui-context-provider";
import {
useGlobalTheme,
useLocale,
} from "../../../providers/ui-context-provider";
export type ChooseWalletProps = {
headerText?: ReactNode | string;
@@ -34,6 +37,7 @@ export function ChooseWallet({
termsOfServiceUrl,
privacyPolicyUrl,
}: ChooseWalletProps) {
const l = useLocale();
const theme = useGlobalTheme();
const themeLightDark = useTheme();
const [isConnecting, setIsConnecting] = useState(false);
@@ -122,14 +126,8 @@ export function ChooseWallet({
color={theme.colors.backgroundInverted}
/>
)}
<Text
variant="header"
ml="xxs"
fontWeight="700"
fontSize={20}
lineHeight={24}
>
Connect
<Text variant="headerBold" ml="xxs" fontSize={20} lineHeight={24}>
{l.connect_wallet_details.connect}
</Text>
</Box>
)
@@ -159,9 +157,11 @@ export function ChooseWallet({
justifyContent="space-between"
alignItems="center"
>
<Text variant="bodySmall">New to wallets?</Text>
<Text variant="bodySmall">
{l.connect_wallet_details.new_to_wallets}
</Text>
<BaseButton onPress={onGetStartedPress}>
<Text variant="link">Get started</Text>
<Text variant="link">{l.connect_wallet_details.get_started}</Text>
</BaseButton>
</Box>
</>
@@ -180,7 +180,6 @@ export function ChooseWallet({
!isConnectAWalletEnabled &&
(guestWallet || connectionWallets.length > 0) ? (
<Box
mb="md"
mt="md"
marginHorizontal="xl"
flexDirection="row"
@@ -189,7 +188,7 @@ export function ChooseWallet({
>
<Box height={1} flex={1} backgroundColor="border" />
<Text variant="subHeader" textAlign="center" marginHorizontal="xxs">
OR
{l.common.or}
</Text>
<Box height={1} flex={1} backgroundColor="border" />
</Box>
@@ -202,7 +201,7 @@ export function ChooseWallet({
marginHorizontal="xl"
paddingHorizontal="none"
paddingVertical="none"
mb="md"
mt="md"
walletIconUrl={connectionWallets[0].meta.iconURL}
name={connectionWallets[0].meta.name}
onPress={onSingleWalletPress}
@@ -212,6 +211,7 @@ export function ChooseWallet({
marginHorizontal="xl"
justifyContent="center"
borderRadius="lg"
mt="md"
paddingVertical="md"
borderColor="border"
flexDirection="row"
@@ -230,8 +230,8 @@ export function ChooseWallet({
</Box>
);
})}
<Text variant="bodySmall" fontWeight="700">
Connect a wallet
<Text variant="bodySmallBold">
{l.connect_wallet_details.connect_a_wallet}
</Text>
</BaseButton>
)
@@ -253,8 +253,8 @@ export function ChooseWallet({
color={theme.colors.textPrimary}
/>
) : (
<Text variant="bodySmall" fontWeight="700">
Continue as guest
<Text variant="bodySmallBold">
{l.connect_wallet_details.continue_as_guest}
</Text>
)}
</BaseButton>
@@ -266,7 +266,7 @@ export function ChooseWallet({
alignItems="center"
>
<Text variant="bodySmallSecondary" fontSize={10} lineHeight={14}>
By connecting, you agree to the
{l.connect_wallet_details.by_connecting_you_agree}
</Text>
<Box flexDirection="row" alignItems="center" justifyContent="center">
{termsOfServiceUrl ? (
@@ -281,7 +281,7 @@ export function ChooseWallet({
padding="none"
lineHeight={14}
>
Terms of Service
{l.connect_wallet_details.tos}
</Text>
</BaseButton>
) : null}
@@ -307,7 +307,7 @@ export function ChooseWallet({
padding="none"
lineHeight={14}
>
Privacy Policy
{l.connect_wallet_details.privacy_policy}
</Text>
</BaseButton>
) : null}
@@ -1,93 +0,0 @@
import { useMemo } from "react";
import type { WalletConfig } from "@thirdweb-dev/react-core";
import { FlatList, Dimensions } from "react-native";
import Box from "../../base/Box";
import { useTheme } from "@shopify/restyle";
import { WalletButtonSquare } from "../../base/WalletButtonSquare";
import Text from "../../base/Text";
const SCREEN_WIDTH = Dimensions.get("screen").width;
const SCREEN_HEIGHT = Dimensions.get("screen").height;
const MAX_HEIGHT = SCREEN_HEIGHT * 0.4;
const NUM_COLUMNS = 3;
const TILE_SIZE = SCREEN_WIDTH / NUM_COLUMNS;
interface ChooseWalletContentProps {
wallets: WalletConfig[];
excludeWalletIds?: string[];
onChooseWallet: (wallet: WalletConfig, data?: any) => void;
}
export const ChooseWalletContentSquare = ({
wallets,
excludeWalletIds,
onChooseWallet,
}: ChooseWalletContentProps) => {
const walletsToDisplay = useMemo(() => {
return wallets.filter(
(w) => !!!excludeWalletIds?.find((ewId) => ewId === w.id),
);
}, [wallets, excludeWalletIds]);
const theme = useTheme();
return (
<Box marginTop="sm" flexDirection="column">
{walletsToDisplay.map((wallet) => {
if (!wallet.selectUI) {
return null;
}
return (
<Box
key={wallet.id}
flexDirection="row"
justifyContent="space-between"
alignItems="center"
borderRadius="sm"
>
<wallet.selectUI
modalSize="compact"
theme={theme}
supportedWallets={wallets}
onSelect={(data) => {
onChooseWallet(wallet, data);
}}
walletConfig={wallet}
/>
</Box>
);
})}
<FlatList
keyExtractor={(item) => item.meta.name}
data={walletsToDisplay}
numColumns={NUM_COLUMNS}
style={{ maxHeight: MAX_HEIGHT }}
fadingEdgeLength={10}
showsVerticalScrollIndicator={false}
renderItem={({ item }) => {
return !item.selectUI ? (
<WalletButtonSquare
walletIconUrl={item.meta.iconURL}
name={item.meta.name}
size={TILE_SIZE}
onPress={() => onChooseWallet(item)}
/>
) : null;
}}
/>
<Box
height={60}
borderTopColor="border"
borderTopWidth={1}
borderBottomColor="border"
borderBottomWidth={1}
flexDirection="row"
justifyContent="space-between"
alignItems="center"
>
<Text variant="bodySmall">New to wallets?</Text>
<Text variant="link">Get started</Text>
</Box>
</Box>
);
};
@@ -4,6 +4,7 @@ import { useConnectionStatus, useWallets } from "@thirdweb-dev/react-core";
import { useState, useEffect } from "react";
import {
useGlobalTheme,
useLocale,
useModalState,
} from "../../providers/ui-context-provider";
import { ThemeProvider, ThemeProviderProps } from "../../styles/ThemeProvider";
@@ -45,6 +46,7 @@ export const ConnectWalletButton = ({
buttonTitle,
theme,
}: ConnectWalletButtonProps) => {
const l = useLocale();
const appTheme = useGlobalTheme();
const connectionStatus = useConnectionStatus();
const isWalletConnecting = connectionStatus === "connecting";
@@ -95,16 +97,18 @@ export const ConnectWalletButton = ({
<ThemeProvider theme={theme ? theme : appTheme}>
<BaseButton
backgroundColor="buttonBackgroundColor"
borderColor="buttonBorderColor"
borderWidth={1}
onPress={onConnectWalletPress}
style={styles.connectWalletButton}
>
<Text variant="bodyLarge" color="buttonTextColor">
<Text variant="bodyLargeBold" color="buttonTextColor">
{showButtonSpinner ? (
<ActivityIndicator size="small" color="buttonTextColor" />
) : buttonTitle ? (
buttonTitle
) : (
"Connect Wallet"
l.connect_wallet.label
)}
</Text>
</BaseButton>
@@ -7,6 +7,7 @@ import { walletIds } from "@thirdweb-dev/wallets";
import { useColorScheme } from "react-native";
import {
useGlobalTheme,
useLocale,
useModalState,
} from "../../providers/ui-context-provider";
import {
@@ -17,6 +18,7 @@ import Box from "../base/Box";
import { ThemeProvider } from "../../styles/ThemeProvider";
export const ConnectWalletFlow = () => {
const l = useLocale();
const { modalState, setModalState } = useModalState();
const {
modalTitle,
@@ -25,7 +27,6 @@ export const ConnectWalletFlow = () => {
termsOfServiceUrl,
walletConfig,
} = (modalState as ConnectWalletFlowModal).data;
const [modalVisible, setModalVisible] = useState(false);
const [activeWallet, setActiveWallet] = useState<WalletConfig | undefined>();
const [isConnecting, setIsConnecting] = useState(false);
@@ -147,7 +148,7 @@ export const ConnectWalletFlow = () => {
content={
activeWallet.id === walletIds.localWallet ? (
<Text variant="bodySmallSecondary" mt="md" textAlign="center">
Creating, encrypting and securing your device wallet.
{l.connecting_wallet.creating_encrypting}
</Text>
) : undefined
}
@@ -1,3 +1,4 @@
import { useLocale } from "../../../providers/ui-context-provider";
import WalletLoadingThumbnail from "../../../wallets/wallets/wallet-connect/WalletLoadingThumbnail";
import { Box, ImageSvgUri } from "../../base";
import Text from "../../base/Text";
@@ -23,6 +24,7 @@ export function ConnectingWallet({
onClose,
onBackPress,
}: ConnectingWalletProps) {
const l = useLocale();
return (
<Box paddingHorizontal="xl">
<ConnectWalletHeader
@@ -39,10 +41,10 @@ export function ConnectingWallet({
) : (
<>
<Text variant="header" mt="lg">
Connecting your wallet
{l.connecting_wallet.connecting_your_wallet}
</Text>
<Text variant="bodySmallSecondary" mt="lg" textAlign="center">
{`Login and connect your wallet through the ${wallet.meta.name} pop-up`}
{l.connecting_wallet.connecting_through_pop_up}
</Text>
</>
)}
@@ -1,5 +1,8 @@
import { Icon } from "../../../assets/icon";
import { useGlobalTheme } from "../../../providers/ui-context-provider";
import {
useGlobalTheme,
useLocale,
} from "../../../providers/ui-context-provider";
import Text from "../../base/Text";
import { FlexAlignType, StyleSheet, View } from "react-native";
@@ -14,13 +17,20 @@ interface ConnectWalletHeaderProps {
export const ConnectWalletHeader = ({
headerText,
subHeaderText = "Connecting your wallet",
subHeaderText,
alignHeader = "center",
middleContent,
onClose,
onBackPress,
}: ConnectWalletHeaderProps) => {
const l = useLocale();
const theme = useGlobalTheme();
subHeaderText =
subHeaderText !== undefined
? subHeaderText
: l.connecting_wallet.connecting_your_wallet;
return (
<>
<View style={styles.header}>
@@ -13,6 +13,7 @@ import {
import { LocalWalletImportModal } from "./LocalWalletImportModal";
import { LocalWallet } from "../../wallets/wallets/LocalWallet";
import Box from "../base/Box";
import { useLocale } from "../../providers/ui-context-provider";
type LocalWalletFlowUIProps = ConnectUIProps<LocalWallet> & {
onConnected?: (wallet: WalletInstance) => void;
@@ -24,6 +25,7 @@ export function LocalWalletFlow({
walletConfig,
onConnected,
}: LocalWalletFlowUIProps) {
const l = useLocale();
const [isImportModalVisible, setIsImportModalVisible] = useState(false);
const [isCreatingWallet, setIsCreatingWallet] = useState(false);
const { setConnectedWallet } = useWalletContext();
@@ -58,7 +60,7 @@ export function LocalWalletFlow({
<>
<ConnectWalletHeader
onBackPress={goBack}
headerText="Guest Wallet"
headerText={l.local_wallet.guest_wallet}
alignHeader="flex-start"
subHeaderText={""}
onClose={connected}
@@ -75,7 +77,7 @@ export function LocalWalletFlow({
<ActivityIndicator size="small" color="buttonTextColor" />
) : (
<Text variant="bodyLarge" color="black">
Create new wallet
{l.local_wallet.create_new_wallet}
</Text>
)}
</BaseButton>
@@ -88,7 +90,7 @@ export function LocalWalletFlow({
>
<Box height={1} flex={1} backgroundColor="border" />
<Text variant="subHeader" textAlign="center">
OR
{l.common.or}
</Text>
<Box height={1} flex={1} backgroundColor="border" />
</Box>
@@ -16,7 +16,7 @@ import * as FileSystem from "expo-file-system";
import { TWModal } from "../base/modal/TWModal";
import { localWallet } from "../../wallets/wallets/local-wallet";
import { TextInput } from "../base";
import { useGlobalTheme } from "../../providers/ui-context-provider";
import { useGlobalTheme, useLocale } from "../../providers/ui-context-provider";
export type LocalWalletImportModalProps = {
isVisible: boolean;
@@ -29,6 +29,7 @@ export const LocalWalletImportModal = ({
onClose,
onWalletImported,
}: LocalWalletImportModalProps) => {
const l = useLocale();
const [password, setPassword] = useState<string | undefined>();
const [privateKeyOrMnemonic, setPrivateKeyOrMnemonic] = useState<
string | undefined
@@ -107,7 +108,7 @@ export const LocalWalletImportModal = ({
}
if (!localWalletInstance) {
setError("Please, double check your password or private key.");
setError(l.local_wallet.double_check_password);
setIsImporting(false);
return;
}
@@ -147,7 +148,7 @@ export const LocalWalletImportModal = ({
setJsonFile(result.uri);
setError(undefined);
} else {
setError("Error accessing the file. Please try again.");
setError(l.local_wallet.error_accessing_file);
}
};
@@ -169,9 +170,7 @@ export const LocalWalletImportModal = ({
onClose={onCloseInternal}
/>
<Text variant="subHeader" mt="md" textAlign="center">
{
"The application can authorize any transactions on behalf of the wallet without any approvals. We recommend only connecting to trusted applications."
}
{l.local_wallet.application_can_authorize_transactions}
</Text>
<BaseButton
backgroundColor="background"
@@ -186,7 +185,7 @@ export const LocalWalletImportModal = ({
</Text>
</BaseButton>
<Text variant="bodySmall" textAlign="left" mt="lg" mb="xxs">
Password
{l.common.password}
</Text>
<PasswordInput onChangeText={onChangeText} />
<Text variant="bodySmall" color="red" mt="xs" textAlign="left">
@@ -200,16 +199,20 @@ export const LocalWalletImportModal = ({
>
<Box height={1} flex={1} backgroundColor="border" />
<Text variant="bodySmall" textAlign="center" marginHorizontal="xxs">
Or Private key or Mnemonic
{l.local_wallet.private_key_mnemonic}
</Text>
<Box height={1} flex={1} backgroundColor="border" />
</Box>
<TextInput
textInputProps={{
secureTextEntry: true,
placeholder: "Private key / Mnemonic",
placeholder: l.local_wallet.private_key_mnemonic_placeholder,
placeholderTextColor: theme.colors.textSecondary,
onChangeText: onPrivateKeyEntered,
style: {
color: theme.colors.textPrimary,
fontFamily: theme.textVariants.defaults.fontFamily,
},
}}
containerProps={{ pl: "xxs" }}
/>
@@ -228,7 +231,7 @@ export const LocalWalletImportModal = ({
<ActivityIndicator size="small" color="buttonTextColor" />
) : (
<Text variant="bodySmall" color="black">
Import
{l.common.import}
</Text>
)}
</BaseButton>
@@ -15,7 +15,10 @@ import WalletLoadingThumbnail from "../../../wallets/wallets/wallet-connect/Wall
import ImageSvgUri from "../../base/ImageSvgUri";
import Box from "../../base/Box";
import { ConnectWalletHeader } from "../ConnectingWallet/ConnectingWalletHeader";
import { useGlobalTheme } from "../../../providers/ui-context-provider";
import {
useGlobalTheme,
useLocale,
} from "../../../providers/ui-context-provider";
export const SmartWalletFlow = ({
connected,
@@ -24,6 +27,7 @@ export const SmartWalletFlow = ({
personalWalletConfig,
...props
}: ConnectUIProps<SmartWallet> & { personalWalletConfig: WalletConfig }) => {
const l = useLocale();
const theme = useGlobalTheme();
const [connectedPersonalWallet, setConnectedPersonalWallet] =
useState<WalletInstance>();
@@ -141,13 +145,13 @@ export const SmartWalletFlow = ({
<View style={styles.connectingContainer}>
<>
<Text variant="header" mt="lg" textAlign="center">
{mismatch ? "Network Mismatch" : "Connecting..."}
{mismatch
? l.smart_wallet.network_mistmach
: `${l.smart_wallet.connecting} ...`}
</Text>
{mismatch ? (
<Text variant="bodySmallSecondary" mt="lg" textAlign="center">
{
"There's a network mismatch between your contract and your wallet"
}
{l.connect_wallet_details.network_mismatch}
</Text>
) : null}
</>
@@ -173,7 +177,7 @@ export const SmartWalletFlow = ({
<ActivityIndicator size="small" color={theme.colors.textPrimary} />
) : (
<Text variant="bodyLarge" textAlign="center">
Switch Network
{l.common.switch_network}
</Text>
)}
</BaseButton>
@@ -1,15 +1,17 @@
import { TextInput } from "react-native";
import Text from "../../base/Text";
import { useLocale } from "../../../providers/ui-context-provider";
export const UsernameInput = ({
onChangeText,
}: {
onChangeText: TextInput["props"]["onChangeText"];
}) => {
const l = useLocale();
return (
<>
<Text variant="bodySmall" textAlign="left" mt="lg" mb="xxs">
Username
{l.common.username}
</Text>
<TextInput onChangeText={onChangeText} />
</>
@@ -28,7 +28,11 @@ export const PasswordInput = ({
pl="xxs"
>
<TextInput
style={{ ...styles.textInput, color: theme.colors.textPrimary }}
style={{
...styles.textInput,
color: theme.colors.textPrimary,
fontFamily: theme.textVariants.defaults.fontFamily,
}}
secureTextEntry={!showPassword}
textContentType="none"
returnKeyType={"done"}
@@ -14,9 +14,10 @@ import {
import DownloadIcon from "../assets/download";
import CopyIcon from "../assets/copy";
import QRCode from "react-native-qrcode-svg";
import { useGlobalTheme } from "../providers/ui-context-provider";
import { useGlobalTheme, useLocale } from "../providers/ui-context-provider";
export const ReceiveButton = () => {
const l = useLocale();
const theme = useGlobalTheme();
const [isModalVisible, setIsModalVisible] = useState(false);
@@ -33,7 +34,7 @@ export const ReceiveButton = () => {
<IconTextButton
flex={1}
ml="xs"
text="Receive"
text={l.common.receive}
justifyContent="center"
icon={
<DownloadIcon
@@ -60,6 +61,7 @@ export const ReceiveFundsModal = ({
isVisible,
onClose,
}: ReceiveFundsModalProps) => {
const l = useLocale();
const theme = useGlobalTheme();
const address = useAddress();
const [addressCopied, setAddressCopied] = useState(false);
@@ -94,7 +96,7 @@ export const ReceiveFundsModal = ({
>
<ModalHeaderTextClose
onClose={onCloseInternal}
headerText="Receive Funds"
headerText={l.connect_wallet_details.receive_funds}
/>
<Text
variant="bodySmallSecondary"
@@ -102,11 +104,10 @@ export const ReceiveFundsModal = ({
mt="md"
marginHorizontal="xmd"
>
Copy the wallet address or scan the QR code to send funds to this
wallet.
{l.connect_wallet_details.copy_address_or_scan}
</Text>
<Text mt="lg" variant="bodySmallSecondary">
Your address
{l.connect_wallet_details.your_address}
</Text>
<BaseButton
mt="xs"
@@ -127,7 +128,7 @@ export const ReceiveFundsModal = ({
<CopyIcon width={14} height={14} color={theme.colors.iconPrimary} />
</BaseButton>
<Text mt="lg" variant="bodySmallSecondary">
QR Code
{l.connect_wallet_details.qr_code}
</Text>
<Box
mt="xs"
@@ -144,7 +145,7 @@ export const ReceiveFundsModal = ({
</Box>
{addressCopied === true ? (
<Toast text={"Address copied to clipboard"} />
<Toast text={l.connect_wallet_details.address_copied_clipboard} />
) : null}
</Box>
</KeyboardAvoidingView>
@@ -2,11 +2,13 @@ import { useBalance, useChain } from "@thirdweb-dev/react-core";
import { TokenInfo } from "./defaultTokens";
import { BaseButton, Box, ChainIcon, ImageSvgUri, Text } from "../base";
import LoadingTextAnimation from "../base/LoadingTextAnimation";
import { useLocale } from "../../providers/ui-context-provider";
export function SelectTokenButton(props: {
token?: TokenInfo;
onPress: () => void;
}) {
const l = useLocale();
const balanceQuery = useBalance(props.token?.address);
const chain = useChain();
const tokenName = props.token?.name || balanceQuery.data?.name;
@@ -27,7 +29,7 @@ export function SelectTokenButton(props: {
<Text variant="bodyLarge">{tokenName}</Text>
{!balanceQuery.data ? (
<LoadingTextAnimation
text="Fetching..."
text={l.common.fetching}
textVariant={"bodySmallSecondary"}
/>
) : (
@@ -29,13 +29,14 @@ import { utils } from "ethers";
import LoadingTextAnimation from "../base/LoadingTextAnimation";
import CheckIcon from "../../assets/check";
import { TokenSelector } from "./TokenSelector";
import { useGlobalTheme } from "../../providers/ui-context-provider";
import { useGlobalTheme, useLocale } from "../../providers/ui-context-provider";
export const SendButton = ({
supportedTokens,
}: {
supportedTokens: SupportedTokens;
}) => {
const l = useLocale();
const theme = useGlobalTheme();
const [isModalVisible, setIsModalVisible] = useState(false);
@@ -51,7 +52,7 @@ export const SendButton = ({
<>
<IconTextButton
flex={1}
text="Send"
text={l.common.send}
justifyContent="center"
icon={
<SendIcon height={16} width={16} color={theme.colors.textPrimary} />
@@ -139,6 +140,7 @@ const SendFundsForm = ({
onTokenSelectorPress: () => void;
token?: TokenInfo;
}) => {
const l = useLocale();
const theme = useGlobalTheme();
const chain = useChain();
const wallet = useWallet();
@@ -219,9 +221,12 @@ const SendFundsForm = ({
borderRadius="md"
p="lg"
>
<ModalHeaderTextClose onClose={onCloseInternal} headerText="Send Funds" />
<ModalHeaderTextClose
onClose={onCloseInternal}
headerText={l.connect_wallet_details.send_funds}
/>
<Text mt="lg" variant="bodySmallSecondary">
Select Token
{l.connect_wallet_details.select_token}
</Text>
<BaseButton
@@ -251,7 +256,7 @@ const SendFundsForm = ({
<Text variant="bodySmall">{tokenName}</Text>
{!balanceQuery.data ? (
<LoadingTextAnimation
text="Fetching..."
text={l.common.fetching}
textVariant={"bodySmallSecondary"}
/>
) : (
@@ -265,7 +270,7 @@ const SendFundsForm = ({
</BaseButton>
<Text mt="md" variant="bodySmallSecondary">
Send to
{l.connect_wallet_details.send_to}
</Text>
<Box
mt="xs"
@@ -284,6 +289,7 @@ const SendFundsForm = ({
onChangeText={setReceiverAddress}
style={{
color: theme.colors.textPrimary,
fontFamily: theme.textVariants.defaults.fontFamily,
textAlign: "left",
flex: 1,
height: 40,
@@ -297,7 +303,7 @@ const SendFundsForm = ({
/>
</Box>
<Text mt="md" variant="bodySmallSecondary">
Amount
{l.common.amount}
</Text>
<Box
mt="xs"
@@ -317,6 +323,7 @@ const SendFundsForm = ({
clearTextOnFocus={false}
style={{
color: theme.colors.textPrimary,
fontFamily: theme.textVariants.defaults.fontFamily,
textAlign: "left",
flex: 1,
height: 40,
@@ -359,7 +366,7 @@ const SendFundsForm = ({
/>
) : (
<Text variant="bodySmall" color="accentButtonTextColor" mr="sm">
Send
{l.common.send}
</Text>
)}
</BaseButton>
@@ -18,7 +18,7 @@ import {
import { SelectTokenButton } from "./SelectTokenButton";
import CloseIcon from "../../assets/close";
import Text from "../base/Text";
import { useGlobalTheme } from "../../providers/ui-context-provider";
import { useGlobalTheme, useLocale } from "../../providers/ui-context-provider";
export function useToken(tokenAddress: string): {
isLoading: boolean;
@@ -82,6 +82,7 @@ export function TokenSelector(props: {
onBack: () => void;
supportedTokens: SupportedTokens;
}) {
const l = useLocale();
const theme = useGlobalTheme();
const [input, setInput] = useState("");
const chainId = useChainId();
@@ -120,7 +121,7 @@ export function TokenSelector(props: {
<Box>
<ModalHeaderTextClose
onBackPress={props.onBack}
headerText="Select a Token"
headerText={l.connect_wallet_details.select_token}
/>
<Box
@@ -140,12 +141,13 @@ export function TokenSelector(props: {
onChangeText={setInput}
style={{
color: theme.colors.textPrimary,
fontFamily: theme.textVariants.defaults.fontFamily,
textAlign: "left",
flex: 1,
height: 40,
paddingHorizontal: 16,
}}
placeholder="Search or paste token address"
placeholder={l.connect_wallet_details.search_or_paste_token}
placeholderTextColor={theme.colors.textSecondary}
autoCapitalize="none"
autoCorrect={false}
@@ -197,8 +199,10 @@ export function TokenSelector(props: {
minHeight={150}
paddingTop="none"
>
<CloseIcon width={16} height={16} />
<Text variant="bodySmall">No Tokens found</Text>
<CloseIcon width={16} height={16} color={theme.colors.border} />
<Text variant="bodySmall">
{l.connect_wallet_details.no_tokens_found}
</Text>
</Box>
)}
</Box>
@@ -15,7 +15,7 @@ import Box from "./Box";
import { ModalHeaderTextClose } from "./modal/ModalHeaderTextClose";
import { TWModal } from "./modal/TWModal";
import { Chain } from "@thirdweb-dev/chains";
import { useGlobalTheme } from "../../providers/ui-context-provider";
import { useGlobalTheme, useLocale } from "../../providers/ui-context-provider";
type NetworkButtonProps = {
chain?: Chain;
@@ -35,6 +35,7 @@ export const NetworkButton = ({
padding,
...props
}: NetworkButtonProps) => {
const l = useLocale();
const theme = useGlobalTheme();
const [isModalVisible, setIsModalVisible] = useState(false);
const [switchError, setSwitchError] = useState<string | undefined>();
@@ -85,7 +86,9 @@ export const NetworkButton = ({
<Box flexDirection="row" alignItems="center">
<ChainIcon chainIconUrl={chain?.icon?.url} size={28} />
<Box ml="md" alignItems="flex-start" justifyContent="center">
<Text variant="bodyLarge">{chain?.name || "Unknown Network"}</Text>
<Text variant="bodyLarge">
{chain?.name || l.common.unknown_network}
</Text>
{isSwitching ? (
<Box flexDirection="row" alignItems="center">
<Text
@@ -94,12 +97,12 @@ export const NetworkButton = ({
mr="xxs"
fontSize={10}
>
Confirm in your wallet
{l.connect_wallet_details.confirm_in_wallet}
</Text>
<ActivityIndicator size={10} color={theme.colors.linkPrimary} />
</Box>
) : switchError ? (
<Text variant="error">Error switching network</Text>
<Text variant="error">{l.common.error_switching_network}</Text>
) : null}
</Box>
</Box>
@@ -129,6 +132,7 @@ export const SwitchChainModal = ({
isVisible,
onClose,
}: SwitchChainModalProps) => {
const l = useLocale();
const supportedChains = useSupportedChains();
const onCloseInternal = () => {
@@ -147,11 +151,11 @@ export const SwitchChainModal = ({
>
<Box flexDirection="row" justifyContent="space-between" mb="sm">
<Text variant="bodyLarge" textAlign="left">
Select Network
{l.connect_wallet_details.select_network}
</Text>
<ModalHeaderTextClose flex={1} onClose={onCloseInternal} />
</Box>
<ScrollView>
<ScrollView contentContainerStyle={{ paddingBottom: 10 }}>
{supportedChains?.length > 0 ? (
supportedChains.map((chain) => {
return (
@@ -167,7 +171,9 @@ export const SwitchChainModal = ({
);
})
) : (
<Text variant="error">No supported chains detected</Text>
<Text variant="error">
{l.connect_wallet_details.no_supported_chains_detected}
</Text>
)}
</ScrollView>
</Box>
@@ -2,17 +2,19 @@ import { useBalance } from "@thirdweb-dev/react-core";
import Text from "./Text";
import LoadingTextAnimation from "./LoadingTextAnimation";
import { baseTheme } from "../../styles/theme";
import { useLocale } from "../../providers/ui-context-provider";
type TextBalance = {
textVariant: keyof typeof baseTheme.textVariants;
textVariant: keyof Omit<typeof baseTheme.textVariants, "defaults">;
tokenAddress?: string;
};
export const TextBalance = ({ textVariant, tokenAddress }: TextBalance) => {
const balanceQuery = useBalance(tokenAddress);
const l = useLocale();
return !balanceQuery.data ? (
<LoadingTextAnimation text="Fetching..." textVariant={textVariant} />
<LoadingTextAnimation text={l.common.fetching} textVariant={textVariant} />
) : (
<Text variant={textVariant}>
{Number(balanceQuery.data?.displayValue).toFixed(3)}{" "}
@@ -5,6 +5,7 @@ import { Label } from "./Label";
import Text from "./Text";
import Box from "./Box";
import { Palette } from "../../styles/colors";
import { useLocale } from "../../providers/ui-context-provider";
type WalletButtonProps = {
onPress?: () => void;
@@ -29,6 +30,7 @@ export const WalletButton = ({
recommended,
...props
}: WalletButtonProps) => {
const l = useLocale();
return (
<BaseButton
mb={mb}
@@ -49,10 +51,12 @@ export const WalletButton = ({
height={iconHeight}
/>
<Box ml="sm" alignItems="flex-start">
<Text variant="bodyLarge" color={nameColor}>
<Text variant="bodyLargeBold" color={nameColor}>
{name}
</Text>
{recommended ? <Text variant="link">Recommended</Text> : null}
{recommended ? (
<Text variant="link">{l.connect_wallet_details.recommended}</Text>
) : null}
</Box>
</Box>
{labelText ? <Label text={labelText} /> : <View />}
@@ -0,0 +1,20 @@
import { DeepPartial, deepMerge } from "../types/deepPartial";
import { Locale, LocaleType, _en } from "./types";
export const setLocale = (locale: Locale): LocaleType => {
if (typeof locale === "string") {
if (locale === "en") {
return en();
}
throw new Error(`Locale ${locale} not supported`);
}
return locale;
};
export const en = (locale?: DeepPartial<LocaleType>): LocaleType => {
if (!locale) {
return _en;
}
return deepMerge(_en, locale);
};
+107
View File
@@ -0,0 +1,107 @@
export type Locale = LocaleType | "en";
export type LocaleType = typeof _en;
export const _en = {
connect_wallet: {
label: "Connect Wallet",
},
connect_wallet_details: {
additional_actions: "Additional Actions",
address_copied_clipboard: "Address copied to clipboard",
backup_wallet: "Backup Wallet",
backup_personal_wallet: "Backup personal wallet",
import_wallet: "Import Wallet",
connected_to_smart_wallet: "Connected to a Smart Wallet",
current_network: "Current Network",
backup: "Backup",
connect_to_app: "Connect to App",
guest: "Guest",
connect: "Connect",
new_to_wallets: "New to wallets?",
view_transaction_history: "View Transaction History",
get_started: "Get started",
receive_funds: "Receive Funds",
search_or_paste_token: "Search or paste token address",
connect_a_wallet: "Connect a wallet",
continue_as_guest: "Continue as guest",
tos: "Terms of Service",
privacy_policy: "Privacy Policy",
by_connecting_you_agree: "By connecting, you agree to the",
copy_address_or_scan:
"Copy the wallet address or scan the QR code to send funds to this wallet.",
request_testnet_funds: "Request Testnet Funds",
view_transatcion_history: "View Transaction History",
your_address: "Your address",
qr_code: "QR Code",
select_token: "Select Token",
send_to: "Send to",
send_funds: "Send Funds",
no_tokens_found: "No Tokens found",
confirm_in_wallet: "Confirm in your wallet",
select_network: "Select Network",
switch_to: "Switch to",
no_supported_chains_detected: "No supported chains detected",
recommended: "Recommended",
network_mismatch:
"There's a network mismatch between your contract and your wallet",
},
connecting_wallet: {
creating_encrypting:
"Creating, encrypting and securing your device wallet.",
connecting_your_wallet: "Connecting your wallet",
connecting_through_pop_up:
"Login and connect your app through the wallet pop-up",
},
local_wallet: {
guest_wallet: "Guest Wallet",
backup_your_wallet: "Backup your wallet",
create_new_wallet: "Create new wallet",
private_key_mnemonic: "Or Private key or Mnemonic",
private_key_mnemonic_placeholder: "Private key / Mnemonic",
application_can_authorize_transactions:
"The application can authorize any transactions on behalf of the wallet without any approvals. We recommend only connecting to trusted applications.",
double_check_password: "Please, double check your password or private key.",
error_accessing_file: "Error accessing the file. Please try again.",
wallet_address: "Wallet Address",
this_will_download_json:
"This will download a JSON file containing your wallet information onto your device encrypted with the password.",
this_is_a_temporary_wallet:
"This is a temporary guest wallet. Download a backup if you don't want to loose access to it.",
},
smart_wallet: {
switch_to_smart: "Switch to Smart Wallet",
switch_to_personal: "Switch to Personal Wallet",
network_mistmach: "Network Mismatch",
connecting: "Connecting",
},
embedded_wallet: {
request_new_code: "Request new code",
sign_in: "Sign In",
sign_in_google: "Sign in with Google",
enter_your_email: "Enter your email address",
},
wallet_connect: {
no_results_found: "No results found",
search_wallets: "Search Wallets",
},
common: {
connect_app: "Connect app",
unknown_network: "Unknown Network",
fetching: "Fetching...",
password: "Password",
reject: "Reject",
approve: "Approve",
switch_network: "Switch Network",
import: "Import",
username: "Username",
amount: "Amount",
send: "Send",
receive: "Receive",
continue: "Continue",
error_switching_network: "Error switching network",
or: "OR",
from: "from",
to: "from",
},
};
+6 -1
View File
@@ -31,7 +31,10 @@ export { useMetaMaskWallet } from "./wallets/hooks/useMetaMaskWallet";
export { useRainbowWallet } from "./wallets/hooks/useRainbowWallet";
export { useTrustWallet } from "./wallets/hooks/useTrustWallet";
export { ConnectWallet } from "./components/ConnectWallet";
export {
ConnectWallet,
type ConnectWalletProps,
} from "./components/ConnectWallet";
export { Web3Button } from "./components/Web3Button";
// utilities
@@ -42,6 +45,8 @@ export { createAsyncLocalStorage } from "../core/AsyncStorage";
export { createSecureStorage } from "../core/SecureStorage";
export { ThirdwebStorage } from "../core/storage/storage";
export * from "./i18n/strings";
// ui components
export * from "./components/base";
export { ConnectWalletHeader } from "./components/ConnectWalletFlow/ConnectingWallet/ConnectingWalletHeader";
@@ -17,6 +17,7 @@ import { SafeAreaProvider } from "react-native-safe-area-context";
import { walletIds } from "@thirdweb-dev/wallets";
import { ThirdwebStorage } from "../../core/storage/storage";
import { useColorScheme } from "react-native";
import type { Locale } from "../i18n/types";
interface ThirdwebProviderProps<TChains extends Chain[]>
extends Omit<
@@ -29,7 +30,7 @@ interface ThirdwebProviderProps<TChains extends Chain[]>
*
* @example
* ```jsx
* import { MetaMaskWallet, CoinbaseWallet } from "@thirdweb-dev/react";
* import { MetaMaskWallet, CoinbaseWallet } from "@thirdweb-dev/react-native";
*
* <ThirdwebProvider
* supportedWallets={[MetaMaskWallet, CoinbaseWallet]}
@@ -37,6 +38,44 @@ interface ThirdwebProviderProps<TChains extends Chain[]>
* ```
*/
supportedWallets?: WalletConfig<any>[];
/**
* Locale that the app will be displayed in
* @defaultValue en()
*
* @example
* ```jsx
* import { en } from "@thirdweb-dev/react-native";
*
* <ThirdwebProvider
* locale={en()}
* />
* ```
*
* * ```jsx
* import { en } from "@thirdweb-dev/react-native";
*
* <ThirdwebProvider
* locale={'en'}
* />
* ```
*
* Note that you can override the locales by passing in a custom locale object of type `Locale`
* ```jsx
* import { en } from "@thirdweb-dev/react-native";
*
* const customLocale = {
* ...en(),
* "connect_wallet": "Connect Wallet"
* }
*
* <ThirdwebProvider
* locale={customLocale}
* />
* ```
*
*/
locale?: Locale;
}
/**
@@ -69,6 +108,7 @@ export const ThirdwebProvider = <
storageInterface,
clientId,
sdkOptions,
locale = "en",
...restProps
}: PropsWithChildren<ThirdwebProviderProps<TChains>>) => {
const colorScheme = useColorScheme();
@@ -114,7 +154,7 @@ export const ThirdwebProvider = <
<ThemeProvider
theme={theme ? theme : colorScheme === "dark" ? "dark" : "light"}
>
<UIContextProvider>
<UIContextProvider locale={locale}>
{hasMagicConfig ? (
<SafeAreaProvider>
<DappContextProvider>
@@ -5,12 +5,15 @@ import { Theme, _darkTheme, _lightTheme } from "../styles/theme";
import { useAppTheme } from "../styles/hooks";
import { useTheme } from "@shopify/restyle";
import { PropsWithChildren } from "react";
import { Locale } from "../i18n/types";
import { setLocale } from "../i18n/strings";
type UIContextType = {
modalState: ModalState;
setModalState: (modalState: ModalState) => void;
theme: ThemeProviderProps["theme"];
setTheme: (theme: ThemeProviderProps["theme"]) => void;
locale: Locale;
};
const UIContext = createContext<UIContextType>({
@@ -24,9 +27,12 @@ const UIContext = createContext<UIContextType>({
setModalState: () => undefined,
theme: "light",
setTheme: () => undefined,
locale: "en",
});
export const UIContextProvider = (props: PropsWithChildren) => {
export const UIContextProvider = (
props: { locale: Locale } & PropsWithChildren,
) => {
const [modalState, setModalState] = useState<ModalState>({
view: "Closed",
data: {},
@@ -41,7 +47,15 @@ export const UIContextProvider = (props: PropsWithChildren) => {
useState<ThemeProviderProps["theme"]>(providerTheme);
return (
<UIContext.Provider value={{ modalState, setModalState, theme, setTheme }}>
<UIContext.Provider
value={{
modalState,
setModalState,
theme,
setTheme,
locale: props.locale,
}}
>
{props.children}
</UIContext.Provider>
);
@@ -63,6 +77,12 @@ export const useModalState = (): {
};
};
export const useLocale = () => {
const context = useContext(UIContext);
return setLocale(context.locale);
};
const getThemeObj = (theme?: ThemeProviderProps["theme"]) => {
if (theme === "dark" || !theme) {
return _darkTheme;
@@ -1,6 +1,7 @@
export type Palette = {
buttonBackgroundColor: string;
buttonTextColor: string;
buttonBorderColor: string;
accentButtonColor: string;
accentButtonTextColor: string;
@@ -41,6 +42,7 @@ export const paletteBase = {
export const paletteLight: Palette = {
buttonBackgroundColor: "black",
buttonBorderColor: "black",
buttonTextColor: "white",
accentButtonColor: "#3385FF",
@@ -67,6 +69,7 @@ export const paletteLight: Palette = {
export const paletteDark: Palette = {
buttonBackgroundColor: "white",
buttonBorderColor: "white",
buttonTextColor: "black",
accentButtonColor: "#3385FF",
@@ -1,17 +1,36 @@
// import { Platform } from "react-native";
export const textVariants = {
defaults: {
fontFamily: undefined as string | undefined,
fontSize: 24,
fontWeight: "700",
lineHeight: 32,
color: "textPrimary",
},
header: {
fontFamily: undefined as string | undefined,
fontSize: 24,
fontWeight: "600",
lineHeight: 32,
color: "textPrimary",
},
headerBold: {
fontFamily: undefined as string | undefined,
fontSize: 24,
fontWeight: "700",
lineHeight: 32,
color: "textPrimary",
},
subHeader: {
fontFamily: undefined as string | undefined,
fontSize: 16,
fontWeight: "500",
lineHeight: 24,
color: "textSecondary",
},
link: {
fontFamily: undefined as string | undefined,
fontWeight: "500",
fontSize: 14,
lineHeight: 24,
@@ -19,20 +38,39 @@ export const textVariants = {
letterSpacing: -0.02,
},
bodyLarge: {
fontFamily: undefined as string | undefined,
color: "textPrimary",
textAlign: "center",
fontWeight: "600",
fontSize: 16,
lineHeight: 24,
},
bodyLargeBold: {
fontFamily: undefined as string | undefined,
color: "textPrimary",
textAlign: "center",
fontWeight: "700",
fontSize: 16,
lineHeight: 24,
},
bodySmall: {
fontFamily: undefined as string | undefined,
color: "textPrimary",
textAlign: "center",
fontWeight: "600",
fontSize: 14,
lineHeight: 16,
},
bodySmallBold: {
fontFamily: undefined as string | undefined,
color: "textPrimary",
textAlign: "center",
fontWeight: "700",
fontSize: 14,
lineHeight: 16,
},
bodySmallSecondary: {
fontFamily: undefined as string | undefined,
color: "textSecondary",
textAlign: "left",
fontWeight: "600",
@@ -40,6 +78,7 @@ export const textVariants = {
lineHeight: 16,
},
error: {
fontFamily: undefined as string | undefined,
color: "error",
fontWeight: "500",
fontSize: 12,
+10 -7
View File
@@ -1,4 +1,4 @@
import { DeepPartial } from "../types/deepPartial";
import { DeepPartial, deepMerge } from "../types/deepPartial";
import { paletteDark, paletteLight } from "./colors";
import { textVariants } from "./textVariants";
import { createTheme } from "@shopify/restyle";
@@ -45,40 +45,43 @@ export type Theme = typeof _darkTheme;
export type ButtonTheme = {
buttonBackgroundColor?: string;
buttonTextColor?: string;
buttonBorderColor?: string;
};
export const darkTheme = ({
buttonBackgroundColor = paletteDark.buttonBackgroundColor,
buttonTextColor = paletteDark.buttonTextColor,
buttonBorderColor = paletteLight.buttonBorderColor,
colors,
...props
}: ButtonTheme & DeepPartial<Theme> = _darkTheme): Theme => {
return {
..._darkTheme,
return deepMerge(_darkTheme, {
colors: {
..._darkTheme.colors,
...colors,
buttonBackgroundColor,
buttonTextColor,
buttonBorderColor,
},
...props,
} as Theme;
});
};
export const lightTheme = ({
buttonBackgroundColor = paletteLight.buttonBackgroundColor,
buttonTextColor = paletteLight.buttonTextColor,
buttonBorderColor = paletteLight.buttonBorderColor,
colors,
...props
}: ButtonTheme & DeepPartial<Theme> = _lightTheme): Theme => {
return {
..._lightTheme,
return deepMerge(_lightTheme, {
colors: {
..._lightTheme.colors,
...colors,
buttonBackgroundColor,
buttonTextColor,
buttonBorderColor,
},
...props,
} as Theme;
});
};
@@ -1,3 +1,22 @@
export type DeepPartial<T> = {
[P in keyof T]?: DeepPartial<T[P]>;
};
export function deepMerge<T>(target: T, source: DeepPartial<T>): T {
for (const key in source) {
if (
source[key] instanceof Object &&
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
key in target &&
target[key] instanceof Object
) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
deepMerge(target[key], source[key]);
} else {
target[key] = source[key] as any;
}
}
return target;
}
@@ -17,6 +17,17 @@ export function shortenWalletAddress(str?: string, extraShort = true) {
)}`;
}
/**
* This function shortens an address if it is a valid EVM address.
*
* @param address The address to shorten
* @param extraShort If true, show the first 4 and last 3 characters
* @returns The shortened address
* @example
* ```ts
* const address = shortenIfAddress("0x1234567890123456789012345678901234567890", true); // result will be "0x1234...890"
* ```
*/
export function shortenIfAddress(address?: string, extraShort?: true): string {
if (!address) {
return "";
@@ -19,7 +19,10 @@ import BaseButton from "../../../components/base/BaseButton";
import * as Clipboard from "expo-clipboard";
import { StyleSheet } from "react-native";
import { EmbeddedSocialConnection } from "./EmbeddedSocialConnection";
import { useGlobalTheme } from "../../../providers/ui-context-provider";
import {
useGlobalTheme,
useLocale,
} from "../../../providers/ui-context-provider";
const OTP_LENGTH = 6;
@@ -30,6 +33,7 @@ export const EmbeddedConnectionUI: React.FC<ConnectUIProps<EmbeddedWallet>> = ({
onLocallyConnected,
...props
}) => {
const l = useLocale();
const theme = useGlobalTheme();
const inputRefs = useRef<(TextInput | null)[]>([]);
const [values, setValues] = useState<string[]>(
@@ -176,7 +180,9 @@ export const EmbeddedConnectionUI: React.FC<ConnectUIProps<EmbeddedWallet>> = ({
return (
<Box marginHorizontal="xl">
<ConnectWalletHeader
middleContent={<Text variant="header">Sign In</Text>}
middleContent={
<Text variant="header">{l.embedded_wallet.sign_in}</Text>
}
subHeaderText={"Please enter the code sent to"}
onBackPress={goBack}
onClose={connected}
@@ -252,7 +258,7 @@ export const EmbeddedConnectionUI: React.FC<ConnectUIProps<EmbeddedWallet>> = ({
/>
) : (
<Text variant="bodySmallSecondary" color="linkPrimary">
Request new code
{l.embedded_wallet.request_new_code}
</Text>
)}
</BaseButton>
@@ -13,7 +13,10 @@ import { GOOGLE_ICON } from "../../../assets/svgs";
import { WalletButton } from "../../../components/base/WalletButton";
import { AuthProvider } from "@paperxyz/embedded-wallet-service-sdk";
import { OauthOptions } from "../../connectors/embedded-wallet/types";
import { useGlobalTheme } from "../../../providers/ui-context-provider";
import {
useGlobalTheme,
useLocale,
} from "../../../providers/ui-context-provider";
/**
* UI for selecting wallet - this UI is rendered in the wallet selection screen
@@ -24,6 +27,7 @@ export const EmailSelectionUI: React.FC<
email?: boolean;
}
> = ({ onSelect, walletConfig, oauthOptions, email }) => {
const l = useLocale();
const theme = useGlobalTheme();
const [emailInput, setEmailInput] = useState<string>("");
const [errorMessage, setErrorMessage] = useState<string>("");
@@ -98,7 +102,7 @@ export const EmailSelectionUI: React.FC<
backgroundColor="buttonBackgroundColor"
nameColor="buttonTextColor"
justifyContent="center"
name="Sign in with Google"
name={l.embedded_wallet.sign_in_google}
walletIconUrl={GOOGLE_ICON}
onPress={onGoogleSignInPress}
/>
@@ -116,7 +120,7 @@ export const EmailSelectionUI: React.FC<
textAlign="center"
marginHorizontal="xxs"
>
OR
{l.common.or}
</Text>
<Box height={1} flex={1} backgroundColor="border" />
</Box>
@@ -127,12 +131,13 @@ export const EmailSelectionUI: React.FC<
<>
<TextInput
textInputProps={{
placeholder: "Enter your email address",
placeholder: l.embedded_wallet.enter_your_email,
placeholderTextColor: theme.colors.textSecondary,
onChangeText: setEmailInput,
style: {
fontSize: 14,
color: theme.colors.textPrimary,
fontFamily: theme.textVariants.defaults.fontFamily,
lineHeight: 16,
padding: 0,
flex: 1,
@@ -166,12 +171,8 @@ export const EmailSelectionUI: React.FC<
color={theme.colors.accentButtonTextColor}
/>
) : (
<Text
variant="bodySmall"
color="accentButtonTextColor"
fontWeight="700"
>
Continue
<Text variant="bodySmallBold" color="accentButtonTextColor">
{l.common.continue}
</Text>
)}
</BaseButton>
@@ -19,7 +19,7 @@ import { useMagicLink } from "../../providers/context-provider";
import BaseButton from "../../components/base/BaseButton";
import React from "react";
import { ConnectingWallet } from "../../components/ConnectWalletFlow/ConnectingWallet/ConnectingWallet";
import { useGlobalTheme } from "../../providers/ui-context-provider";
import { useGlobalTheme, useLocale } from "../../providers/ui-context-provider";
export const magicLink = (
magicLinkOptions: MagicLinkOptions & { recommended?: boolean },
@@ -54,6 +54,7 @@ export const magicLink = (
};
const MagicSelectionUI: React.FC<SelectUIProps<MagicLink>> = (props) => {
const l = useLocale();
const theme = useGlobalTheme();
const [email, setEmail] = React.useState("");
@@ -68,7 +69,7 @@ const MagicSelectionUI: React.FC<SelectUIProps<MagicLink>> = (props) => {
<Box paddingHorizontal="xl" mt="lg">
<TextInput
textInputProps={{
placeholder: "Enter your email address",
placeholder: l.embedded_wallet.enter_your_email,
placeholderTextColor: theme.colors.textSecondary,
onChangeText: (text: string) => {
setEmail(text);
@@ -76,6 +77,7 @@ const MagicSelectionUI: React.FC<SelectUIProps<MagicLink>> = (props) => {
style: {
fontSize: 14,
color: theme.colors.textPrimary,
fontFamily: theme.textVariants.defaults.fontFamily,
lineHeight: 16,
padding: 0,
},
@@ -99,7 +101,7 @@ const MagicSelectionUI: React.FC<SelectUIProps<MagicLink>> = (props) => {
color="accentButtonTextColor"
fontWeight="700"
>
Continue
{l.common.continue}
</Text>
</BaseButton>
</Box>
@@ -21,7 +21,10 @@ import {
import { WalletConnect } from "./WalletConnect";
import { WalletConnectButton } from "./WalletConnectButton";
import { ModalHeaderTextClose } from "../../../components/base";
import { useGlobalTheme } from "../../../providers/ui-context-provider";
import {
useGlobalTheme,
useLocale,
} from "../../../providers/ui-context-provider";
type WCWallet = {
iconURL: string;
@@ -41,6 +44,7 @@ export function WalletConnectUI({
goBack,
projectId,
}: ConnectUIProps<WalletConnect> & { projectId: string }) {
const l = useLocale();
const theme = useGlobalTheme();
const [wallets, setWallets] = useState<WCWallet[]>([]);
const [error, setError] = useState<string | undefined>();
@@ -189,11 +193,12 @@ export function WalletConnectUI({
>
<TextInput
onChangeText={onChangeText}
placeholder="Search Wallets"
placeholder={l.wallet_connect.search_wallets}
placeholderTextColor={theme.colors.textSecondary}
style={{
...styles.textInput,
color: theme.colors.textSecondary,
fontFamily: theme.textVariants.defaults.fontFamily,
}}
/>
</Box>
@@ -209,7 +214,9 @@ export function WalletConnectUI({
{ height: Math.round(MODAL_HEIGHT) },
]}
>
<Text variant="bodySmall">No results found</Text>
<Text variant="bodySmall">
{l.wallet_connect.no_results_found}
</Text>
</View>
)
}
+17
View File
@@ -1,5 +1,22 @@
# @thirdweb-dev/react
## 4.0.8
### Patch Changes
- [#1797](https://github.com/thirdweb-dev/js/pull/1797) [`246b0d4a`](https://github.com/thirdweb-dev/js/commit/246b0d4aace8c785d89bc8f0bd156c96fc53ed10) Thanks [@MananTank](https://github.com/MananTank)! - Fix wrong Icon size of few icons in Firefox in ConnectWallet Modal
- [#1787](https://github.com/thirdweb-dev/js/pull/1787) [`ff996646`](https://github.com/thirdweb-dev/js/commit/ff996646b228d4d095eea04b05004dd26fc7e522) Thanks [@MananTank](https://github.com/MananTank)! - Enable typedoc for packages
- [#1815](https://github.com/thirdweb-dev/js/pull/1815) [`5ffbcfc3`](https://github.com/thirdweb-dev/js/commit/5ffbcfc302f74167768b196d93a328f979344036) Thanks [@ElasticBottle](https://github.com/ElasticBottle)! - Add onAuthSuccess for paperWallet
- [#1826](https://github.com/thirdweb-dev/js/pull/1826) [`2307f11a`](https://github.com/thirdweb-dev/js/commit/2307f11ab311aa4a775edd23e777d10f8015ce86) Thanks [@MananTank](https://github.com/MananTank)! - Add OKX wallet
- Updated dependencies [[`5ffbcfc3`](https://github.com/thirdweb-dev/js/commit/5ffbcfc302f74167768b196d93a328f979344036), [`42ba15f2`](https://github.com/thirdweb-dev/js/commit/42ba15f2c0e77e23e62650119dfaaa5c0dbe4481), [`d27a3dee`](https://github.com/thirdweb-dev/js/commit/d27a3dee8398d5707d2d1343c428abf8e03f67e3), [`ff996646`](https://github.com/thirdweb-dev/js/commit/ff996646b228d4d095eea04b05004dd26fc7e522), [`d8d48a95`](https://github.com/thirdweb-dev/js/commit/d8d48a9516fc8fdd173fbb91a858fe7ec0725ddd), [`aa9f48d1`](https://github.com/thirdweb-dev/js/commit/aa9f48d1361194fc81146da530c95a3409bd0799), [`fd7a9f09`](https://github.com/thirdweb-dev/js/commit/fd7a9f09989e39b02a93d9dfd01cc7378e6ead53), [`fd7a9f09`](https://github.com/thirdweb-dev/js/commit/fd7a9f09989e39b02a93d9dfd01cc7378e6ead53), [`2307f11a`](https://github.com/thirdweb-dev/js/commit/2307f11ab311aa4a775edd23e777d10f8015ce86), [`64138642`](https://github.com/thirdweb-dev/js/commit/64138642e84d8b56b254762eca613d443cca292b), [`6d1eabe9`](https://github.com/thirdweb-dev/js/commit/6d1eabe9f9818ee2a79ce5bf6aa74417dbfd0558)]:
- @thirdweb-dev/wallets@2.0.8
- @thirdweb-dev/sdk@4.0.7
- @thirdweb-dev/react-core@4.0.8
## 4.0.7
### Patch Changes
+5 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@thirdweb-dev/react",
"version": "4.0.7",
"version": "4.0.8",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react",
"author": "thirdweb eng <[email protected]>",
"license": "Apache-2.0",
@@ -67,7 +67,8 @@
"generate-docs:evm": "api-extractor run --local --config ./config/api-extractor-evm.json && api-documenter markdown -i ./temp -o ./docs/evm && rm -rf ./temp-evm && mv ./temp ./temp-evm",
"generate-snippets": "node ./scripts/generate-snippets-evm.mjs && node ./scripts/generate-feature-snippets-evm.mjs",
"build": "tsc && preconstruct build",
"push": "yalc push"
"push": "yalc push",
"typedoc": "rimraf typedoc && node typedoc.js"
},
"sideEffects:": false,
"devDependencies": {
@@ -102,7 +103,9 @@
"prettier": "^3.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"rimraf": "^3.0.2",
"stream": "npm:stream-browserify@^3.0.0",
"typedoc": "^0.25.2",
"typescript": "^5.1.6"
},
"dependencies": {
+2 -2
View File
@@ -110,9 +110,9 @@ export const Modal: React.FC<{
<Dialog.Close asChild>
<IconButton type="button" aria-label="Close">
<Cross2Icon
width={iconSize.md}
height={iconSize.md}
style={{
width: iconSize.md,
height: iconSize.md,
color: "inherit",
}}
/>
+2 -2
View File
@@ -10,8 +10,8 @@ export const Spinner: React.FC<{
return (
<Svg
style={{
width: iconSize[props.size],
height: iconSize[props.size],
width: iconSize[props.size] + "px",
height: iconSize[props.size] + "px",
}}
viewBox="0 0 50 50"
>
@@ -44,12 +44,7 @@ export const BackButton: React.FC<{
style={{ transform: "translateX(-25%)", ...props.style }}
type="button"
>
<ChevronLeftIcon
style={{
width: iconSize.md,
height: iconSize.md,
}}
/>
<ChevronLeftIcon width={iconSize.md} height={iconSize.md} />
</IconButton>
);
};
@@ -1,2 +1,3 @@
/** @internal */
// eslint-disable-next-line turbo/no-undeclared-env-vars, better-tree-shaking/no-top-level-side-effects
export const __DEV__ = process.env.NODE_ENV !== "production";
+5 -1
View File
@@ -6,7 +6,10 @@ export {
export { useSafe } from "./connectors/gnosis";
export { useMagic } from "./connectors/magic";
export { ConnectWallet } from "../wallet/ConnectWallet/ConnectWallet";
export {
ConnectWallet,
type ConnectWalletProps,
} from "../wallet/ConnectWallet/ConnectWallet";
export { ConnectModalInline } from "../wallet/ConnectWallet/Modal/ConnectModalInline";
export { NetworkSelector } from "../wallet/ConnectWallet/NetworkSelector";
@@ -53,6 +56,7 @@ export {
PhantomWallet,
RainbowWallet,
MetaMaskWallet,
OKXWallet,
TrustWallet,
CoinbaseWallet,
BloctoWallet,
+1
View File
@@ -18,6 +18,7 @@ export { trustWallet } from "./wallet/wallets/trustWallet/TrustWallet";
export { walletConnect } from "./wallet/wallets/walletConnect/walletConnect";
export { walletConnectV1 } from "./wallet/wallets/walletConnectV1";
export { zerionWallet } from "./wallet/wallets/zerion/zerionWallet";
export { okxWallet } from "./wallet/wallets/okx/okxWallet";
export { darkTheme, lightTheme } from "./design-system/index";
export type { Theme, ThemeOverrides } from "./design-system/index";
@@ -0,0 +1,109 @@
import { ConnectUIProps, useConnect } from "@thirdweb-dev/react-core";
import { ConnectingScreen } from "../../ConnectWallet/screens/ConnectingScreen";
import { isMobile } from "../../../evm/utils/isMobile";
import { useCallback, useEffect, useRef, useState } from "react";
import { OKXScan } from "./OKXScan";
import { GetStartedScreen } from "../../ConnectWallet/screens/GetStartedScreen";
import type { OKXWallet } from "@thirdweb-dev/wallets";
import { wait } from "../../../utils/wait";
export const OKXConnectUI = (props: ConnectUIProps<OKXWallet>) => {
const [screen, setScreen] = useState<
"connecting" | "scanning" | "get-started"
>("connecting");
const { walletConfig, connected } = props;
const connect = useConnect();
const [errorConnecting, setErrorConnecting] = useState(false);
const hideBackButton = props.supportedWallets.length === 1;
const connectToExtension = useCallback(async () => {
try {
connectPrompted.current = true;
setErrorConnecting(false);
setScreen("connecting");
await wait(1000);
await connect(walletConfig);
connected();
} catch (e) {
setErrorConnecting(true);
console.error(e);
}
}, [connected, connect, walletConfig]);
const connectPrompted = useRef(false);
useEffect(() => {
if (connectPrompted.current) {
return;
}
const isInstalled = walletConfig.isInstalled
? walletConfig.isInstalled()
: false;
// if loading
(async () => {
if (isInstalled) {
connectToExtension();
}
// if wallet is not injected
else {
// on mobile, deep link to the okx app
if (isMobile()) {
window.open(
`okx://wallet/dapp/details?dappUrl=${window.location.toString()}`,
);
} else {
// on desktop, show the OKX scan qr code
setScreen("scanning");
}
}
})();
}, [connectToExtension, walletConfig]);
if (screen === "connecting") {
return (
<ConnectingScreen
errorConnecting={errorConnecting}
onGetStarted={() => {
setScreen("get-started");
}}
onRetry={connectToExtension}
hideBackButton={hideBackButton}
onBack={props.goBack}
walletName={walletConfig.meta.name}
walletIconURL={walletConfig.meta.iconURL}
/>
);
}
if (screen === "get-started") {
return (
<GetStartedScreen
walletIconURL={walletConfig.meta.iconURL}
walletName={walletConfig.meta.name}
chromeExtensionLink={walletConfig.meta.urls?.chrome}
googlePlayStoreLink={walletConfig.meta.urls?.android}
appleStoreLink={walletConfig.meta.urls?.ios}
onBack={props.goBack}
/>
);
}
if (screen === "scanning") {
return (
<OKXScan
onBack={props.goBack}
onConnected={props.connected}
onGetStarted={() => {
setScreen("get-started");
}}
hideBackButton={hideBackButton}
walletConfig={walletConfig}
/>
);
}
return null;
};
@@ -0,0 +1,61 @@
import { ScanScreen } from "../../ConnectWallet/screens/ScanScreen";
import {
useCreateWalletInstance,
useWalletContext,
} from "@thirdweb-dev/react-core";
import { useEffect, useRef, useState } from "react";
import type { OKXWallet } from "@thirdweb-dev/wallets";
import type { WalletConfig } from "@thirdweb-dev/react-core";
export const OKXScan: React.FC<{
onBack: () => void;
onGetStarted: () => void;
onConnected: () => void;
walletConfig: WalletConfig<OKXWallet>;
hideBackButton: boolean;
}> = ({ onBack, onConnected, onGetStarted, walletConfig, hideBackButton }) => {
const createInstance = useCreateWalletInstance();
const [qrCodeUri, setQrCodeUri] = useState<string | undefined>();
const { setConnectedWallet, chainToConnect, setConnectionStatus } =
useWalletContext();
const scanStarted = useRef(false);
useEffect(() => {
if (scanStarted.current) {
return;
}
scanStarted.current = true;
const wallet = createInstance(walletConfig);
setConnectionStatus("connecting");
wallet.connectWithQrCode({
chainId: chainToConnect?.chainId,
onQrCodeUri(uri) {
setQrCodeUri(uri);
},
onConnected() {
setConnectedWallet(wallet);
onConnected();
},
});
}, [
createInstance,
setConnectedWallet,
chainToConnect,
onConnected,
walletConfig,
setConnectionStatus,
]);
return (
<ScanScreen
onBack={onBack}
onGetStarted={onGetStarted}
qrCodeUri={qrCodeUri}
walletName={walletConfig.meta.name}
walletIconURL={walletConfig.meta.iconURL}
hideBackButton={hideBackButton}
/>
);
};
@@ -0,0 +1,52 @@
import type { WalletOptions, WalletConfig } from "@thirdweb-dev/react-core";
import { OKXWallet, getInjectedOKXProvider } from "@thirdweb-dev/wallets";
import { OKXConnectUI } from "./OKXConnectUI";
type OKXWalletOptions = {
/**
* When connecting OKX using the QR Code - Wallet Connect connector is used which requires a project id.
* This project id is Your project’s unique identifier for wallet connect that can be obtained at cloud.walletconnect.com.
*
* https://docs.walletconnect.com/2.0/web3modal/options#projectid-required
*/
projectId?: string;
/**
* If true, the wallet will be tagged as "reccomended" in ConnectWallet Modal
*/
recommended?: boolean;
};
export const okxWallet = (
options?: OKXWalletOptions,
): WalletConfig<OKXWallet> => {
return {
id: OKXWallet.id,
recommended: options?.recommended,
meta: {
name: "OKX Wallet",
urls: {
chrome:
"https://chrome.google.com/webstore/detail/okx-wallet/mcohilncbfahbmgdjkbpemcciiolgcge",
android:
"https://play.google.com/store/apps/details?id=com.okinc.okex.gp&pli=1",
ios: "https://apps.apple.com/us/app/okx-buy-bitcoin-eth-crypto/id1327268470",
},
iconURL:
"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iODAiIGhlaWdodD0iODAiIHZpZXdCb3g9IjAgMCA4MCA4MCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjgwIiBoZWlnaHQ9IjgwIiByeD0iMTIiIGZpbGw9ImJsYWNrIi8+CjxwYXRoIGQ9Ik00Ni4wMjg0IDMyLjk2NjhIMzMuMDE5OUMzMi40Njc3IDMyLjk2NjggMzIuMDE1IDMzLjQxOTUgMzIuMDE1IDMzLjk3MTZWNDYuOTgwMUMzMi4wMTUgNDcuNTMyMyAzMi40Njc3IDQ3Ljk4NSAzMy4wMTk5IDQ3Ljk4NUg0Ni4wMjg0QzQ2LjU4MDUgNDcuOTg1IDQ3LjAzMzIgNDcuNTMyMyA0Ny4wMzMyIDQ2Ljk4MDFWMzMuOTcxNkM0Ny4wMzMyIDMzLjQxOTUgNDYuNTgwNSAzMi45NjY4IDQ2LjAyODQgMzIuOTY2OFoiIGZpbGw9IndoaXRlIi8+CjxwYXRoIGQ9Ik0zMS4wMTMzIDE4SDE4LjAwNDlDMTcuNDUyNyAxOCAxNyAxOC40NTI3IDE3IDE5LjAwNDlWMzIuMDEzM0MxNyAzMi41NjU1IDE3LjQ1MjcgMzMuMDE4MiAxOC4wMDQ5IDMzLjAxODJIMzEuMDEzM0MzMS41NjU1IDMzLjAxODIgMzIuMDE4MiAzMi41NjU1IDMyLjAxODIgMzIuMDEzM1YxOS4wMDQ5QzMyLjAxNSAxOC40NTI3IDMxLjU2NTUgMTggMzEuMDEzMyAxOFoiIGZpbGw9IndoaXRlIi8+CjxwYXRoIGQ9Ik02MC45OTUyIDE4SDQ3Ljk4NjdDNDcuNDM0NSAxOCA0Ni45ODE4IDE4LjQ1MjcgNDYuOTgxOCAxOS4wMDQ5VjMyLjAxMzNDNDYuOTgxOCAzMi41NjU1IDQ3LjQzNDUgMzMuMDE4MiA0Ny45ODY3IDMzLjAxODJINjAuOTk1MkM2MS41NDczIDMzLjAxODIgNjIgMzIuNTY1NSA2MiAzMi4wMTMzVjE5LjAwNDlDNjIgMTguNDUyNyA2MS41NDczIDE4IDYwLjk5NTIgMThaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBkPSJNMzEuMDEzMyA0Ny45MzM3SDE4LjAwNDlDMTcuNDUyNyA0Ny45MzM3IDE3IDQ4LjM4NjQgMTcgNDguOTM4NlY2MS45NDcxQzE3IDYyLjQ5OTIgMTcuNDUyNyA2Mi45NTE5IDE4LjAwNDkgNjIuOTUxOUgzMS4wMTMzQzMxLjU2NTUgNjIuOTUxOSAzMi4wMTgyIDYyLjQ5OTIgMzIuMDE4MiA2MS45NDcxVjQ4LjkzODZDMzIuMDE1IDQ4LjM4NjQgMzEuNTY1NSA0Ny45MzM3IDMxLjAxMzMgNDcuOTMzN1oiIGZpbGw9IndoaXRlIi8+CjxwYXRoIGQ9Ik02MC45OTUyIDQ3LjkzMzdINDcuOTg2N0M0Ny40MzQ1IDQ3LjkzMzcgNDYuOTgxOCA0OC4zODY0IDQ2Ljk4MTggNDguOTM4NlY2MS45NDcxQzQ2Ljk4MTggNjIuNDk5MiA0Ny40MzQ1IDYyLjk1MTkgNDcuOTg2NyA2Mi45NTE5SDYwLjk5NTJDNjEuNTQ3MyA2Mi45NTE5IDYyIDYyLjQ5OTIgNjIgNjEuOTQ3MVY0OC45Mzg2QzYyIDQ4LjM4NjQgNjEuNTQ3MyA0Ny45MzM3IDYwLjk5NTIgNDcuOTMzN1oiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPgo=",
},
create: (walletOptions: WalletOptions) => {
const wallet = new OKXWallet({
...walletOptions,
projectId: options?.projectId,
qrcode: false,
});
return wallet;
},
connectUI: OKXConnectUI,
isInstalled() {
return !!getInjectedOKXProvider();
},
};
};
@@ -5,7 +5,7 @@ export type PaperConfig = Omit<
"chain" | "clientId"
> & {
/**
* If true, the wallet will be tagged as "reccomended" in ConnectWallet Modal
* If true, the wallet will be tagged as "recomended" in ConnectWallet Modal
*/
recommended?: boolean;
};
+39
View File
@@ -0,0 +1,39 @@
// eslint-disable-next-line @typescript-eslint/no-var-requires, better-tree-shaking/no-top-level-side-effects
const TypeDoc = require("typedoc");
async function main() {
// Application.bootstrap also exists, which will not load plugins
// Also accepts an array of option readers if you want to disable
// TypeDoc's tsconfig.json/package.json/typedoc.json option readers
const app = await TypeDoc.Application.bootstrapWithPlugins({
entryPoints: ["src/index.ts"],
excludeInternal: true,
externalPattern: [
"**/node_modules/**",
"**/packages/sdk/**",
"**/packages/wallets/**",
"**/packages/chains/**",
],
exclude: [
"**/node_modules/**",
"**/packages/sdk/**",
"**/packages/wallets/**",
"**/packages/chains/**",
],
});
const project = await app.convert();
if (project) {
// Project may not have converted correctly
const outputDir = "typedoc/";
// Rendered docs
await app.generateDocs(project, outputDir);
// Alternatively generate JSON output
await app.generateJson(project, outputDir + "/documentation.json");
}
}
// eslint-disable-next-line better-tree-shaking/no-top-level-side-effects
main();
+17
View File
@@ -1,5 +1,22 @@
# @thirdweb-dev/sdk
## 4.0.7
### Patch Changes
- [#1795](https://github.com/thirdweb-dev/js/pull/1795) [`42ba15f2`](https://github.com/thirdweb-dev/js/commit/42ba15f2c0e77e23e62650119dfaaa5c0dbe4481) Thanks [@kien-ngo](https://github.com/kien-ngo)! - Improve performance for prebuilt implementations"
- [#1787](https://github.com/thirdweb-dev/js/pull/1787) [`ff996646`](https://github.com/thirdweb-dev/js/commit/ff996646b228d4d095eea04b05004dd26fc7e522) Thanks [@MananTank](https://github.com/MananTank)! - Enable typedoc for packages
- [#1824](https://github.com/thirdweb-dev/js/pull/1824) [`d8d48a95`](https://github.com/thirdweb-dev/js/commit/d8d48a9516fc8fdd173fbb91a858fe7ec0725ddd) Thanks [@kien-ngo](https://github.com/kien-ngo)! - Performance improve for erc-1155-signature-mintable
- [#1800](https://github.com/thirdweb-dev/js/pull/1800) [`fd7a9f09`](https://github.com/thirdweb-dev/js/commit/fd7a9f09989e39b02a93d9dfd01cc7378e6ead53) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - Expose getCompositeABI for dynamic contracts
- [#1813](https://github.com/thirdweb-dev/js/pull/1813) [`6d1eabe9`](https://github.com/thirdweb-dev/js/commit/6d1eabe9f9818ee2a79ce5bf6aa74417dbfd0558) Thanks [@kien-ngo](https://github.com/kien-ngo)! - [SDK] Various small improvements
- Updated dependencies [[`ff996646`](https://github.com/thirdweb-dev/js/commit/ff996646b228d4d095eea04b05004dd26fc7e522)]:
- @thirdweb-dev/storage@2.0.1
## 4.0.6
### Patch Changes
+5 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@thirdweb-dev/sdk",
"version": "4.0.6",
"version": "4.0.7",
"description": "The main thirdweb SDK.",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/sdk",
"license": "Apache-2.0",
@@ -71,7 +71,8 @@
"test:all": "SWC_NODE_PROJECT=./tsconfig.test.json nyc --reporter lcovonly --report-dir ./coverage/evm mocha --config './test/evm/.mocharc.json' --timeout 90000 --parallel './test/evm/**/*.test.ts'",
"test": "make test-evm",
"test:single": "SWC_NODE_PROJECT=./tsconfig.test.json mocha --config './test/evm/.mocharc.json' --timeout 90000",
"push": "yalc push"
"push": "yalc push",
"typedoc": "rimraf typedoc && node typedoc.js"
},
"devDependencies": {
"@aws-sdk/client-secrets-manager": "^3.378.0",
@@ -110,6 +111,8 @@
"mocha": "^10.2.0",
"nyc": "^15.1.0",
"prettier": "^3.0.0",
"rimraf": "^3.0.2",
"typedoc": "^0.25.2",
"typescript": "^5.1.6",
"zksync-web3": "^0.14.3"
},
@@ -154,4 +154,3 @@ export function generateSnippets(ecosystem) {
}
generateSnippets("evm");
generateSnippets("solana");
+1
View File
@@ -29,6 +29,7 @@ export * from "./feature-detection/assertEnabled";
export * from "./feature-detection/detectContractFeature";
export * from "./feature-detection/hasFunction";
export * from "./plugin/joinABIs";
export * from "./plugin/getCompositePluginABI";
export * from "./version-checker";
export * from "./fetchSourceFilesFromMetadata";
+6 -5
View File
@@ -7,12 +7,13 @@ export async function getPrebuiltInfo(
): Promise<{ type: string; version: number } | undefined> {
try {
const contract = new Contract(address, IThirdwebContractABI, provider);
const [type, version] = await Promise.all([
utils
.toUtf8String(await contract.contractType()) // eslint-disable-next-line no-control-regex
.replace(/\x00/g, ""),
await contract.contractVersion(),
const [_type, version] = await Promise.all([
contract.contractType(),
contract.contractVersion(),
]);
const type = utils
.toUtf8String(_type) // eslint-disable-next-line no-control-regex
.replace(/\x00/g, "");
return {
type,
version,

Some files were not shown because too many files have changed in this diff Show More