Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add loader when processing payment and check sent amount #5

Merged
merged 6 commits into from
May 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/build-publish.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jobs:
uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
with:
version: v8.x.x
version: latest
- uses: actions/setup-node@v4
with:
node-version: '20'
Expand Down
28 changes: 28 additions & 0 deletions app/components/loader.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { motion } from "framer-motion";
import { useBackdropContext } from "~/lib/context/backdrop";

export function Fallback() {
return null;
}

export function Loader() {
const { isLoading } = useBackdropContext();
return (
<>
{isLoading ? (
<div className="absolute inset-0 flex flex-col items-center justify-center gap-y-10">
<motion.div
className="h-24 w-24 rounded-full border-[16px] border-gray-200 border-t-green-1"
animate={{ rotate: 360 }}
transition={{
repeat: Infinity,
ease: "linear",
duration: 1,
}}
/>
<h2 className="text-2xl uppercase">Processing payment...</h2>
</div>
) : null}
</>
);
}
22 changes: 22 additions & 0 deletions app/components/providers/backdropProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { type ReactNode, useState } from "react";
import { BackdropContext } from "~/lib/context/backdrop";

type BackdropProviderProps = {
children: ReactNode;
};

export const BackdropProvider = ({ children }: BackdropProviderProps) => {
const [isLoading, setIsLoading] = useState(true);

return (
<BackdropContext.Provider
value={{
isLoading,
setIsLoading,
}}
>
{children}
</BackdropContext.Provider>
);
};
BackdropProvider.displayName = "BackdropProvider";
2 changes: 1 addition & 1 deletion app/entry.server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { RemixServer } from "@remix-run/react";
import isbot from "isbot";
import { renderToPipeableStream } from "react-dom/server";

const ABORT_DELAY = 5_000;
const ABORT_DELAY = 10_000;

export default function handleRequest(
request: Request,
Expand Down
20 changes: 20 additions & 0 deletions app/lib/context/backdrop.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { createContext, useContext } from "react";

type BackdropContextProps = {
isLoading: boolean;
setIsLoading: (isLoading: boolean) => void;
};

export const BackdropContext = createContext<BackdropContextProps | null>(null);

export const useBackdropContext = () => {
const backdropContext = useContext(BackdropContext);

if (!backdropContext) {
throw new Error(
'"useBackdropContext" is used outside the BackdropContextProps.'
);
}

return backdropContext;
};
75 changes: 67 additions & 8 deletions app/lib/open-payments.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
} from "@interledger/open-payments";
import { createId } from "@paralleldrive/cuid2";
import { randomUUID } from "crypto";
import { formatAmount } from "~/utils/helpers";

async function createClient() {
return await createAuthenticatedClient({
Expand All @@ -30,7 +31,6 @@ export async function fetchQuote(
): Promise<QuoteResponse> {
const opClient = await createClient();
const walletAddress = await getWalletAddress(args.walletAddress, opClient);
// const receiver = await getWalletAddress(args.receiver, opClient);

const amountObj = {
value: BigInt(args.amount * 10 ** walletAddress.assetScale).toString(),
Expand Down Expand Up @@ -226,9 +226,9 @@ export interface Amount {

type CreateOutgoingPaymentParams = {
walletAddress: WalletAddress;
debitAmount: Amount;
receiveAmount: Amount;
nonce: string;
debitAmount?: Amount;
receiveAmount?: Amount;
nonce?: string;
paymentId: string;
opClient: AuthenticatedClient;
};
Expand Down Expand Up @@ -269,7 +269,7 @@ async function createOutgoingPaymentGrant(
finish: {
method: "redirect",
uri: `${process.env.REDIRECT_URL}?paymentId=${paymentId}`,
nonce: nonce,
nonce: nonce || "",
},
},
}
Expand All @@ -293,7 +293,7 @@ export async function finishPayment(
accessToken: string,
receiver: string,
isRequestPayment?: boolean
): Promise<void> {
): Promise<{ url: string; accessToken: string }> {
const opClient = await createClient();

const continuation = await opClient.grant.continue(
Expand All @@ -306,10 +306,12 @@ export async function finishPayment(
}
);

await opClient.outgoingPayment
const url = new URL(walletAddress.id).origin;

const outgoingPayment = await opClient.outgoingPayment
.create(
{
url: new URL(walletAddress.id).origin,
url: url,
accessToken: continuation.access_token.value,
},
{
Expand All @@ -335,6 +337,63 @@ export async function finishPayment(
throw new Error("Could not complete incoming payment.");
});
}

return {
url: outgoingPayment.id,
accessToken: continuation.access_token.value,
};
}

function timeout(delay: number) {
return new Promise((res) => setTimeout(res, delay));
}

export type PaymentResultType = {
message: string;
color: "red" | "green";
error: boolean;
};

export async function checkOutgoingPayment(
url: string,
accessToken: string
): Promise<PaymentResultType> {
const opClient = await createClient();
await timeout(7000);

// get outgoing payment, to check if there was enough balance
const checkOutgoingPaymentResponse = await opClient.outgoingPayment
.get({
url: url,
accessToken: accessToken,
})
.then((op) => {
let paymentResult: PaymentResultType;
if (Number(op.sentAmount.value) >= Number(op.receiveAmount.value)) {
paymentResult = {
message: "Payment successful",
color: "green",
error: false,
};
} else if (Number(op.sentAmount.value) === 0) {
paymentResult = {
message: "Payment failed. Check your balance and try again.",
color: "red",
error: true,
};
} else {
const amountSent = formatAmount(op.sentAmount);
paymentResult = {
message: `Payment failed. Only ${amountSent.amountWithCurrency} was sent. Check your balance and try again.`,
color: "red",
error: true,
};
}

return paymentResult;
});

return checkOutgoingPaymentResponse;
}

export async function getRequestPaymentDetails(
Expand Down
13 changes: 8 additions & 5 deletions app/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { type ReactNode, useEffect } from "react";
import { Button } from "./components/ui/button";
import { FinishError } from "./components/icons";
import { DialogProvider } from "./components/providers/dialogProvider";
import { BackdropProvider } from "./components/providers/backdropProvider";

export const links: LinksFunction = () => [
{
Expand Down Expand Up @@ -54,11 +55,13 @@ export default function App() {

<body className="bg-foreground text-primary flex justify-center items-center h-screen">
<div className="w-full h-full p-20">
<DialogProvider>
<DialPadProvider>
<Outlet />
</DialPadProvider>
</DialogProvider>
<BackdropProvider>
<DialogProvider>
<DialPadProvider>
<Outlet />
</DialPadProvider>
</DialogProvider>
</BackdropProvider>
</div>
<ScrollRestoration />
<Scripts />
Expand Down
Loading