forked from devSabz404/cashu-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
98 lines (93 loc) · 2.94 KB
/
index.js
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
var app = new Vue({
el: "#app",
data: {
status: "",
invoice: "",
token: "",
amountLabel: "",
mintUrl: "",
wallet: null,
showCheckFeeButton: false,
showTokenInput: true,
showPayButton: false,
showInvoiceInput: false,
payAmount: 0,
decodedInvoice: null,
},
methods: {
checkToken: async function () {
try {
this.status = "";
var tokenBase64 = this.token;
var token = JSON.parse(atob(tokenBase64));
this.mintUrl = token.mints[0].url;
this.wallet = new Wallet(this.mintUrl);
this.wallet.loadMint();
let spendable = await this.wallet.checkSpendable(token.proofs);
if (!spendable) {
throw Error("Token already spent.");
}
let tokenAmount = this.wallet.sumProofs(token.proofs);
let feeAmount = Math.ceil(Math.max(2, tokenAmount * 0.02));
this.payAmount = tokenAmount - feeAmount;
if (!(this.payAmount > 0)) {
throw Error("Token amount is too low for a Lightning payment.");
}
this.amountLabel = `Receive ${this.payAmount} sats (incl. ${feeAmount} sats network fees) via Lightning.`;
this.showInvoiceInput = true;
} catch (error) {
this.status = error;
}
},
checkLnurl: async function () {
// check whether the input is an lnurl and replace with bolt11 invoice
let address = this.invoice;
if (
address.split("@").length != 2 &&
address.toLowerCase().slice(0, 6) != "lnurl1"
) {
return;
}
this.status = "Resolving LNURL ...";
this.invoice = await this.wallet.lnurlPay(address, this.payAmount);
},
pay: async function () {
try {
await this.checkLnurl();
this.status = "";
var tokenBase64 = this.token;
var bolt11 = this.invoice;
var token = JSON.parse(atob(tokenBase64));
this.decodedInvoice = this.wallet.decodeInvoice(bolt11);
// check if tokens are actually enough by checking the fees
const amountWithFees =
this.decodedInvoice.satoshis +
(await this.wallet.checkFees(this.invoice));
// check if tokens are worth the payAmount
if (this.wallet.sumProofs(token.proofs) < amountWithFees) {
throw Error(
`Token amount too low (${this.wallet.sumProofs(
token.proofs
)} instead of ${amountWithFees})`
);
}
this.wallet.loadMint();
this.wallet.proofs = token.proofs;
this.status = "Paying invoice ...";
await this.wallet.melt(this.invoice);
this.status = "Invoice paid ⚡️";
} catch (error) {
this.status = error;
}
},
},
created() {
let params = new URL(document.location).searchParams;
if (params.get("lnurl")) {
this.invoice = params.get("lnurl");
}
if (params.get("token")) {
this.token = params.get("token");
}
},
});