Skip to content

fix: balance checker issues and debug mode #72

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
7 changes: 4 additions & 3 deletions packages/e2e/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ window.Buffer = window.Buffer || require('buffer').Buffer;

const App = () => {
const [paymentId, setPaymentId] = useState<string | null>(
'6438011a8fdd74a899bd0f51'
'641ad861c1d104c62898362d'
);

return (
Expand All @@ -24,8 +24,9 @@ const App = () => {
onChange={(e) => setPaymentId(e.target.value)}
/>
<HelioPay
debugMode={true}
additionalJSON={{ key1: 'value1' }}
cluster="devnet"
cluster="mainnet-beta"
// customApiUrl="https://dev.api.hel.io/v1"
paymentRequestId={paymentId}
onSuccess={(event: SuccessPaymentEvent) => {
Expand All @@ -40,7 +41,7 @@ const App = () => {
onStartPayment={() => {
console.log('onStartPayment');
}}
// supportedCurrencies={['USDC', 'SOL']}
supportedCurrencies={['USDC']}
// paymentType={PaymentRequestType.PAYSTREAM}
// totalAmount={0.01} // @TODO bug when also has normalizedPrice
/>
Expand Down
1 change: 1 addition & 0 deletions packages/react/src/components/baseCheckout/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ export const handleSubmit =
paymentType,
}: IHandleSubmit) =>
(values: FormikValues) => {

const details = {
fullName: values.fullName,
email: values.email,
Expand Down
2 changes: 2 additions & 0 deletions packages/react/src/components/baseCheckout/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { Currency, PaymentRequestType } from '@heliofi/common';

import { SubmitPaymentsTypesProps } from '../heliopayContainer/constants';

export const NOT_ENOUGH_FUNDS_TOOLTIP = 'Not enough funds in your wallet';

export type InheritedOnSubmit = (
data: SubmitPaymentsTypesProps
) => Promise<void>;
Expand Down
79 changes: 61 additions & 18 deletions packages/react/src/components/baseCheckout/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import SwapsForm from '../swapsForm';
import CustomerInfo from '../customerInfo';
import { CheckoutHeader } from '../checkoutHeader';
import validationSchema from './validation-schema';
import { InheritedBaseCheckoutProps } from './constants';
import { InheritedBaseCheckoutProps, NOT_ENOUGH_FUNDS_TOOLTIP } from './constants';
import { useCompositionRoot } from '../../hooks/compositionRoot';
import { useHelioProvider } from '../../providers/helio/HelioContext';

Expand All @@ -35,6 +35,7 @@ import {
} from './styles';
import { CheckoutSearchParamsManager } from '../../domain/services/CheckoutSearchParamsManager';
import { useCheckoutSearchParamsProvider } from '../../providers/checkoutSearchParams/CheckoutSearchParamsContext';
import { useUserSetProperties } from '../../providers/userSetProperties/UserSetPropertiesContext';

type BaseCheckoutProps = InheritedBaseCheckoutProps & {
PricingComponent: FC<PaylinkPricingProps & PaystreamPricingProps>;
Expand All @@ -56,7 +57,10 @@ const BaseCheckout = ({
tokenSwapError,
removeTokenSwapError,
paymentType,
setTokenSwapQuote
} = useHelioProvider();

const { debugMode } = useUserSetProperties();
const { customerDetails } = useCheckoutSearchParamsProvider();
const { HelioSDK } = useCompositionRoot();

Expand All @@ -67,21 +71,36 @@ const BaseCheckout = ({

const canSelectCurrency = allowedCurrencies.length > 1;

const isSwapValid = showSwapMenu && tokenSwapQuote?.from?.symbol && !tokenSwapError;

const payButtonText =
showSwapMenu && tokenSwapQuote?.from?.symbol && !tokenSwapError
isSwapValid
? `PAY IN ${tokenSwapQuote.from.symbol}`
: 'PAY';
const payButtonDisable =
(showSwapMenu && !!tokenSwapError) || tokenSwapLoading;

const paymentDetails = getPaymentDetails();

const getSwapsFormPrice = (formValues: FormikValues) => {
const amount = (decimalAmount || totalAmount) ?? 0;

const amount = (totalAmount || decimalAmount) ?? 0;
return paymentType === PaymentRequestType.PAYLINK
? amount * (formValues.quantity ?? 1)
: amount * (formValues.interval ?? 1);
};

const getSwapOrStandardPrice = (formValues: FormikValues) : number => {

return (isSwapValid ? HelioSDK.tokenConversionService.convertFromMinimalUnits(
tokenSwapQuote.from.symbol,
BigInt(tokenSwapQuote.inAmount)
) : formValues.customPrice)
}

const getSwapOrStandardCurrency = (formValues: FormikValues) : string => {

return (isSwapValid ? tokenSwapQuote.from.symbol : formValues.currency)
}

const searchParams =
CheckoutSearchParamsManager.getFilteredCheckoutSearchParams(
getPaymentFeatures(),
Expand Down Expand Up @@ -121,6 +140,29 @@ const BaseCheckout = ({
interval,
});

const isPayButtonDisabled = (values: FormikValues) =>
(showSwapMenu && !!tokenSwapError) || tokenSwapLoading || !isBalanceEnough(
getSwapOrStandardPrice(values),
values.quantity,
getSwapOrStandardCurrency(values),
values.interval
);

const getPayButtonTooltip = (values: FormikValues) => {
const isDisabled = isPayButtonDisabled(values);
const swapOrStandardPrice = getSwapOrStandardPrice(values);
const swapOrStandardCurrency = getSwapOrStandardCurrency(values);

const tooltipText = debugMode
? isDisabled
? `${NOT_ENOUGH_FUNDS_TOOLTIP} (${swapOrStandardPrice} ${swapOrStandardCurrency})`
: `(${swapOrStandardPrice} ${swapOrStandardCurrency})`
: NOT_ENOUGH_FUNDS_TOOLTIP;

return tooltipText;
}


useEffect(() => {
if (allowedCurrencies.length === 1) {
setActiveCurrency(allowedCurrencies[0]);
Expand Down Expand Up @@ -163,7 +205,15 @@ const BaseCheckout = ({
title={activeCurrency ? `Pay with ${activeCurrency?.symbol}` : 'Pay'}
showSwap={!!getPaymentFeatures().canSwapTokens}
isSwapShown={showSwapMenu}
toggleSwap={() => setShowSwapMenu(!showSwapMenu)}
toggleSwap={() => {
if (showSwapMenu) {
setTokenSwapQuote(null);
setShowSwapMenu(false);
} else {
setShowSwapMenu(true);
}

}}
onHide={onHide}
showQRCode={showQRCode}
/>
Expand Down Expand Up @@ -233,24 +283,17 @@ const BaseCheckout = ({

<ButtonWithTooltip
type="submit"
disabled={
payButtonDisable ||
!isBalanceEnough(
values.customPrice,
values.quantity,
values.currency,
values.interval
)
}
disabled={isPayButtonDisabled(values)}
showTooltip={
debugMode ||
!isBalanceEnough(
values.customPrice,
getSwapOrStandardPrice(values),
values.quantity,
values.currency,
getSwapOrStandardCurrency(values),
values.interval
)
}
tooltipText="Not enough funds in your wallet"
tooltipText={getPayButtonTooltip(values)}
>
{payButtonText}
</ButtonWithTooltip>
Expand Down
33 changes: 19 additions & 14 deletions packages/react/src/components/heliopay/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { SolanaProvider } from '../../providers';
import HelioPayContainer from '../heliopayContainer';
import { useCompositionRoot } from '../../hooks/compositionRoot';
import { CheckoutSearchParamsValues } from '../../domain/services/CheckoutSearchParams';
import { UserSetPropertiesProvider } from '../../providers/userSetProperties/UserSetPropertiesContext';

interface HelioPayProps {
paymentRequestId: string;
Expand All @@ -31,6 +32,7 @@ interface HelioPayProps {
searchCustomerDetails?: CheckoutSearchParamsValues;
additionalJSON?: {};
customApiUrl?: string;
debugMode?: boolean;
}

export const HelioPay = ({
Expand All @@ -48,6 +50,7 @@ export const HelioPay = ({
searchCustomerDetails,
additionalJSON,
customApiUrl,
debugMode = false,
}: HelioPayProps) => {
const [currentTheme, setCurrentTheme] = useState(defaultTheme);

Expand All @@ -71,20 +74,22 @@ export const HelioPay = ({
return (
<ThemeProvider theme={currentTheme}>
<SolanaProvider cluster={cluster}>
<HelioPayContainer
paymentRequestId={paymentRequestId}
onStartPayment={onStartPayment}
onSuccess={onSuccess}
onError={onError}
onPending={onPending}
cluster={cluster}
payButtonTitle={payButtonTitle}
supportedCurrencies={supportedCurrencies}
totalAmount={totalAmount}
paymentType={paymentType}
searchCustomerDetails={searchCustomerDetails}
additionalJSON={additionalJSON}
/>
<UserSetPropertiesProvider debugMode={debugMode}>
<HelioPayContainer
paymentRequestId={paymentRequestId}
onStartPayment={onStartPayment}
onSuccess={onSuccess}
onError={onError}
onPending={onPending}
cluster={cluster}
payButtonTitle={payButtonTitle}
supportedCurrencies={supportedCurrencies}
totalAmount={totalAmount}
paymentType={paymentType}
searchCustomerDetails={searchCustomerDetails}
additionalJSON={additionalJSON}
/>
</UserSetPropertiesProvider>
<Toaster />
</SolanaProvider>
</ThemeProvider>
Expand Down
9 changes: 6 additions & 3 deletions packages/react/src/components/heliopayContainer/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ import React, { FC, useEffect, useMemo, useState } from 'react';
import {
ClusterType,
CreatePaystreamResponse,
CreatePaystreamProps,
ErrorPaymentEvent,
PendingPaymentEvent,
SuccessPaymentEvent,
CreatePaymentProps,
} from '@heliofi/sdk';
import {
AnchorWallet,
Expand Down Expand Up @@ -46,6 +48,7 @@ import {
CheckoutSearchParamsValues,
} from '../../domain/services/CheckoutSearchParams';
import { useCheckoutSearchParamsProvider } from '../../providers/checkoutSearchParams/CheckoutSearchParamsContext';
import { NOT_ENOUGH_FUNDS_TOOLTIP } from '../baseCheckout/constants';

interface HeliopayContainerProps {
paymentRequestId: string;
Expand Down Expand Up @@ -183,7 +186,7 @@ const HelioPayContainer: FC<HeliopayContainerProps> = ({
const recipient = String(paymentDetails?.wallet?.publicKey);
const { symbol } = getCurrency(currency.symbol);

const payload = {
const payload: CreatePaymentProps = {
anchorProvider: helioProvider,
recipientPK: recipient,
symbol,
Expand Down Expand Up @@ -233,7 +236,7 @@ const HelioPayContainer: FC<HeliopayContainerProps> = ({
const recipient = String(paymentDetails?.wallet?.publicKey);
const { symbol } = getCurrency(currency.symbol);

const payload = {
const payload: CreatePaystreamProps = {
anchorProvider: helioProvider,
recipientPK: recipient,
symbol,
Expand Down Expand Up @@ -339,7 +342,7 @@ const HelioPayContainer: FC<HeliopayContainerProps> = ({
!paymentRequestId || !paymentDetails?.id || notEnoughFunds
}
showTooltip={notEnoughFunds}
tooltipText="Not enough funds in your wallet"
tooltipText={NOT_ENOUGH_FUNDS_TOOLTIP}
>
{payButtonTitle}
</ButtonWithTooltip>
Expand Down
7 changes: 4 additions & 3 deletions packages/react/src/providers/helio/HelioContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export const HelioContext = createContext<{
tokenSwapCurrencies: Currency[] | null;
setTokenSwapCurrencies: (tokenSwapCurrencies: Currency[]) => void;
tokenSwapQuote: TokenSwapQuote | null;
setTokenSwapQuote: (tokenSwapQuote: TokenSwapQuote) => void;
setTokenSwapQuote: (tokenSwapQuote: TokenSwapQuote | null) => void;
tokenSwapError: string;
setTokenSwapError: (error: string) => void;
paymentType?: PaymentRequestType;
Expand Down Expand Up @@ -144,7 +144,7 @@ export const useHelioProvider = () => {
validatedMintAddress
);

const currencies = mintAddresses.map((address) =>
const currencies: Currency[] = mintAddresses.map((address) =>
HelioSDK.currencyService.getCurrencyByMint(address)
);

Expand All @@ -160,7 +160,7 @@ export const useHelioProvider = () => {
currencies.push(bonkCurrency);
}

setTokenSwapCurrencies(currencies as unknown as Currency[]);
setTokenSwapCurrencies(currencies);
}
setTokenSwapLoading(false);
};
Expand Down Expand Up @@ -242,6 +242,7 @@ export const useHelioProvider = () => {
getTokenSwapCurrencies,
tokenSwapQuote,
tokenSwapError,
setTokenSwapQuote,
getTokenSwapQuote,
removeTokenSwapError,
paymentType,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { createContext, useContext, FC, ReactNode } from 'react';

interface UserSetPropertiesType {
debugMode: boolean;
}

const UserSetPropertiesContext = createContext<UserSetPropertiesType | undefined>(undefined);

export const UserSetPropertiesProvider: FC<{children: ReactNode, debugMode: boolean}> = ({ children, debugMode = false }) => {

return (
<UserSetPropertiesContext.Provider value={{ debugMode}}>
{children}
</UserSetPropertiesContext.Provider>
);
};

export const useUserSetProperties = (): UserSetPropertiesType => {
const context = useContext(UserSetPropertiesContext);

if (context === undefined) {
throw new Error('userSetProperties must be used within a UserSetPropertiesProvider');
}

return context;
};
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import { BaseTransactionPayload } from '../models/TransactionPayload';
import { ExecuteTransactionPayload, SignedTxAndToken } from '../../types';
import { signSwapTransactions, signTransaction } from '../../SignTransaction';

interface CreatePaystreamProps
export interface CreatePaystreamProps
extends BasePaymentProps<CreatePaystreamResponse> {
interval: number;
maxTime: number;
Expand Down