forked from ZyntariHQ/Invoisio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpayment-link.ts
More file actions
107 lines (89 loc) · 2.58 KB
/
Copy pathpayment-link.ts
File metadata and controls
107 lines (89 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import type { Invoice } from "./invoices";
type PaymentLinkParams = {
amount?: string;
assetCode?: string;
assetIssuer?: string;
destination: string;
memo?: string;
memoType?: "text" | "id" | "hash" | "return";
};
export function getInvoiceAsset(invoice: Invoice): string {
return invoice.asset_code ?? invoice.asset ?? "XLM";
}
export function getInvoiceDestination(invoice: Invoice): string | undefined {
return invoice.destination_address ?? invoice.destination;
}
export function getInvoiceMemoType(
invoice: Invoice,
): "text" | "id" | "hash" | "return" {
const memoType = invoice.memo_type?.toLowerCase();
if (
memoType === "text" ||
memoType === "id" ||
memoType === "hash" ||
memoType === "return"
) {
return memoType;
}
return "id";
}
export function generatePaymentUri({
amount,
assetCode,
assetIssuer,
destination,
memo,
memoType = "id",
}: PaymentLinkParams): string {
const queryParts = [`destination=${encodeURIComponent(destination)}`];
if (amount) {
queryParts.push(`amount=${encodeURIComponent(amount)}`);
}
if (assetCode) {
queryParts.push(`asset_code=${encodeURIComponent(assetCode)}`);
}
if (assetIssuer) {
queryParts.push(`asset_issuer=${encodeURIComponent(assetIssuer)}`);
}
if (memo) {
queryParts.push(`memo=${encodeURIComponent(memo)}`);
queryParts.push(`memo_type=${memoType}`);
}
return `web+stellar:pay?${queryParts.join("&")}`;
}
function formatAmount(amount: number): string {
return amount.toLocaleString(undefined, {
maximumFractionDigits: 2,
});
}
export function buildInvoiceShareMessage(invoice: Invoice): string {
const assetCode = getInvoiceAsset(invoice);
const destination = getInvoiceDestination(invoice);
const paymentUri = destination
? generatePaymentUri({
amount: String(invoice.amount),
assetCode,
destination,
...(invoice.asset_issuer !== undefined && {
assetIssuer: invoice.asset_issuer,
}),
...(invoice.memo !== undefined && { memo: invoice.memo }),
memoType: getInvoiceMemoType(invoice),
})
: undefined;
const lines = [
`Invoice ${invoice.invoiceNumber ?? invoice.id}`,
invoice.clientName ?? "Payment request",
"",
`Amount: ${formatAmount(invoice.amount)} ${assetCode}`,
`Destination: ${destination ?? "Unavailable"}`,
`Memo: ${invoice.memo ?? "Unavailable"}`,
];
if (invoice.description) {
lines.push(`Context: ${invoice.description}`);
}
if (paymentUri) {
lines.push("", `Payment link: ${paymentUri}`);
}
return lines.join("\n");
}