Skip to content

Commit

Permalink
fetch user sessions with thirdweb sdk
Browse files Browse the repository at this point in the history
  • Loading branch information
alecananian committed Sep 20, 2024
1 parent cfe7ebd commit b156e0f
Show file tree
Hide file tree
Showing 16 changed files with 151 additions and 926 deletions.
9 changes: 6 additions & 3 deletions apps/api/src/middleware/chain.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
import * as Sentry from "@sentry/node";
import { DEFAULT_TDK_CHAIN_ID } from "@treasure-dev/tdk-core";
import { type Chain, defineChain } from "thirdweb";

import type { App } from "../utils/app";

declare module "fastify" {
interface FastifyRequest {
chainId: number;
chain: Chain;
}
}

export const withChain = (app: App) => {
app.decorateRequest("chain");
app.decorateRequest("chainId");
app.addHook("onRequest", async (req) => {
req.chainId =
const chainId =
typeof req.headers["x-chain-id"] === "string"
? Number(req.headers["x-chain-id"])
: DEFAULT_TDK_CHAIN_ID;
Sentry.setContext("chain", { chainId: req.chainId });
req.chain = defineChain(chainId);
Sentry.setContext("chain", { chainId });
});
};
38 changes: 21 additions & 17 deletions apps/api/src/routes/auth.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {
DEFAULT_TDK_CHAIN_ID,
type UserContext,
getAllActiveSigners,
getUserSessions,
} from "@treasure-dev/tdk-core";
import type { FastifyPluginAsync } from "fastify";

Expand Down Expand Up @@ -31,8 +31,8 @@ export const authRoutes =
auth,
thirdwebAuth,
db,
client,
engine,
wagmiConfig,
}: TdkApiContext): FastifyPluginAsync =>
async (app) => {
app.get<{
Expand All @@ -53,7 +53,7 @@ export const authRoutes =
async (req, reply) => {
const payload = await thirdwebAuth.generatePayload({
address: req.query.address,
chainId: req.chainId,
chainId: req.chain.id,
});
reply.send(payload);
},
Expand Down Expand Up @@ -141,17 +141,17 @@ export const authRoutes =
smartAccountAddress: user.address,
};

const [authToken, allActiveSigners, profile] = await Promise.all([
const [authToken, userSessions, profile] = await Promise.all([
auth.generateJWT(user.address, {
issuer: payload.domain,
issuedAt: new Date(payload.issued_at),
expiresAt: new Date(payload.expiration_time),
context: userContext,
}),
getAllActiveSigners({
chainId: Number(chainId),
getUserSessions({
client,
chain: req.chain,
address: user.address,
wagmiConfig,
}),
db.userProfile.upsert({
where: { userId: user.id },
Expand All @@ -161,23 +161,27 @@ export const authRoutes =
}),
]);

const sessions = userSessions.map((session) => ({
...session,
approvedTargets: session.approvedTargets.map((target) =>
target.toLowerCase(),
),
nativeTokenLimitPerTransaction:
session.nativeTokenLimitPerTransaction.toString(),
startTimestamp: session.startTimestamp.toString(),
endTimestamp: session.endTimestamp.toString(),
}));

reply.send({
token: authToken,
user: {
...userContext,
...user,
...profile,
...transformUserProfileResponseFields(profile),
allActiveSigners: allActiveSigners.map((activeSigner) => ({
...activeSigner,
approvedTargets: activeSigner.approvedTargets.map((target) =>
target.toLowerCase(),
),
nativeTokenLimitPerTransaction:
activeSigner.nativeTokenLimitPerTransaction.toString(),
startTimestamp: activeSigner.startTimestamp.toString(),
endTimestamp: activeSigner.endTimestamp.toString(),
})),
sessions,
// Fields for backwards compatibility
allActiveSigners: sessions,
},
});
},
Expand Down
10 changes: 5 additions & 5 deletions apps/api/src/routes/harvesters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,14 @@ export const harvestersRoutes =
},
async (req, reply) => {
const {
chainId,
chain,
params: { id },
userAddress,
} = req;

const harvesterAddress = id as AddressString;
const harvesterInfo = await getHarvesterInfo({
chainId,
chainId: chain.id,
harvesterAddress,
wagmiConfig,
});
Expand All @@ -70,7 +70,7 @@ export const harvestersRoutes =

const harvesterUserInfo = userAddress
? await getHarvesterUserInfo({
chainId,
chainId: chain.id,
harvesterInfo,
userAddress,
inventoryApiUrl: env.TROVE_API_URL,
Expand Down Expand Up @@ -104,14 +104,14 @@ export const harvestersRoutes =
},
async (req, reply) => {
const {
chainId,
chain,
params: { id },
userAddress,
} = req;

const harvesterCorruptionRemovalInfo =
await fetchHarvesterCorruptionRemovalInfo({
chainId,
chainId: chain.id,
harvesterAddress: id,
userAddress,
inventoryApiUrl: env.TROVE_API_URL,
Expand Down
32 changes: 16 additions & 16 deletions apps/api/src/routes/magicswap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export const magicswapRoutes =
},
async (req, reply) => {
const pools = await fetchPools({
chainId: req.chainId,
chainId: req.chain.id,
inventoryApiUrl: env.TROVE_API_URL,
inventoryApiKey: env.TROVE_API_KEY,
wagmiConfig,
Expand Down Expand Up @@ -92,7 +92,7 @@ export const magicswapRoutes =
async (req, reply) => {
const pool = await fetchPool({
pairId: req.params.id,
chainId: req.chainId,
chainId: req.chain.id,
inventoryApiUrl: env.TROVE_API_URL,
inventoryApiKey: env.TROVE_API_KEY,
wagmiConfig,
Expand Down Expand Up @@ -127,10 +127,10 @@ export const magicswapRoutes =
},
},
async (req, reply) => {
const { chainId, body } = req;
const { chain, body } = req;

const pools = await fetchPools({
chainId,
chainId: chain.id,
inventoryApiUrl: env.TROVE_API_URL,
inventoryApiKey: env.TROVE_API_KEY,
wagmiConfig,
Expand Down Expand Up @@ -165,7 +165,7 @@ export const magicswapRoutes =
},
},
async (req, reply) => {
const { userAddress, authError, body, chainId } = req;
const { userAddress, authError, body, chain } = req;

if (!userAddress) {
throw new TdkError({
Expand All @@ -191,7 +191,7 @@ export const magicswapRoutes =
} = body;

const pools = await fetchPools({
chainId,
chainId: chain.id,
inventoryApiUrl: env.TROVE_API_URL,
inventoryApiKey: env.TROVE_API_KEY,
wagmiConfig,
Expand Down Expand Up @@ -227,7 +227,7 @@ export const magicswapRoutes =
}

const swapArguments = getSwapArgs({
chainId,
chainId: chain.id,
toAddress: userAddress,
tokenIn,
tokenOut,
Expand All @@ -243,7 +243,7 @@ export const magicswapRoutes =
try {
const result = await writeTransaction({
engine,
chainId,
chainId: chain.id,
contractAddress: swapArguments.address,
backendWallet: req.backendWallet ?? backendWallet,
smartAccountAddress: userAddress,
Expand Down Expand Up @@ -285,7 +285,7 @@ export const magicswapRoutes =
},
},
async (req, reply) => {
const { userAddress, authError, body, chainId, params } = req;
const { userAddress, authError, body, chain, params } = req;

if (!userAddress) {
throw new TdkError({
Expand All @@ -309,7 +309,7 @@ export const magicswapRoutes =

const pool = await fetchPool({
pairId: params.id,
chainId,
chainId: chain.id,
inventoryApiUrl: env.TROVE_API_URL,
inventoryApiKey: env.TROVE_API_KEY,
wagmiConfig,
Expand All @@ -325,7 +325,7 @@ export const magicswapRoutes =
}

const addLiquidityArgs = getAddLiquidityArgs({
chainId,
chainId: chain.id,
toAddress: userAddress,
amount0: amount0 ? BigInt(amount0) : undefined,
amount1: amount1 ? BigInt(amount1) : undefined,
Expand All @@ -339,7 +339,7 @@ export const magicswapRoutes =
try {
const result = await writeTransaction({
engine,
chainId,
chainId: chain.id,
contractAddress: addLiquidityArgs.address,
backendWallet: req.backendWallet ?? backendWallet,
smartAccountAddress: userAddress,
Expand Down Expand Up @@ -381,7 +381,7 @@ export const magicswapRoutes =
},
},
async (req, reply) => {
const { userAddress, authError, body, chainId, params } = req;
const { userAddress, authError, body, chain, params } = req;

if (!userAddress) {
throw new TdkError({
Expand All @@ -405,7 +405,7 @@ export const magicswapRoutes =

const pool = await fetchPool({
pairId: params.id,
chainId,
chainId: chain.id,
inventoryApiUrl: env.TROVE_API_URL,
inventoryApiKey: env.TROVE_API_KEY,
wagmiConfig,
Expand All @@ -421,7 +421,7 @@ export const magicswapRoutes =
}

const removeLiquidityArgs = getRemoveLiquidityArgs({
chainId,
chainId: chain.id,
toAddress: userAddress,
amountLP: BigInt(amountLP),
amount0Min: BigInt(amount0Min),
Expand All @@ -435,7 +435,7 @@ export const magicswapRoutes =
try {
const result = await writeTransaction({
engine,
chainId,
chainId: chain.id,
contractAddress: removeLiquidityArgs.address,
backendWallet: req.backendWallet ?? backendWallet,
smartAccountAddress: userAddress,
Expand Down
6 changes: 3 additions & 3 deletions apps/api/src/routes/projects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export const projectsRoutes =
},
},
},
async ({ chainId, params: { slug } }, reply) => {
async ({ chain, params: { slug } }, reply) => {
const project = await db.project.findUnique({
where: { slug },
select: {
Expand All @@ -42,15 +42,15 @@ export const projectsRoutes =
color: true,
backendWallets: {
where: {
chainId,
chainId: chain.id,
},
select: {
address: true,
},
},
callTargets: {
where: {
chainId,
chainId: chain.id,
},
select: {
address: true,
Expand Down
12 changes: 6 additions & 6 deletions apps/api/src/routes/transactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export const transactionsRoutes =
checkMaintenanceMode();

const {
chainId,
chain,
userAddress,
authError,
body: {
Expand Down Expand Up @@ -107,7 +107,7 @@ export const transactionsRoutes =
);

const { result } = await engine.contract.write(
chainId.toString(),
chain.id.toString(),
address,
req.backendWallet ?? backendWallet,
{
Expand All @@ -119,7 +119,7 @@ export const transactionsRoutes =
simulateTransaction,
undefined,
userAddress,
getContractAddress(chainId, "ManagedAccountFactory"),
getContractAddress(chain.id, "ManagedAccountFactory"),
);
reply.send(result);
} catch (err) {
Expand Down Expand Up @@ -153,7 +153,7 @@ export const transactionsRoutes =
checkMaintenanceMode();

const {
chainId,
chain,
userAddress,
authError,
body: {
Expand All @@ -177,7 +177,7 @@ export const transactionsRoutes =
try {
Sentry.setExtra("transaction", { to, value, data });
const { result } = await engine.backendWallet.sendTransaction(
chainId.toString(),
chain.id.toString(),
req.backendWallet ?? backendWallet,
{
toAddress: to,
Expand All @@ -188,7 +188,7 @@ export const transactionsRoutes =
simulateTransaction,
undefined,
userAddress,
getContractAddress(chainId, "ManagedAccountFactory"),
getContractAddress(chain.id, "ManagedAccountFactory"),
);
reply.send(result);
} catch (err) {
Expand Down
Loading

0 comments on commit b156e0f

Please sign in to comment.