@smartinvoicexyz/utils
Version:
Unified source for utility functions used across the Smart Invoice protocol.
67 lines (66 loc) • 2.4 kB
JavaScript
import { INVOICE_TYPES } from '@smartinvoicexyz/constants';
import _ from 'lodash';
import { logError } from '.';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const schemaContext = (schema, defaultValues) => {
if (!schema) {
throw new Error('Schema is required');
}
const localSchema = schema;
const isRequired = (name) => {
return schema[name].required;
};
Object.entries(schema.describe({ value: defaultValues }).fields).forEach(([key, value]) => {
localSchema[key] = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
required: value?.tests.some((t) => t.name === 'required'),
};
});
return {
schema: localSchema,
isRequired,
};
};
const checkedAtIndex = (index, checked) => _.map(checked, (_c, i) => i <= index);
export const getUpdatedCheckAmount = ({ e, i, invoice, previousChecked, }) => {
const { amounts, deposited, invoiceType } = _.pick(invoice, [
'amounts',
'deposited',
'invoiceType',
]);
const localDeposited = deposited ? BigInt(deposited) : BigInt(0);
const updateChecked = e.target.checked
? checkedAtIndex(i, previousChecked)
: checkedAtIndex(i - 1, previousChecked);
// calculate values
const sumChecked = amounts?.reduce(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(tot, cur, ind) => updateChecked[ind] ? tot + BigInt(cur) : tot, BigInt(0));
const updateAmount = sumChecked > BigInt(localDeposited)
? sumChecked - BigInt(localDeposited)
: BigInt(0);
if (invoiceType === INVOICE_TYPES.Instant) {
return {
updateChecked,
updateAmount: sumChecked,
};
}
return { updateAmount, updateChecked };
};
export const errorToastHandler = (label, error, toast) => {
const localError = error;
if (localError.name === 'TransactionExecutionError' &&
localError.message.includes('User rejected the request')) {
toast.error({
title: 'Signature rejected!',
description: 'Please accept the transaction in your wallet',
});
}
else {
logError(label, [error]);
toast.error({
title: 'Error occurred!',
description: 'An error occurred while processing the transaction.',
});
}
};