Skip to content

Commit

Permalink
Merge pull request #332 from shocknet/test
Browse files Browse the repository at this point in the history
fixes
  • Loading branch information
shocknet-justin authored Oct 8, 2024
2 parents dcc9b17 + 4333203 commit 14a38c9
Show file tree
Hide file tree
Showing 8 changed files with 85 additions and 35 deletions.
24 changes: 15 additions & 9 deletions src/Api/nostrHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -282,23 +282,29 @@ export const newNip78ChangelogEvent = (data: string, pubkey: string) => {
return {
content: data,
created_at: Math.floor(Date.now() / 1000),
kind: 5500,
kind: 2121,
tags: [["d", changelogsTag]],
pubkey
}
}

export const subToNip78Changelogs = (pubkey: string, relays: string[], timestamp: number, onEvent: (e: Event) => Promise<void>) => {
return pool.subscribeMany(relays, [
return pool.subscribeMany(
relays,
[
{
since: timestamp,
kinds: [2121],
'#d': [changelogsTag],
authors: [pubkey]
}
],
{
since: timestamp,
kinds: [5500],
'#d': [changelogsTag],
authors: [pubkey]
onevent: (e) => {
onEvent(e)
},
}
], {
onevent: (e) => { onEvent(e) }
})
)
}


Expand Down
24 changes: 21 additions & 3 deletions src/Components/Modals/EditSourceModal/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ import { CrossIcon, ShieldIcon, TrashIcon } from '../../../Assets/SvgIconLibrary

import { arrangeIcon } from "../../../jsxHelpers";
import Dropdown from "../../Dropdowns/LVDropdown";
import { useCallback, useEffect, useState } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { nip19 } from "nostr-tools";
import classNames from "classnames";
import { setSourceToEdit } from "../../../State/Slices/modalsSlice";
import { setSourceToEdit, SourceToEdit } from "../../../State/Slices/modalsSlice";
import { deletePaySources, editPaySources } from "../../../State/Slices/paySourcesSlice";
import { toast } from "react-toastify";
import Toast from "../../Toast";
Expand All @@ -36,7 +36,25 @@ export const EditSourceModal = () => {
const dispatch = useDispatch()
const paySources = useSelector(state => state.paySource)
const spendSources = useSelector(state => state.spendSource)
const sourceToEdit = useSelector(state => state.modalsSlice.sourceToEdit);
const stateSourceToEdit = useSelector(state => state.modalsSlice.sourceToEdit);

// When it's a new source it will take some time to get populated with all data
// such as bridge_url, ndebit, etc; so useMemo to reflect the most updated version of the source
const sourceToEdit: SourceToEdit = useMemo(() => {
if (!stateSourceToEdit) return null;
if (stateSourceToEdit.type === "payTo") {
return {
source: paySources.sources[stateSourceToEdit.source.id],
type: "payTo"
}
} else {
return {
source: spendSources.sources[stateSourceToEdit.source.id],
type: "spendFrom"
}
}
}, [spendSources, paySources, stateSourceToEdit])

const [editValues, setEditValues] = useState({
relay: "",
nameService: "",
Expand Down
26 changes: 21 additions & 5 deletions src/Components/SwItem/SwItem.scss
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
.SwItem{
font-size: 1.2rem;
border: none;
display: flow-root;
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: nowrap;
margin: auto;
width: 100%;
cursor: pointer;
Expand All @@ -19,19 +22,21 @@
}

&_left{
float: left;
display: flex;
margin-top: 5px;
max-width: 80%;
flex: 1;
}

&_right{
margin-right: 5px;
float: right;
margin-top: 5px;
flex-shrink: 0;
max-width: 20%;
}

&_text{
margin-left: 5px;
width: 100%;
}

&_date{
Expand All @@ -41,8 +46,16 @@

&_station{
margin-top: 7px;
font-size: 18px;
font-size: clamp(14px, 3vw, 18px);
color: #2aabe1;
width: 80%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;




}

&_price{
Expand All @@ -58,6 +71,9 @@
text-align: right;
font-size: 16px;
margin-bottom: 2px;
@media (max-width: 480px) {
font-size: 14px;
}
}

&_divider {
Expand Down
2 changes: 1 addition & 1 deletion src/Components/SwItem/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export const SwItem = ({
if (link !== operation.identifier) {
return link
}
if ((operation.type === Types.UserOperationType.INCOMING_INVOICE || operation.type === Types.UserOperationType.OUTGOING_INVOICE)) {
if ((operation.type === Types.UserOperationType.INCOMING_INVOICE || operation.type === Types.UserOperationType.OUTGOING_INVOICE) && operation.identifier.startsWith("lnbc") || operation.identifier.startsWith("lntbs")) {
let network = undefined
if (operation.identifier.startsWith("lntbs")) {
network = {
Expand Down
4 changes: 2 additions & 2 deletions src/Pages/Send/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ export const Send = () => {
case InputClassification.LN_ADDRESS:
case InputClassification.LNURL: {
let invoice = "";
if (destination.noffer) {
if (destination.noffer && selectedSource.pubSource) {
invoice = await createNofferInvoice(destination.noffer, selectedSource.keys, amount);
} else {
invoice = await createLnurlInvoice(amount, destination);
Expand Down Expand Up @@ -293,7 +293,7 @@ export const Send = () => {
pub: selectedSource.id,
operation: {
amount,
identifier: destination.data,
identifier: payRes.data,
inbound: false,
operationId: `${destination.data}-${amount}-${timestamp}`,
paidAtUnix: timestamp,
Expand Down
2 changes: 1 addition & 1 deletion src/State/Slices/modalsSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { PayTo, SpendFrom } from '../../globalTypes';
type ModalRequest = { request: LiveDebitRequest, sourceId: string }
export type EditDebit = DebitAuthorization & { sourceId: string, domainName?: string, avatarUrl?: string }

type SourceToEdit = {
export type SourceToEdit = {
type: "payTo";
source: PayTo;
} | {
Expand Down
29 changes: 20 additions & 9 deletions src/State/backupMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,7 @@ const syncNewDeviceWithRemote = async (api: ListenerEffectAPI<State, ThunkDispat
}
}
}

let changelogsTasksQueue: Changelog[] = [];
export const backupMiddleware = {
predicate: (action: AnyAction) => {
return (
Expand All @@ -434,16 +434,26 @@ export const backupMiddleware = {
);
},
effect: async (action: AnyAction, listenerApi: ListenerEffectAPI<State, ThunkDispatch<unknown, unknown, AnyAction>>) => {


console.log("changelog sending triggered", action)
const state = listenerApi.getState();
const newHash = getStateHash(state);
const previousHash = localStorage.getItem(STATE_HASH) || getStateHash(listenerApi.getOriginalState());
localStorage.setItem(STATE_HASH, newHash)
const id = getDeviceId()
const changelog: Changelog = { action: { type: action.type, payload: action.payload }, id, previousHash: previousHash!, newHash: getStateHash(listenerApi.getState()) }
await shardAndBackupState(state, newHash, [changelog])
changelogsTasksQueue.push(changelog)
try {
await listenerApi.delay(100)
console.log("Releasing")
} catch(err) {
if (err instanceof TaskAbortError) {
return;
}
}
listenerApi.cancelActiveListeners();

await shardAndBackupState(state, newHash, changelogsTasksQueue)
changelogsTasksQueue = []
}
}

Expand Down Expand Up @@ -529,10 +539,13 @@ export const backupPollingMiddleware = {
localStorage.setItem(CHANGELOG_TIMESTAMP, timestamp.toString());
}

const pollingTask = listenerApi.fork(async (forkApi) => {
const pollingTask = listenerApi.fork(async () => {
let subCloser = {
close: () => {}
}
try {
console.log("Now stable device, listenting for changelogs")
const unsubFunc = await subscribeToRemoteChangelogs(
subCloser = await subscribeToRemoteChangelogs(
Number(timestamp),
async (decrypted, eventTimestamp) => {
const changelog = JSON.parse(decrypted) as Changelog;
Expand All @@ -546,11 +559,9 @@ export const backupPollingMiddleware = {
}
);

forkApi.signal.addEventListener("abort", () => {
unsubFunc();
})

} catch (err) {
subCloser.close()
listenerApi.subscribe()
if (err instanceof TaskAbortError) {
console.log("task was aborted")
Expand Down
9 changes: 4 additions & 5 deletions src/helpers/remoteBackups.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { SubCloser } from "nostr-tools/lib/types/abstract-pool"
import logger from "../Api/helpers/logger"
import { getNip78Event, newNip78ChangelogEvent, newNip78Event, publishNostrEvent, pubServiceTag, subToNip78Changelogs } from "../Api/nostrHandler"
import { getDeviceId } from "../constants"
Expand All @@ -23,20 +24,18 @@ export const fetchRemoteBackup = async (dTag?: string): Promise<{ result: 'acces
export const subscribeToRemoteChangelogs = async (
latestTimestamp: number,
handleChangelogCallback: (decrypted: string, eventTimestamp: number) => Promise<void>,
): Promise<() => void> => {
): Promise<SubCloser> => {
const ext = getSanctumNostrExtention()
if (!ext.valid) {
throw new Error("accessTokenMissing")
}
const pubkey = await ext.getPublicKey()
const relays = await ext.getRelays()
const closer = subToNip78Changelogs(pubkey, Object.keys(relays), latestTimestamp, async event => {
const subCloser = subToNip78Changelogs(pubkey, Object.keys(relays), latestTimestamp, async event => {
const decrypted = await ext.decrypt(pubkey, event.content);
await handleChangelogCallback(decrypted, event.created_at);
});
return () => {
closer.close()
}
return subCloser
}

export const saveChangelog = async (changelog: string): Promise<number> => {
Expand Down

0 comments on commit 14a38c9

Please sign in to comment.