Skip to content

Commit 1cf9c56

Browse files
authored
Merge pull request #150 from jimasuen/main
Added module for Split Payments extension
2 parents 6c2f644 + 46c0118 commit 1cf9c56

File tree

4 files changed

+163
-0
lines changed

4 files changed

+163
-0
lines changed

pylnbits/__init__.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,4 +44,8 @@
4444
4545
- `lndhub.py`: for fetching admin and invoice lndhub urls
4646
47+
- `split_payments.py`: For target wallets, calls Rest API methods for LNbits Split Payments Extension
48+
- List target wallets
49+
- Add target wallet
50+
- Delete a target wallet
4751
"""

pylnbits/split_payments.py

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
import json
2+
import logging
3+
4+
from aiohttp.client import ClientSession
5+
6+
from pylnbits.utils import delete_url, get_url, put_url
7+
8+
"""
9+
Rest API methods for LNbits Split Payments Extension
10+
11+
GET target wallets
12+
PUT target wallet
13+
DELETE target wallets
14+
"""
15+
16+
###################################
17+
logging.basicConfig(level=logging.INFO,
18+
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
19+
logging.getLogger("pylnbits").setLevel(level=logging.WARNING)
20+
logger = logging.getLogger(__name__)
21+
###################################
22+
23+
class SplitPayments:
24+
def __init__(self, config, session: ClientSession = None):
25+
"""__init__
26+
27+
Initializes a Split Payments extension via API
28+
29+
"""
30+
self._session = session
31+
self._config = config
32+
self._lnbits_url = config.lnbits_url
33+
self._invoice_headers = config.invoice_headers()
34+
self._admin_headers = config.admin_headers()
35+
self.splitpath = "/splitpayments/api/v1/targets"
36+
37+
# Return list of target wallets
38+
async def get_target_wallets(self):
39+
"""
40+
GET /splitpayments/api/v1/targets
41+
42+
Headers
43+
{"X-Api-Key": "Admin key"}
44+
45+
Returns an array
46+
200 OK (application/json)
47+
[{'wallet': <string>, 'source': <string>, 'percent': <float>, 'alias': <string>}]
48+
49+
"""
50+
try:
51+
path = self._lnbits_url + self.splitpath
52+
res = await get_url(self._session, path=path, headers=self._admin_headers)
53+
return res
54+
except Exception as e:
55+
logger.info(e)
56+
return e
57+
58+
# Add target wallet
59+
async def add_target_wallet(self, wallet: str, alias: str, percent: float):
60+
"""
61+
PUT /splitpayments/api/v1/targets
62+
63+
Headers
64+
{"X-Api-Key": "Admin key"}
65+
66+
Returns null
67+
200 OK (application/json)
68+
69+
`wallet` can either be a lightning address, lnurl, lnbits internal wallet id.
70+
`percent` can up to 6 decimal places
71+
"""
72+
try:
73+
path = self._lnbits_url + self.splitpath
74+
75+
# check if there are other targets to avoid overwriting
76+
targets = await self.get_target_wallets()
77+
data = [{"wallet": wallet, "alias" : alias, "percent": percent}]
78+
if targets is not None:
79+
data = targets + data
80+
body = {"targets": data}
81+
j = json.dumps(body)
82+
res = await put_url(self._session, path=path, headers=self._admin_headers, body=j)
83+
84+
# response body is null when successful. Return the updated list
85+
if res is None:
86+
updatedlist = await self.get_target_wallets()
87+
return {"targets" : updatedlist}
88+
89+
return res
90+
except Exception as e:
91+
logger.info(e)
92+
return e
93+
94+
# Delete all target wallets
95+
async def delete_target_wallets(self):
96+
"""
97+
DELETE /splitpayments/api/v1/targets
98+
99+
Headers
100+
{"X-Api-Key": "Admin key"}
101+
102+
Returns null
103+
200 OK
104+
"""
105+
try:
106+
path = self._lnbits_url + self.splitpath
107+
res = await delete_url(self._session, path=path, headers=self._admin_headers)
108+
# response body is null when successful.
109+
return res
110+
except Exception as e:
111+
logger.info(e)
112+
return e

tests/test_splitpayments.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import asyncio
2+
3+
from aiohttp.client import ClientSession
4+
5+
from pylnbits.config import Config
6+
from pylnbits.split_payments import SplitPayments
7+
8+
async def main():
9+
10+
c = Config(config_file="config.yml")
11+
url = c.lnbits_url
12+
print(f"url: {url}")
13+
print(f"headers: {c.headers()}")
14+
print(f"admin_headers: {c.admin_headers()}")
15+
16+
async with ClientSession() as session:
17+
sp = SplitPayments(c, session)
18+
19+
# get list of target wallets
20+
targetwallets = await sp.get_target_wallets()
21+
print(f"Target wallets : {targetwallets}")
22+
23+
# add target wallets
24+
addwallets = await sp.add_target_wallet("[email protected]", "Me", 50)
25+
print(f"Updated list of target wallets: {addwallets}")
26+
27+
# delete list of target wallets
28+
# deletewallets = await sp.delete_target_wallets()
29+
# print(f"status: {deletewallets}")
30+
31+
32+
loop = asyncio.get_event_loop()
33+
loop.run_until_complete(main())

tests/test_userwallet.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,20 @@ async def main():
4343
res = await uw.pay_invoice(True, bolt)
4444
print(res)
4545

46+
# pay lnurl
47+
# This is a fictional LNURL for example purposes. Replace with your own.
48+
paylnurl = "LNURL1DP68GURN8GHJ7MRWW4EXCTNZD3SHXCTE0D3SKUM0W4KHU7DF89KHK7YM89KCMRDV0658QSTVV4RY"
49+
# pay_lnurl(lnurl, amount, comment, description)
50+
res = await uw.pay_lnurl(paylnurl, 10, "hello", "hello")
51+
print(res)
52+
53+
# pay lnaddress
54+
# This is a fictional lightning address for example purposes. Replace with your own.
55+
lnaddress = "[email protected]"
56+
# pay_lnaddress(lnurl, amount, comment, description)
57+
res = await uw.pay_lnaddress(lnaddress, 10, "sunshine", "hello")
58+
print(res)
59+
4660

4761
loop = asyncio.get_event_loop()
4862
loop.run_until_complete(main())

0 commit comments

Comments
 (0)