From ad4a2073c30006039ab4081d95f4db2cebd19f01 Mon Sep 17 00:00:00 2001 From: jekrimo Date: Thu, 24 Oct 2024 08:35:22 -0600 Subject: [PATCH 01/52] basic --- src/routes/chat/+page.svelte | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/routes/chat/+page.svelte b/src/routes/chat/+page.svelte index d9d2a1344..cbc6a9e97 100644 --- a/src/routes/chat/+page.svelte +++ b/src/routes/chat/+page.svelte @@ -743,7 +743,12 @@ {:else} {#each message.text as line} {#if getValidPaymentRequest(line) != undefined} - +
+ + +
{:else if !line.includes(tempCDN)} {:else if line.includes(tempCDN)} @@ -967,6 +972,10 @@ border: var(--border-width) solid var(--primary-color); margin-top: var(--gap); } + .payment_buttons { + display: inline-flex; + gap: var(--gap-more); + } } .aside { From 91c538f7c321d84aa5dc863a2bb77b8f27650dc7 Mon Sep 17 00:00:00 2001 From: jekrimo Date: Thu, 24 Oct 2024 10:44:33 -0600 Subject: [PATCH 02/52] add decline tacker --- src/routes/chat/+page.svelte | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/routes/chat/+page.svelte b/src/routes/chat/+page.svelte index cbc6a9e97..91fe2f7a5 100644 --- a/src/routes/chat/+page.svelte +++ b/src/routes/chat/+page.svelte @@ -296,6 +296,13 @@ }) } + let rejectedPayments = [""] + + function rejectPaymentRequest(messageId: string) { + rejectedPayments.push(messageId) + console.log(rejectedPayments) + } + let activeCallInProgress = false let activeCallDid = "" @@ -745,7 +752,7 @@ {#if getValidPaymentRequest(line) != undefined}
-
From 9a3e4076ce5b1be8998242f78d5dc02e6135c9cc Mon Sep 17 00:00:00 2001 From: jekrimo Date: Mon, 28 Oct 2024 08:25:35 -0600 Subject: [PATCH 03/52] fixed --- src/lib/lang/en.json | 3 ++- src/lib/state/Store.ts | 1 + src/lib/state/initial.ts | 1 + src/routes/chat/+page.svelte | 35 +++++++++++++++++++++++++---------- 4 files changed, 29 insertions(+), 11 deletions(-) diff --git a/src/lib/lang/en.json b/src/lib/lang/en.json index d065d74ee..414382050 100644 --- a/src/lib/lang/en.json +++ b/src/lib/lang/en.json @@ -200,7 +200,8 @@ "note": "Note", "date": "Date", "create": "Create Payment Request", - "network": "Network", + "decline_payment": "", + "payment_declined": "Payment Declined", "assetType": "Asset type", "assetName": "Asset name", "assetId": "Asset Id", diff --git a/src/lib/state/Store.ts b/src/lib/state/Store.ts index 98312d281..d6b279972 100644 --- a/src/lib/state/Store.ts +++ b/src/lib/state/Store.ts @@ -47,6 +47,7 @@ class GlobalStore { openFolders: createPersistentState>("uplink.openFolders", {}), toasts: writable({}), userCache: writable({}), + paymentTracker: createPersistentState("uplink.paymentTracker", []), pageState: writable(""), } } diff --git a/src/lib/state/initial.ts b/src/lib/state/initial.ts index be7029536..c8c3cdb4d 100644 --- a/src/lib/state/initial.ts +++ b/src/lib/state/initial.ts @@ -34,5 +34,6 @@ export interface IState { // A cache of all fetched user data // We use a Writable to also allow easy subscription to changes if only that user interests us userCache: Writable<{ [key: string]: Writable }> + paymentTracker: Writable pageState: Writable } diff --git a/src/routes/chat/+page.svelte b/src/routes/chat/+page.svelte index 91fe2f7a5..f31c55741 100644 --- a/src/routes/chat/+page.svelte +++ b/src/routes/chat/+page.svelte @@ -57,6 +57,7 @@ import BrowseFiles from "../files/BrowseFiles.svelte" import AttachmentRenderer from "$lib/components/messaging/AttachmentRenderer.svelte" import ShareFile from "$lib/components/files/ShareFile.svelte" + import { StateEffect } from "@codemirror/state" let loading = false let contentAsideOpen = false @@ -296,11 +297,17 @@ }) } - let rejectedPayments = [""] + $: rejectedPayments = Store.state.paymentTracker function rejectPaymentRequest(messageId: string) { - rejectedPayments.push(messageId) - console.log(rejectedPayments) + Store.state.paymentTracker.update(payments => { + if (!payments.includes(messageId)) { + return [...payments, messageId] + } else { + console.log(`MessageId ${messageId} is already in the rejected payments list`) + return payments + } + }) } let activeCallInProgress = false @@ -750,15 +757,21 @@ {:else} {#each message.text as line} {#if getValidPaymentRequest(line) != undefined} -
- - -
+ {#if !$rejectedPayments.find(id => id === message.id)} +
+ + +
+ {:else} +
+
+ {/if} {:else if !line.includes(tempCDN)} - {:else if line.includes(tempCDN)} + {:else}
@@ -778,11 +791,13 @@ {/if} {/if} + reactTo(message.id, emoji, true)} close={close} on:openPicker={_ => (reactingTo = message.id)}> {/if} + {#if Object.keys(message.reactions).length > 0} reactTo(message.id, emoji, true)} /> {/if} From 3928b995fcdc311dc41fccda6247fd8eab0ab21d Mon Sep 17 00:00:00 2001 From: jekrimo Date: Mon, 28 Oct 2024 08:56:28 -0600 Subject: [PATCH 04/52] better --- src/routes/chat/+page.svelte | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/src/routes/chat/+page.svelte b/src/routes/chat/+page.svelte index f31c55741..0b88798f9 100644 --- a/src/routes/chat/+page.svelte +++ b/src/routes/chat/+page.svelte @@ -758,16 +758,13 @@ {#each message.text as line} {#if getValidPaymentRequest(line) != undefined} {#if !$rejectedPayments.find(id => id === message.id)} -
- - -
+ + {:else} -
-
+ - {:else} From 8e583e54294626408be4d63d3332038b0b05af4f Mon Sep 17 00:00:00 2001 From: jekrimo Date: Thu, 31 Oct 2024 07:56:37 -0600 Subject: [PATCH 06/52] one more --- src/lib/state/initial.ts | 4 +- src/lib/types/index.ts | 6 +++ src/lib/utils/Wallet.ts | 29 +++++++++-- src/routes/chat/+page.svelte | 93 +++++++++++++++++++++++++++++------- 4 files changed, 109 insertions(+), 23 deletions(-) diff --git a/src/lib/state/initial.ts b/src/lib/state/initial.ts index c8c3cdb4d..61acc547c 100644 --- a/src/lib/state/initial.ts +++ b/src/lib/state/initial.ts @@ -1,4 +1,4 @@ -import type { Call, Chat, FileInfo, FriendRequest, User } from "$lib/types" +import type { Call, Chat, FileInfo, FriendRequest, PaymentTracker, User } from "$lib/types" import type { Writable } from "svelte/store" import type { ToastMessage } from "./ui/toast" import type { VoiceRTCUser } from "$lib/media/Voice" @@ -34,6 +34,6 @@ export interface IState { // A cache of all fetched user data // We use a Writable to also allow easy subscription to changes if only that user interests us userCache: Writable<{ [key: string]: Writable }> - paymentTracker: Writable + paymentTracker: Writable pageState: Writable } diff --git a/src/lib/types/index.ts b/src/lib/types/index.ts index aa812690d..bcd6e6ba4 100644 --- a/src/lib/types/index.ts +++ b/src/lib/types/index.ts @@ -411,6 +411,12 @@ export type Transaction = { note: string } +export type PaymentTracker = { + messageId: string + senderId: string + rejectedPayment: boolean +} + export type Keybind = { action: KeybindAction key: string diff --git a/src/lib/utils/Wallet.ts b/src/lib/utils/Wallet.ts index 73503115e..1238fa900 100644 --- a/src/lib/utils/Wallet.ts +++ b/src/lib/utils/Wallet.ts @@ -460,12 +460,14 @@ export class Transfer { amount: bigint toAddress: string amountPreview: string + id: string constructor() { this.asset = { kind: AssetType.None, id: "" } this.amount = BigInt(0) this.toAddress = "" this.amountPreview = "" + this.id = "" } isValid(): boolean { @@ -489,6 +491,11 @@ export class Transfer { return `/request ${transfer}` } + torejectString(id: string) { + let transfer = JSON.stringify(this, (k, v) => (k === "amount" && typeof v === "bigint" ? v.toString() : v)) + return `/reject ${id}` + } + toDisplayString(): string { let id = this.asset.id === "n/a" ? "" : this.asset.id return `Send ${this.amountPreview} to ${shortenAddr(this.toAddress, 6)}` @@ -502,9 +509,25 @@ export class Transfer { } export function getValidPaymentRequest(msg: string): Transfer | undefined { - let cmd = "/request " - if (msg.startsWith(cmd)) { - let json = msg.substring(cmd.length, msg.length) + let requestCmd = "/request" + let rejectCmd = "/reject" + if (msg.startsWith(requestCmd)) { + let json = msg.substring(requestCmd.length, msg.length) + let transfer = new Transfer() + try { + let parsed = JSON.parse(json, (k, v) => (k === "amount" && typeof v === "string" ? BigInt(v) : v)) + transfer.asset = parsed.asset + transfer.amount = parsed.amount + transfer.toAddress = parsed.toAddress + transfer.amountPreview = parsed.amountPreview + } catch { + // if it wasn't valid json, do nothing. + } + if (transfer.asset.kind !== AssetType.None && transfer.isValid()) { + return transfer + } + } else if (msg.startsWith(rejectCmd)) { + let json = msg.substring(rejectCmd.length, msg.length) let transfer = new Transfer() try { let parsed = JSON.parse(json, (k, v) => (k === "amount" && typeof v === "string" ? BigInt(v) : v)) diff --git a/src/routes/chat/+page.svelte b/src/routes/chat/+page.svelte index fd84b97b0..e42c48aac 100644 --- a/src/routes/chat/+page.svelte +++ b/src/routes/chat/+page.svelte @@ -46,7 +46,7 @@ import FileUploadPreview from "$lib/elements/FileUploadPreview.svelte" import TextDocument from "$lib/components/messaging/embeds/TextDocument.svelte" import StoreResolver from "$lib/components/utils/StoreResolver.svelte" - import { getValidPaymentRequest } from "$lib/utils/Wallet" + import { getValidPaymentRequest, Transfer } from "$lib/utils/Wallet" import { onMount } from "svelte" import PinnedMessages from "$lib/components/messaging/PinnedMessages.svelte" import { MessageEvent } from "warp-wasm" @@ -63,6 +63,7 @@ let contentAsideOpen = false let showBrowseFilesModal = false let clipboardWrite = false + // const user = get(Store.state.user) const checkClipboardPermission = async () => { try { @@ -299,15 +300,56 @@ $: rejectedPayments = Store.state.paymentTracker - function rejectPaymentRequest(messageId: string) { - Store.state.paymentTracker.update(payments => { - if (!payments.includes(messageId)) { - return [...payments, messageId] - } else { - console.log(`MessageId ${messageId} is already in the rejected payments list`) - return payments - } - }) + async function sendPaymentMessage(message: MessageType, paymentType: string) { + let transfer = new Transfer() + let chat = get(Store.state.activeChat) + let rejectTranser = transfer.torejectString(message.id) + let txt = rejectTranser.split("\n") + if (paymentType === "result") { + console.log($rejectedPayments) + let result = await RaygunStoreInstance.send(chat.id, txt, []) + result.onSuccess(res => { + if (getValidPaymentRequest(message.text[0])) { + console.log(message, res, "resecvexd?") + getValidPaymentRequest(message.text[0])?.execute() + } + Store.state.paymentTracker.update(payments => { + // Check if any PaymentTracker object has the same messageId + const alreadyRejected = payments.some(payment => payment.messageId === message.id) + + if (!alreadyRejected) { + // Add a new PaymentTracker object + return [...payments, { messageId: message.id, senderId: message.details.origin, rejectedPayment: false }] + } else { + console.log(`MessageId ${message.id} is already in the rejected payments list`) + return payments // No changes + } + }) + transfer.toCmdString() + ConversationStore.addPendingMessages(chat.id, res.message, txt) + }) + } + if (paymentType === "reject") { + console.log("REJECTED") + let result = await RaygunStoreInstance.send(chat.id, txt, []) + result.onSuccess(res => { + console.log(message, res, "resecvexd?") + Store.state.paymentTracker.update(payments => { + // Check if any PaymentTracker object has the same messageId + const alreadyRejected = payments.some(payment => payment.messageId === message.id) + + if (!alreadyRejected) { + // Add a new PaymentTracker object + return [...payments, { messageId: message.id, senderId: message.details.origin, rejectedPayment: true }] + } else { + console.log(`MessageId ${message.id} is already in the rejected payments list`) + return payments // No changes + } + }) + transfer.torejectString(message.id) + ConversationStore.addPendingMessages(chat.id, res.message, txt) + }) + } } let activeCallInProgress = false @@ -756,15 +798,30 @@ edit_message(message.id, editing_text ? editing_text : "")} /> {:else} {#each message.text as line} - {#if getValidPaymentRequest(line) != undefined} - {#if !$rejectedPayments.find(id => id === message.id)} - - + {#if line.includes("/reject")} + + + {:else if getValidPaymentRequest(line) !== undefined} + {#if !$rejectedPayments.find(payments => payments.messageId === message.id)} + {#if $own_user.key !== message.details.origin} + + + {:else} + + + {/if} {:else} - + + {:else if !checkForActiveRequest(message, line)} + + {:else} {/if} {:else} - {#if $own_user.key !== message.details.origin} + {#if $own_user.key !== message.details.origin && !checkForActiveRequest(message, line)} {/if} + {:else if $own_user.key !== message.details.origin && checkForActiveRequest(message, line)} + + + diff --git a/src/routes/chat/+page.svelte b/src/routes/chat/+page.svelte index b66743929..987bd1fa5 100644 --- a/src/routes/chat/+page.svelte +++ b/src/routes/chat/+page.svelte @@ -836,7 +836,7 @@ {/if} - {:else if $own_user.key !== message.details.origin && !checkForActiveRequest(message, line)} + {:else if $own_user.key !== message.details.origin && checkForActiveRequest(message, line)} + }}>{$_("payments.send")} + }}>{$_("payments.request")} -
{$_("payments.assetType") + ":"} ({ value: value, text: value }))} on:change={onChangeAssetKind} />
{#if needsAssetId()}
{$_("payments.assetId") + ":"}
{/if} @@ -92,17 +94,28 @@ diff --git a/src/lib/lang/en.json b/src/lib/lang/en.json index 721db8dbb..1dc53b5ec 100644 --- a/src/lib/lang/en.json +++ b/src/lib/lang/en.json @@ -192,6 +192,7 @@ "payments": { "send": "Send", "receive": "Receive", + "type": "Type", "receiving_to": "Receiving to", "send_coin": "Send Coin", "amount": "Amount", From 0a7c9b1f244d1a17d4d4981f633fa399e7244d5e Mon Sep 17 00:00:00 2001 From: jekrimo Date: Mon, 11 Nov 2024 08:01:15 -0700 Subject: [PATCH 17/52] merfge and fix --- src/lib/lang/en.json | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/lib/lang/en.json b/src/lib/lang/en.json index 23bf3ccd2..2ab6d3863 100644 --- a/src/lib/lang/en.json +++ b/src/lib/lang/en.json @@ -213,11 +213,9 @@ "note": "Note", "date": "Date", "decline": "Decline", - "decline": "Decline", "create": "Create Payment Request", "decline_payment": "Decline Payment", "sent_request": "Sent Request", - "cancel_request": "Cancel Request", "canceled_request": "Canceled Request", "declinePayment": "Decline Payment", "sentRequest": "Request has been sent", From c6c4be4a0abff03bec1127efdac2d29c99cc224e Mon Sep 17 00:00:00 2001 From: jekrimo Date: Mon, 11 Nov 2024 08:34:32 -0700 Subject: [PATCH 18/52] bad merge --- src/lib/utils/Wallet.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/lib/utils/Wallet.ts b/src/lib/utils/Wallet.ts index 56f896587..e18f9ae1d 100644 --- a/src/lib/utils/Wallet.ts +++ b/src/lib/utils/Wallet.ts @@ -461,7 +461,6 @@ export class Transfer { toAddress: string amountPreview: string id: string - id: string constructor() { this.asset = { kind: AssetType.None, id: "" } From 978d3273f9d52671df2219a29d18a20c736b279e Mon Sep 17 00:00:00 2001 From: jekrimo Date: Mon, 11 Nov 2024 08:43:37 -0700 Subject: [PATCH 19/52] smol --- src/lib/components/wallet/CreateTransaction.svelte | 2 +- src/lib/lang/en.json | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/lib/components/wallet/CreateTransaction.svelte b/src/lib/components/wallet/CreateTransaction.svelte index 970022bf7..39dcb1490 100644 --- a/src/lib/components/wallet/CreateTransaction.svelte +++ b/src/lib/components/wallet/CreateTransaction.svelte @@ -90,7 +90,7 @@ on:click={async () => { await sendMessage(transfer.toCmdString()) onClose() - }}>{$_("payments.request")} + }}>{$_("payments.create_transaction")} diff --git a/src/lib/enums/icons.ts b/src/lib/enums/icons.ts index b641dd4cd..1776c7ef0 100644 --- a/src/lib/enums/icons.ts +++ b/src/lib/enums/icons.ts @@ -15,6 +15,18 @@ export const enum Shape { Boot = ``, ID = ``, Details = ``, + QRCodeScan = ``, + QRCode = ` + + + + + + + + + + `, Tag = ``, Shield = ``, Popout = ``, From cdd36bb56316fb2803809effa0bed2d35dc03622 Mon Sep 17 00:00:00 2001 From: jekrimo Date: Tue, 12 Nov 2024 08:57:38 -0700 Subject: [PATCH 22/52] close --- .../wallet/CreateTransaction.svelte | 131 +++++++++++++----- src/lib/lang/en.json | 1 + 2 files changed, 94 insertions(+), 38 deletions(-) diff --git a/src/lib/components/wallet/CreateTransaction.svelte b/src/lib/components/wallet/CreateTransaction.svelte index 21fbb1a46..b1be2460b 100644 --- a/src/lib/components/wallet/CreateTransaction.svelte +++ b/src/lib/components/wallet/CreateTransaction.svelte @@ -13,7 +13,7 @@ export let onClose let transfer = new Transfer() - + let sendCoin = "" async function sendMessage(text: string) { let chat = get(Store.state.activeChat) let txt = text.split("\n") @@ -67,39 +67,44 @@ appearance={Appearance.Alt} on:click={async () => { // onClose() + sendCoin = "send" }}>{$_("payments.send")} -
-
+
+
+
+
+ + + + + {#if needsAssetId()} +
{$_("payments.assetId") + ":"}
+ {/if} + + + +
+ +
{/if} -
- -
diff --git a/src/lib/components/wallet/QRScanner.svelte b/src/lib/components/wallet/QRScanner.svelte new file mode 100644 index 000000000..cbeeb571c --- /dev/null +++ b/src/lib/components/wallet/QRScanner.svelte @@ -0,0 +1,135 @@ + + +{#if startScanning} +
+
+ + +
+
+
+
+
+
+
+
+{:else} + +{/if} + + From 3ec994852d04a725953fe156da59c58ae4048b7c Mon Sep 17 00:00:00 2001 From: jekrimo Date: Thu, 14 Nov 2024 09:25:42 -0700 Subject: [PATCH 24/52] got it --- .../components/messaging/ChatPreview.svelte | 39 ++++++++++- .../wallet/CreateTransaction.svelte | 4 +- src/lib/enums/index.ts | 1 + src/lib/lang/en.json | 2 + src/lib/utils/Wallet.ts | 43 +++++++++--- src/routes/chat/+page.svelte | 69 ++++++++++++++++++- 6 files changed, 145 insertions(+), 13 deletions(-) diff --git a/src/lib/components/messaging/ChatPreview.svelte b/src/lib/components/messaging/ChatPreview.svelte index 958a6ccc7..995fe0b54 100644 --- a/src/lib/components/messaging/ChatPreview.svelte +++ b/src/lib/components/messaging/ChatPreview.svelte @@ -60,7 +60,8 @@ } catch (error) { return "Invalid message format" } - } else if (chat.last_message_preview.startsWith(PaymentRequestsEnum.Reject)) { + } + if (chat.last_message_preview.startsWith(PaymentRequestsEnum.Reject)) { try { const sendingUserId = ConversationStore.getMessage(chat.id, chat.last_message_id)?.details.origin const sendingUserDetails = get(Store.getUser(sendingUserId!)) @@ -73,6 +74,42 @@ return "Invalid message format" } } + if (chat.last_message_preview.startsWith(PaymentRequestsEnum.Send)) { + console.log("Reached PaymentRequestsEnum.Send condition") + + try { + const sendingUserId = ConversationStore.getMessage(chat.id, chat.last_message_id)?.details.origin + const sendingUserDetails = get(Store.getUser(sendingUserId!)) + + // Find the JSON part of the string + const jsonStartIndex = chat.last_message_preview.indexOf("{") + if (jsonStartIndex === -1) { + console.error("No JSON found in last_message_preview:", chat.last_message_preview) + return "Invalid message format" + } + + const jsonPart = chat.last_message_preview.slice(jsonStartIndex) + console.log("Extracted JSON part:", jsonPart) + + let amountPreview + try { + amountPreview = JSON.parse(jsonPart) + console.log("Parsed amountPreview:", amountPreview) + } catch (error) { + console.error("JSON parsing error:", error) + return "Invalid message format" + } + + if (get(Store.getUser(sendingUserId!)).key !== ownId.key) { + return $_("payments.recievedPayment", { values: { user: sendingUserDetails.name, amount: amountPreview.amountPreview } }) + } else { + return $_("payments.sentPayment", { values: { amount: amountPreview.amountPreview } }) + } + } catch (error) { + console.error("Error in PaymentRequestsEnum.Send condition:", error) + return "Invalid message format" + } + } return chat.last_message_preview })() diff --git a/src/lib/components/wallet/CreateTransaction.svelte b/src/lib/components/wallet/CreateTransaction.svelte index ebddd5ff9..16e5c6a01 100644 --- a/src/lib/components/wallet/CreateTransaction.svelte +++ b/src/lib/components/wallet/CreateTransaction.svelte @@ -134,7 +134,7 @@ @@ -144,7 +144,7 @@ {#if transfer.toAddress !== ""}
-
-
@@ -108,33 +99,15 @@
{/if} - - - - {#if needsAssetId()}
{$_("payments.assetId") + ":"}
{/if} - - -
@@ -150,8 +123,6 @@
- -
@@ -159,33 +130,15 @@
{/if} - - - - {#if needsAssetId()}
{$_("payments.assetId") + ":"}
{/if} - - -
diff --git a/src/lib/utils/Wallet.ts b/src/lib/utils/Wallet.ts index 88829a4d9..c94388ff6 100644 --- a/src/lib/utils/Wallet.ts +++ b/src/lib/utils/Wallet.ts @@ -2,6 +2,7 @@ import Wallet, { AddressPurpose, AddressType, RpcErrorCode } from "sats-connect" import { ethers } from "ethers" import { log } from "./Logger" import { PaymentRequestsEnum } from "$lib/enums" +import type { MessageType } from "warp-wasm" export type Account = { address: string @@ -498,9 +499,19 @@ export class Transfer { } toDisplayString(): string { + // Match and extract "kind" and "amountPreview" from the input JSON + // console.log(message) + // const kindMatch = message.match(/"kind":"(.*?)"/) + // const amountPreviewMatch = message.match(/"amountPreview":"(.*?)"/) + // const toAddressMatch = message.match(/"toAddress":"(.*?)"/) + + // // Extract values, defaulting to an empty string if not found + // // const kind = kindMatch ? kindMatch[1] : "" + // const amountPreview = amountPreviewMatch ? amountPreviewMatch[1] : "" + // const toAddress = toAddressMatch ? toAddressMatch[1] : "" let transfer = JSON.stringify(this, (k, v) => (k === "amount" && typeof v === "bigint" ? v.toString() : v)) - console.log(transfer, "HERE DISPLAY") - return `/send ${this.amountPreview} to ${shortenAddr(this.toAddress, 6)} ${transfer}` + // Return the formatted string using extracted values + return `/send ${transfer}` } async execute() { diff --git a/src/routes/chat/+page.svelte b/src/routes/chat/+page.svelte index ea1a6dd52..214cd98e6 100644 --- a/src/routes/chat/+page.svelte +++ b/src/routes/chat/+page.svelte @@ -386,37 +386,21 @@ }) } if (paymentType === PaymentRequestsEnum.Send) { - console.log("FUCK THIS SHIT", message.text[0]) + console.log("Extracting payment details", message.text[0]) + + // Use the toDisplayString function to format the message + const formattedMessage = transfer.toDisplayString(message.text[0]) + let chat = get(Store.state.activeChat) - let txt = message.text[0].split("\n") - console.log(txt) + let txt = formattedMessage.split("\n") + + console.log("Formatted Transfer Message", formattedMessage) + let result = await RaygunStoreInstance.send(chat.id, txt, []) result.onSuccess(res => { - console.log(res) - transfer.toDisplayString() + console.log("Message Sent Successfully", res) ConversationStore.addPendingMessages(chat.id, res.message, txt) }) - // let sendTranfser = transfer.toDisplayString() - // let txt = sendTranfser.split("\n") - // let result = await RaygunStoreInstance.send(chat.id, txt, []) - // result.onSuccess(res => { - // if (getValidPaymentRequest(message.text[0])) { - // getValidPaymentRequest(message.text[0])?.execute() - // } - // console.log(txt) - // Store.state.paymentTracker.update(payments => { - // const alreadyRejected = payments.some(payment => payment.messageId === message.id) - - // if (!alreadyRejected) { - // return [...payments, { messageId: message.id, senderId: message.details.origin, rejectedPayment: false }] - // } else { - // console.log(`MessageId ${message.id} is already in the rejected payments list`) - // return payments - // } - // }) - // transfer.toDisplayString() - // ConversationStore.addPendingMessages(chat.id, message.text[0], txt) - // }) } } From cdf817e1307d61c8239599c0c64c589865d767bd Mon Sep 17 00:00:00 2001 From: jekrimo Date: Wed, 20 Nov 2024 07:57:54 -0700 Subject: [PATCH 28/52] clean --- src/routes/chat/+page.svelte | 41 ++++++++---------------------------- 1 file changed, 9 insertions(+), 32 deletions(-) diff --git a/src/routes/chat/+page.svelte b/src/routes/chat/+page.svelte index 214cd98e6..493172f06 100644 --- a/src/routes/chat/+page.svelte +++ b/src/routes/chat/+page.svelte @@ -154,40 +154,17 @@ } function sanitizePaymentSent(message: string, sender: string, reciever: string): string { - // Match and extract "kind", "amountPreview", and "toAddress" from the input string + const kindMatch = message.match(/"kind":"(.*?)"/) + const amountPreviewMatch = message.match(/"amountPreview":"(.*?)"/) + const kind = kindMatch ? kindMatch[1] : "" + let amountPreview = amountPreviewMatch ? amountPreviewMatch[1] : "" + if (amountPreview.includes(kind)) { + amountPreview = amountPreview.replace(kind, "").trim() + } + amountPreview = amountPreview.replace(/(\.\d*?[1-9])0+$|\.0*$/, "$1") if (sender !== "") { - const kindMatch = message.match(/"kind":"(.*?)"/) - const amountPreviewMatch = message.match(/"amountPreview":"(.*?)"/) - // const toAddressMatch = message.match(/"toAddress":"(.*?)"/) - - // Extract the values from the match results, defaulting to an empty string if not found - const kind = kindMatch ? kindMatch[1] : "" - let amountPreview = amountPreviewMatch ? amountPreviewMatch[1] : "" - // const toAddress = toAddressMatch ? toAddressMatch[1] : "" - - // Remove any extra occurrence of the currency symbol in `amountPreview` - if (amountPreview.includes(kind)) { - amountPreview = amountPreview.replace(kind, "").trim() - } - amountPreview = amountPreview.replace(/(\.\d*?[1-9])0+$|\.0*$/, "$1") - // Return the formatted string return `${sender} sent you ${amountPreview} ${kind}` } else { - const kindMatch = message.match(/"kind":"(.*?)"/) - const amountPreviewMatch = message.match(/"amountPreview":"(.*?)"/) - // const toAddressMatch = message.match(/"toAddress":"(.*?)"/) - - // Extract the values from the match results, defaulting to an empty string if not found - const kind = kindMatch ? kindMatch[1] : "" - let amountPreview = amountPreviewMatch ? amountPreviewMatch[1] : "" - // const toAddress = toAddressMatch ? toAddressMatch[1] : "" - - // Remove any extra occurrence of the currency symbol in `amountPreview` - if (amountPreview.includes(kind)) { - amountPreview = amountPreview.replace(kind, "").trim() - } - amountPreview = amountPreview.replace(/(\.\d*?[1-9])0+$|\.0*$/, "$1") - // Return the formatted string return `You sent ${amountPreview} ${kind} to ${reciever}` } } @@ -389,7 +366,7 @@ console.log("Extracting payment details", message.text[0]) // Use the toDisplayString function to format the message - const formattedMessage = transfer.toDisplayString(message.text[0]) + const formattedMessage = transfer.toDisplayString() let chat = get(Store.state.activeChat) let txt = formattedMessage.split("\n") From 12ada6daba3df7e0fb3bccf5d378f254ade81af6 Mon Sep 17 00:00:00 2001 From: jekrimo Date: Wed, 20 Nov 2024 11:54:46 -0700 Subject: [PATCH 29/52] YUS --- .../components/messaging/ChatPreview.svelte | 24 ++-- src/lib/utils/Wallet.ts | 25 ++-- src/routes/chat/+page.svelte | 110 ++++++++++++++---- 3 files changed, 106 insertions(+), 53 deletions(-) diff --git a/src/lib/components/messaging/ChatPreview.svelte b/src/lib/components/messaging/ChatPreview.svelte index 6831b1b11..3ef580d1b 100644 --- a/src/lib/components/messaging/ChatPreview.svelte +++ b/src/lib/components/messaging/ChatPreview.svelte @@ -80,14 +80,16 @@ try { const sendingUserId = ConversationStore.getMessage(chat.id, chat.last_message_id)?.details.origin const sendingUserDetails = get(Store.getUser(sendingUserId!)) - const jsonStartIndex = chat.last_message_preview.indexOf("{") + const jsonStartIndex = chat.last_message_preview.indexOf("{") if (jsonStartIndex === -1) { console.error("No JSON found in last_message_preview:", chat.last_message_preview) return "Invalid message format" } + // Extract the JSON part from the preview const jsonPart = chat.last_message_preview.slice(jsonStartIndex) + let parsedMessage try { parsedMessage = JSON.parse(jsonPart) @@ -96,19 +98,19 @@ return "Invalid message format" } - const kind = parsedMessage.asset?.kind || "" - let amountPreview = parsedMessage.amountPreview || "" + // Extract values from the parsed JSON + const kind = parsedMessage.kind || "unknown" + let amount = parsedMessage.amount || "unknown" - if (amountPreview.includes(kind)) { - amountPreview = amountPreview.replace(kind, "").trim() - } - amountPreview = amountPreview.replace(/(\.\d*?[1-9])0+$|\.0*$/, "$1") + // Format `amount` to remove trailing zeros + amount = amount.replace(/(\.\d*?[1-9])0+$|\.0*$/, "$1") - if (get(Store.getUser(sendingUserId!)).key !== ownId.key) { - return `${sendingUserDetails.name} sent you ${amountPreview} ${kind}` + // Determine the sender and recipient + if (sendingUserDetails.key !== ownId.key) { + return `${sendingUserDetails.name} sent you ${amount} ${kind}` } else { - const recipientId = parsedMessage.toAddress || "unknown address" - return `You sent ${amountPreview} ${kind} to ${recipientId}` + const recipientId = parsedMessage.details?.toAddress || "unknown address" + return `You sent ${amount} ${kind} to ${recipientId}` } } catch (error) { console.error("Error in PaymentRequestsEnum.Send condition:", error) diff --git a/src/lib/utils/Wallet.ts b/src/lib/utils/Wallet.ts index c94388ff6..8ec85c5b2 100644 --- a/src/lib/utils/Wallet.ts +++ b/src/lib/utils/Wallet.ts @@ -494,28 +494,21 @@ export class Transfer { } toRejectString(id: string) { - let transfer = JSON.stringify(this, (k, v) => (k === "amount" && typeof v === "bigint" ? v.toString() : v)) return `/reject ${id}` } - toDisplayString(): string { - // Match and extract "kind" and "amountPreview" from the input JSON - // console.log(message) - // const kindMatch = message.match(/"kind":"(.*?)"/) - // const amountPreviewMatch = message.match(/"amountPreview":"(.*?)"/) - // const toAddressMatch = message.match(/"toAddress":"(.*?)"/) - - // // Extract values, defaulting to an empty string if not found - // // const kind = kindMatch ? kindMatch[1] : "" - // const amountPreview = amountPreviewMatch ? amountPreviewMatch[1] : "" - // const toAddress = toAddressMatch ? toAddressMatch[1] : "" - let transfer = JSON.stringify(this, (k, v) => (k === "amount" && typeof v === "bigint" ? v.toString() : v)) - // Return the formatted string using extracted values - return `/send ${transfer}` + toDisplayString(kind: string, amount: string): string { + // Serialize the `this` object with custom handling for `amount` as `bigint` + const transfer = JSON.stringify(this, (key, value) => (key === "amount" && typeof value === "bigint" ? value.toString() : value)) + console.log(transfer) + + // Return a well-structured JSON-like string + return `/send {"kind":"${kind}", "amount":"${amount}", "details":${transfer}}` } async execute() { if (this.isValid()) { + console.log("EXECUTE SEND BACK", this.asset, this.amount, this.toAddress) await wallet.transfer(this.asset, this.amount, this.toAddress) } } @@ -523,10 +516,8 @@ export class Transfer { export function getValidPaymentRequest(msg: string, msgId?: string): Transfer | undefined { let transfer = new Transfer() - // console.log(msg) if (msg.startsWith(PaymentRequestsEnum.Request)) { let json = msg.substring(PaymentRequestsEnum.Request.length, msg.length).trim() - try { let parsed = JSON.parse(json, (k, v) => (k === "amount" && typeof v === "string" ? BigInt(v) : v)) transfer.asset = parsed.asset diff --git a/src/routes/chat/+page.svelte b/src/routes/chat/+page.svelte index 493172f06..b2177dd19 100644 --- a/src/routes/chat/+page.svelte +++ b/src/routes/chat/+page.svelte @@ -153,19 +153,50 @@ return `Send ${amountPreview} ${kind}` } - function sanitizePaymentSent(message: string, sender: string, reciever: string): string { - const kindMatch = message.match(/"kind":"(.*?)"/) - const amountPreviewMatch = message.match(/"amountPreview":"(.*?)"/) - const kind = kindMatch ? kindMatch[1] : "" - let amountPreview = amountPreviewMatch ? amountPreviewMatch[1] : "" + function sanitizePaymentSent(message: string, sender: string, receiver: string): string { + const jsonStartIndex = message.indexOf("{") + const jsonEndIndex = message.lastIndexOf("}") + + if (jsonStartIndex === -1 || jsonEndIndex === -1 || jsonStartIndex > jsonEndIndex) { + return "Invalid message format" + } + + const jsonPart = message.slice(jsonStartIndex, jsonEndIndex + 1) + + let parsedMessage + try { + parsedMessage = JSON.parse(jsonPart) + } catch (error) { + console.error("Error parsing JSON:", error, message) + return "Invalid message format" + } + + const kind = parsedMessage.kind || "unknown" + const amount = parsedMessage.amount || "unknown" + const amountPreview = parsedMessage.details?.amountPreview || "unknown" + const toAddress = parsedMessage.details?.toAddress || "unknown address" + + let cleanedAmountPreview = amountPreview if (amountPreview.includes(kind)) { - amountPreview = amountPreview.replace(kind, "").trim() + cleanedAmountPreview = amountPreview.replace(kind, "").trim() } - amountPreview = amountPreview.replace(/(\.\d*?[1-9])0+$|\.0*$/, "$1") + + cleanedAmountPreview = cleanedAmountPreview.replace(/(\.\d*?[1-9])0+$|\.0*$/, "$1") + + if (cleanedAmountPreview === "unknown" && amount !== "unknown") { + cleanedAmountPreview = amount.replace(kind, "").trim() + cleanedAmountPreview = cleanedAmountPreview.replace(/(\.\d*?[1-9])0+$|\.0*$/, "$1") + } + // let recieverName = get(Store.state.friends).find(f => f === receiver) + console.log($users, receiver) + let receiverName = $users[receiver]?.name || "Unknown" + const formattedAmount = cleanedAmountPreview if (sender !== "") { - return `${sender} sent you ${amountPreview} ${kind}` + console.log(formattedAmount, kind, message) + return `${sender} sent you ${formattedAmount}` } else { - return `You sent ${amountPreview} ${kind} to ${reciever}` + console.log(formattedAmount, kind, message) + return `You sent ${formattedAmount} to ${$users[$activeChat.users[1]]?.name}` } } @@ -326,9 +357,6 @@ let txt = rejectTranfser.split("\n") let result = await RaygunStoreInstance.send(chat.id, txt, []) result.onSuccess(res => { - if (getValidPaymentRequest(message.text[0])) { - getValidPaymentRequest(message.text[0])?.execute() - } Store.state.paymentTracker.update(payments => { const alreadyRejected = payments.some(payment => payment.messageId === message.id) @@ -363,21 +391,54 @@ }) } if (paymentType === PaymentRequestsEnum.Send) { - console.log("Extracting payment details", message.text[0]) + try { + console.log("Extracting payment details", message.text[0]) - // Use the toDisplayString function to format the message - const formattedMessage = transfer.toDisplayString() + // Identify the start of the JSON part + const jsonStartIndex = message.text[0].indexOf("{") + if (jsonStartIndex === -1) { + throw new Error("No JSON part found in message") + } - let chat = get(Store.state.activeChat) - let txt = formattedMessage.split("\n") + // Extract and parse the JSON part + const jsonPart = message.text[0].slice(jsonStartIndex) + const paymentDetails = JSON.parse(jsonPart) - console.log("Formatted Transfer Message", formattedMessage) + // Extract `kind` and `amount` from the parsed JSON + const kind = paymentDetails.asset?.kind || "unknown" + const amount = paymentDetails.amountPreview || "0" - let result = await RaygunStoreInstance.send(chat.id, txt, []) - result.onSuccess(res => { - console.log("Message Sent Successfully", res) - ConversationStore.addPendingMessages(chat.id, res.message, txt) - }) + console.log("Extracted payment details:", { kind, amount }) + + // Use the `toDisplayString` function to format the message with `kind` and `amount` + const formattedMessage = transfer.toDisplayString(kind, amount) + + let chat = get(Store.state.activeChat) + let txt = formattedMessage.split("\n") + + console.log("Formatted Transfer Message", formattedMessage) + + let result = await RaygunStoreInstance.send(chat.id, txt, []) + result.onSuccess(res => { + // if (getValidPaymentRequest(message.text[0])) { + // getValidPaymentRequest(message.text[0])?.execute() + // } + Store.state.paymentTracker.update(payments => { + const alreadyRejected = payments.some(payment => payment.messageId === message.id) + + if (!alreadyRejected) { + return [...payments, { messageId: message.id, senderId: message.details.origin, rejectedPayment: true }] + } else { + console.log(`MessageId ${message.id} is already in the rejected payments list`) + return payments + } + }) + console.log("Message Sent Successfully", res) + ConversationStore.addPendingMessages(chat.id, res.message, txt) + }) + } catch (error) { + console.error("Error extracting payment details or sending message:", error) + } } } @@ -880,7 +941,7 @@ {#if $own_user.key !== message.details.origin} {:else} - + {/if} {/if} {:else if getValidPaymentRequest(line) !== undefined} @@ -893,7 +954,6 @@ text={sanitizePaymentRequest(line, resolved.name)} on:click={async () => { sendPaymentMessage(message, PaymentRequestsEnum.Send) - // getValidPaymentRequest(line, message.id)?.execute() }}> - - - diff --git a/src/lib/components/wallet/QRScanner.svelte b/src/lib/components/wallet/QRScanner.svelte deleted file mode 100644 index cbeeb571c..000000000 --- a/src/lib/components/wallet/QRScanner.svelte +++ /dev/null @@ -1,135 +0,0 @@ - - -{#if startScanning} -
-
- - -
-
-
-
-
-
-
-
-{:else} - -{/if} - - diff --git a/src/lib/utils/Wallet.ts b/src/lib/utils/Wallet.ts index 8ec85c5b2..9bb27c011 100644 --- a/src/lib/utils/Wallet.ts +++ b/src/lib/utils/Wallet.ts @@ -498,17 +498,12 @@ export class Transfer { } toDisplayString(kind: string, amount: string): string { - // Serialize the `this` object with custom handling for `amount` as `bigint` const transfer = JSON.stringify(this, (key, value) => (key === "amount" && typeof value === "bigint" ? value.toString() : value)) - console.log(transfer) - - // Return a well-structured JSON-like string return `/send {"kind":"${kind}", "amount":"${amount}", "details":${transfer}}` } async execute() { if (this.isValid()) { - console.log("EXECUTE SEND BACK", this.asset, this.amount, this.toAddress) await wallet.transfer(this.asset, this.amount, this.toAddress) } } @@ -541,10 +536,10 @@ export function getValidPaymentRequest(msg: string, msgId?: string): Transfer | transfer.toAddress = parsed.toAddress transfer.amountPreview = parsed.amountPreview } catch (err) { - console.log("Parse Failed", err) + console.error("Parse Failed", err) } } else { - console.log("Reject message is not JSON, possibly an ID or UUID:", json) + console.error("Reject message is not JSON, possibly an ID or UUID:", json) return undefined } @@ -553,8 +548,6 @@ export function getValidPaymentRequest(msg: string, msgId?: string): Transfer | } } else if (msg.startsWith(PaymentRequestsEnum.Send)) { let json = msg.substring(PaymentRequestsEnum.Send.length, msg.length).trim() - - console.log("Catch send", msg) let jsonStartIndex = json.indexOf("{") if (jsonStartIndex !== -1) { json = json.substring(jsonStartIndex).trim() @@ -566,15 +559,14 @@ export function getValidPaymentRequest(msg: string, msgId?: string): Transfer | transfer.toAddress = parsed.toAddress transfer.amountPreview = parsed.amountPreview } catch (err) { - console.log("Parse Failed", err) + console.error("Parse Failed", err) } } else { - console.log("Send message is not JSON:", json) + console.error("Send message is not JSON:", json) return undefined } if (transfer.asset.kind !== AssetType.None && transfer.isValid()) { - console.log("tranfer botrtom", transfer) return transfer } } diff --git a/src/routes/chat/+page.svelte b/src/routes/chat/+page.svelte index dbdd5581f..f5ee1ea13 100644 --- a/src/routes/chat/+page.svelte +++ b/src/routes/chat/+page.svelte @@ -180,10 +180,8 @@ } const formattedAmount = cleanedAmountPreview if (sender !== "") { - console.log(formattedAmount, kind, message) return `${sender} sent you ${formattedAmount}` } else { - console.log(formattedAmount, kind, message) return `You sent ${formattedAmount} to ${$users[$activeChat.users[1]]?.name}` } } @@ -370,7 +368,7 @@ if (!alreadyRejected) { return [...payments, { messageId: message.id, senderId: message.details.origin, rejectedPayment: true }] } else { - console.log(`MessageId ${message.id} is already in the rejected payments list`) + console.error(`MessageId ${message.id} is already in the rejected payments list`) return payments } }) @@ -380,25 +378,14 @@ } if (paymentType === PaymentRequestsEnum.Send) { try { - console.log("Extracting payment details", message.text[0]) - - // Identify the start of the JSON part const jsonStartIndex = message.text[0].indexOf("{") if (jsonStartIndex === -1) { throw new Error("No JSON part found in message") } - - // Extract and parse the JSON part const jsonPart = message.text[0].slice(jsonStartIndex) const paymentDetails = JSON.parse(jsonPart) - - // Extract `kind` and `amount` from the parsed JSON const kind = paymentDetails.asset?.kind || "unknown" const amount = paymentDetails.amountPreview || "0" - - console.log("Extracted payment details:", { kind, amount }) - - // Use the `toDisplayString` function to format the message with `kind` and `amount` const formattedMessage = transfer.toDisplayString(kind, amount) let chat = get(Store.state.activeChat) @@ -408,20 +395,16 @@ let result = await RaygunStoreInstance.send(chat.id, txt, []) result.onSuccess(res => { - // if (getValidPaymentRequest(message.text[0])) { - // getValidPaymentRequest(message.text[0])?.execute() - // } Store.state.paymentTracker.update(payments => { const alreadyRejected = payments.some(payment => payment.messageId === message.id) if (!alreadyRejected) { return [...payments, { messageId: message.id, senderId: message.details.origin, rejectedPayment: true }] } else { - console.log(`MessageId ${message.id} is already in the rejected payments list`) + console.error(`MessageId ${message.id} is already in the rejected payments list`) return payments } }) - console.log("Message Sent Successfully", res) ConversationStore.addPendingMessages(chat.id, res.message, txt) }) } catch (error) { @@ -971,8 +954,6 @@ {/if} - {:else} diff --git a/src/lib/utils/Wallet.ts b/src/lib/utils/Wallet.ts index 0f645e622..064be10b7 100644 --- a/src/lib/utils/Wallet.ts +++ b/src/lib/utils/Wallet.ts @@ -498,8 +498,9 @@ export class Transfer { return `/reject ${id} {"details":${transfer}}` } - toDisplayString(kind: string, amount: string): string { + toDisplayString(kind: string, amount: string, to: string): string { const transfer = JSON.stringify(this, (key, value) => (key === "amount" && typeof value === "bigint" ? value.toString() : value)) + console.log(transfer) return `/send {"kind":"${kind}", "amount":"${amount}", "details":${transfer}}` } diff --git a/src/routes/chat/+page.svelte b/src/routes/chat/+page.svelte index 2980be541..4c7c60303 100644 --- a/src/routes/chat/+page.svelte +++ b/src/routes/chat/+page.svelte @@ -407,7 +407,6 @@ let txt = formattedMessage.split("\n") console.log("Formatted Transfer Message", formattedMessage) - let result = await RaygunStoreInstance.send(chat.id, txt, []) result.onSuccess(res => { Store.state.paymentTracker.update(payments => { From 992deb4762156e2cad2977f08441d536aaa3d39d Mon Sep 17 00:00:00 2001 From: jekrimo Date: Wed, 4 Dec 2024 09:23:44 -0700 Subject: [PATCH 38/52] so close --- .../wallet/CreateTransaction.svelte | 38 +++++++++++------ src/lib/utils/Wallet.ts | 36 ++++++++++++---- src/routes/chat/+page.svelte | 42 ++++++++++--------- 3 files changed, 77 insertions(+), 39 deletions(-) diff --git a/src/lib/components/wallet/CreateTransaction.svelte b/src/lib/components/wallet/CreateTransaction.svelte index b13076f03..540925a3b 100644 --- a/src/lib/components/wallet/CreateTransaction.svelte +++ b/src/lib/components/wallet/CreateTransaction.svelte @@ -2,12 +2,12 @@ import Button from "$lib/elements/Button.svelte" import { ConversationStore } from "$lib/state/conversation" import { Store } from "$lib/state/Store" - import { AssetType, shortenAddr, Transfer, wallet, type Asset } from "$lib/utils/Wallet" + import { AssetType, getValidPaymentRequest, shortenAddr, Transfer, wallet, type Asset } from "$lib/utils/Wallet" import { RaygunStoreInstance } from "$lib/wasm/RaygunStore" import { get } from "svelte/store" import { _ } from "svelte-i18n" import { Icon, Input, Label, Select, Text } from "$lib/elements" - import { Appearance, Shape, Size } from "$lib/enums" + import { Appearance, PaymentRequestsEnum, Shape, Size } from "$lib/enums" export let onClose enum ViewMode { @@ -20,16 +20,33 @@ let transfer = new Transfer() let sendCoin = ViewMode.None async function sendMessage(text: string) { - let chat = get(Store.state.activeChat) - let txt = text.split("\n") - let result = await RaygunStoreInstance.send(chat.id, txt, []) - result.onSuccess(res => { - ConversationStore.addPendingMessages(chat.id, res.message, txt) - }) + if (sendCoin === ViewMode.Send) { + let chat = get(Store.state.activeChat) + let txt = text.split("\n") + let whatReturned = await getValidPaymentRequest(txt[0])?.execute() + console.log(whatReturned) + if (whatReturned !== undefined) { + let result = await RaygunStoreInstance.send(chat.id, txt, []) + result.onSuccess(res => { + console.log(txt) + // getValidPaymentRequest(txt[0])?.execute() + ConversationStore.addPendingMessages(chat.id, res.message, txt) + }) + } + } + if (sendCoin === ViewMode.Receive) { + let chat = get(Store.state.activeChat) + let txt = text.split("\n") + let result = await RaygunStoreInstance.send(chat.id, txt, []) + result.onSuccess(res => { + console.log(txt) + // getValidPaymentRequest(txt[0])?.execute() + ConversationStore.addPendingMessages(chat.id, res.message, txt) + }) + } } let inputAmount = "" - let currentView: ViewMode = ViewMode.None function onInputAmount() { inputAmount = inputAmount.replace(/[^0-9.]/g, "") if (inputAmount.split(".").length > 2) { @@ -48,7 +65,6 @@ wallet.myAddress(transfer.asset).then(address => { transfer.toAddress = addressInput }) - console.log(addressInput) } onInputAmount() function onChangeAssetKind() { @@ -63,8 +79,6 @@ wallet.myAddress(transfer.asset).then(address => { transfer.toAddress = addressInput }) - console.log(addressInput) - // transfer.toAddress = addressInput } } onChangeAssetKind() diff --git a/src/lib/utils/Wallet.ts b/src/lib/utils/Wallet.ts index 064be10b7..aca946bc6 100644 --- a/src/lib/utils/Wallet.ts +++ b/src/lib/utils/Wallet.ts @@ -501,12 +501,14 @@ export class Transfer { toDisplayString(kind: string, amount: string, to: string): string { const transfer = JSON.stringify(this, (key, value) => (key === "amount" && typeof value === "bigint" ? value.toString() : value)) console.log(transfer) + getValidPaymentRequest(transfer) return `/send {"kind":"${kind}", "amount":"${amount}", "details":${transfer}}` } async execute() { if (this.isValid()) { await wallet.transfer(this.asset, this.amount, this.toAddress) + return true } } } @@ -550,26 +552,46 @@ export function getValidPaymentRequest(msg: string, msgId?: string): Transfer | } } else if (msg.startsWith(PaymentRequestsEnum.Send)) { let json = msg.substring(PaymentRequestsEnum.Send.length, msg.length).trim() + console.log(msg) let jsonStartIndex = json.indexOf("{") if (jsonStartIndex !== -1) { json = json.substring(jsonStartIndex).trim() try { - let parsed = JSON.parse(json, (k, v) => (k === "amount" && typeof v === "string" ? BigInt(v) : v)) - transfer.asset = parsed.asset - transfer.amount = parsed.amount - transfer.toAddress = parsed.toAddress - transfer.amountPreview = parsed.amountPreview + let parsed = JSON.parse(json, (key, value) => { + if (key === "amount" && typeof value === "string") { + // Check if the value can be converted to BigInt + if (/^\d+$/.test(value)) { + return BigInt(value) // Convert to BigInt if it's an integer + } else { + return value // Keep as string if it's a decimal + } + } + return value + }) + + // Extract the details object for nested properties + const details = parsed.details || {} + + transfer.asset = details.asset || {} // Ensure asset is retrieved from details + transfer.amount = details.amount || "0" // Use the nested amount + transfer.toAddress = details.toAddress || "" // Use the nested toAddress + transfer.amountPreview = details.amountPreview || "" // Use the nested amountPreview } catch (err) { console.error("Parse Failed", err) + return undefined // Early return on parse failure } } else { console.error("Send message is not JSON:", json) - return undefined + return undefined // Early return if message is not JSON } - if (transfer.asset.kind !== AssetType.None && transfer.isValid()) { + // Validate transfer object properties safely + if (transfer.asset && transfer.asset.kind !== undefined && transfer.asset.kind !== AssetType.None && transfer.isValid()) { return transfer + } else { + console.error("Invalid transfer object:", transfer) + return undefined } } diff --git a/src/routes/chat/+page.svelte b/src/routes/chat/+page.svelte index 4c7c60303..195cee1a9 100644 --- a/src/routes/chat/+page.svelte +++ b/src/routes/chat/+page.svelte @@ -350,7 +350,7 @@ $: rejectedPayments = Store.state.paymentTracker - async function sendPaymentMessage(message: MessageType, paymentType: string) { + async function sendPaymentMessage(message: MessageType, line: string, paymentType: string) { let transfer = new Transfer() let chat = get(Store.state.activeChat) if (paymentType === PaymentRequestsEnum.Request) { @@ -401,26 +401,28 @@ const paymentDetails = JSON.parse(jsonPart) const kind = paymentDetails.asset?.kind || "unknown" const amount = paymentDetails.amountPreview || "0" - const formattedMessage = transfer.toDisplayString(kind, amount) + const formattedMessage = transfer.toDisplayString(kind, amount, message.id) let chat = get(Store.state.activeChat) let txt = formattedMessage.split("\n") - console.log("Formatted Transfer Message", formattedMessage) - let result = await RaygunStoreInstance.send(chat.id, txt, []) - result.onSuccess(res => { - Store.state.paymentTracker.update(payments => { - const alreadyRejected = payments.some(payment => payment.messageId === message.id) - - if (!alreadyRejected) { - return [...payments, { messageId: message.id, senderId: message.details.origin, rejectedPayment: true }] - } else { - console.error(`MessageId ${message.id} is already in the rejected payments list`) - return payments - } + let walletSuccess = await getValidPaymentRequest(line, message.id)?.execute() + if (walletSuccess) { + let result = await RaygunStoreInstance.send(chat.id, txt, []) + result.onSuccess(res => { + Store.state.paymentTracker.update(payments => { + const alreadyRejected = payments.some(payment => payment.messageId === message.id) + + if (!alreadyRejected) { + return [...payments, { messageId: message.id, senderId: message.details.origin, rejectedPayment: true }] + } else { + console.error(`MessageId ${message.id} is already in the rejected payments list`) + return payments + } + }) + ConversationStore.addPendingMessages(chat.id, res.message, txt) }) - ConversationStore.addPendingMessages(chat.id, res.message, txt) - }) + } } catch (error) { console.error("Error extracting payment details or sending message:", error) } @@ -926,14 +928,14 @@ class="send_coin" text={sanitizePaymentRequest(line, resolved.name)} on:click={async () => { - sendPaymentMessage(message, PaymentRequestsEnum.Send) + sendPaymentMessage(message, line, PaymentRequestsEnum.Send) }}> @@ -943,7 +945,7 @@ hook="text-chat-message" text={$_("payments.cancel_request")} appearance={Appearance.Error} - on:click={async () => sendPaymentMessage(message, PaymentRequestsEnum.Reject)}> + on:click={async () => sendPaymentMessage(message, line, PaymentRequestsEnum.Reject)}> {:else} @@ -952,7 +954,7 @@ hook="text-chat-message" text={$_("payments.canceledRequest")} appearance={Appearance.Error} - on:click={async () => sendPaymentMessage(message, PaymentRequestsEnum.Reject)}> + on:click={async () => sendPaymentMessage(message, line, PaymentRequestsEnum.Reject)}> {/if} From 4c3edd5f54d167c9d0a2b5ca60e5f59968924979 Mon Sep 17 00:00:00 2001 From: jekrimo Date: Wed, 4 Dec 2024 10:24:00 -0700 Subject: [PATCH 39/52] HUZZAH --- src/lib/components/messaging/ChatPreview.svelte | 5 +++-- src/lib/utils/Wallet.ts | 2 +- src/routes/chat/+page.svelte | 5 ++++- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/lib/components/messaging/ChatPreview.svelte b/src/lib/components/messaging/ChatPreview.svelte index 682f809b0..604fa1682 100644 --- a/src/lib/components/messaging/ChatPreview.svelte +++ b/src/lib/components/messaging/ChatPreview.svelte @@ -85,6 +85,7 @@ return "Invalid message format" } const jsonPart = chat.last_message_preview.slice(jsonStartIndex) + console.log(JSON.parse(jsonPart)) let parsedMessage try { parsedMessage = JSON.parse(jsonPart) @@ -92,14 +93,14 @@ console.error("Error parsing JSON:", error, chat.last_message_preview) return "Invalid message format" } - let amount = parsedMessage.details.amountPreview || "unknown" + let amount = parsedMessage.amount || "unknown" amount = amount.replace(/(\.\d*?[1-9])0+$|\.0*$/, "$1") if (sendingUserDetails.key !== ownId.key) { return `${sendingUserDetails.name} sent you ${amount}` } else { const recipientId = parsedMessage.details?.toAddress || "unknown address" - return `You sent ${amount} to ${recipientId}` + return `You sent ${amount} to ${sendingUserDetails.name}` } } catch (error) { console.error("Error in PaymentRequestsEnum.Send condition:", error) diff --git a/src/lib/utils/Wallet.ts b/src/lib/utils/Wallet.ts index aca946bc6..f123d55d1 100644 --- a/src/lib/utils/Wallet.ts +++ b/src/lib/utils/Wallet.ts @@ -501,7 +501,7 @@ export class Transfer { toDisplayString(kind: string, amount: string, to: string): string { const transfer = JSON.stringify(this, (key, value) => (key === "amount" && typeof value === "bigint" ? value.toString() : value)) console.log(transfer) - getValidPaymentRequest(transfer) + // getValidPaymentRequest(transfer) return `/send {"kind":"${kind}", "amount":"${amount}", "details":${transfer}}` } diff --git a/src/routes/chat/+page.svelte b/src/routes/chat/+page.svelte index 195cee1a9..ddb13190d 100644 --- a/src/routes/chat/+page.svelte +++ b/src/routes/chat/+page.svelte @@ -163,6 +163,7 @@ function sanitizePaymentSent(message: string, sender: string, receiver: string): string { const jsonStartIndex = message.indexOf("{") const jsonEndIndex = message.lastIndexOf("}") + // console.log(message) if (jsonStartIndex === -1 || jsonEndIndex === -1 || jsonStartIndex > jsonEndIndex) { return "Invalid message format" @@ -174,7 +175,7 @@ try { parsedMessage = JSON.parse(jsonPart) } catch (error) { - console.error("Error parsing JSON:", error, message) + // console.error("Error parsing JSON:", error, message) return "Invalid message format" } @@ -405,6 +406,7 @@ let chat = get(Store.state.activeChat) let txt = formattedMessage.split("\n") + console.log(txt) let walletSuccess = await getValidPaymentRequest(line, message.id)?.execute() if (walletSuccess) { @@ -420,6 +422,7 @@ return payments } }) + console.log(txt) ConversationStore.addPendingMessages(chat.id, res.message, txt) }) } From 023b8e5db707a23e2ac9ec1aaa01542e1674fc2b Mon Sep 17 00:00:00 2001 From: jekrimo Date: Thu, 5 Dec 2024 08:48:25 -0700 Subject: [PATCH 40/52] clean --- .../components/messaging/ChatPreview.svelte | 1 - src/lib/lang/en.json | 2 +- src/lib/utils/Wallet.ts | 19 ++++++++----------- src/routes/chat/+page.svelte | 17 ++++++++--------- 4 files changed, 17 insertions(+), 22 deletions(-) diff --git a/src/lib/components/messaging/ChatPreview.svelte b/src/lib/components/messaging/ChatPreview.svelte index 604fa1682..78bf379a8 100644 --- a/src/lib/components/messaging/ChatPreview.svelte +++ b/src/lib/components/messaging/ChatPreview.svelte @@ -85,7 +85,6 @@ return "Invalid message format" } const jsonPart = chat.last_message_preview.slice(jsonStartIndex) - console.log(JSON.parse(jsonPart)) let parsedMessage try { parsedMessage = JSON.parse(jsonPart) diff --git a/src/lib/lang/en.json b/src/lib/lang/en.json index 585299591..63587b2cf 100644 --- a/src/lib/lang/en.json +++ b/src/lib/lang/en.json @@ -229,7 +229,7 @@ "network": "Network", "payment_declined": "Payment Declined", "you_canceled_request": "You Canceled Request", - "paymentDeclined": "Payment Canceled", + "paymentCanceled": "Payment Canceled", "youCanceledRequest": "You Canceled Payment Request", "declinedPayment": "{user} Canceled Payment", "recievedPayment": "{user} Sent You {amount}", diff --git a/src/lib/utils/Wallet.ts b/src/lib/utils/Wallet.ts index f123d55d1..5c0721fe6 100644 --- a/src/lib/utils/Wallet.ts +++ b/src/lib/utils/Wallet.ts @@ -560,33 +560,30 @@ export function getValidPaymentRequest(msg: string, msgId?: string): Transfer | try { let parsed = JSON.parse(json, (key, value) => { if (key === "amount" && typeof value === "string") { - // Check if the value can be converted to BigInt if (/^\d+$/.test(value)) { - return BigInt(value) // Convert to BigInt if it's an integer + return BigInt(value) } else { - return value // Keep as string if it's a decimal + return value } } return value }) - // Extract the details object for nested properties const details = parsed.details || {} - transfer.asset = details.asset || {} // Ensure asset is retrieved from details - transfer.amount = details.amount || "0" // Use the nested amount - transfer.toAddress = details.toAddress || "" // Use the nested toAddress - transfer.amountPreview = details.amountPreview || "" // Use the nested amountPreview + transfer.asset = details.asset || {} + transfer.amount = details.amount || "0" + transfer.toAddress = details.toAddress || "" + transfer.amountPreview = details.amountPreview || "" } catch (err) { console.error("Parse Failed", err) - return undefined // Early return on parse failure + return undefined } } else { console.error("Send message is not JSON:", json) - return undefined // Early return if message is not JSON + return undefined } - // Validate transfer object properties safely if (transfer.asset && transfer.asset.kind !== undefined && transfer.asset.kind !== AssetType.None && transfer.isValid()) { return transfer } else { diff --git a/src/routes/chat/+page.svelte b/src/routes/chat/+page.svelte index ddb13190d..d6b2bc79a 100644 --- a/src/routes/chat/+page.svelte +++ b/src/routes/chat/+page.svelte @@ -163,7 +163,6 @@ function sanitizePaymentSent(message: string, sender: string, receiver: string): string { const jsonStartIndex = message.indexOf("{") const jsonEndIndex = message.lastIndexOf("}") - // console.log(message) if (jsonStartIndex === -1 || jsonEndIndex === -1 || jsonStartIndex > jsonEndIndex) { return "Invalid message format" @@ -175,7 +174,7 @@ try { parsedMessage = JSON.parse(jsonPart) } catch (error) { - // console.error("Error parsing JSON:", error, message) + console.error("Error parsing JSON:", error, message) return "Invalid message format" } @@ -406,7 +405,6 @@ let chat = get(Store.state.activeChat) let txt = formattedMessage.split("\n") - console.log(txt) let walletSuccess = await getValidPaymentRequest(line, message.id)?.execute() if (walletSuccess) { @@ -416,13 +414,12 @@ const alreadyRejected = payments.some(payment => payment.messageId === message.id) if (!alreadyRejected) { - return [...payments, { messageId: message.id, senderId: message.details.origin, rejectedPayment: true }] + return [...payments, { messageId: message.id, senderId: message.details.origin, rejectedPayment: false }] } else { console.error(`MessageId ${message.id} is already in the rejected payments list`) return payments } }) - console.log(txt) ConversationStore.addPendingMessages(chat.id, res.message, txt) }) } @@ -467,7 +464,7 @@ let wasAdded = false Store.state.paymentTracker.update(payments => { const alreadyRejected = payments.some(payment => payment.messageId === messageId) - + console.log(message, payments) if (!alreadyRejected) { wasAdded = true return [...payments, { messageId, senderId: message.details.origin, rejectedPayment: false }] @@ -952,17 +949,19 @@ {:else} - + {/if} + {:else if line.startsWith(PaymentRequestsEnum.Send) && $rejectedPayments.find(payments => payments.messageId === message.id && payments.rejectedPayment)} + - {:else if !checkForActiveRequest(message, line)} + {:else if !checkForActiveRequest(message, line) && !$rejectedPayments.some(payment => payment.messageId === message.id)} {:else} - + {/if} - {:else if line.startsWith(PaymentRequestsEnum.Send) && $rejectedPayments.find(payments => payments.messageId === message.id && payments.rejectedPayment)} - + {/if} -
- -
{:else if sendCoin === ViewMode.Receive}
-
diff --git a/src/routes/chat/+page.svelte b/src/routes/chat/+page.svelte index c291ebcc9..507266dca 100644 --- a/src/routes/chat/+page.svelte +++ b/src/routes/chat/+page.svelte @@ -456,7 +456,6 @@ function checkForActiveRequest(message: MessageType, messageLine: string) { const rejectidMatch = messageLine.match(/^\/reject\s([a-f0-9-]{36})$/) const sendidMatch = messageLine.match(/^\/send\s.*"messageID":"([a-f0-9-]{36})"/) - console.log(message, sendidMatch) if (rejectidMatch) { const messageId = rejectidMatch[1] let wasAdded = false From 173fd0e7d01a04a66894b310b8ffb45b08cf4837 Mon Sep 17 00:00:00 2001 From: jekrimo Date: Thu, 12 Dec 2024 08:39:31 -0700 Subject: [PATCH 44/52] fix busted btc messages --- src/lib/components/messaging/ChatPreview.svelte | 2 +- src/routes/chat/+page.svelte | 7 +++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/lib/components/messaging/ChatPreview.svelte b/src/lib/components/messaging/ChatPreview.svelte index 15ddb5277..c77402c4f 100644 --- a/src/lib/components/messaging/ChatPreview.svelte +++ b/src/lib/components/messaging/ChatPreview.svelte @@ -92,7 +92,7 @@ console.error("Error parsing JSON:", error, chat.last_message_preview) return "Invalid message format" } - const amountWei = parsedMessage.details.transfer.amountPreview || BigInt(0) + const amountWei = parsedMessage.details.amount if (sendingUserDetails.key !== ownId.key) { return `${sendingUserDetails.name} sent you ${amountWei}` } else { diff --git a/src/routes/chat/+page.svelte b/src/routes/chat/+page.svelte index 60edde887..8669a1480 100644 --- a/src/routes/chat/+page.svelte +++ b/src/routes/chat/+page.svelte @@ -179,14 +179,13 @@ } const details = parsedMessage.details || {} - const amountWei = details.amount || BigInt(0) - const amountEther = `${(Number(amountWei) / 1e18).toFixed(18)} ETH` + const amountWei = details.amount if (sender !== "") { - return `${sender} sent you ${amountEther}` + return `${sender} sent you ${amountWei}` } else { const recipientName = $users[$activeChat.users[1]]?.name || receiver || "unknown recipient" - return `You sent ${amountEther} to ${recipientName}` + return `You sent ${amountWei} to ${recipientName}` } } From 1fb8246138b97890fb31f8316a571931c781d6c4 Mon Sep 17 00:00:00 2001 From: jekrimo Date: Thu, 12 Dec 2024 09:04:54 -0700 Subject: [PATCH 45/52] fix cancel message --- src/routes/chat/+page.svelte | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/routes/chat/+page.svelte b/src/routes/chat/+page.svelte index 8669a1480..4366359b7 100644 --- a/src/routes/chat/+page.svelte +++ b/src/routes/chat/+page.svelte @@ -168,7 +168,7 @@ parsedMessage = JSON.parse(jsonPart, (key, value) => { if (key === "amount" && typeof value === "string") { if (/^\d+$/.test(value)) { - return BigInt(value) // Parse amount as BigInt + return BigInt(value) } } return value @@ -450,7 +450,7 @@ }) function checkForActiveRequest(message: MessageType, messageLine: string) { - const rejectidMatch = messageLine.match(/^\/reject\s([a-f0-9-]{36})$/) + const rejectidMatch = messageLine.match(/^\/reject\s([a-f0-9-]{36})(?:\s|$)/) const sendidMatch = messageLine.match(/^\/send\s.*"messageID":"([a-f0-9-]{36})"/) if (rejectidMatch) { const messageId = rejectidMatch[1] @@ -467,9 +467,11 @@ return wasAdded } + if (sendidMatch) { const messageId = sendidMatch[1] let wasAdded = false + Store.state.paymentTracker.update(payments => { const alreadyRejected = payments.some(payment => payment.messageId === messageId) @@ -482,6 +484,7 @@ return wasAdded } + return false } From fd34dfd7ab0099280b5e823a3119b9624e0efda7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luis=20Carden=CC=83a?= <35935591+luisecm@users.noreply.github.com> Date: Thu, 12 Dec 2024 11:33:53 -0600 Subject: [PATCH 46/52] update(files): attempt to fix ci bugs --- src/lib/components/messaging/ChatPreview.svelte | 2 +- src/routes/chat/+page.svelte | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib/components/messaging/ChatPreview.svelte b/src/lib/components/messaging/ChatPreview.svelte index c77402c4f..6f2c6a0e6 100644 --- a/src/lib/components/messaging/ChatPreview.svelte +++ b/src/lib/components/messaging/ChatPreview.svelte @@ -92,7 +92,7 @@ console.error("Error parsing JSON:", error, chat.last_message_preview) return "Invalid message format" } - const amountWei = parsedMessage.details.amount + const amountWei = parsedMessage.details?.amount if (sendingUserDetails.key !== ownId.key) { return `${sendingUserDetails.name} sent you ${amountWei}` } else { diff --git a/src/routes/chat/+page.svelte b/src/routes/chat/+page.svelte index 4366359b7..9c7e6c513 100644 --- a/src/routes/chat/+page.svelte +++ b/src/routes/chat/+page.svelte @@ -179,7 +179,7 @@ } const details = parsedMessage.details || {} - const amountWei = details.amount + const amountWei = details?.amount if (sender !== "") { return `${sender} sent you ${amountWei}` From 55e98ee49fd8221024670887e66c68cba433c538 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luis=20Carden=CC=83a?= <35935591+luisecm@users.noreply.github.com> Date: Thu, 12 Dec 2024 11:46:16 -0600 Subject: [PATCH 47/52] update(src): remove my changes since does nothing --- src/lib/components/messaging/ChatPreview.svelte | 2 +- src/routes/chat/+page.svelte | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib/components/messaging/ChatPreview.svelte b/src/lib/components/messaging/ChatPreview.svelte index 6f2c6a0e6..c77402c4f 100644 --- a/src/lib/components/messaging/ChatPreview.svelte +++ b/src/lib/components/messaging/ChatPreview.svelte @@ -92,7 +92,7 @@ console.error("Error parsing JSON:", error, chat.last_message_preview) return "Invalid message format" } - const amountWei = parsedMessage.details?.amount + const amountWei = parsedMessage.details.amount if (sendingUserDetails.key !== ownId.key) { return `${sendingUserDetails.name} sent you ${amountWei}` } else { diff --git a/src/routes/chat/+page.svelte b/src/routes/chat/+page.svelte index 9c7e6c513..4366359b7 100644 --- a/src/routes/chat/+page.svelte +++ b/src/routes/chat/+page.svelte @@ -179,7 +179,7 @@ } const details = parsedMessage.details || {} - const amountWei = details?.amount + const amountWei = details.amount if (sender !== "") { return `${sender} sent you ${amountWei}` From df7ffd512a95304ad849b3b9dd6a41edc3a626ac Mon Sep 17 00:00:00 2001 From: jekrimo Date: Thu, 12 Dec 2024 11:12:26 -0700 Subject: [PATCH 48/52] test --- src/routes/chat/+page.svelte | 1 + 1 file changed, 1 insertion(+) diff --git a/src/routes/chat/+page.svelte b/src/routes/chat/+page.svelte index 4366359b7..b9c5699c2 100644 --- a/src/routes/chat/+page.svelte +++ b/src/routes/chat/+page.svelte @@ -346,6 +346,7 @@ async function sendPaymentMessage(message: MessageType, line: string, paymentType: string) { let transfer = new Transfer() let chat = get(Store.state.activeChat) + console.log("just testing push") if (paymentType === PaymentRequestsEnum.Request) { let rejectTranfser = transfer.toCmdString() let txt = rejectTranfser.split("\n") From 555c63f912e8661f65aa2fd3e82a8b3a62005723 Mon Sep 17 00:00:00 2001 From: jekrimo Date: Tue, 17 Dec 2024 08:35:44 -0700 Subject: [PATCH 49/52] btc and eth error handles --- .../components/messaging/ChatPreview.svelte | 1 - src/lib/utils/Wallet.ts | 9 +- src/routes/chat/+page.svelte | 144 ++++++++++++++---- 3 files changed, 122 insertions(+), 32 deletions(-) diff --git a/src/lib/components/messaging/ChatPreview.svelte b/src/lib/components/messaging/ChatPreview.svelte index c77402c4f..b4d0ade60 100644 --- a/src/lib/components/messaging/ChatPreview.svelte +++ b/src/lib/components/messaging/ChatPreview.svelte @@ -34,7 +34,6 @@ $: user = chat.typing_indicator.users().map(u => { return $lookupUsers[u] }) - $: self = get(Store.state.user) let timeago = getTimeAgo(chat.last_message_at) const dispatch = createEventDispatcher() let ownId = get(Store.state.user) diff --git a/src/lib/utils/Wallet.ts b/src/lib/utils/Wallet.ts index 34fac2b24..0536230a6 100644 --- a/src/lib/utils/Wallet.ts +++ b/src/lib/utils/Wallet.ts @@ -515,8 +515,12 @@ export class Transfer { async execute() { if (this.isValid()) { - await wallet.transfer(this.asset, this.amount, this.toAddress) - return true + let verifyTansfer = await wallet.transfer(this.asset, this.amount, this.toAddress) + if (verifyTansfer === undefined) { + return false + } else { + return true + } } } } @@ -563,7 +567,6 @@ export function getValidPaymentRequest(msg: string, msgId?: string): Transfer | let jsonStartIndex = json.indexOf("{") if (jsonStartIndex !== -1) { json = json.substring(jsonStartIndex).trim() - try { let parsed = JSON.parse(json, (key, value) => { if (key === "amount" && typeof value === "string") { diff --git a/src/routes/chat/+page.svelte b/src/routes/chat/+page.svelte index b9c5699c2..359e14571 100644 --- a/src/routes/chat/+page.svelte +++ b/src/routes/chat/+page.svelte @@ -155,39 +155,91 @@ return result } - function sanitizePaymentSent(message: string, sender: string, receiver: string): string { - const jsonStartIndex = message.indexOf("{") - const jsonEndIndex = message.lastIndexOf("}") - if (jsonStartIndex === -1 || jsonEndIndex === -1 || jsonStartIndex > jsonEndIndex) { + $: sanitizePaymentSent = (() => { + // const jsonStartIndex = message.indexOf("{") + // const jsonEndIndex = message.lastIndexOf("}") + // if (jsonStartIndex === -1 || jsonEndIndex === -1 || jsonStartIndex > jsonEndIndex) { + // return "Invalid message format" + // } + + // const jsonPart = message.slice(jsonStartIndex, jsonEndIndex + 1).trim() + // let parsedMessage + // try { + // parsedMessage = JSON.parse(jsonPart, (key, value) => { + // if (key === "amount" && typeof value === "string") { + // if (/^\d+$/.test(value)) { + // return BigInt(value) + // } + // } + // return value + // }) + // } catch (error) { + // console.error("Error parsing JSON:", error, message) + // return "Invalid message format" + // } + + // const details = parsedMessage.details || {} + // const amountWei = details.amount + + // if (sender !== "") { + // return `${sender} sent you ${amountWei}` + // } else { + // const recipientName = $users[$activeChat.users[1]]?.name || receiver || "unknown recipient" + // return `You sent ${amountWei} to ${recipientName}` + // } + // try { + // const sendingUserId = ConversationStore.getMessage($activeChat.id, $activeChat.last_message_id)?.details.origin + // const sendingUserDetails = get(Store.getUser(sendingUserId!)) + // const jsonStartIndex = $activeChat.last_message_preview.indexOf("{") + // if (jsonStartIndex === -1) { + // console.error("No JSON found in last_message_preview:", $activeChat.last_message_preview) + // return "Invalid message format" + // } + // const jsonPart = $activeChat.last_message_preview.slice(jsonStartIndex) + // let parsedMessage + // try { + // parsedMessage = JSON.parse(jsonPart) + // } catch (error) { + // console.error("Error parsing JSON:", error, $activeChat.last_message_preview) + // return "Invalid message format" + // } + // const amountWei = parsedMessage.details.amount + // if (sender !== "") { + // return `${sender} sent you ${amountWei}` + // } else { + // const recipientName = $users[$activeChat.users[1]]?.name || receiver || "unknown recipient" + // return `You sent ${amountWei} to ${recipientName}` + // } + // } catch (error) { + // console.error("Error in PaymentRequestsEnum.Send condition:", error) + // return "Invalid message format" + // } + // try { + const sendingUserId = ConversationStore.getMessage($activeChat.id, $activeChat.last_message_id)?.details.origin + const sendingUserDetails = get(Store.getUser(sendingUserId!)) + const jsonStartIndex = $activeChat.last_message_preview.indexOf("{") + if (jsonStartIndex === -1) { + console.error("No JSON found in last_message_preview:", $activeChat.last_message_preview) return "Invalid message format" } - - const jsonPart = message.slice(jsonStartIndex, jsonEndIndex + 1).trim() + const jsonPart = $activeChat.last_message_preview.slice(jsonStartIndex) let parsedMessage try { - parsedMessage = JSON.parse(jsonPart, (key, value) => { - if (key === "amount" && typeof value === "string") { - if (/^\d+$/.test(value)) { - return BigInt(value) - } - } - return value - }) + parsedMessage = JSON.parse(jsonPart) } catch (error) { - console.error("Error parsing JSON:", error, message) + console.error("Error parsing JSON:", error, $activeChat.last_message_preview) return "Invalid message format" } - - const details = parsedMessage.details || {} - const amountWei = details.amount - - if (sender !== "") { - return `${sender} sent you ${amountWei}` + if (sendingUserDetails.key !== $own_user.key) { + return `${sendingUserDetails.name} sent you ${parsedMessage.details}` } else { - const recipientName = $users[$activeChat.users[1]]?.name || receiver || "unknown recipient" - return `You sent ${amountWei} to ${recipientName}` + return `You sent ${parsedMessage.details} to ${sendingUserDetails.name}` } - } + // } catch (error) { + // console.error("Error in PaymentRequestsEnum.Send condition:", error) + // return "Invalid message format" + // } + })() function addFilesToUpload(selected: File[]) { let files: [File?, string?][] = [] @@ -346,7 +398,6 @@ async function sendPaymentMessage(message: MessageType, line: string, paymentType: string) { let transfer = new Transfer() let chat = get(Store.state.activeChat) - console.log("just testing push") if (paymentType === PaymentRequestsEnum.Request) { let rejectTranfser = transfer.toCmdString() let txt = rejectTranfser.split("\n") @@ -357,7 +408,7 @@ if (!alreadyRejected) { return [...payments, { messageId: message.id, senderId: message.details.origin, rejectedPayment: false }] } else { - console.log(`MessageId ${message.id} is already in the rejected payments list`) + console.error(`MessageId ${message.id} is already in the rejected payments list`) return payments } }) @@ -416,8 +467,45 @@ }) ConversationStore.addPendingMessages(chat.id, res.message, txt) }) + } else { + let rejectTranfser = transfer.toRejectString(message.id) + let txt = rejectTranfser.split("\n") + let result = await RaygunStoreInstance.send(chat.id, txt, []) + result.onSuccess(res => { + Store.state.paymentTracker.update(payments => { + const alreadyRejected = payments.some(payment => payment.messageId === message.id) + + if (!alreadyRejected) { + return [...payments, { messageId: message.id, senderId: message.details.origin, rejectedPayment: true }] + } else { + console.error(`MessageId ${message.id} is already in the rejected payments list`) + return payments + } + }) + transfer.toRejectString(message.id) + ConversationStore.addPendingMessages(chat.id, res.message, txt) + }) + Store.addToastNotification(new ToastMessage("", "Error extracting payment details or sending message:", 4, undefined, Appearance.Warning)) } } catch (error) { + let rejectTranfser = transfer.toRejectString(message.id) + let txt = rejectTranfser.split("\n") + let result = await RaygunStoreInstance.send(chat.id, txt, []) + result.onSuccess(res => { + Store.state.paymentTracker.update(payments => { + const alreadyRejected = payments.some(payment => payment.messageId === message.id) + + if (!alreadyRejected) { + return [...payments, { messageId: message.id, senderId: message.details.origin, rejectedPayment: true }] + } else { + console.error(`MessageId ${message.id} is already in the rejected payments list`) + return payments + } + }) + transfer.toRejectString(message.id) + ConversationStore.addPendingMessages(chat.id, res.message, txt) + }) + Store.addToastNotification(new ToastMessage("", "Error extracting payment details or sending message:", 4, undefined, Appearance.Warning)) console.error("Error extracting payment details or sending message:", error) } } @@ -928,9 +1016,9 @@ {:else if line.startsWith(PaymentRequestsEnum.Send)} {#if !checkForActiveRequest(message, line)} {#if $own_user.key !== message.details.origin} - + {sanitizePaymentSent} {:else if $own_user.key === message.details.origin} - + {sanitizePaymentSent} {/if} {/if} {:else if getValidPaymentRequest(line) !== undefined} From 72f2908066b98c96f797e27e4c01504a1da85d67 Mon Sep 17 00:00:00 2001 From: jekrimo Date: Tue, 17 Dec 2024 10:00:00 -0700 Subject: [PATCH 50/52] missing needed return --- src/lib/utils/Wallet.ts | 2 +- src/routes/chat/+page.svelte | 63 ------------------------------------ 2 files changed, 1 insertion(+), 64 deletions(-) diff --git a/src/lib/utils/Wallet.ts b/src/lib/utils/Wallet.ts index 0536230a6..a577ea140 100644 --- a/src/lib/utils/Wallet.ts +++ b/src/lib/utils/Wallet.ts @@ -363,7 +363,7 @@ async function ethToBigIntAmount(amount: string): Promise { } async function ethTransfer(ethWallet: EthWallet, amount: bigint, toAddress: string) { - let tx = await ethWallet.signer.sendTransaction({ + return await ethWallet.signer.sendTransaction({ to: toAddress, value: amount, }) diff --git a/src/routes/chat/+page.svelte b/src/routes/chat/+page.svelte index 41dfe80d9..d328639a3 100644 --- a/src/routes/chat/+page.svelte +++ b/src/routes/chat/+page.svelte @@ -139,65 +139,6 @@ } $: sanitizePaymentSent = (() => { - // const jsonStartIndex = message.indexOf("{") - // const jsonEndIndex = message.lastIndexOf("}") - // if (jsonStartIndex === -1 || jsonEndIndex === -1 || jsonStartIndex > jsonEndIndex) { - // return "Invalid message format" - // } - - // const jsonPart = message.slice(jsonStartIndex, jsonEndIndex + 1).trim() - // let parsedMessage - // try { - // parsedMessage = JSON.parse(jsonPart, (key, value) => { - // if (key === "amount" && typeof value === "string") { - // if (/^\d+$/.test(value)) { - // return BigInt(value) - // } - // } - // return value - // }) - // } catch (error) { - // console.error("Error parsing JSON:", error, message) - // return "Invalid message format" - // } - - // const details = parsedMessage.details || {} - // const amountWei = details.amount - - // if (sender !== "") { - // return `${sender} sent you ${amountWei}` - // } else { - // const recipientName = $users[$activeChat.users[1]]?.name || receiver || "unknown recipient" - // return `You sent ${amountWei} to ${recipientName}` - // } - // try { - // const sendingUserId = ConversationStore.getMessage($activeChat.id, $activeChat.last_message_id)?.details.origin - // const sendingUserDetails = get(Store.getUser(sendingUserId!)) - // const jsonStartIndex = $activeChat.last_message_preview.indexOf("{") - // if (jsonStartIndex === -1) { - // console.error("No JSON found in last_message_preview:", $activeChat.last_message_preview) - // return "Invalid message format" - // } - // const jsonPart = $activeChat.last_message_preview.slice(jsonStartIndex) - // let parsedMessage - // try { - // parsedMessage = JSON.parse(jsonPart) - // } catch (error) { - // console.error("Error parsing JSON:", error, $activeChat.last_message_preview) - // return "Invalid message format" - // } - // const amountWei = parsedMessage.details.amount - // if (sender !== "") { - // return `${sender} sent you ${amountWei}` - // } else { - // const recipientName = $users[$activeChat.users[1]]?.name || receiver || "unknown recipient" - // return `You sent ${amountWei} to ${recipientName}` - // } - // } catch (error) { - // console.error("Error in PaymentRequestsEnum.Send condition:", error) - // return "Invalid message format" - // } - // try { const sendingUserId = ConversationStore.getMessage($activeChat.id, $activeChat.last_message_id)?.details.origin const sendingUserDetails = get(Store.getUser(sendingUserId!)) const jsonStartIndex = $activeChat.last_message_preview.indexOf("{") @@ -218,10 +159,6 @@ } else { return `You sent ${parsedMessage.details} to ${sendingUserDetails.name}` } - // } catch (error) { - // console.error("Error in PaymentRequestsEnum.Send condition:", error) - // return "Invalid message format" - // } })() function addFilesToUpload(selected: File[]) { From 4d2fba25b877bc6015d01e5189a3406f4d70f71f Mon Sep 17 00:00:00 2001 From: jekrimo Date: Tue, 17 Dec 2024 10:17:03 -0700 Subject: [PATCH 51/52] sending user details got changed from wallet response updated the variable to acount for this change in the chat file --- src/routes/chat/+page.svelte | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/routes/chat/+page.svelte b/src/routes/chat/+page.svelte index d328639a3..d07129a46 100644 --- a/src/routes/chat/+page.svelte +++ b/src/routes/chat/+page.svelte @@ -155,9 +155,9 @@ return "Invalid message format" } if (sendingUserDetails.key !== $own_user.key) { - return `${sendingUserDetails.name} sent you ${parsedMessage.details}` + return `${sendingUserDetails.name} sent you ${parsedMessage.details.amount}` } else { - return `You sent ${parsedMessage.details} to ${sendingUserDetails.name}` + return `You sent ${parsedMessage.details.amount} to ${sendingUserDetails.name}` } })() From 29fb6f89e34509318fafc853469170dd23e479ea Mon Sep 17 00:00:00 2001 From: jekrimo Date: Thu, 26 Dec 2024 10:45:16 -0700 Subject: [PATCH 52/52] up --- src/routes/chat/+page.svelte | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/routes/chat/+page.svelte b/src/routes/chat/+page.svelte index d07129a46..c35de2e81 100644 --- a/src/routes/chat/+page.svelte +++ b/src/routes/chat/+page.svelte @@ -154,10 +154,19 @@ console.error("Error parsing JSON:", error, $activeChat.last_message_preview) return "Invalid message format" } - if (sendingUserDetails.key !== $own_user.key) { - return `${sendingUserDetails.name} sent you ${parsedMessage.details.amount}` + console.log(parsedMessage) + if (parsedMessage.details) { + if (sendingUserDetails.key !== $own_user.key) { + return `${sendingUserDetails.name} sent you ${parsedMessage.details.amount}` + } else { + return `You sent ${parsedMessage.details.amount} to ${sendingUserDetails.name}` + } } else { - return `You sent ${parsedMessage.details.amount} to ${sendingUserDetails.name}` + if (sendingUserDetails.key !== $own_user.key) { + return `${sendingUserDetails.name} sent you ${parsedMessage.amount}` + } else { + return `You sent ${parsedMessage.amount} to ${sendingUserDetails.name}` + } } })() @@ -457,7 +466,7 @@ } }, 500) }) - + $: sanitizePaymentSent function checkForActiveRequest(message: MessageType, messageLine: string) { const rejectidMatch = messageLine.match(/^\/reject\s([a-f0-9-]{36})(?:\s|$)/) const sendidMatch = messageLine.match(/^\/send\s.*"messageID":"([a-f0-9-]{36})"/)