coinforbarter-react-native
Version:
CoinForBarter ReactNative Library - Integrate cryptocurrency payments for goods and services in your Mobile App
130 lines (129 loc) • 6.37 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
/* eslint-disable @typescript-eslint/no-unused-vars */
import React, { createContext, useReducer, useCallback, useState, } from 'react';
import { useErrorBoundary, useNotification, usePreloader } from '../../hooks';
import { coinForBarterRequest } from '../../server';
import { CoinForBarterStatus, MethodTypes } from '../../types';
import { paymentReducer, initialState } from './reducer';
import { PaymentStatus, PaymentTypeOptions, } from './types';
const defaultPaymentContextValue = {
state: initialState(),
submitCurrency: (id, network, currency, handleError) => { },
lockCurrency: (id, handleError, publicKey) => { },
cancelPayment: (id, handleError, publicKey) => { },
findPayment: () => { },
downloadReceipt: () => { },
tryAgain: (shouldClearState) => { },
};
export const PaymentContext = createContext(defaultPaymentContextValue);
export const PaymentProvider = ({ children, config }) => {
const [state, dispatch] = useReducer(paymentReducer, initialState());
const { setIsLoading } = usePreloader();
const { setError } = useErrorBoundary();
const path = '/payments/checkout';
const { success, setExpiryTime } = useNotification();
const [intervalId, setIntervalId] = useState(undefined);
const submitCurrency = useCallback((id, network, currency, handleError, publicKey) => __awaiter(void 0, void 0, void 0, function* () {
setIsLoading(true);
const { status, data, statusCode, message } = yield coinForBarterRequest.call(`${path}/${id}/currency/set/${currency}/${network}`, MethodTypes.Patch, {}, publicKey);
if (status === CoinForBarterStatus.Success) {
success(`Currency changed to ${currency}, ${network}`);
dispatch({ type: PaymentTypeOptions.UPDATE, payload: data });
}
else {
handleError(data, statusCode, message);
}
setIsLoading(false);
}), [setIsLoading, success]);
const startWebSocket = useCallback((id, publicKey) => __awaiter(void 0, void 0, void 0, function* () {
if (intervalId) {
clearInterval(intervalId);
setIntervalId(undefined);
}
setIntervalId(setTimeout(() => {
findPayment(id, publicKey);
}, 60000));
// eslint-disable-next-line react-hooks/exhaustive-deps
}), []);
const lockCurrency = useCallback((id, handleError, publicKey) => __awaiter(void 0, void 0, void 0, function* () {
setIsLoading(true);
const { status, data, statusCode, message } = yield coinForBarterRequest.call(`${path}/${id}/currency/lock`, MethodTypes.Patch, {}, publicKey);
if (status === CoinForBarterStatus.Success) {
setExpiryTime(data.expiresBy);
startWebSocket(id, publicKey);
dispatch({ type: PaymentTypeOptions.UPDATE, payload: data });
}
else {
handleError(data, statusCode, message);
}
setIsLoading(false);
}), [setIsLoading, setExpiryTime, startWebSocket]);
const findPayment = useCallback((id, publicKey) => __awaiter(void 0, void 0, void 0, function* () {
setIsLoading(true);
const { status, data, statusCode, message } = yield coinForBarterRequest.call(`${path}/${id}`, MethodTypes.Get, {}, publicKey);
if (status === CoinForBarterStatus.Success) {
if (data.isCurrencyLocked &&
![
PaymentStatus.Cancelled,
PaymentStatus.Error,
PaymentStatus.Success,
].includes(data.status)) {
setExpiryTime(data.expiresBy);
startWebSocket(id, publicKey);
}
dispatch({ type: PaymentTypeOptions.UPDATE, payload: data });
}
else {
setError({ message, statusCode, data });
}
setIsLoading(false);
}), [setIsLoading, setError, setExpiryTime, startWebSocket]);
const tryAgain = useCallback((shouldClearState = true) => __awaiter(void 0, void 0, void 0, function* () {
setIsLoading(true);
if (shouldClearState) {
dispatch({ type: PaymentTypeOptions.CLEAR, payload: {} });
}
setIsLoading(false);
}), [setIsLoading]);
const downloadReceipt = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
setIsLoading(true);
yield coinForBarterRequest.call(`${path}/${state.payment._id}/download`, MethodTypes.Get, {});
setIsLoading(false);
}), [setIsLoading, state.payment._id]);
const cancelPayment = useCallback((id, handleError, publicKey) => __awaiter(void 0, void 0, void 0, function* () {
setIsLoading(true);
const { status, data, statusCode, message } = yield coinForBarterRequest.call(`${path}/${id}/cancel`, MethodTypes.Patch, {}, publicKey);
if (status === CoinForBarterStatus.Success) {
success(message);
dispatch({
type: PaymentTypeOptions.UPDATE,
payload: Object.assign(Object.assign({}, state), { status: PaymentStatus.Cancelled }),
});
}
else {
handleError(data, statusCode, message);
}
setIsLoading(false);
}), [setIsLoading, state, success]);
return (<PaymentContext.Provider value={{
state,
dispatch,
submitCurrency,
lockCurrency,
cancelPayment,
findPayment,
downloadReceipt,
tryAgain,
config,
}}>
{children}
</PaymentContext.Provider>);
};