Skip to content

Commit

Permalink
Merge pull request #9 from lightsparkdev/feat/tojson
Browse files Browse the repository at this point in the history
Add a to_json() object function that's consistent with from_json()
  • Loading branch information
jklein24 authored Nov 9, 2023
2 parents ace5e3e + 26eb908 commit 92c437e
Show file tree
Hide file tree
Showing 108 changed files with 1,213 additions and 0 deletions.
23 changes: 23 additions & 0 deletions lightspark/__tests__/test_serialization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import json
from lightspark.objects.InvoiceData import from_json as InvoiceData_from_json
from lightspark.objects.Node import from_json as Node_from_json


class TestSerialization:
def test_serialize_deserialize_invoice_data(self):
serialized = '{"__typename": "InvoiceData", "invoice_data_encoded_payment_request":"lnbcrt34170n1pj5vdn4pp56jhw0672v566u4rvl333v8hwwuvavvu9gx4a2mqag4pkrvm0hwkqhp5xaz278y6cejcvpqnndl4wfq3slgthjduwlfksg778aevn23v2pdscqzpgxqyz5vqsp5ee5jezfvjqvvz7hfwta3ekk8hs6dq36szkgp40qh7twa8upquxlq9qyyssqjg2slc95falxf2t67y0wu2w43qwfcvfflwl8tn4ppqw9tumwqxk36qkfct9p2w8c3yy2ld7c6nacy4ssv2gl6qyqfpmhl4jmarnjf8cpvjlxek","invoice_data_bitcoin_network":"REGTEST","invoice_data_payment_hash":"d4aee7ebca6535ae546cfc63161eee7719d6338541abd56c1d454361b36fbbac","invoice_data_amount":{"currency_amount_original_value":3417,"currency_amount_original_unit":"SATOSHI","currency_amount_preferred_currency_unit":"USD","currency_amount_preferred_currency_value_rounded":118,"currency_amount_preferred_currency_value_approx":118.89352818371607},"invoice_data_created_at":"2023-11-04T12:17:57+00:00","invoice_data_expires_at":"2023-11-05T12:17:57+00:00","invoice_data_memo":null,"invoice_data_destination":{"graph_node_id":"GraphNode:0189a572-6dba-cf00-0000-ac0908d34ea6","graph_node_created_at":"2023-07-30T06:18:07.162759+00:00","graph_node_updated_at":"2023-11-04T12:01:04.015414+00:00","graph_node_alias":"ls_test_vSViIQitob_SE","graph_node_bitcoin_network":"REGTEST","graph_node_color":"#3399ff","graph_node_conductivity":null,"graph_node_display_name":"ls_test_vSViIQitob_SE","graph_node_public_key":"02253935a5703a6f0429081e08d2defce0faa15f4d75305302284751d53a4e0608", "__typename":"GraphNode"}}'
deserialized = InvoiceData_from_json(None, json.loads(serialized))
reserialized = deserialized.to_json()
assert reserialized == json.loads(serialized)

deserialized_again = InvoiceData_from_json(None, reserialized)
assert deserialized_again == deserialized

def test_serialize_deserialize_graph_node(self):
serialized = '{"graph_node_id":"GraphNode:0189a572-6dba-cf00-0000-ac0908d34ea6","graph_node_created_at":"2023-07-30T06:18:07.162759+00:00","graph_node_updated_at":"2023-11-04T12:01:04.015414+00:00","graph_node_alias":"ls_test_vSViIQitob_SE","graph_node_bitcoin_network":"REGTEST","graph_node_color":"#3399ff","graph_node_conductivity":null,"graph_node_display_name":"ls_test_vSViIQitob_SE","graph_node_public_key":"02253935a5703a6f0429081e08d2defce0faa15f4d75305302284751d53a4e0608", "__typename":"GraphNode"}'
deserialized = Node_from_json(None, json.loads(serialized))
reserialized = deserialized.to_json()
assert reserialized == json.loads(serialized)

deserialized_again = Node_from_json(None, reserialized)
assert deserialized_again == deserialized
9 changes: 9 additions & 0 deletions lightspark/objects/Account.py
Original file line number Diff line number Diff line change
Expand Up @@ -1762,6 +1762,15 @@ def get_wallets(
connection = json["entity"]["wallets"]
return AccountToWalletsConnection_from_json(self.requester, connection)

def to_json(self) -> Mapping[str, Any]:
return {
"__typename": "Account",
"account_id": self.id,
"account_created_at": self.created_at.isoformat(),
"account_updated_at": self.updated_at.isoformat(),
"account_name": self.name,
}


FRAGMENT = """
fragment AccountFragment on Account {
Expand Down
10 changes: 10 additions & 0 deletions lightspark/objects/AccountToApiTokensConnection.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,16 @@ class AccountToApiTokensConnection(Connection):
"""The API tokens for the current page of this connection."""
typename: str

def to_json(self) -> Mapping[str, Any]:
return {
"__typename": "AccountToApiTokensConnection",
"account_to_api_tokens_connection_count": self.count,
"account_to_api_tokens_connection_page_info": self.page_info.to_json(),
"account_to_api_tokens_connection_entities": [
e.to_json() for e in self.entities
],
}


FRAGMENT = """
fragment AccountToApiTokensConnectionFragment on AccountToApiTokensConnection {
Expand Down
8 changes: 8 additions & 0 deletions lightspark/objects/AccountToChannelsConnection.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ class AccountToChannelsConnection:
entities: List[Channel]
"""The channels for the current page of this connection."""

def to_json(self) -> Mapping[str, Any]:
return {
"account_to_channels_connection_count": self.count,
"account_to_channels_connection_entities": [
e.to_json() for e in self.entities
],
}


FRAGMENT = """
fragment AccountToChannelsConnectionFragment on AccountToChannelsConnection {
Expand Down
10 changes: 10 additions & 0 deletions lightspark/objects/AccountToNodesConnection.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,16 @@ class AccountToNodesConnection(Connection):
"""The nodes for the current page of this connection."""
typename: str

def to_json(self) -> Mapping[str, Any]:
return {
"__typename": "AccountToNodesConnection",
"account_to_nodes_connection_count": self.count,
"account_to_nodes_connection_page_info": self.page_info.to_json(),
"account_to_nodes_connection_entities": [
e.to_json() for e in self.entities
],
}


FRAGMENT = """
fragment AccountToNodesConnectionFragment on AccountToNodesConnection {
Expand Down
10 changes: 10 additions & 0 deletions lightspark/objects/AccountToPaymentRequestsConnection.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,16 @@ class AccountToPaymentRequestsConnection(Connection):
"""The payment requests for the current page of this connection."""
typename: str

def to_json(self) -> Mapping[str, Any]:
return {
"__typename": "AccountToPaymentRequestsConnection",
"account_to_payment_requests_connection_count": self.count,
"account_to_payment_requests_connection_page_info": self.page_info.to_json(),
"account_to_payment_requests_connection_entities": [
e.to_json() for e in self.entities
],
}


FRAGMENT = """
fragment AccountToPaymentRequestsConnectionFragment on AccountToPaymentRequestsConnection {
Expand Down
19 changes: 19 additions & 0 deletions lightspark/objects/AccountToTransactionsConnection.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,25 @@ class AccountToTransactionsConnection(Connection):
"""The transactions for the current page of this connection."""
typename: str

def to_json(self) -> Mapping[str, Any]:
return {
"__typename": "AccountToTransactionsConnection",
"account_to_transactions_connection_count": self.count,
"account_to_transactions_connection_page_info": self.page_info.to_json(),
"account_to_transactions_connection_profit_loss": self.profit_loss.to_json()
if self.profit_loss
else None,
"account_to_transactions_connection_average_fee_earned": self.average_fee_earned.to_json()
if self.average_fee_earned
else None,
"account_to_transactions_connection_total_amount_transacted": self.total_amount_transacted.to_json()
if self.total_amount_transacted
else None,
"account_to_transactions_connection_entities": [
e.to_json() for e in self.entities
],
}


FRAGMENT = """
fragment AccountToTransactionsConnectionFragment on AccountToTransactionsConnection {
Expand Down
10 changes: 10 additions & 0 deletions lightspark/objects/AccountToWalletsConnection.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,16 @@ class AccountToWalletsConnection(Connection):
"""The wallets for the current page of this connection."""
typename: str

def to_json(self) -> Mapping[str, Any]:
return {
"__typename": "AccountToWalletsConnection",
"account_to_wallets_connection_count": self.count,
"account_to_wallets_connection_page_info": self.page_info.to_json(),
"account_to_wallets_connection_entities": [
e.to_json() for e in self.entities
],
}


FRAGMENT = """
fragment AccountToWalletsConnectionFragment on AccountToWalletsConnection {
Expand Down
11 changes: 11 additions & 0 deletions lightspark/objects/ApiToken.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,17 @@ class ApiToken(Entity):
"""A list of permissions granted to the token."""
typename: str

def to_json(self) -> Mapping[str, Any]:
return {
"__typename": "ApiToken",
"api_token_id": self.id,
"api_token_created_at": self.created_at.isoformat(),
"api_token_updated_at": self.updated_at.isoformat(),
"api_token_client_id": self.client_id,
"api_token_name": self.name,
"api_token_permissions": [e.value for e in self.permissions],
}


FRAGMENT = """
fragment ApiTokenFragment on ApiToken {
Expand Down
7 changes: 7 additions & 0 deletions lightspark/objects/Balances.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ class Balances:
It represents the amount currently available to withdraw and is usually equal to the `owned_balance` but it does not include in-flight operations (which would likely succeed and therefore likely make your withdrawal fail)."""

def to_json(self) -> Mapping[str, Any]:
return {
"balances_owned_balance": self.owned_balance.to_json(),
"balances_available_to_send_balance": self.available_to_send_balance.to_json(),
"balances_available_to_withdraw_balance": self.available_to_withdraw_balance.to_json(),
}


FRAGMENT = """
fragment BalancesFragment on Balances {
Expand Down
22 changes: 22 additions & 0 deletions lightspark/objects/BlockchainBalance.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,28 @@ class BlockchainBalance:
available_balance: Optional[CurrencyAmount]
"""Funds available for creating channels or withdrawing."""

def to_json(self) -> Mapping[str, Any]:
return {
"blockchain_balance_total_balance": self.total_balance.to_json()
if self.total_balance
else None,
"blockchain_balance_confirmed_balance": self.confirmed_balance.to_json()
if self.confirmed_balance
else None,
"blockchain_balance_unconfirmed_balance": self.unconfirmed_balance.to_json()
if self.unconfirmed_balance
else None,
"blockchain_balance_locked_balance": self.locked_balance.to_json()
if self.locked_balance
else None,
"blockchain_balance_required_reserve": self.required_reserve.to_json()
if self.required_reserve
else None,
"blockchain_balance_available_balance": self.available_balance.to_json()
if self.available_balance
else None,
}


FRAGMENT = """
fragment BlockchainBalanceFragment on BlockchainBalance {
Expand Down
41 changes: 41 additions & 0 deletions lightspark/objects/Channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,47 @@ def get_transactions(
connection = json["entity"]["transactions"]
return ChannelToTransactionsConnection_from_json(self.requester, connection)

def to_json(self) -> Mapping[str, Any]:
return {
"__typename": "Channel",
"channel_id": self.id,
"channel_created_at": self.created_at.isoformat(),
"channel_updated_at": self.updated_at.isoformat(),
"channel_funding_transaction": {"id": self.funding_transaction_id}
if self.funding_transaction_id
else None,
"channel_capacity": self.capacity.to_json() if self.capacity else None,
"channel_local_balance": self.local_balance.to_json()
if self.local_balance
else None,
"channel_local_unsettled_balance": self.local_unsettled_balance.to_json()
if self.local_unsettled_balance
else None,
"channel_remote_balance": self.remote_balance.to_json()
if self.remote_balance
else None,
"channel_remote_unsettled_balance": self.remote_unsettled_balance.to_json()
if self.remote_unsettled_balance
else None,
"channel_unsettled_balance": self.unsettled_balance.to_json()
if self.unsettled_balance
else None,
"channel_total_balance": self.total_balance.to_json()
if self.total_balance
else None,
"channel_status": self.status.value if self.status else None,
"channel_estimated_force_closure_wait_minutes": self.estimated_force_closure_wait_minutes,
"channel_commit_fee": self.commit_fee.to_json()
if self.commit_fee
else None,
"channel_fees": self.fees.to_json() if self.fees else None,
"channel_remote_node": {"id": self.remote_node_id}
if self.remote_node_id
else None,
"channel_local_node": {"id": self.local_node_id},
"channel_short_channel_id": self.short_channel_id,
}


FRAGMENT = """
fragment ChannelFragment on Channel {
Expand Down
24 changes: 24 additions & 0 deletions lightspark/objects/ChannelClosingTransaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,30 @@ class ChannelClosingTransaction(OnChainTransaction, Transaction, Entity):
"""If known, the channel this transaction is closing."""
typename: str

def to_json(self) -> Mapping[str, Any]:
return {
"__typename": "ChannelClosingTransaction",
"channel_closing_transaction_id": self.id,
"channel_closing_transaction_created_at": self.created_at.isoformat(),
"channel_closing_transaction_updated_at": self.updated_at.isoformat(),
"channel_closing_transaction_status": self.status.value,
"channel_closing_transaction_resolved_at": self.resolved_at.isoformat()
if self.resolved_at
else None,
"channel_closing_transaction_amount": self.amount.to_json(),
"channel_closing_transaction_transaction_hash": self.transaction_hash,
"channel_closing_transaction_fees": self.fees.to_json()
if self.fees
else None,
"channel_closing_transaction_block_hash": self.block_hash,
"channel_closing_transaction_block_height": self.block_height,
"channel_closing_transaction_destination_addresses": self.destination_addresses,
"channel_closing_transaction_num_confirmations": self.num_confirmations,
"channel_closing_transaction_channel": {"id": self.channel_id}
if self.channel_id
else None,
}


FRAGMENT = """
fragment ChannelClosingTransactionFragment on ChannelClosingTransaction {
Expand Down
6 changes: 6 additions & 0 deletions lightspark/objects/ChannelFees.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ class ChannelFees:

fee_rate_per_mil: Optional[int]

def to_json(self) -> Mapping[str, Any]:
return {
"channel_fees_base_fee": self.base_fee.to_json() if self.base_fee else None,
"channel_fees_fee_rate_per_mil": self.fee_rate_per_mil,
}


FRAGMENT = """
fragment ChannelFeesFragment on ChannelFees {
Expand Down
24 changes: 24 additions & 0 deletions lightspark/objects/ChannelOpeningTransaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,30 @@ class ChannelOpeningTransaction(OnChainTransaction, Transaction, Entity):
"""If known, the channel this transaction is opening."""
typename: str

def to_json(self) -> Mapping[str, Any]:
return {
"__typename": "ChannelOpeningTransaction",
"channel_opening_transaction_id": self.id,
"channel_opening_transaction_created_at": self.created_at.isoformat(),
"channel_opening_transaction_updated_at": self.updated_at.isoformat(),
"channel_opening_transaction_status": self.status.value,
"channel_opening_transaction_resolved_at": self.resolved_at.isoformat()
if self.resolved_at
else None,
"channel_opening_transaction_amount": self.amount.to_json(),
"channel_opening_transaction_transaction_hash": self.transaction_hash,
"channel_opening_transaction_fees": self.fees.to_json()
if self.fees
else None,
"channel_opening_transaction_block_hash": self.block_hash,
"channel_opening_transaction_block_height": self.block_height,
"channel_opening_transaction_destination_addresses": self.destination_addresses,
"channel_opening_transaction_num_confirmations": self.num_confirmations,
"channel_opening_transaction_channel": {"id": self.channel_id}
if self.channel_id
else None,
}


FRAGMENT = """
fragment ChannelOpeningTransactionFragment on ChannelOpeningTransaction {
Expand Down
21 changes: 21 additions & 0 deletions lightspark/objects/ChannelSnapshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,27 @@ class ChannelSnapshot:

remote_unsettled_balance: Optional[CurrencyAmount]

def to_json(self) -> Mapping[str, Any]:
return {
"channel_snapshot_channel": {"id": self.channel_id},
"channel_snapshot_timestamp": self.timestamp.isoformat(),
"channel_snapshot_local_balance": self.local_balance.to_json()
if self.local_balance
else None,
"channel_snapshot_local_unsettled_balance": self.local_unsettled_balance.to_json()
if self.local_unsettled_balance
else None,
"channel_snapshot_local_channel_reserve": self.local_channel_reserve.to_json()
if self.local_channel_reserve
else None,
"channel_snapshot_remote_balance": self.remote_balance.to_json()
if self.remote_balance
else None,
"channel_snapshot_remote_unsettled_balance": self.remote_unsettled_balance.to_json()
if self.remote_unsettled_balance
else None,
}


FRAGMENT = """
fragment ChannelSnapshotFragment on ChannelSnapshot {
Expand Down
14 changes: 14 additions & 0 deletions lightspark/objects/ChannelToTransactionsConnection.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,20 @@ class ChannelToTransactionsConnection:
total_fees: Optional[CurrencyAmount]
"""The total amount of fees for the transactions that transited through this channel, according to the filters and constraints of the connection."""

def to_json(self) -> Mapping[str, Any]:
return {
"channel_to_transactions_connection_count": self.count,
"channel_to_transactions_connection_average_fee": self.average_fee.to_json()
if self.average_fee
else None,
"channel_to_transactions_connection_total_amount_transacted": self.total_amount_transacted.to_json()
if self.total_amount_transacted
else None,
"channel_to_transactions_connection_total_fees": self.total_fees.to_json()
if self.total_fees
else None,
}


FRAGMENT = """
fragment ChannelToTransactionsConnectionFragment on ChannelToTransactionsConnection {
Expand Down
6 changes: 6 additions & 0 deletions lightspark/objects/CreateApiTokenInput.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ class CreateApiTokenInput:
permissions: List[Permission]
"""List of permissions to grant to the API token"""

def to_json(self) -> Mapping[str, Any]:
return {
"create_api_token_input_name": self.name,
"create_api_token_input_permissions": [e.value for e in self.permissions],
}


def from_json(obj: Mapping[str, Any]) -> CreateApiTokenInput:
return CreateApiTokenInput(
Expand Down
Loading

0 comments on commit 92c437e

Please sign in to comment.