Skip to content

Commit

Permalink
Merge pull request #152 from UnitapApp/fix/lnpay
Browse files Browse the repository at this point in the history
Fix/lnpay
  • Loading branch information
Mohamad Bastin authored Oct 24, 2023
2 parents 90bd8ad + 4039091 commit d9cb85d
Show file tree
Hide file tree
Showing 13 changed files with 585 additions and 231 deletions.
11 changes: 8 additions & 3 deletions .github/workflows/django.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ jobs:
strategy:
max-parallel: 1
matrix:
python-version: [3.10.13]
python-version: [3.10.12]

steps:
- uses: actions/checkout@v3
Expand All @@ -22,8 +22,6 @@ jobs:
python-version: ${{ matrix.python-version }}
- name: Update pip
run: python -m pip install --upgrade pip
- name: Install requests
run: pip install requests
- name: Install Dependencies
run: pip install -r requirements.txt
- name: Run Tests
Expand All @@ -35,3 +33,10 @@ jobs:
DEBUG: False
SENTRY_DSN: "DEBUG-DSN"
DATABASE_URL: sqlite:///db/db.sqlite3
MEMCACHEDCLOUD_SERVERS: " "
MEMCACHEDCLOUD_USERNAME: " "
MEMCACHEDCLOUD_PASSWORD: " "
LIGHTNING_INVOICE: lnbc100n1pjxtceppp5q65xc3w8tnnmzkhqgg9c7h4a8hzplm0dppr944upwsq4q62sjeesdqu2askcmr9wssx7e3q2dshgmmndp5scqzzsxqyz5vqsp5hj2vzha0x4qvuyzrym6ryvxwnccn4kjwa57037dgcshl5ls4tves9qyyssqj24t4j2dkp2r29ptgxqz2etsk0qp8ggwmt20czfu48h5akgme43zevg6x040scjzx3qgtp8mkcg2gurv0hy8d8xm3hhf8k68uefl9sqqqscuvz
LIGHTNING_RPC_URL: https://api.lnpay.co/v1/
LIGHTNING_WALLET: ${{ secrets.LIGHTNING_WALLET }}
LIGHTNING_FUND_MANAGER: ${{ secrets.LIGHTNING_FUND_MANAGER }}
2 changes: 0 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ WORKDIR /code
RUN apt update && apt install gcc
COPY ./requirements.txt /code/requirements.txt
RUN pip install pip --upgrade
#installing requests befor the rest for lnpay compatibility
RUN pip install requests
RUN pip install -r requirements.txt
COPY . .
RUN mkdir db
Expand Down
62 changes: 31 additions & 31 deletions brightIDfaucet/settings.py
Original file line number Diff line number Diff line change
@@ -1,51 +1,51 @@
import logging
import os
from pathlib import Path
from faucet.faucet_manager.bright_id_interface import BrightIDInterface

import dj_database_url
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
from dotenv import load_dotenv
import dj_database_url
import logging
from sentry_sdk.integrations.django import DjangoIntegration

from faucet.faucet_manager.bright_id_interface import BrightIDInterface

load_dotenv()
# Build paths inside the project like this: BASE_DIR / 'subdir'.

BASE_DIR = Path(__file__).resolve().parent.parent

logging.basicConfig(
level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s"
)
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s")

LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
"version": 1,
"disable_existing_loggers": False,
"handlers": {
"console": {
"class": "logging.StreamHandler",
},
},
'root': {
'handlers': ['console'],
'level': 'WARNING',
"root": {
"handlers": ["console"],
"level": "WARNING",
},
'loggers': {
'django': {
'handlers': ['console'],
'level': 'INFO',
"loggers": {
"django": {
"handlers": ["console"],
"level": "INFO",
},
'django.server': {
'handlers': ['console'],
'level': 'INFO',
"django.server": {
"handlers": ["console"],
"level": "INFO",
},
'django.db.backends': {
'handlers': ['console'],
'level': 'INFO',
"django.db.backends": {
"handlers": ["console"],
"level": "INFO",
},
'django.core.cache': {
'handlers': ['console'],
'level': 'ERROR', # Change this to control the log level
}
}
"django.core.cache": {
"handlers": ["console"],
"level": "ERROR", # Change this to control the log level
},
},
}


Expand Down Expand Up @@ -117,7 +117,7 @@ def before_send(event, hint):
"encrypted_model_fields",
"drf_yasg",
"corsheaders",
"django_filters"
"django_filters",
]

MIDDLEWARE = [
Expand Down
2 changes: 1 addition & 1 deletion faucet/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ class TransactionBatchAdmin(admin.ModelAdmin):
"age",
"is_expired",
"claims_count",
"claims_amount",
# "claims_amount",
]
search_fields = ["tx_hash"]
list_filter = ["chain", "_status", "updating"]
Expand Down
16 changes: 9 additions & 7 deletions faucet/faucet_manager/fund_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,9 @@ def get_fund_manager_checksum_address(self):

@property
def contract(self):
return self.w3.eth.contract(address=self.get_fund_manager_checksum_address(), abi=self.abi)
return self.w3.eth.contract(
address=self.get_fund_manager_checksum_address(), abi=self.abi
)

def transfer(self, bright_user: BrightUser, amount: int):
tx = self.single_eth_transfer_signed_tx(amount, bright_user.address)
Expand Down Expand Up @@ -133,7 +135,7 @@ def get_tx(self, tx_hash):
tx = self.w3.eth.get_transaction(tx_hash)
return tx

def from_wei(self, value: int, unit: str = 'ether'):
def from_wei(self, value: int, unit: str = "ether"):
return self.w3.from_wei(value, unit)


Expand Down Expand Up @@ -223,14 +225,15 @@ def multi_transfer(self, data):
if self.is_initialized:
instruction = [
instructions.withdraw(
{"amount": item['amount']},
{"amount": item["amount"]},
{
"lock_account": self.lock_account_address,
"operator": self.operator,
"recipient": Pubkey.from_string(item["to"])
"recipient": Pubkey.from_string(item["to"]),
},
self.program_id
) for item in data
self.program_id,
)
for item in data
]
if self.is_gas_price_too_high(instruction):
raise FundMangerException.GasPriceTooHigh()
Expand Down Expand Up @@ -302,7 +305,6 @@ def __check_max_cap_exceeds(self, amount) -> bool:

def multi_transfer(self, data):
client = self.lnpay_client

with memcache_lock(MEMCACHE_LIGHTNING_LOCK_KEY, os.getpid()) as acquired:
assert acquired, "Could not acquire Lightning multi-transfer lock"

Expand Down
36 changes: 17 additions & 19 deletions faucet/faucet_manager/lnpay_client.py
Original file line number Diff line number Diff line change
@@ -1,42 +1,40 @@
import logging
import json
import lnpay_py
from lnpay_py.wallet import LNPayWallet
from lnpay_py.lntx import LNPayLnTx
from lnpay_py.utility_helpers import get_request
from .lnpay_manager.lnpay_main import initialize
from .lnpay_manager.wallet import LNPayWallet
from .lnpay_manager.lntx import LNPayLnTx
from .lnpay_manager.utility_helpers import get_request


class LNPayClient:
def __init__(self, api_url: str, api_key: str, wallet: str) -> None:
self.api_key = api_key
self.wallet_address = wallet

lnpay_py.initialize(api_key, params={
'endpoint_url': api_url
})

initialize(api_key, params={"endpoint_url": api_url})

@property
def wallet(self):
return LNPayWallet(self.wallet_address)

def pay_invoice(self, invoice: str) -> json:
invoice_params = {
'payment_request': invoice
}
invoice_params = {"payment_request": invoice}
pay_result = self.wallet.pay_invoice(invoice_params)
if 'lnTx' not in pay_result:
logging.error(pay_result['message'])
if "lnTx" not in pay_result:
logging.error(pay_result["message"])
return False
return pay_result

def decode_invoice(self, invoice: str) -> json:
return get_request(
f"node/default/payments/decodeinvoice?payment_request={invoice}")

f"node/default/payments/decodeinvoice?payment_request={invoice}"
)

def get_balance(self):
info = self.wallet.get_info()
return info['balance']
return info["balance"]

def get_invoice_status(self, lntx_id):
ln_tx = LNPayLnTx(lntx_id)
invoice_result = ln_tx.get_info()
return invoice_result
return invoice_result
39 changes: 39 additions & 0 deletions faucet/faucet_manager/lnpay_manager/lnpay_main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# from .utility_helpers import post_request

__version__ = "0.1.1"

__VERSION__ = "py" + __version__
__ENDPOINT_URL__ = "https://api.lnpay.co/v1/"
__DEFAULT_WAK__ = ""
__PUBLIC_API_KEY__ = ""


def initialize(public_api_key, default_wak=None, params=None):
"""
LNPay module initialization function required for interacting with the LNPay API.
Parameters
----------
public_api_key (str): Account public key from https://lnpay.co/dashboard/developers
default_wak (str, optional): Default Wallet Access Key to use for a specific wallet when creating a `LNPayWallet`.
params (Object): Object representing additional parameters to set globally. Example: {'endpoint_url': 'https://lnpay.co/v1/'}
"""

if params is None:
params = {}

print("initializing lnpay..")

global __VERSION__
global __PUBLIC_API_KEY__
global __ENDPOINT_URL__
global __DEFAULT_WAK__

__VERSION__ = "py" + __version__
__PUBLIC_API_KEY__ = public_api_key
__ENDPOINT_URL__ = params.get("endpoint_url", __ENDPOINT_URL__)
__DEFAULT_WAK__ = default_wak


# def create_wallet(params):
# return post_request('wallet', params)
49 changes: 49 additions & 0 deletions faucet/faucet_manager/lnpay_manager/lntx.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
from .utility_helpers import get_request


class LNPayLnTx:
"""
A class used for LnTx API Functions
Learn more at https://docs.lnpay.co
"""

def __init__(self, tx_id):
"""
Parameters
----------
tx_id (str) : The LNPay transaction id (ex. lntx_tVompfuizfryXznKhc38J8)
"""

self.tx_id = tx_id

def get_info(self):
"""
Gets the invoice information for the `tx_id` set in the `__init__` of this class.
Returns
-------
LnTx (Lightning Invoice) Object
https://docs.lnpay.co/lntx/
Example:
```
{
"id": "lntx_IaWG3yS6FB3ZQJDRjXkkkkk",
"created_at": 1577600922,
"updated_at": 1577600922,
"dest_pubkey": "033868c219bdb51a33560d854d500fe7d3898a1ad9e05dd89d0007e11313588500",
"payment_request": "lnbc10n1pw7l9l3pp5pr2sr8pdt2yjm04am0wktr7cphkt8c3gtlvq8qlgaqw9jsh3d6qsdpj2pshjampd3kzunrfde4jq3npw43k2ap6ypgx7mmjgesh2cm9wscqzpgxqrrss4z9zac6gtpskjkhtdsxjd0m4are599k4ya9al0ktqqf7y70xqt5xs3as53va424nsh2dxumdln3ymm2048550hrj5sw8nw2ajzc9p9l3s97",
"r_hash_decoded": "f646ff04116d16b7a70e953034b1c7c475c771847eb43e66892039ff5589863b",
"description_hash": null,
"memo": "This is a memo",
"num_satoshis": 11,
"expiry": 86400,
"expires_at": 1578992143,
"payment_preimage": "71566c546f304e70507a486b7561356177426a7535716345713670482f45582b4e4262337a654mmmmm6d673d",
"settled": 1,
"settled_at": 1575992143
}
```
"""
return get_request('lntx/{}'.format(self.tx_id))
57 changes: 57 additions & 0 deletions faucet/faucet_manager/lnpay_manager/utility_helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import pprint
import requests
import json


def get_request(location):
from .lnpay_main import __ENDPOINT_URL__, __PUBLIC_API_KEY__, __VERSION__

"""
Network utility method for making a GET call to a LNPay endpoint
Parameters
----------
location (str): URL path requested
Returns
-------
Network response as a JSON Object.
"""
endpoint = __ENDPOINT_URL__ + location
headers = {
"X-Api-Key": __PUBLIC_API_KEY__,
"X-LNPay-sdk": __VERSION__,
}

r = requests.get(url=endpoint, headers=headers)
return r.json()


def post_request(location, params):
from .lnpay_main import __ENDPOINT_URL__, __PUBLIC_API_KEY__, __VERSION__

"""
Network utility method for making a POST call to a LNPay endpoint
Parameters
----------
location (str): URL path requested
params (object): the `data` to be POSTed in the network request
Returns
-------
Network response as a JSON Object.
"""

endpoint = __ENDPOINT_URL__ + location
headers = {
"Content-Type": "application/json",
"X-Api-Key": __PUBLIC_API_KEY__,
"X-LNPay-sdk": __VERSION__,
}

data = json.dumps(params)

r = requests.post(url=endpoint, data=data, headers=headers)
print("salam", r.text)
return r.json()
Loading

0 comments on commit d9cb85d

Please sign in to comment.