├── .env.example ├── .gitignore ├── README.md ├── client ├── App.scss ├── App.tsx ├── components │ ├── PostForm.tsx │ └── Posts.tsx ├── index.html ├── index.tsx ├── lib │ └── api.ts ├── tsconfig.json ├── types.ts └── webpack.config.js ├── nodemon.json ├── package.json ├── server ├── env.ts ├── index.ts ├── node.ts ├── posts.ts └── tsconfig.json └── yarn.lock /.env.example: -------------------------------------------------------------------------------- 1 | # Server configuration 2 | PORT=3001 3 | 4 | # Client configuration 5 | API_PATH="http://localhost:3001/api" 6 | 7 | # LND Node configuration 8 | LND_GRPC_URL="127.0.0.1:10006" 9 | LND_MACAROON="[base64 encoded]" 10 | LND_TLS_CERT="[base64 encoded]" 11 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .env 2 | node_modules 3 | *.log -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Lightning App Tutorial 2 | 3 | This is a step-by-step tutorial project for learning to build Lightning applications. It's broken out into 5 parts, which you can find as separate posts on Medium and branches here on GitHub. 4 | 5 | * [Part 1 - Connecting to your Node](https://medium.com/p/4a13c82f3f78) ([`part-1` branch](https://github.com/wbobeirne/lightning-app-tutorial/tree/part-1)) 6 | * [Part 2 - Receiving Payments](https://medium.com/@wbobeirne/making-a-lightning-web-app-part-2-414f5d23c2d7) ([`part-2` branch](https://github.com/wbobeirne/lightning-app-tutorial/tree/part-2)) 7 | * [Part 3 - Instant Updates w/ Websockets](https://medium.com/@wbobeirne/making-a-lightning-web-app-part-3-58d8c7351175) ([`part-3` branch](https://github.com/wbobeirne/lightning-app-tutorial/tree/part-3)) 8 | * Part 4 - Integrating WebLN (Coming soon!) 9 | * Part 5 - Launching to Production (Coming soon!) 10 | 11 | If you'd rather read the code than a post, feel free to dive in directly with the following instructions: 12 | 13 | ## Requirements 14 | 15 | * Node 8+ 16 | * An [LND node](https://github.com/lightningnetwork/lnd) 17 | 18 | If you want an LND node but have trouble setting it up with LND directly, I suggest either following [Pierre Rochard's Easiest Lightning Node guide](https://medium.com/lightning-power-users/windows-macos-lightning-network-284bd5034340), or downloading the [Lightning App from Lightning Labs](https://github.com/lightninglabs/lightning-app). 19 | 20 | If you'd rather not deal with getting your hands on some Bitcoin or waiting for block times to open channels, you can setup your own [simulated Lightning network cluster](https://dev.lightning.community/tutorial/01-lncli/). 21 | 22 | If you just want to fiddle around with this you can use [Polar](https://github.com/jamaljsr/polar) to setup your own local regtest network. 23 | 24 | ## Setup the Project 25 | 26 | Copy the environment configuration file with 27 | ``` 28 | cp .env.example .env 29 | ``` 30 | 31 | Edit the following fields in your new .env file with information about your node. You can get some help finding this info using this tool: https://lightningjoule.com/tools/node-info 32 | * `LND_GRPC_URL` - The location to connect to your node. If you're running with default settings locally, this should be `127.0.0.1:10009`. 33 | * `LND_MACAROON` - Your `invoice.macaroon` file, base64 encoded. Run `base64 invoice.macaroon` in your macaroon directory to get this. 34 | * `LND_TLS_CERT` - Your TLS certificate, also base 64 encoded. Run `base64 tls.cert` in your data directory to get this. 35 | 36 | If you don't know how to get these, [this tool will tell you where to find these](https://lightningjoule.com/tools/node-info). 37 | 38 | ## Development 39 | 40 | Install dependencies and run the app with 41 | ```sh 42 | npm install && npm run dev 43 | # OR # 44 | yarn && yarn dev 45 | ``` 46 | 47 | ## Building & Deploying 48 | 49 | Coming soon. 50 | -------------------------------------------------------------------------------- /client/App.scss: -------------------------------------------------------------------------------- 1 | .App { 2 | &-title { 3 | text-align: center; 4 | margin-top: 1rem; 5 | margin-bottom: 2rem; 6 | color: #f1c40f; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /client/App.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Container, Row, Col, Spinner, Alert, Button } from 'reactstrap'; 3 | import PostForm from 'components/PostForm'; 4 | import Posts from 'components/Posts'; 5 | import api from 'lib/api'; 6 | import { Post } from 'types'; 7 | import './App.scss'; 8 | 9 | interface State { 10 | posts: Post[]; 11 | isConnecting: boolean; 12 | error: Error | null; 13 | } 14 | 15 | // Starting state, can be used for "resetting" as well 16 | const INITIAL_STATE: State = { 17 | posts: [], 18 | isConnecting: true, 19 | error: null, 20 | }; 21 | 22 | export default class App extends React.Component { 23 | state: State = { ...INITIAL_STATE }; 24 | 25 | // Connect websocket immediately 26 | componentDidMount() { 27 | this.connect(); 28 | } 29 | 30 | // Reset our state, connect websocket, and update state on new data or error 31 | private connect = () => { 32 | this.setState({ ...INITIAL_STATE }); 33 | const socket = api.getPostsWebSocket(); 34 | 35 | // Mark isConnecting false once connected 36 | socket.addEventListener('open', () => { 37 | this.setState({ isConnecting: false }); 38 | }); 39 | 40 | // Add new posts when they're sent 41 | socket.addEventListener('message', ev => { 42 | try { 43 | const msg = JSON.parse(ev.data.toString()); 44 | if (msg && msg.type === 'post') { 45 | // Add new post, sort them by most recent 46 | const posts = [...this.state.posts, msg.data] 47 | .sort((a, b) => b.time - a.time); 48 | this.setState({ posts }); 49 | } 50 | } catch(err) { 51 | console.error(err); 52 | } 53 | }); 54 | 55 | // Handle closes and errors 56 | socket.addEventListener('close', () => { 57 | this.setState({ error: new Error('Connection to server closed unexpectedly.') }); 58 | }); 59 | socket.addEventListener('error', (ev) => { 60 | this.setState({ error: new Error('There was an error, see your console for more information.') }); 61 | console.error(ev); 62 | }); 63 | }; 64 | 65 | render() { 66 | const { posts, isConnecting, error } = this.state; 67 | 68 | let content; 69 | if (isConnecting) { 70 | content = ( 71 |
72 | 73 |
74 | ); 75 | } else if (error) { 76 | content = ( 77 | 78 |

Something went wrong!

79 |

{error.message}

80 | 83 |
84 | ) 85 | } else { 86 | content = ( 87 | <> 88 | 89 | 90 | 91 | ); 92 | } 93 | 94 | return ( 95 |
96 | 97 |

Lightning Posts

98 | 99 | 100 | {content} 101 | 102 | 103 |
104 |
105 | ); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /client/components/PostForm.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { 3 | Card, 4 | CardHeader, 5 | CardBody, 6 | Form, 7 | FormGroup, 8 | Input, 9 | Button, 10 | Alert, 11 | Spinner, 12 | } from 'reactstrap'; 13 | import api from 'lib/api'; 14 | import { Post } from 'types'; 15 | 16 | interface Props { 17 | posts: Post[]; 18 | } 19 | 20 | interface State { 21 | name: string; 22 | content: string; 23 | isPosting: boolean; 24 | pendingPost: null | Post; 25 | paymentRequest: null | string; 26 | error: null | string; 27 | } 28 | 29 | const INITIAL_STATE: State = { 30 | name: '', 31 | content: '', 32 | isPosting: false, 33 | pendingPost: null, 34 | paymentRequest: null, 35 | error: null, 36 | }; 37 | 38 | export default class PostForm extends React.Component { 39 | state = { ...INITIAL_STATE }; 40 | 41 | componentDidUpdate() { 42 | const { posts } = this.props; 43 | const { pendingPost } = this.state; 44 | 45 | // Reset the form if our pending post comes in 46 | if (pendingPost) { 47 | const hasPosted = !!posts.find(p => pendingPost.id === p.id); 48 | if (hasPosted) { 49 | this.setState({ ...INITIAL_STATE }); 50 | } 51 | } 52 | } 53 | 54 | render() { 55 | const { name, content, isPosting, error, paymentRequest } = this.state; 56 | const disabled = !content.length || !name.length || isPosting; 57 | 58 | let cardContent; 59 | if (paymentRequest) { 60 | cardContent = ( 61 |
62 | 63 | 69 | 70 | 73 |
74 | ); 75 | } else { 76 | cardContent = ( 77 |
78 | 79 | 85 | 86 | 87 | 88 | 96 | 97 | 98 | {error && ( 99 | 100 |

Failed to submit post

101 |

{error}

102 |
103 | )} 104 | 105 | 112 |
113 | ); 114 | } 115 | 116 | return ( 117 | 118 | 119 | Submit a Post 120 | 121 | 122 | {cardContent} 123 | 124 | 125 | ); 126 | } 127 | 128 | private handleChange = (ev: React.ChangeEvent) => { 129 | this.setState({ [ev.target.name]: ev.target.value } as any); 130 | }; 131 | 132 | private handleSubmit = (ev: React.FormEvent) => { 133 | const { name, content } = this.state; 134 | ev.preventDefault(); 135 | 136 | this.setState({ 137 | isPosting: true, 138 | error: null, 139 | }); 140 | 141 | api.submitPost(name, content) 142 | .then(res => { 143 | this.setState({ 144 | isPosting: false, 145 | pendingPost: res.post, 146 | paymentRequest: res.paymentRequest, 147 | }); 148 | }).catch(err => { 149 | this.setState({ 150 | isPosting: false, 151 | error: err.message, 152 | }) 153 | }); 154 | }; 155 | } 156 | -------------------------------------------------------------------------------- /client/components/Posts.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Card, CardTitle, CardBody, CardText, Jumbotron } from 'reactstrap'; 3 | import { Post } from 'types'; 4 | 5 | interface Props { 6 | posts: Post[]; 7 | } 8 | 9 | export default class Posts extends React.Component { 10 | render() { 11 | const { posts } = this.props; 12 | 13 | let content; 14 | if (posts.length) { 15 | content = posts.map(p => ( 16 | 17 | 18 | {p.name} says: 19 | {p.content} 20 | 21 | 22 | )); 23 | } else { 24 | content = ( 25 | 26 |

No posts yet.

27 |

Why not be the first?

28 |
29 | ); 30 | } 31 | 32 | return ( 33 | <> 34 |

Latest Posts

35 | {content} 36 | 37 | ); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /client/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Lightning Posts 7 | 8 | 9 |
10 | 11 | 12 | -------------------------------------------------------------------------------- /client/index.tsx: -------------------------------------------------------------------------------- 1 | import 'bootstrap/dist/css/bootstrap.min.css'; 2 | import React from 'react'; 3 | import { render } from 'react-dom'; 4 | import { hot } from 'react-hot-loader'; 5 | import App from './App'; 6 | 7 | const HotApp = hot(module)(() => ( 8 | 9 | )); 10 | 11 | render( 12 | , 13 | document.getElementById('root'), 14 | ); -------------------------------------------------------------------------------- /client/lib/api.ts: -------------------------------------------------------------------------------- 1 | import { stringify } from 'query-string'; 2 | import { Post } from 'types'; 3 | 4 | type ApiMethod = 'GET' | 'POST' | 'PUT' | 'DELETE'; 5 | 6 | class API { 7 | url: string; 8 | 9 | constructor(url: string) { 10 | this.url = url; 11 | } 12 | 13 | // Public methods 14 | submitPost(name: string, content: string) { 15 | return this.request<{ post: Post; paymentRequest: string; }>( 16 | 'POST', 17 | '/posts', 18 | { name, content }, 19 | ); 20 | } 21 | 22 | getPosts() { 23 | return this.request('GET', '/posts'); 24 | } 25 | 26 | getPost(id: number) { 27 | return this.request('GET', `/posts/${id}`); 28 | } 29 | 30 | getPostsWebSocket() { 31 | let wsUrl = this.url.replace('https', 'wss').replace('http', 'ws'); 32 | return new WebSocket(`${wsUrl}/posts`); 33 | } 34 | 35 | // Internal fetch function. Makes a request to the server, and either returns 36 | // JSON parsed data from the request, or throws an error. 37 | protected request( 38 | method: ApiMethod, 39 | path: string, 40 | args?: object, 41 | ): Promise { 42 | let body = null; 43 | let query = ''; 44 | const headers = new Headers(); 45 | headers.append('Accept', 'application/json'); 46 | 47 | if (method === 'POST' || method === 'PUT') { 48 | body = JSON.stringify(args); 49 | headers.append('Content-Type', 'application/json'); 50 | } 51 | else if (args !== undefined) { 52 | // TS Still thinks it might be undefined(?) 53 | query = `?${stringify(args as any)}`; 54 | } 55 | 56 | return fetch(this.url + path + query, { 57 | method, 58 | headers, 59 | body, 60 | }) 61 | .then(async res => { 62 | if (!res.ok) { 63 | let errMsg; 64 | try { 65 | const errBody = await res.json(); 66 | if (!errBody.error) throw new Error(); 67 | errMsg = errBody.error; 68 | } catch(err) { 69 | throw new Error(`${res.status}: ${res.statusText}`); 70 | } 71 | throw new Error(errMsg); 72 | } 73 | return res.json(); 74 | }) 75 | .then(res => res.data as R) 76 | .catch((err) => { 77 | console.error(`API error calling ${method} ${path}`, err); 78 | throw err; 79 | }); 80 | } 81 | } 82 | 83 | // Export a default API that points at the API_PATH environment variable 84 | export default new API(process.env.API_PATH as string); 85 | -------------------------------------------------------------------------------- /client/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "module": "commonjs", 5 | "jsx": "react", 6 | "moduleResolution": "node", 7 | "lib": ["es2017", "dom"], 8 | "strict": true, 9 | "baseUrl": ".", 10 | "esModuleInterop": true, 11 | "allowSyntheticDefaultImports": true, 12 | "resolveJsonModule": true, 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /client/types.ts: -------------------------------------------------------------------------------- 1 | // This file contains TypeScript types used throught the project 2 | 3 | export interface Post { 4 | id: number; 5 | name: string; 6 | content: string; 7 | time: number; 8 | hasPaid: boolean; 9 | } 10 | -------------------------------------------------------------------------------- /client/webpack.config.js: -------------------------------------------------------------------------------- 1 | require('dotenv').config(); 2 | const path = require('path'); 3 | const webpack = require('webpack'); 4 | const HtmlWebpackPlugin = require('html-webpack-plugin'); 5 | const DotenvPlugin = require('dotenv-webpack'); 6 | 7 | const clientDir = path.resolve(__dirname); 8 | const serverDir = path.resolve(__dirname, '../server'); 9 | const publicPath = '/'; 10 | 11 | // Loaders, determine what files we can import and how they're compiled 12 | const typescriptLoader = { 13 | test: /\.tsx?$/, 14 | use: [ 15 | { 16 | loader: 'ts-loader', 17 | options: { transpileOnly: true }, 18 | }, 19 | ], 20 | }; 21 | const cssLoader = { 22 | test: /\.css$/, 23 | use: [ 24 | 'style-loader', 25 | 'css-loader', 26 | ].filter(Boolean), 27 | }; 28 | const sassLoader = { 29 | test: /\.scss$/, 30 | use: [ 31 | ...cssLoader.use, 32 | 'sass-loader', 33 | ], 34 | }; 35 | const fileLoader = { 36 | test: /\.(png|jpg|woff|woff2|eot|ttf|svg)$/, 37 | use: [{ 38 | loader: 'file-loader', 39 | options: { 40 | publicPath, 41 | name: '[folder]/[name].[ext]', 42 | }, 43 | }], 44 | } 45 | 46 | // Plugins run additional functionality on our build 47 | const plugins = [ 48 | // Adds our .env variables to the build 49 | new DotenvPlugin({ systemvars: true }), 50 | // Takes our index.html template, and injects our build into it 51 | new HtmlWebpackPlugin({ 52 | template: `${clientDir}/index.html`, 53 | inject: true, 54 | }), 55 | ]; 56 | 57 | module.exports = { 58 | mode: 'development', 59 | name: 'main', 60 | target: 'web', 61 | devtool: 'cheap-module-inline-source-map', 62 | entry: path.join(clientDir, 'index.tsx'), 63 | output: { 64 | path: path.join(serverDir, 'public'), 65 | filename: 'script.js', 66 | publicPath, 67 | chunkFilename: '[name].chunk.js', 68 | }, 69 | module: { 70 | rules: [ 71 | typescriptLoader, 72 | sassLoader, 73 | cssLoader, 74 | fileLoader, 75 | ], 76 | }, 77 | plugins, 78 | resolve: { 79 | extensions: ['.ts', '.tsx', '.js', '.mjs', '.json'], 80 | modules: [clientDir, path.join(__dirname, '../node_modules')], 81 | }, 82 | devServer: { 83 | port: 3000, 84 | hot: true, 85 | stats: 'minimal', 86 | }, 87 | }; 88 | -------------------------------------------------------------------------------- /nodemon.json: -------------------------------------------------------------------------------- 1 | { 2 | "verbose": false, 3 | "ext": "ts,json", 4 | "watch": ["server"], 5 | "exec": "ts-node --project server/tsconfig.json server/index.ts" 6 | } 7 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ln-sample-app", 3 | "version": "0.1.0", 4 | "description": "A sample Lightning application", 5 | "main": "index.js", 6 | "license": "MIT", 7 | "scripts": { 8 | "dev": "concurrently -n server,client \"npm run dev:server\" \"npm run dev:client\"", 9 | "dev:client": "webpack-dev-server --config ./client/webpack.config.js", 10 | "dev:server": "nodemon" 11 | }, 12 | "dependencies": { 13 | "@radar/lnrpc": "0.6.0-beta.0", 14 | "body-parser": "1.19.0", 15 | "bootstrap": "4.3.1", 16 | "cors": "2.8.5", 17 | "css-loader": "2.1.1", 18 | "dotenv": "7.0.0", 19 | "dotenv-webpack": "1.7.0", 20 | "express": "4.16.4", 21 | "express-ws": "4.0.0", 22 | "file-loader": "3.0.1", 23 | "html-webpack-plugin": "3.2.0", 24 | "node-sass": "4.12.0", 25 | "query-string": "6.5.0", 26 | "react": "16.8.6", 27 | "react-dom": "16.8.6", 28 | "react-hot-loader": "4.8.4", 29 | "reactstrap": "8.0.0", 30 | "sass-loader": "7.1.0", 31 | "style-loader": "0.23.1", 32 | "ts-loader": "6.0.0", 33 | "typescript": "3.4.5", 34 | "webpack": "4.30.0", 35 | "webpack-cli": "3.3.2", 36 | "webpack-dev-server": "3.3.1" 37 | }, 38 | "devDependencies": { 39 | "@types/cors": "2.8.5", 40 | "@types/dotenv": "6.1.1", 41 | "@types/express": "4.16.1", 42 | "@types/express-ws": "3.0.0", 43 | "@types/react": "16.8.16", 44 | "@types/react-dom": "16.8.4", 45 | "@types/reactstrap": "8.0.1", 46 | "concurrently": "4.1.0", 47 | "nodemon": "1.19.0", 48 | "ts-node": "8.1.0" 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /server/env.ts: -------------------------------------------------------------------------------- 1 | import dotenv from 'dotenv'; 2 | dotenv.config(); 3 | 4 | const env = { 5 | PORT: process.env.PORT as string, 6 | LND_GRPC_URL: process.env.LND_GRPC_URL as string, 7 | LND_MACAROON: process.env.LND_MACAROON as string, 8 | LND_TLS_CERT: process.env.LND_TLS_CERT as string, 9 | }; 10 | 11 | // Ensure all keys exist 12 | Object.entries(env).forEach(([key, value]) => { 13 | if (!value) { 14 | throw new Error(`Required environment variable '${key}' is missing!`); 15 | } 16 | }); 17 | 18 | export default env; -------------------------------------------------------------------------------- /server/index.ts: -------------------------------------------------------------------------------- 1 | import express from 'express'; 2 | import expressWs from 'express-ws'; 3 | import cors from 'cors'; 4 | import bodyParser from 'body-parser'; 5 | import { Invoice, Readable } from '@radar/lnrpc'; 6 | import env from './env'; 7 | import { node, initNode } from './node'; 8 | import postsManager from './posts'; 9 | 10 | // Configure server 11 | const app = expressWs(express()).app; 12 | app.use(cors({ origin: '*' })); 13 | app.use(bodyParser.json()); 14 | 15 | 16 | // API Routes 17 | app.ws('/api/posts', (ws) => { 18 | // Send all the posts we have initially 19 | postsManager.getPaidPosts().forEach(post => { 20 | console.log(post); 21 | ws.send(JSON.stringify({ 22 | type: 'post', 23 | data: post, 24 | })); 25 | }); 26 | 27 | // Send each new post as it's paid for. If we error out, just close 28 | // the connection and stop listening. 29 | const postListener = (post: any) => { 30 | ws.send(JSON.stringify({ 31 | type: 'post', 32 | data: post, 33 | })); 34 | }; 35 | postsManager.addListener('post', postListener); 36 | 37 | // Keep-alive by pinging every 10s 38 | const pingInterval = setInterval(() => { 39 | ws.send(JSON.stringify({ type: 'ping' })); 40 | }, 10000); 41 | 42 | // Stop listening if they close the connection 43 | ws.addEventListener('close', () => { 44 | postsManager.removeListener('post', postListener); 45 | clearInterval(pingInterval); 46 | }); 47 | }); 48 | 49 | app.get('/api/posts', (req, res) => { 50 | res.json({ data: postsManager.getPaidPosts() }); 51 | }); 52 | 53 | app.get('/api/posts/:id', (req, res) => { 54 | const post = postsManager.getPost(parseInt(req.params.id, 10)); 55 | if (post) { 56 | res.json({ data: post }); 57 | } else { 58 | res.status(404).json({ error: `No post found with ID ${req.params.id}`}); 59 | } 60 | }); 61 | 62 | app.post('/api/posts', async (req, res, next) => { 63 | try { 64 | const { name, content } = req.body; 65 | 66 | if (!name || !content) { 67 | throw new Error('Fields name and content are required to make a post'); 68 | } 69 | 70 | const post = postsManager.addPost(name, content); 71 | const invoice = await node.addInvoice({ 72 | memo: `Lightning Posts post #${post.id}`, 73 | value: content.length, 74 | expiry: '120', // 2 minutes 75 | }); 76 | 77 | res.json({ 78 | data: { 79 | post, 80 | paymentRequest: invoice.paymentRequest, 81 | }, 82 | }); 83 | } catch(err) { 84 | next(err); 85 | } 86 | }); 87 | 88 | app.get('/', (req, res) => { 89 | res.send('You need to load the webpack-dev-server page, not the server page!'); 90 | }); 91 | 92 | 93 | // Initialize node & server 94 | console.log('Initializing Lightning node...'); 95 | initNode().then(() => { 96 | console.log('Lightning node initialized!'); 97 | console.log('Starting server...'); 98 | app.listen(env.PORT, () => { 99 | console.log(`API Server started at http://localhost:${env.PORT}!`); 100 | }); 101 | 102 | // Subscribe to all invoices, mark posts as paid 103 | const stream = node.subscribeInvoices() as any as Readable; 104 | stream.on('data', chunk => { 105 | // Skip unpaid / irrelevant invoice updates 106 | if (!chunk.settled || !chunk.amtPaidSat || !chunk.memo) return; 107 | 108 | // Extract post id from memo, skip if we can't find an id 109 | const id = parseInt(chunk.memo.replace('Lightning Posts post #', ''), 10); 110 | if (!id) return; 111 | 112 | // Mark the invoice as paid! 113 | postsManager.markPostPaid(id); 114 | }); 115 | }); 116 | -------------------------------------------------------------------------------- /server/node.ts: -------------------------------------------------------------------------------- 1 | import createLnRpc, { LnRpc } from '@radar/lnrpc'; 2 | import env from './env'; 3 | 4 | export let node: LnRpc; 5 | 6 | export async function initNode() { 7 | node = await createLnRpc({ 8 | server: env.LND_GRPC_URL, 9 | cert: new Buffer(env.LND_TLS_CERT, 'base64').toString('ascii'), 10 | macaroon: new Buffer(env.LND_MACAROON, 'base64').toString('hex'), 11 | }); 12 | } 13 | -------------------------------------------------------------------------------- /server/posts.ts: -------------------------------------------------------------------------------- 1 | import { EventEmitter } from 'events'; 2 | 3 | // All logic and storage around posts happens in here. To keep things simple, 4 | // we're just storing posts in memory. Every time you restart the server, all 5 | // posts will be lost. For long term storage, you'd want to look into putting 6 | // these into a database. 7 | 8 | export interface Post { 9 | id: number; 10 | time: number; 11 | name: string; 12 | content: string; 13 | hasPaid: boolean; 14 | }; 15 | 16 | class PostsManager extends EventEmitter { 17 | posts: Post[] = []; 18 | 19 | // Add a new post to the list 20 | addPost(name: string, content: string): Post { 21 | const post = { 22 | name, 23 | content, 24 | id: Math.floor(Math.random() * 100000000) + 1000, 25 | time: Date.now(), 26 | hasPaid: false, 27 | }; 28 | this.posts.push(post); 29 | return post; 30 | } 31 | 32 | // Gets a particular post given an ID 33 | getPost(id: number): Post | undefined { 34 | return this.posts.find(p => p.id === id); 35 | } 36 | 37 | // Mark a post as paid 38 | markPostPaid(id: number) { 39 | let updatedPost; 40 | this.posts = this.posts.map(p => { 41 | if (p.id === id) { 42 | updatedPost = { ...p, hasPaid: true }; 43 | return updatedPost; 44 | } 45 | return p; 46 | }); 47 | 48 | if (updatedPost) { 49 | this.emit('post', updatedPost); 50 | } 51 | } 52 | 53 | // Return posts that have been paid for in time order 54 | getPaidPosts() { 55 | return this.posts 56 | .filter(p => !!p.hasPaid) 57 | .sort((a, b) => b.time - a.time); 58 | } 59 | } 60 | 61 | export default new PostsManager(); 62 | -------------------------------------------------------------------------------- /server/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es6", 4 | "module": "commonjs", 5 | "lib": ["es2017"], 6 | "outDir": "build", 7 | "strict": true, 8 | "baseUrl": ".", 9 | "esModuleInterop": true, 10 | "allowSyntheticDefaultImports": true, 11 | "resolveJsonModule": true, 12 | } 13 | } 14 | --------------------------------------------------------------------------------