Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions pylnbits/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,8 @@

- `lndhub.py`: for fetching admin and invoice lndhub urls

- `split_payments.py`: For target wallets, calls Rest API methods for LNbits Split Payments Extension
- List target wallets
- Add target wallet
- Delete a target wallet
"""
112 changes: 112 additions & 0 deletions pylnbits/split_payments.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import json
import logging

from aiohttp.client import ClientSession

from pylnbits.utils import delete_url, get_url, put_url

"""
Rest API methods for LNbits Split Payments Extension

GET target wallets
PUT target wallet
DELETE target wallets
"""

###################################
logging.basicConfig(level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logging.getLogger("pylnbits").setLevel(level=logging.WARNING)
logger = logging.getLogger(__name__)
###################################

class SplitPayments:
def __init__(self, config, session: ClientSession = None):
"""__init__

Initializes a Split Payments extension via API

"""
self._session = session
self._config = config
self._lnbits_url = config.lnbits_url
self._invoice_headers = config.invoice_headers()
self._admin_headers = config.admin_headers()
self.splitpath = "/splitpayments/api/v1/targets"

# Return list of target wallets
async def get_target_wallets(self):
"""
GET /splitpayments/api/v1/targets

Headers
{"X-Api-Key": "Admin key"}

Returns an array
200 OK (application/json)
[{'wallet': <string>, 'source': <string>, 'percent': <float>, 'alias': <string>}]

"""
try:
path = self._lnbits_url + self.splitpath
res = await get_url(self._session, path=path, headers=self._admin_headers)
return res
except Exception as e:
logger.info(e)
return e

# Add target wallet
async def add_target_wallet(self, wallet: str, alias: str, percent: float):
"""
PUT /splitpayments/api/v1/targets

Headers
{"X-Api-Key": "Admin key"}

Returns null
200 OK (application/json)

`wallet` can either be a lightning address, lnurl, lnbits internal wallet id.
`percent` can up to 6 decimal places
"""
try:
path = self._lnbits_url + self.splitpath

# check if there are other targets to avoid overwriting
targets = await self.get_target_wallets()
data = [{"wallet": wallet, "alias" : alias, "percent": percent}]
if targets is not None:
data = targets + data
body = {"targets": data}
j = json.dumps(body)
res = await put_url(self._session, path=path, headers=self._admin_headers, body=j)

# response body is null when successful. Return the updated list
if res is None:
updatedlist = await self.get_target_wallets()
return {"targets" : updatedlist}

return res
except Exception as e:
logger.info(e)
return e

# Delete all target wallets
async def delete_target_wallets(self):
"""
DELETE /splitpayments/api/v1/targets

Headers
{"X-Api-Key": "Admin key"}

Returns null
200 OK
"""
try:
path = self._lnbits_url + self.splitpath
res = await delete_url(self._session, path=path, headers=self._admin_headers)
# response body is null when successful.
return res
except Exception as e:
logger.info(e)
return e
33 changes: 33 additions & 0 deletions tests/test_splitpayments.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import asyncio

from aiohttp.client import ClientSession

from pylnbits.config import Config
from pylnbits.split_payments import SplitPayments

async def main():

c = Config(config_file="config.yml")
url = c.lnbits_url
print(f"url: {url}")
print(f"headers: {c.headers()}")
print(f"admin_headers: {c.admin_headers()}")

async with ClientSession() as session:
sp = SplitPayments(c, session)

# get list of target wallets
targetwallets = await sp.get_target_wallets()
print(f"Target wallets : {targetwallets}")

# add target wallets
addwallets = await sp.add_target_wallet("me@example.com", "Me", 50)
print(f"Updated list of target wallets: {addwallets}")

# delete list of target wallets
# deletewallets = await sp.delete_target_wallets()
# print(f"status: {deletewallets}")


loop = asyncio.get_event_loop()
loop.run_until_complete(main())
14 changes: 14 additions & 0 deletions tests/test_userwallet.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,20 @@ async def main():
res = await uw.pay_invoice(True, bolt)
print(res)

# pay lnurl
# This is a fictional LNURL for example purposes. Replace with your own.
paylnurl = "LNURL1DP68GURN8GHJ7MRWW4EXCTNZD3SHXCTE0D3SKUM0W4KHU7DF89KHK7YM89KCMRDV0658QSTVV4RY"
# pay_lnurl(lnurl, amount, comment, description)
res = await uw.pay_lnurl(paylnurl, 10, "hello", "hello")
print(res)

# pay lnaddress
# This is a fictional lightning address for example purposes. Replace with your own.
lnaddress = "wonderful@example.com"
# pay_lnaddress(lnurl, amount, comment, description)
res = await uw.pay_lnaddress(lnaddress, 10, "sunshine", "hello")
print(res)


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