Skip to content

Commit

Permalink
creating provider configuration
Browse files Browse the repository at this point in the history
  • Loading branch information
diyahir committed Feb 28, 2024
1 parent 256e589 commit 5350707
Show file tree
Hide file tree
Showing 8 changed files with 66 additions and 30 deletions.
12 changes: 8 additions & 4 deletions packages/nextjs/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
"use client";

import { useState } from "react";
import { Button, Card, CardFooter, CardHeader, Container, Heading, useDisclosure } from "@chakra-ui/react";
import { Button, Card, CardFooter, CardHeader, Container, Heading, Tooltip, useDisclosure } from "@chakra-ui/react";
// import { QrScanner } from "@yudiel/react-qr-scanner";
import type { NextPage } from "next";
import { useAccount } from "wagmi";
import { HistoryTable } from "~~/components/HistoryTable";
import SendModal from "~~/components/SendModalPopup";
import { useLightningApp } from "~~/hooks/LightningProvider";
import { useAccountBalance, useNativeCurrencyPrice } from "~~/hooks/scaffold-eth";

// Import the CSS file with your animation
Expand All @@ -15,6 +16,7 @@ const Home: NextPage = () => {
const { address } = useAccount();
const { balance } = useAccountBalance(address);
const price = useNativeCurrencyPrice();
const { isWebSocketConnected } = useLightningApp();
const { isOpen, onClose, onOpen } = useDisclosure();
const [balanceVisibility, setBalanceVisibility] = useState(0);

Expand Down Expand Up @@ -60,9 +62,11 @@ const Home: NextPage = () => {
},
}}
>
<Button onClick={onOpen} flex="1">
Send over Lightning
</Button>
<Tooltip label={!isWebSocketConnected ? "Lightning Service Provider offline, try refreshing the page." : ""}>
<Button isDisabled={!isWebSocketConnected} onClick={onOpen} flex="1">
Send over Lightning
</Button>
</Tooltip>
</CardFooter>
</Card>

Expand Down
21 changes: 5 additions & 16 deletions packages/nextjs/components/PaymentInvoice.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import React from "react";
import { CopyIcon } from "@chakra-ui/icons";
import {
Box,
Button,
ButtonGroup,
Flex,
Icon,
Step,
StepDescription,
StepIcon,
Expand All @@ -21,6 +19,7 @@ import {
Tr,
} from "@chakra-ui/react";
import { DotLoader } from "react-spinners";
import { useNativeCurrencyPrice } from "~~/hooks/scaffold-eth";
import { LnPaymentInvoice } from "~~/types/utils";

/**
Expand All @@ -45,8 +44,9 @@ export const steps = [
{ title: "Paid", description: "The lightning provider pays lightning invoice. The reciever must be online." },
];

export const PaymentInvoice = ({ invoice, contractId, submitPayment, cancelPayment, step }: PaymentInvoiceProps) => {
export const PaymentInvoice = ({ invoice, submitPayment, cancelPayment, step }: PaymentInvoiceProps) => {
const expiryDate = new Date(invoice.timeExpireDate * 1000);
const price = useNativeCurrencyPrice();

return (
<Flex h="100%" flexDir={"column"} justifyContent={"space-evenly"} alignContent={"space-evenly"} gap={["", "", "5"]}>
Expand All @@ -71,20 +71,9 @@ export const PaymentInvoice = ({ invoice, contractId, submitPayment, cancelPayme
</Td>
</Tr> */}
<Tr>
<Td border="transparent">Contract Id</Td>
<Td border="transparent">USD</Td>
<Td border="transparent" textAlign={"end"}>
{contractId ? contractId.substring(0, 10) + "... " : "Pending"}
{contractId && (
<Button
colorScheme="blue"
size="xs"
onClick={() => {
navigator.clipboard.writeText(contractId || "");
}}
>
<Icon as={CopyIcon} />
</Button>
)}
${((invoice.satoshis * price) / 100_000_000).toFixed(3)}
</Td>
</Tr>
</Tbody>
Expand Down
5 changes: 4 additions & 1 deletion packages/nextjs/components/SendModalPopup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
} from "@chakra-ui/react";
import { QrScanner } from "@yudiel/react-qr-scanner";
import { PaymentRequestObject, decode } from "bolt11";
import toast from "react-hot-toast";
import { useWalletClient } from "wagmi";
import { PaymentInvoice, steps } from "~~/components/PaymentInvoice";
import { useLightningApp } from "~~/hooks/LightningProvider";
Expand Down Expand Up @@ -119,7 +120,9 @@ function SendModal({ isOpen, onClose }: SendModalProps) {
setActiveStep(2);
})
.catch(e => {
console.error(e);
console.error(e.message);
toast.error("User rejected transaction");
cleanAndClose();
});
}

Expand Down
5 changes: 0 additions & 5 deletions packages/nextjs/hooks/LightningProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,6 @@ export const LightningProvider = ({ children }: { children: React.ReactNode }) =
};

const { sendMessage, isWebSocketConnected, data } = useWebSocket("ws://localhost:3003");
// const { data: walletClient } = useWalletClient();
// const { data: yourContract } = useScaffoldContract({
// contractName: "HashedTimelock",
// walletClient,
// });

useScaffoldEventSubscriber({
contractName: "HashedTimelock",
Expand Down
2 changes: 1 addition & 1 deletion packages/server/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import dotenv from "dotenv";
import { ethers } from "ethers";
import { decode } from "bolt11";
import { validateLnInvoiceAndContract } from "./utils/validation";
import { InvoiceRequest, ContractDetails } from "./types";
import { InvoiceRequest, ContractDetails } from "./types/types";
import deployedContracts from "./contracts/deployedContracts";

dotenv.config();
Expand Down
15 changes: 15 additions & 0 deletions packages/server/src/provider.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export type ProviderConfig = {
minSats: number;
maxSats: number;
baseFee: number;
basisPointFee: number; // 100 = 1%
secondsTillInvoiceExpires: number;
};

export const providerConfig: ProviderConfig = {
minSats: 2,
maxSats: 42,
baseFee: 0, // 100 = 1%
basisPointFee: 0,
secondsTillInvoiceExpires: 3 * 60,
};
File renamed without changes.
36 changes: 33 additions & 3 deletions packages/server/src/utils/validation.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { PaymentRequestObject } from "bolt11";
import { ContractDetails } from "../types";
import { ContractDetails } from "../types/types";
import { providerConfig } from "../provider.config";

type validationResponse = {
isValid: boolean;
Expand All @@ -16,10 +17,25 @@ export function validateLnInvoiceAndContract(
message: "Invoice amount is less than contract amount",
};
}
if (lnInvoiceDetails.satoshis > 42) {
if (lnInvoiceDetails.satoshis > providerConfig.maxSats) {
return {
isValid: false,
message: "Invoice amount is higher than 42 satoshis ;(",
message: `Invoice amount is higher than ${providerConfig.maxSats} satoshis ;(`,
};
}
if (lnInvoiceDetails.satoshis < providerConfig.minSats) {
return {
isValid: false,
message: `Invoice amount is less than ${providerConfig.minSats} satoshis ;(`,
};
}
if (
Number(contractDetails.amount) <
getContractAmountFromInvoice(lnInvoiceDetails.satoshis)
) {
return {
isValid: false,
message: "Invoice amount is less than contract amount with fees",
};
}

Expand All @@ -32,6 +48,13 @@ export function validateLnInvoiceAndContract(
return { isValid: false, message: "Contract has expired" };
}

if (
Number(contractDetails.timelock) - currentTimestamp <
providerConfig.secondsTillInvoiceExpires
) {
return { isValid: false, message: "Insufficient buffer to claim contract" };
}

if (getPaymentHash(lnInvoiceDetails) !== contractDetails.hashlock) {
return { isValid: false, message: "Hashlock mismatch" };
}
Expand Down Expand Up @@ -65,3 +88,10 @@ export function getPaymentHash(
}
return ("0x" + paymentHash.data.toString()) as `0x${string}`;
}

export function getContractAmountFromInvoice(satsInInvoice: number) {
return (
satsInInvoice * (1 + providerConfig.basisPointFee / 10000) +
providerConfig.baseFee
);
}

0 comments on commit 5350707

Please sign in to comment.