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

V0.3.1 #104

Merged
merged 3 commits into from
Sep 13, 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
16 changes: 8 additions & 8 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"deluser": "ts-node -r tsconfig-paths/register src/scripts/delUser.js"
},
"dependencies": {
"@cashu/cashu-ts": "^1.0.0-rc.12",
"@cashu/cashu-ts": "^1.1.0",
"@cashu/crypto": "^0.2.6",
"@gandlaf21/bc-ur": "^1.1.12",
"@heroicons/react": "^2.1.1",
Expand Down
87 changes: 61 additions & 26 deletions src/components/buttons/Receive.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,15 @@ import { Token } from '@cashu/cashu-ts';
import QRScannerButton from './QRScannerButton';
import { TxStatus, addTransaction } from '@/redux/slices/HistorySlice';
import { useCashu } from '@/hooks/cashu/useCashu';
import { postUserMintQuote, pollForInvoicePayment } from '@/utils/appApiRequests';
import {
postUserMintQuote,
pollForInvoicePayment,
getInvoiceForLNReceive,
getInvoiceStatus,
} from '@/utils/appApiRequests';
import { getTokenFromUrl } from '@/utils/cashu';
import { WaitForInvoiceModalBody } from '../modals/WaitForInvoiceModal';
import { useCashuContext } from '@/hooks/contexts/cashuContext';

const Receive = () => {
const [isReceiveModalOpen, setIsReceiveModalOpen] = useState(false);
Expand All @@ -22,8 +28,11 @@ const Receive = () => {
const [amountUsdCents, setAmountUsdCents] = useState<number | null>(null);
const [currentPage, setCurrentPage] = useState<'input' | 'invoice'>('input');
const [fetchingInvoice, setFetchingInvoice] = useState(false);
const [invoiceTimeout, setInvoiceTimeout] = useState(false);
const [checkingId, setCheckingId] = useState<string | undefined>();

const { requestMintInvoice, decodeToken } = useCashu();
const { decodeToken } = useCashu();
const { activeWallet } = useCashuContext();
const { addToast } = useToast();
const dispatch = useDispatch();
const wallets = useSelector((state: RootState) => state.wallet.keysets);
Expand Down Expand Up @@ -51,7 +60,7 @@ const Receive = () => {
if (!isNaN(parsedAmount)) {
setAmountUsdCents(parsedAmount * 100);
} else {
addToast('Invalid amount' + parsedAmount + '' + inputValue, 'error');
addToast('Invalid amount', 'error');
}
};

Expand All @@ -60,7 +69,7 @@ const Receive = () => {

if (inputValue.includes('http') || inputValue.includes('cashu')) {
handleTokenInput();
} else {
} else if (!isNaN(parseFloat(inputValue))) {
handleAmountInput();
}
};
Expand All @@ -86,15 +95,14 @@ const Receive = () => {

try {
setFetchingInvoice(true);
const { quote, request } = await requestMintInvoice(amountUsdCents);
setInvoiceToPay(request);
const { invoice, checkingId } = await getInvoiceForLNReceive(pubkey, amountUsdCents);
setInvoiceToPay(invoice);
setCheckingId(checkingId);
setFetchingInvoice(false);

await postUserMintQuote(pubkey, quote, request, activeWallet.url, activeWallet.id);

setCurrentPage('invoice');

waitForPayment(pubkey, quote, amountUsdCents, activeWallet.url, activeWallet.id);
waitForPayment(pubkey, checkingId, amountUsdCents, activeWallet.url);
} catch (error) {
console.error('Error receiving ', error);
handleModalClose();
Expand All @@ -103,26 +111,36 @@ const Receive = () => {

const waitForPayment = async (
pubkey: string,
quote: string,
checkingId: string,
amountUsdCents: number,
mintUrl: string,
walletId: string,
) => {
try {
const pollingResponse = await pollForInvoicePayment(
pubkey,
quote,
amountUsdCents,
mintUrl,
walletId,
);

if (pollingResponse.success) {
handlePaymentSuccess(amountUsdCents, mintUrl, quote);
let attempts = 0;
const maxAttempts = 4;
const interval = setInterval(async () => {
const success = await checkPaymentStatus(pubkey, checkingId);
if (success) {
clearInterval(interval);
handlePaymentSuccess(amountUsdCents, mintUrl, checkingId);
}
if (attempts >= maxAttempts) {
clearInterval(interval);
setInvoiceTimeout(true);
return;
} else {
attempts++;
}
console.log('looking up payment for ', checkingId + '...');
}, 5000);
};

const checkPaymentStatus = async (pubkey: string, checkingId: string) => {
try {
const statusResponse = await getInvoiceStatus(pubkey, checkingId);
return statusResponse.paid;
} catch (error) {
addToast('Error receiving', 'error');
console.error('Error polling for invoice payment:', error);
console.error('Error fetching tip status', error);
return false;
}
};

Expand Down Expand Up @@ -152,7 +170,24 @@ const Receive = () => {
setCurrentPage('input');
};

const handleCheckAgain = async () => {};
const handleCheckAgain = async () => {
if (!checkingId || !amountUsdCents) throw new Error('Missing required parameters');
setInvoiceTimeout(false);
const pubkey = window.localStorage.getItem('pubkey');
if (!pubkey) {
throw new Error('No pubkey found');
}
const mintUrl = activeWallet?.mint.mintUrl;
if (!mintUrl) {
throw new Error('No mint url found for active wallet');
}
const paid = await checkPaymentStatus(pubkey, checkingId);
if (paid) {
handlePaymentSuccess(amountUsdCents, mintUrl, checkingId);
} else {
setInvoiceTimeout(true);
}
};

return (
<>
Expand Down Expand Up @@ -188,7 +223,7 @@ const Receive = () => {
<WaitForInvoiceModalBody
invoice={invoiceToPay}
amountUsdCents={amountUsdCents || 0}
invoiceTimeout={false}
invoiceTimeout={invoiceTimeout}
onCheckAgain={handleCheckAgain}
/>
)}
Expand Down
6 changes: 3 additions & 3 deletions src/components/modals/ConfirmEcashReceiveModal.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { RootState, useAppDispatch } from '@/redux/store';
import { CashuMint, CashuWallet, MintKeys, Proof, Token, getEncodedToken } from '@cashu/cashu-ts';
import { CashuMint, CashuWallet, MintKeys, Proof, Token, getEncodedTokenV4 } from '@cashu/cashu-ts';
import { Button, Modal, Spinner } from 'flowbite-react';
import Tooltip from '@/components/utility/Toolttip';
import { useCallback, useEffect, useMemo, useState } from 'react';
Expand Down Expand Up @@ -84,7 +84,7 @@ const ConfirmEcashReceiveModal = ({
addTransaction({
type: 'ecash',
transaction: {
token: getEncodedToken(token),
token: getEncodedTokenV4(token),
amount: amountUsd * 100,
mint: mintUrl,
date: new Date().toLocaleString(),
Expand Down Expand Up @@ -333,7 +333,7 @@ const ConfirmEcashReceiveModal = ({

const handleCopy = () => {
try {
navigator.clipboard.writeText(getEncodedToken(token));
navigator.clipboard.writeText(getEncodedTokenV4(token));
addToast('Copied to clipboard', 'info');
} catch (e) {
addToast('Failed to copy to clipboard', 'error');
Expand Down
4 changes: 2 additions & 2 deletions src/components/notifications/buttons/ClaimTokenButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useToast } from '@/hooks/util/useToast';
import { EcashTransaction, TxStatus, addTransaction } from '@/redux/slices/HistorySlice';
import { useAppDispatch } from '@/redux/store';
import { isTokenSpent } from '@/utils/cashu';
import { Token, getEncodedToken } from '@cashu/cashu-ts';
import { Token, getEncodedTokenV4 } from '@cashu/cashu-ts';
import { Spinner } from 'flowbite-react';
import { useState } from 'react';

Expand Down Expand Up @@ -33,7 +33,7 @@ const ClaimTokenButton = ({ token, clearNotification }: ClaimTokenButtonProps) =
addTransaction({
type: 'ecash',
transaction: {
token: getEncodedToken(token),
token: getEncodedTokenV4(token),
amount: token.token[0].proofs.reduce((acc, p) => acc + p.amount, 0),
unit: 'usd',
mint: token.token[0].mint,
Expand Down
4 changes: 2 additions & 2 deletions src/components/sidebar/Reserve/ConnectReserveSetting.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { setSuccess } from '@/redux/slices/ActivitySlice';
import { TxStatus, addTransaction } from '@/redux/slices/HistorySlice';
import { useAppDispatch } from '@/redux/store';
import { createBlindedMessages } from '@/utils/crypto';
import { CashuMint, getEncodedToken } from '@cashu/cashu-ts';
import { CashuMint, getEncodedTokenV4 } from '@cashu/cashu-ts';
import { constructProofs } from '@/utils/crypto';
import EyeIcon from '@heroicons/react/20/solid/EyeIcon';
import EyeSlashIcon from '@heroicons/react/20/solid/EyeSlashIcon';
Expand Down Expand Up @@ -181,7 +181,7 @@ const ConnectWalletSetting = () => {

addProofs(proofs);

const token = getEncodedToken({
const token = getEncodedTokenV4({
token: [{ proofs: proofs, mint: reserveWallet.mint.mintUrl }],
});

Expand Down
4 changes: 2 additions & 2 deletions src/hooks/boardwalk/useGifts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { request } from '@/utils/appApiRequests';
import { computeTxId } from '@/utils/cashu';
import { GetAllGiftsResponse, GetGiftResponse, GiftAsset } from '@/types';
import { Gift } from '@prisma/client';
import { Token, getEncodedToken } from '@cashu/cashu-ts';
import { Token, getEncodedTokenV4 } from '@cashu/cashu-ts';
import useContacts from './useContacts';
import { RootState } from '@/redux/store';
import { useSelector } from 'react-redux';
Expand Down Expand Up @@ -124,7 +124,7 @@ export const GiftProvider: React.FC<GiftProviderProps> = ({ children }) => {

const getGiftFromToken = async (token: string | Token): Promise<GiftAsset | null> => {
const txid =
typeof token === 'string' ? computeTxId(token) : computeTxId(getEncodedToken(token));
typeof token === 'string' ? computeTxId(token) : computeTxId(getEncodedTokenV4(token));
console.log('txid', txid);
const { gift } = await request<{ gift: string }>(`/api/token/${txid}`, 'GET');
console.log('gift', gift);
Expand Down
6 changes: 3 additions & 3 deletions src/hooks/cashu/useCashu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import {
MeltQuoteResponse,
MintQuoteResponse,
Proof,
getEncodedToken,
getDecodedToken,
MintQuoteState,
Token,
getEncodedTokenV4,
} from '@cashu/cashu-ts';
import { useProofStorage } from './useProofStorage';
import { useNostrMintConnect } from '../nostr/useNostrMintConnect';
Expand Down Expand Up @@ -341,7 +341,7 @@ export const useCashu = () => {
const feeProofs = await getProofsToSend(opts?.feeCents, wallet, {
pubkey: '02' + process.env.NEXT_PUBLIC_FEE_PUBKEY!,
});
const feeToken = getEncodedToken({
const feeToken = getEncodedTokenV4({
token: [{ proofs: feeProofs, mint: wallet.mint.mintUrl }],
unit: 'usd',
});
Expand All @@ -351,7 +351,7 @@ export const useCashu = () => {
}
}

const token = getEncodedToken({
const token = getEncodedTokenV4({
token: [{ proofs, mint: wallet.mint.mintUrl }],
unit: 'usd',
});
Expand Down
6 changes: 3 additions & 3 deletions src/pages/api/invoice/polling/[slug].ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { VercelRequest, VercelResponse } from '@vercel/node';
import { CashuMint, CashuWallet, getEncodedToken, Proof } from '@cashu/cashu-ts';
import { CashuMint, CashuWallet, getEncodedTokenV4, Proof } from '@cashu/cashu-ts';
import { createManyProofs } from '@/lib/proofModels';
import { findUserByPubkey, updateUser } from '@/lib/userModels';
import { updateMintQuote } from '@/lib/mintQuoteModels';
Expand Down Expand Up @@ -128,7 +128,7 @@ export default async function handler(req: VercelRequest, res: VercelResponse) {
pubkey: '02' + process.env.NEXT_PUBLIC_FEE_PUBKEY!,
});

const feeToken = getEncodedToken({
const feeToken = getEncodedTokenV4({
token: [{ proofs: lockedFeeProofs, mint: wallet.mint.mintUrl }],
});

Expand Down Expand Up @@ -157,7 +157,7 @@ export default async function handler(req: VercelRequest, res: VercelResponse) {
let token: string | undefined;
if (isTip) {
/* if its a tip, send as a notification */
token = getEncodedToken({
token = getEncodedTokenV4({
token: [{ proofs: proofsToSendToUser, mint: wallet.mint.mintUrl }],
});
/* not sure why gift is ending up as 'undefined' */
Expand Down
23 changes: 12 additions & 11 deletions src/pages/api/tip/[pubkey].ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,17 +44,18 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
parseFloat(amount as string),
);

axios.post(
`${process.env.NEXT_PUBLIC_PROJECT_URL}/api/invoice/polling/${quote}?isTip=true`,
{
pubkey: user.pubkey,
amount: amount,
keysetId: wallet.keys.id,
mintUrl: wallet.mint.mintUrl,
gift,
fee,
},
);
const host = req.headers.host;
const protocol = process.env.NODE_ENV === 'production' ? 'https' : 'http';
const baseUrl = `${protocol}://${host}`;

axios.post(`${baseUrl}/api/invoice/polling/${quote}?isTip=true`, {
pubkey: user.pubkey,
amount: amount,
keysetId: wallet.keys.id,
mintUrl: wallet.mint.mintUrl,
gift,
fee,
});

return res.status(200).json({
invoice,
Expand Down
Loading