Feature 4: Modify Upvote Action
Currently in our app, when a user clicks the Upvote button, we immediately make the API request to the backend to increment the number of votes for the post. We want to change that behavior to require the user to make a payment of 100 satoshis (0.00000100 BTC) to the post’s author before the upvote is submitted. Since we want the payment to go directly to the node of the user that created the post, we will need perform a few steps when the Upvote button is clicked:
    1.
    Create a new invoice on the post author’s node
    2.
    Present the invoice’s payment request string to the user performing the upvote
    3.
    Wait for the user to pay the invoice over the Lightning Network
    4.
    Once the invoice is paid, we’ll proceed with submitting the upvote to the backend
    5.
    Finally, we’ll have a bit of fun by making it rain confetti on the post’s author’s screen
Let’s go to the feat-4a branch to see how we can implement this feature.
1
git checkout feat-4a
Copied!

Request an invoice from the post author’s node

In order to make a standard payment on Lightning, the recipient must first create an invoice. To do this in our app, we created a new API endpoint on the backend.
source: /backend/index.ts
1
app.post('/api/posts/:id/invoice', catchAsyncErrors(routes.postInvoice));
Copied!
source: /backend/routes.ts
1
/**
2
* POST /api/posts/:id/invoice
3
*/
4
export const postInvoice = async (req: Request, res: Response) => {
5
const { id } = req.params;
6
// find the post
7
const post = db.getPostById(parseInt(id));
8
if (!post) throw new Error('Post not found');
9
// find the node that made this post
10
const node = db.getNodeByPubkey(post.pubkey);
11
if (!node) throw new Error('Node not found for this post');
12
13
// create an invoice on the poster's node
14
const rpc = nodeManager.getRpc(node.token);
15
const amount = 100;
16
const inv = await rpc.addInvoice({ value: amount.toString() });
17
res.send({
18
payreq: inv.paymentRequest,
19
hash: (inv.rHash as Buffer).toString('base64'),
20
amount,
21
});
22
};
Copied!
We added a new API route handler called postInvoice() which will receive the post’s id from the url. It then gets the full post object from the database in order to get the node that should receive the payment. We use the pubkey stored in the post to retrieve the node’s connection information from our database. Next, it calls the AddInvoice lnd endpoint to create a new invoice for 100 sats. Once the invoice is created, we send the generated payment request and the invoice hash back to the client. The hash is what is used to uniquely identify this invoice on the node. We’ll need this later to check if the invoice is paid.
These are all the changes we needed on the backend for now. Let’s move on to the frontend.
source: /src/lib/api.ts
1
export const createInvoice = async (postId: number) => {
2
return await httpPost(`posts/${postId}/invoice`);
3
};
Copied!
We added a createInvoice() function to the API wrapper on the frontend which is used to make the http request to the backend.
source: /src/store/store.ts
1
// PayModal state
2
showPayModal = false; // show the payment request modal dialog
3
pmtForPost: Post | undefined; // reference to the post that is being upvoted
4
pmtAmount = ''; // the amount of the payment
5
pmtRequest = ''; // the invoice’s payment request string
6
pmtHash = ''; // the hash (or id) of the payment from lnd
7
pmtSuccessMsg = ''; // message to display after payment is complete
8
pmtError = ''; // message to display if the payment fails
Copied!
In the mobx store, we need to maintain some application state that will be used for the upvote process.
source: /src/store/store.ts
1
showPaymentRequest = async (post: Post) => {
2
this.clearError();
3
try {
4
const res = await api.createInvoice(post.id);
5
this.pmtForPost = post;
6
this.pmtAmount = res.amount;
7
this.pmtRequest = res.payreq;
8
this.pmtHash = res.hash;
9
this.pmtSuccessMsg = '';
10
this.pmtError = '';
11
this.showPayModal = true;
12
} catch (err) {
13
this.error = err.message;
14
}
15
};
16
17
hidePaymentRequest = () => {
18
this.pmtForPost = undefined;
19
this.pmtAmount = '';
20
this.pmtRequest = '';
21
this.pmtHash = '';
22
this.pmtSuccessMsg = '';
23
this.pmtError = '';
24
this.showPayModal = false;
25
};
Copied!
Also in the store, we added two functions which we will call when we want to show or hide the payment request modal dialog.
The most interesting is showPaymentRequest() which accepts a post object. It makes the API request to the backend to create the invoice, then sets the state variables with the data returned in the API response. It also sets showPayModal to true in order to display the payment request on screen. We’ll discuss pmtSuccessMsg and pmtError a little later.
The hidePaymentRequest() function is straight-forward. It just resets the state variables and sets showPayModal to false to hide the payment request screen.
source: /src/pages/PostList.tsx
1
{store.showPayModal && <PayModal />}
Copied!
We just added one line to the PostList component to display a newly added PayModal component, which is shown below.
source: /src/components/PayModal.tsx
1
const PayModal: React.FC = () => {
2
const store = useStore();
3
4
const body = !store.pmtSuccessMsg ? (
5
<>
6
<Form.Group controlId="title">
7
{store.pmtError && <Alert variant="danger">{store.pmtError}</Alert>}
8
<Form.Label>
9
Payment Request for <strong>{store.pmtAmount} sats</strong> to{' '}
10
<strong>{store.pmtForPost?.username}</strong>
11
</Form.Label>
12
<Form.Control
13
required
14
as="textarea"
15
rows={5}
16
value={store.pmtRequest}
17
readOnly
18
/>
19
<Form.Text></Form.Text>
20
</Form.Group>
21
<div className="text-center">
22
<Spinner animation="border" size="sm" className="mr-2" />
23
Waiting for payment to be completed...
24
</div>
25
</>
26
) : (
27
<Alert variant="success">{store.pmtSuccessMsg}</Alert>
28
);
29
30
return (
31
<Modal show={true} onHide={store.hidePaymentRequest}>
32
<Modal.Header closeButton>
33
<Modal.Title>{store.pmtForPost?.title}</Modal.Title>
34
</Modal.Header>
35
<Modal.Body>{body}</Modal.Body>
36
</Modal>
37
);
38
};
Copied!
We added a new component called PayModal. This component will be displayed when store.showPayModal is true. It overlays the full screen displaying a textbox containing the invoice’s payment request and a message informing the user that we are waiting on them to send the payment. If pmtSuccessMsg has a value then the message will be displayed instead of the payment request.
source: /src/components/VoteButton.tsx
1
// create an invoice and show the modal when the button is clicked
2
const handleUpvoteClick = useCallback(async () => {
3
await store.showPaymentRequest(post);
4
}, [store, post]);
Copied!
The final change we made on the frontend is to the VoteButton component. When the “Upvote” button is clicked, we call the showPaymentRequest() function on the store instead of the upvotePost() function. This way, we collect the payment before submitting the upvote.
With these changes made, we can test the functionality in the browser.
Now when you click on the “Upvote” button for a post, you should see a modal dialog popup like above.
In the next section we’ll go over how to respond in our app when the payment is made over the Lightning Network.

After payment, proceed with the upvote

Now that we have shown the payment request to the user, they can pay the invoice directly over the Lightning Network using their node. In your local environment, you can right-click on the carol node and click the “Pay Invoice” option. Paste in the payment request and click the “Pay Invoice” button. You should see the payment succeed, but our app still says “Waiting for payment…”. In this section, we’ll see how to get the app to listen for incoming payments and perform some action when this happens.
Checkout the feat-4b branch to view the new changes to the code.
1
git checkout feat-4b
Copied!
As usual, let’s start with the backend updates first.
source: /backend/routes.ts
1
/**
2
* POST /api/posts/:id/upvote
3
*/
4
export const upvotePost = async (req: Request, res: Response) => {
5
const { id } = req.params;
6
const { hash } = req.body;
7
8
// validate that a invoice hash was provided
9
if (!hash) throw new Error('hash is required');
10
// find the post
11
const post = db.getPostById(parseInt(id));
12
if (!post) throw new Error('Post not found');
13
// find the node that made this post
14
const node = db.getNodeByPubkey(post.pubkey);
15
if (!node) throw new Error('Node not found for this post');
16
17
const rpc = nodeManager.getRpc(node.token);
18
const rHash = Buffer.from(hash, 'base64');
19
const { settled } = await rpc.lookupInvoice({ rHash });
20
if (!settled) {
21
throw new Error('The payment has not been paid yet!');
22
}
23
24
db.upvotePost(post.id);
25
res.send(post);
26
};
Copied!
We updated the upvotePost() route handler to now require the invoice hash in the request. This change was made because we do not want to allow the user to upvote a post unless we can verify that the invoice identified by the hash has been paid already. We use lnd’s LookupInvoice endpoint to find the invoice using the hash. The returned invoice has a settled flag indicating if it has been paid. If it is not paid then we throw an error. Otherwise, we continue to increment the number of votes.
Note: there is vulnerability in our sample app here. A crafty user can make one payment and repeatedly upvote using the same hash over and over again. This can be fixed by storing a list of previously used invoice hashes in our database, then preventing them from being used more than once. We’ll leave fixing this as an exercise for the reader.
source: /backend/node-manager.ts
1
/**
2
* listen for payments made to the node. When a payment is settled, emit
3
* the `invoicePaid` event to notify listeners of the NodeManager
4
*/
5
listenForPayments(rpc: LnRpc, pubkey: string) {
6
const stream = rpc.subscribeInvoices();
7
stream.on('data', invoice => {
8
if (invoice.settled) {
9
const hash = (invoice.rHash as Buffer).toString('base64');
10
const amount = invoice.amtPaidSat;
11
this.emit(NodeEvents.invoicePaid, { hash, amount, pubkey });
12
}
13
});
14
}
Copied!
In the NodeManager class, we’ve added a listenForPayments function. This showcases a powerful feature of lnd, streaming API endpoints. There are some API endpoints that return a stream of responses instead of a single response. When you subscribe to these streams, the app will hold a connection open to the node and will periodically receive data as events occur in lnd. In our case here, we are using the SubscribeInvoices streaming endpoint. This endpoint will send a message to us any time an invoice is created or settled (paid). We are only interested in knowing when an invoice is paid, so we check if the settled flag is true on the incoming invoice. If so, then we grab the hash and the amount from the invoice and call this.emit() with information about the payment.
You are probably wondering what the emit() function is doing here. If you are not familiar with EventEmitters, let’s briefly explain what this is. Similar to how we described lnd’s streaming endpoints above, NodeJS has a similar concept internally which allows you to create an object that can notify other portions of your app when certain events occur. Those other portions of your app can listen for these events and take action accordingly. There is a great explainer blog post over at freecodecamp.org that goes into much more detail.
We made our NodeManager class inherit from EventEmitter so that our expressjs API server can listen for these invoicePaid events and send them down to the web clients as they happen. Let’s look at the code for this next.
source: /backend/index.ts
1
app.ws('/api/events', ws => {
2
// when a websocket connection is made, add listeners for posts and invoices
3
const postsListener = (posts: Post[]) => {
4
const event = { type: SocketEvents.postUpdated, data: posts };
5
ws.send(JSON.stringify(event));
6
};
7
8
const paymentsListener = (info: any) => {
9
const event = { type: SocketEvents.invoicePaid, data: info };
10
ws.send(JSON.stringify(event));
11
};
12
13
// add listeners to to send data over the socket
14
db.on(PostEvents.updated, postsListener);
15
nodeManager.on(NodeEvents.invoicePaid, paymentsListener);
16
17
// remove listeners when the socket is closed
18
ws.on('close', () => {
19
db.off(PostEvents.updated, postsListener);
20
nodeManager.off(NodeEvents.invoicePaid, paymentsListener);
21
});
22
});
Copied!
In the backend’s entrypoint file, we previously had the WebSocket code to notify the connected browsers whenever a post was updated in the database. We have now updated the socket to also send events when a node receives a payment. Calling the nodeManager.on() function adds a listener to execute the paymentsListener function whenever the invoicePaid event is triggered. In paymentsListener, we simply forward that event to the connected browsers.
Note: this code notifies every browser that has the website open about every payment that is made for any post. This is very inefficient. It would be better to only notify the sender and receiver of the payment since they are the only ones that need to know. We didn’t implement it this way because it would add more complexity for functionality that isn’t directly specific to Lightning.
Now that the browser clients are being notified when invoices are paid, let see what changes were made to the frontend to update the UI.
source: /src/store/store.ts
1
onSocketMessage = (msg: MessageEvent) => {
2
const event = JSON.parse(msg.data);
3
// update the posts array when a post is updated on the server
4
if (event.type === SocketEvents.postUpdated) {
5
// replacing the existing post with this new one
6
this._updatePost(event.data);
7
}
8
if (event.type === SocketEvents.invoicePaid) {
9
const { hash } = event.data;
10
// upvote the post when the incoming payment is made for the
11
// pmtHash the we are waiting for
12
if (hash === this.pmtHash) {
13
this.upvotePost();
14
}
15
}
16
};
Copied!
In the mobx store, we already had the onSocketMessage function which listened for postUpdated messages. We added another check for invoicePaid messages. If we receive one of them, and the hash of the received payment matches the hash of the payment request we just paid, then we call the upvotePost() function in the store.
source: /src/store/store.ts
1
upvotePost = async () => {
2
this.pmtError = '';
3
try {
4
if (!this.pmtForPost) throw new Error('No post selected to upvote');
5
await api.upvotePost(this.pmtForPost.id, this.pmtHash);
6
this.pmtSuccessMsg = `Your payment of ${this.pmtAmount} sats to ${this.pmtForPost.username} was successful! The post has been upvoted!`;
7
} catch (err) {
8
this.pmtError = err.message;
9
}
10
};
Copied!
Also in the mobx store, we changed the upvotePost() function to send the invoice’s hash along with the post id. Remember we updated the backend to require the hash to verify that the payment was made. If the upvote is successful, we set pmtSuccessMsg so that it is displayed to the user in the modal.
source: /src/lib/api.ts
1
export const upvotePost = async (postId: number, hash: string) => {
2
const request = { hash };
3
return await httpPost(`posts/${postId}/upvote`, request);
4
};
Copied!
Finally, we updated the upvotePost() function in the API wrapper module to accept the hash as a parameter and send it to the backend in the http request body.
With those changes made, let’s test it out in the browser.
    1.
    Connect to your alice node and create some posts.
    2.
    Open a new tab and connect using your carol node.
    3.
    Click on the Upvote button for one of the posts to see the payment request popup.
    4.
    Pay the invoice using the carol node in Polar
    5.
    The success message should immediately display in the browser that’s connected to carol
It’s pretty cool seeing the real time updates in your browser based on activity on the Lightning Network. The only problem is the browser that’s connected to the alice node still shows her previous balance. You need to refresh the page to see it updated. Let’s fix that and have a bit of fun while we’re at it.

Notify the post’s author of their received payment

We’re almost at the finish line. Let’s just add one last improvement to update the balance on the payment recipient’s browser after the upvote. We’ll also make it rain confetti in celebration of their gains.
Checkout the feat-4c branch to view the new changes to the code.
1
git checkout feat-4c
Copied!
This feature doesn’t require any backend changes since the payment recipient’s browser is already receiving a WebSocket message when any payment is made. We only needed to modify the frontend to update the UI if the payment was sent to the connected node.
source: /src/store/store.ts
1
onSocketMessage = (msg: MessageEvent) => {
2
const event = JSON.parse(msg.data);
3
// update the posts array when a post is updated on the server
4
if (event.type === SocketEvents.postUpdated) {
5
// replacing the existing post with this new one
6
this._updatePost(event.data);
7
}
8
if (event.type === SocketEvents.invoicePaid) {
9
const { hash, amount, pubkey } = event.data;
10
// upvote the post when the incoming payment is made for the
11
// pmtHash the we are waiting for
12
if (hash === this.pmtHash) {
13
this.upvotePost();
14
}
15
// update the balance when an invoice is paid to the current user
16
if (pubkey === this.pubkey) {
17
this._incrementBalance(parseInt(amount));
18
}
19
}
20
};
21
22
.
23
.
24
.
25
26
private _incrementBalance = (amount: number) => {
27
this.balance = this.balance + amount;
28
29
// make it rain for 3 seconds 💸
30
this.makeItRain = true;
31
setTimeout(() => {
32
this.makeItRain = false;
33
}, 3000);
34
};
Copied!
In the mobx store, we’ve made a few changes. We updated the onSocketMessage() function to check if the recipient of the payment is the currently connected node. If so, it calls the _incrementBalance() function. This function just updates the state variable balance, which will automatically update what is displayed in the Navbar. It also sets a new makeItRain flag to true for 3 seconds. Let’s see what that will do.
source: /src/App.tsx
1
<Confetti numberOfPieces={store.makeItRain ? 1000 : 0} />
Copied!
In the App component we added a third-party component from the react-confetti npm package. This just displays a specified number of confetti flakes on the screen. We use the makeItRain flag to determine if we display 1000 or 0. With the change we made to the mobx store, this component will now display confetti on the payment recipient’s browser for 3 seconds after they receive a payment due to their post being upvoted.
Let’s try it out in the browser. Using the browser connected to carol’s node, upvote one of alice’s posts, then pay the invoice in Polar. Be sure to keep the browser connected to alice’s node visible on your screen as well.
Here is alice before the upvote. The top post has 10 votes and her channel balance is 90,000 sats.
After the upvote, the balance updates automatically to 90,100 sats and the confetti rains down on the screen. 🥳 🎉 🎊
Congratulations! We have now completed all of the Lightning functionality we wanted to add to this sample application.
Last modified 1yr ago