Skip to content

Add transfers

Course: PayTM Part-2 - chapter 3

Once money has been onramped, users should be allowed to transfer money to various wallets

Let’s create a P2P transfer page

  • Got to user-app/app/(dashboard)/layout.tsx
<SidebarItem href={"/p2p"} icon={<P2PTransferIcon />} title="P2P Transfer" />
function P2PTransferIcon() {
return <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" className="w-6 h-6">
<path stroke-linecap="round" stroke-linejoin="round" d="m4.5 19.5 15-15m0 0H8.25m11.25 0v11.25" />
</svg>
}
  • Create a handler for /p2p page by creating user-app/app/(dashboarD)/p2p/page.tsx
export default function() {
return <div>
Dashboard
</div>
}

  • Add a SendCard component that let’s you put the number of a user and amount to send

user-app/components/SendCard.tsx

$1b

user-app/app/(dashboard)/p2p/page.tsx

import { SendCard } from "../../../components/SendCard";
export default function() {
return <div className="w-full">
<SendCard />
</div>
}
  • Create a new action in lib/actions/p2pTransfer.tsx
$1d
  • Update SendCard to call this action
$1f

Try sending money a few times and see if it works. You can inspect the DB by using npx prisma studio in packages/db

Try simulating two request together by adding a 4s sleep timeout in the transaction

$21

Send two requests in two tabs and see if you are able to receive negative balances?

In postgres, a transaction ensure that either all the statements happen or none. It does not lock rows/ revert a transaction if something from this transaction got updated before the transaction committed (unlike MongoDB)

So we need to explicitly lock the balance row for the sending user so that only one transaction can access it at at time, and the other one waits until the first transaction has committed

Hint 1 - https://www.cockroachlabs.com/blog/select-for-update/

Hint 2 - https://www.prisma.io/docs/orm/prisma-client/queries/raw-database-access/raw-queries

Solution
"use server"
import { getServerSession } from "next-auth";
import { authOptions } from "../auth";
import prisma from "@repo/db/client";
export async function p2pTransfer(to: string, amount: number) {
const session = await getServerSession(authOptions);
const from = session?.user?.id;
if (!from) {
return {
message: "Error while sending"
}
}
const toUser = await prisma.user.findFirst({
where: {
number: to
}
});
if (!toUser) {
return {
message: "User not found"
}
}
await prisma.$transaction(async (tx) => {
await tx.$queryRaw`SELECT * FROM "Balance" WHERE "userId" = ${Number(from)} FOR UPDATE`;
const fromBalance = await tx.balance.findUnique({
where: { userId: Number(from) },
});
if (!fromBalance || fromBalance.amount < amount) {
throw new Error('Insufficient funds');
}
await new Promise(r => setTimeout(r, 4000));
await tx.balance.update({
where: { userId: Number(from) },
data: { amount: { decrement: amount } },
});
await tx.balance.update({
where: { userId: toUser.id },
data: { amount: { increment: amount } },
});
});
}