Skip to content
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
45 changes: 25 additions & 20 deletions react/lib/components/Widget/Widget.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ import {
getAddressBalance,
isFiat,
Transaction,
getCashtabProviderStatus,
openCashtabPayment,
initializeCashtabStatus,
DECIMALS,
CurrencyObject,
getCurrencyObject,
Expand Down Expand Up @@ -415,6 +416,7 @@ export const Widget: React.FunctionComponent<WidgetProps> = props => {
const [text, setText] = useState(`Send any amount of ${thisAddressType}`);
const [widgetButtonText, setWidgetButtonText] = useState('Send Payment');
const [opReturn, setOpReturn] = useState<string | undefined>();
const [isCashtabAvailable, setIsCashtabAvailable] = useState<boolean>(false);

const [isAboveMinimumAltpaymentAmount, setIsAboveMinimumAltpaymentAmount] = useState<boolean | null>(null);

Expand Down Expand Up @@ -460,6 +462,19 @@ export const Widget: React.FunctionComponent<WidgetProps> = props => {
setHasPrice(price !== undefined && price > 0)
}, [price])

useEffect(() => {
const initCashtab = async () => {
try {
const isAvailable = await initializeCashtabStatus();
setIsCashtabAvailable(isAvailable);
} catch (error) {
setIsCashtabAvailable(false);
}
};

initCashtab();
}, []);

useEffect(() => {
(async () => {
if (isChild !== true) {
Expand Down Expand Up @@ -597,7 +612,12 @@ export const Widget: React.FunctionComponent<WidgetProps> = props => {
let url;

setThisAddressType(thisAddressType);
setWidgetButtonText(`Send with ${thisAddressType} wallet`);

if (thisAddressType === 'XEC' && isCashtabAvailable) {
setWidgetButtonText('Send with Cashtab');
} else {
setWidgetButtonText(`Send with ${thisAddressType} wallet`);
}

if (thisCurrencyObject && hasPrice) {
const convertedAmount = thisCurrencyObject.float / price
Expand Down Expand Up @@ -628,7 +648,7 @@ export const Widget: React.FunctionComponent<WidgetProps> = props => {
}
setUrl(url ?? "");
}
}, [to, thisCurrencyObject, price, thisAmount, opReturn, hasPrice]);
}, [to, thisCurrencyObject, price, thisAmount, opReturn, hasPrice, isCashtabAvailable]);

useEffect(() => {
try {
Expand Down Expand Up @@ -693,24 +713,9 @@ export const Widget: React.FunctionComponent<WidgetProps> = props => {
}
}, [totalReceived, currency, goalAmount, price, hasPrice, contributionOffset]);

const handleButtonClick = () => {
const handleButtonClick = async () => {
if (thisAddressType === 'XEC') {
const hasExtension = getCashtabProviderStatus();
if (!hasExtension) {
const webUrl = `https://cashtab.com/#/send?bip21=${url}`;
window.open(webUrl, '_blank');
} else {
return window.postMessage(
{
type: 'FROM_PAGE',
text: 'Cashtab',
txInfo: {
bip21: url
},
},
'*',
);
}
await openCashtabPayment(url);
} else {
window.location.href = url;
}
Expand Down
8 changes: 0 additions & 8 deletions react/lib/util/api-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,3 @@ export default {
getAddressBalance,
};

export const getCashtabProviderStatus = () => {
const windowAny = window as any
if (window && windowAny.bitcoinAbc && windowAny.bitcoinAbc === 'cashtab') {
return true;
}
return false;
};

119 changes: 119 additions & 0 deletions react/lib/util/cashtab.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import {
CashtabConnect,
CashtabExtensionUnavailableError,
CashtabAddressDeniedError,
CashtabTimeoutError
} from 'cashtab-connect';

const cashtab = new CashtabConnect();

// Cache for extension status to avoid multiple checks
let extensionStatusCache: boolean | null = null;
let extensionStatusPromise: Promise<boolean> | null = null;

/**
* Check if the Cashtab extension is available (with caching)
* This function caches the result to avoid multiple extension checks per page load
* @returns Promise<boolean> - true if extension is available, false otherwise
*/
export const getCashtabProviderStatus = async (): Promise<boolean> => {
// Return cached result if available
if (extensionStatusCache !== null) {
return extensionStatusCache;
}

// If a check is already in progress, wait for it
if (extensionStatusPromise !== null) {
return extensionStatusPromise;
}

extensionStatusPromise = (async () => {
try {
const isAvailable = await cashtab.isExtensionAvailable();
extensionStatusCache = isAvailable;
return isAvailable;
} catch (error) {
extensionStatusCache = false;
return false;
} finally {
// Clear the promise so future calls can make a fresh check if needed
extensionStatusPromise = null;
}
})();

return extensionStatusPromise;
};

/**
* Clear the cached extension status (useful for testing or if extension state changes)
*/
export const clearCashtabStatusCache = (): void => {
extensionStatusCache = null;
extensionStatusPromise = null;
};


export const initializeCashtabStatus = async (): Promise<boolean> => {
return getCashtabProviderStatus();
};

export const waitForCashtabExtension = async (timeout?: number): Promise<void> => {
return cashtab.waitForExtension(timeout);
};

/**
* Request the user's eCash address from their Cashtab wallet
* @returns Promise<string> - The user's address
* @throws {CashtabExtensionUnavailableError} When the Cashtab extension is not available
* @throws {CashtabAddressDeniedError} When the user denies the address request
* @throws {CashtabTimeoutError} When the request times out
*/
export const requestCashtabAddress = async (): Promise<string> => {
return cashtab.requestAddress();
};

export const sendXecWithCashtab = async (address: string, amount: string | number): Promise<any> => {
return cashtab.sendXec(address, amount);
};

/**
* Open Cashtab with a BIP21 payment URL
* @param bip21Url - The BIP21 formatted payment URL
* @param fallbackUrl - Optional fallback URL if extension is not available
*/
export const openCashtabPayment = async (bip21Url: string, fallbackUrl?: string): Promise<void> => {
try {
const isAvailable = await getCashtabProviderStatus();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this approach -- checking status on button click -- is probably effective in most current contexts. However it would be wasteful for any application where multiple clicks are expected.

The cashtab provider status is not expected to change during a user's visit (and, even if it did --- e.g. if the user installs the cashtab extension --- a refresh is required for this to be detected).

Would be more robust and payments would be faster if this check were performed on page load. This would also allow you to conditionally render the button, i.e. show the user that it will open Cashtab or the mobile app or Electrum before a click.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea - now we can make this nice little text change on widget load:

image


if (isAvailable) {
const url = new URL(bip21Url);
const address = url.pathname;
const amount = url.searchParams.get('amount');

if (amount) {
await sendXecWithCashtab(address, amount);
} else {
const webUrl = fallbackUrl || `https://cashtab.com/#/send?bip21=${encodeURIComponent(bip21Url)}`;
window.open(webUrl, '_blank');
}
} else {
const webUrl = fallbackUrl || `https://cashtab.com/#/send?bip21=${encodeURIComponent(bip21Url)}`;
window.open(webUrl, '_blank');
}
} catch (error) {
if (error instanceof CashtabAddressDeniedError) {
// User rejected the transaction - do nothing for now
// This case is handled here in case we want to add specific behavior in the future
return;
}

const webUrl = fallbackUrl || `https://cashtab.com/#/send?bip21=${encodeURIComponent(bip21Url)}`;
window.open(webUrl, '_blank');
}
};

export {
CashtabExtensionUnavailableError,
CashtabAddressDeniedError,
CashtabTimeoutError
};
1 change: 1 addition & 0 deletions react/lib/util/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export * from './address';
export * from './api-client';
export * from './cashtab';
export * from './constants';
export * from './format';
export * from './opReturn';
Expand Down
1 change: 1 addition & 0 deletions react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
"@types/jest": "^29.5.11",
"axios": "1.6.5",
"bignumber.js": "9.0.2",
"cashtab-connect": "^1.1.0",
"copy-to-clipboard": "3.3.3",
"crypto-js": "^4.2.0",
"jest": "^29.7.0",
Expand Down