aboutsummaryrefslogtreecommitdiffstats
path: root/lib/createLnrpc.js
blob: 16a59b3c14c63051d0ced5786965da7920a169d1 (plain) (blame)
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
import fs from 'fs'
import grpc from 'grpc'
import createLnrpc from 'lnrpc'
import {promisify} from 'util'

export default async ({ server, tls, macaroon, channelpeers }) => {
  const lnrpc = await createLnrpc({ server, tls })
  lnrpc.meta = new grpc.Metadata()
  lnrpc.meta.add('macaroon', fs.readFileSync(macaroon).toString('hex'))
  lnrpc.channelpeers = channelpeers

  // Resolve proxy instance
  return new Proxy(lnrpc, {
    /**
     * Promisify each lightning RPC method
     * @param  {lnrpc.Lightning} target
     * @param  {String}          key
     * @return {Promise} {Any}
     */
    get(target, key) {
      const method = target[key]

      if (typeof key === 'string' && typeof method === 'function') {
        const streaming = key.match(/openChannel$|sendPayment|subscribe.*/)
        let fn

        if (streaming) {
          if (key === 'sendPayment') {
            fn = params => method.call(lnrpc, target.meta, params)
          } else {
            fn = params => method.call(lnrpc, params, target.meta)
          } 
        } else {
          fn = params => promisify(method).call(lnrpc, params, target.meta)
        } 

        return fn
      }

      return target[key]; // forward
    }
  });
}