From 3afdb24f1043126f325235bf407e0dc16c292b38 Mon Sep 17 00:00:00 2001 From: Emilie Ma Date: Fri, 30 Dec 2022 14:35:33 -0800 Subject: [PATCH] ETH Testrun Bugfixes --- src/pages/Background/index.ts | 44 ++++++-- src/pages/Background/lib/cleanUpStreams.ts | 18 ++- src/pages/Background/lib/createStream.ts | 87 +++++++------- .../Background/lib/deleteStreamByTabId.ts | 15 ++- .../Background/lib/fetchAndUpdateBalance.ts | 8 +- src/pages/Background/lib/updateRateSetting.ts | 4 +- src/pages/Content/index.ts | 19 ---- src/pages/Popup/CobwebInfo.tsx | 2 + src/pages/Popup/ListSettings.tsx | 14 ++- src/pages/Popup/ListStreamsIn.tsx | 60 ---------- src/pages/Popup/ListStreamsOut.tsx | 1 + src/pages/Popup/Popup.tsx | 60 ++++------ .../components/CurrentStreamComponent.tsx | 2 +- .../Popup/components/OnboardingCarousel.tsx | 35 ++++-- src/pages/Popup/components/Setting.tsx | 106 ++++++++++-------- .../Popup/components/StreamComponent.tsx | 14 ++- src/pages/Popup/components/ToastHandler.tsx | 5 +- src/pages/Popup/index.tsx | 2 - src/pages/Popup/lib/getStreams.ts | 56 ++------- src/pages/shared/events.ts | 1 - worker/src/index.ts | 32 ++++-- 21 files changed, 274 insertions(+), 311 deletions(-) delete mode 100644 src/pages/Popup/ListStreamsIn.tsx diff --git a/src/pages/Background/index.ts b/src/pages/Background/index.ts index 5c72432..3c3bdbb 100644 --- a/src/pages/Background/index.ts +++ b/src/pages/Background/index.ts @@ -18,7 +18,7 @@ import { DELETE_STREAM, BLOCK_TAG, UPDATE_SETTING, - EDIT_CURRENT_STREAM, + UPDATE_STREAM, FETCH_BALANCE, APPROVE_AMT, DOWNGRADE_TOKEN, @@ -52,7 +52,7 @@ import { isDev } from "./lib/isDev"; chrome.runtime.onInstalled.addListener((details) => { if (details.reason === chrome.runtime.OnInstalledReason.INSTALL) { setDefaultSettings(); - chrome.runtime.setUninstallURL("https://kewbi.sh/cobweb"); + chrome.runtime.setUninstallURL("https://kewbi.sh/cobweb/removed"); } }); @@ -64,6 +64,10 @@ metamaskProvider?.on("error", (error) => { storage.local.set({ mmNotFound: true }); }); +metamaskProvider.on("disconnect", () => { + storage.local.set({ mmNotFound: true }); +}); + metamaskProvider.on("accountsChanged", (accounts) => { setNewAddress({ address: (accounts as Array)[0], @@ -99,7 +103,6 @@ try { toast("Error - failed to initialize provider"); throw new Error("Error - failed to initialize provider"); } - let sf: Framework | null = null; try { sf = await Framework.create({ @@ -184,8 +187,11 @@ const montagFound = async ({ if (rate.payWhen === PayRates.BLOCKED) { return; } + const { address: mmAddress } = (await storage.local.get("address")) ?? { + address: "", + }; createStream({ - from: walletRes.address, + from: mmAddress, toTag: request.options.address, to: address, tabId, @@ -195,7 +201,9 @@ const montagFound = async ({ sfSigner, sfToken, infuraProvider: infuraProvider as InfuraProvider, + mmSigner: mmProvider.getSigner(), }); + cleanUpStreams({ sfSigner, sfToken, sf, mmSigner: mmProvider.getSigner() }); }; const deleteStream = async ({ request }: { request: any }) => { @@ -209,6 +217,7 @@ const deleteStream = async ({ request }: { request: any }) => { sf, sfSigner, sfToken, + mmSigner: mmProvider.getSigner(), }); } }; @@ -245,6 +254,7 @@ const editCurrentStream = async ({ request }: { request: any }) => { sf, sfSigner, sfToken, + mmSigner: mmProvider.getSigner(), }); }; @@ -359,7 +369,7 @@ const handleMessaging = async ( sendResponse(); return; } - case EDIT_CURRENT_STREAM: { + case UPDATE_STREAM: { editCurrentStream({ request }); sendResponse(); return; @@ -412,7 +422,13 @@ chrome.runtime.onMessage.addListener(handleMessaging); chrome.tabs.onRemoved.addListener(async (tabId, _) => { const { signer: sfSigner } = await getWalletAndSigner(); if (sf && sfSigner && sfToken) { - deleteStreamByTabId({ tabId, sf, sfSigner, sfToken }); + deleteStreamByTabId({ + tabId, + sf, + sfSigner, + sfToken, + mmSigner: mmProvider.getSigner(), + }); } }); @@ -422,7 +438,14 @@ chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, _) => { } const { signer: sfSigner } = await getWalletAndSigner(); if (changeInfo.url && sf && sfSigner && sfToken) { - deleteStreamByTabId({ tabId, sf, sfSigner, sfToken, checkFocus: true }); + deleteStreamByTabId({ + tabId, + sf, + sfSigner, + sfToken, + checkFocus: true, + mmSigner: mmProvider.getSigner(), + }); } }); @@ -453,7 +476,12 @@ chrome.alarms.onAlarm.addListener(async (alarm) => { return; } if (name === "cobwebStreamCleanup") { - cleanUpStreams({ sfSigner, sfToken, sf }); + cleanUpStreams({ + sfSigner, + sfToken, + sf, + mmSigner: mmProvider.getSigner(), + }); } else if (name === "cobwebAllowanceCheck") { const { address } = await storage.local.get("address"); if (!wallet || !address) { diff --git a/src/pages/Background/lib/cleanUpStreams.ts b/src/pages/Background/lib/cleanUpStreams.ts index b13552c..5ab2559 100644 --- a/src/pages/Background/lib/cleanUpStreams.ts +++ b/src/pages/Background/lib/cleanUpStreams.ts @@ -9,11 +9,13 @@ const cleanUpStreams = async ({ sfToken, sf, all = false, + mmSigner, }: { sf: Framework; sfSigner: Signer; sfToken: SuperToken; all?: boolean; + mmSigner: Signer; }) => { const { streams }: { streams: Array } = await storage.local.get( "streams" @@ -25,13 +27,25 @@ const cleanUpStreams = async ({ for (const stream of streams) { if (all) { - deleteStreamByTabId({ tabId: stream.tabId, sf, sfSigner, sfToken }); + deleteStreamByTabId({ + tabId: stream.tabId, + sf, + sfSigner, + sfToken, + mmSigner, + }); continue; } try { await chrome.tabs.get(stream.tabId); } catch { - deleteStreamByTabId({ tabId: stream.tabId, sf, sfSigner, sfToken }); + deleteStreamByTabId({ + tabId: stream.tabId, + sf, + sfSigner, + sfToken, + mmSigner, + }); } } }; diff --git a/src/pages/Background/lib/createStream.ts b/src/pages/Background/lib/createStream.ts index 2f134f8..2c4414e 100644 --- a/src/pages/Background/lib/createStream.ts +++ b/src/pages/Background/lib/createStream.ts @@ -12,7 +12,6 @@ import { startMonetization, stopMonetization, } from "../../shared/monetization"; -import TOKEN_MAP from "../../shared/tokens"; const createStream = async ({ from, @@ -25,6 +24,7 @@ const createStream = async ({ sfSigner, sfToken, infuraProvider, + mmSigner, }: { from: string; to: string; @@ -36,8 +36,8 @@ const createStream = async ({ sfSigner: Signer; sfToken: SuperToken; infuraProvider: InfuraProvider; + mmSigner: Signer; }) => { - /* const possibleName = await infuraProvider.resolveName(to); if (!possibleName || !utils.isAddress(to)) { return; @@ -51,7 +51,7 @@ const createStream = async ({ const response = await fetch( "https://cobweb-worker.kewbish.workers.dev/get?" + - new URLSearchParams({ address: to }) + new URLSearchParams({ address: to.toLowerCase() }).toString() ); const responseJson = await response.json(); if (responseJson.error) { @@ -60,7 +60,6 @@ const createStream = async ({ // hasn't been added to Cobweb network return; } - */ const uuid = fromString( to + tabId.toString() + new Date().toString(), @@ -75,7 +74,6 @@ const createStream = async ({ let newStream = null; - /* try { if ( ( @@ -90,56 +88,56 @@ const createStream = async ({ ) { const newStreamOperation = sf.cfaV1.createFlowByOperator({ sender: from, - flowRate: rateAmount.toString(), + flowRate: BigNumber.from(rateAmount).toString(), receiver: to, superToken: sfToken.address, - userData: `${to} ${new Date()}`, + userData: utils.hexlify(utils.toUtf8Bytes(`${to} ${new Date()}`)), }); - newStream = await newStreamOperation.exec(sfSigner); + newStream = await newStreamOperation.exec(mmSigner); + + const { streams } = await storage.local.get("streams"); + + storage.local.set({ + streams: [ + ...streams, + { + recipient: to, + recipientTag: toTag, + tabId, + rateAmount: BigNumber.from(rateAmount), + requestId: uuid, + startTime: new Date().getTime(), + token: { + name: sfToken.name, + decimals: 18, // TODO - hardcoding for now + symbol: sfToken.symbol, + xAddress: sfToken.address, + }, + url, + }, + ], + }); + + chrome.scripting.executeScript({ + args: [to, uuid], + target: { tabId }, + func: startMonetization, + world: "MAIN", + }); + return newStream; } } catch (e) { chrome.scripting.executeScript({ args: [to, uuid], target: { tabId }, func: stopMonetization, - world: "MAIN", + world: "MAIN", }); errorToast(e as Error); toast( "Check that you've approved enough spending tokens in your account page." ); - }*/ - - const { streams } = await storage.local.get("streams"); - - storage.local.set({ - streams: [ - ...streams, - { - recipient: to, - recipientTag: toTag, - tabId, - rateAmount, - requestId: uuid, - startTime: new Date().getTime(), - token: { - name: sfToken.name, - decimals: 18, // TODO - hardcoding for now - symbol: sfToken.symbol, - xAddress: sfToken.address, - }, - url, - }, - ], - }); - - chrome.scripting.executeScript({ - args: [to, uuid], - target: { tabId }, - func: startMonetization, - world: "MAIN", - }); - return newStream; + } }; export const updateStream = async ({ @@ -150,6 +148,7 @@ export const updateStream = async ({ sf, sfSigner, sfToken, + mmSigner, }: { from: string; to: string; @@ -158,6 +157,7 @@ export const updateStream = async ({ sf: Framework; sfSigner: Signer; sfToken: SuperToken; + mmSigner: Signer; }) => { const uuid = fromString( to + tabId.toString() + new Date().toString(), @@ -174,18 +174,17 @@ export const updateStream = async ({ try { const updateStreamOperation = sf.cfaV1.updateFlowByOperator({ sender: from, - flowRate: rateAmount.toString(), + flowRate: BigNumber.from(rateAmount).toString(), receiver: to, superToken: sfToken.address, userData: `${to} ${new Date()}`, }); - updateStream = await updateStreamOperation.exec(sfSigner); + updateStream = await updateStreamOperation.exec(mmSigner); } catch (e) { errorToast(e as Error); } const { streams } = await storage.local.get("streams"); - storage.local.set({ streams: [ ...streams.map((stream: Stream) => diff --git a/src/pages/Background/lib/deleteStreamByTabId.ts b/src/pages/Background/lib/deleteStreamByTabId.ts index 8df1700..6cdd5a1 100644 --- a/src/pages/Background/lib/deleteStreamByTabId.ts +++ b/src/pages/Background/lib/deleteStreamByTabId.ts @@ -10,22 +10,29 @@ const deleteStreamByTabId = async ({ sfSigner, sfToken, checkFocus = false, + mmSigner, }: { tabId: number; sf: Framework; sfSigner: Signer; sfToken: SuperToken; checkFocus?: boolean; + mmSigner: Signer; }) => { const cancelStream = async (recipient: string) => { - const { wallet }: { wallet: Wallet } = await storage.local.get("wallet"); + const { address }: { address: string | null } = await storage.local.get( + "address" + ); + if (!address) { + return; + } try { const deleteStreamOperation = sf.cfaV1.deleteFlowByOperator({ - sender: wallet.address, + sender: address, receiver: recipient, superToken: sfToken.address, }); - await deleteStreamOperation.exec(sfSigner); + await deleteStreamOperation.exec(mmSigner); } catch (e) { errorToast(e as Error); return; @@ -52,7 +59,7 @@ const deleteStreamByTabId = async ({ streams: streams.filter((stream: Stream) => stream.tabId !== tabId), }); - // cancelStream(stream.recipient); + cancelStream(stream.recipient); }; export default deleteStreamByTabId; diff --git a/src/pages/Background/lib/fetchAndUpdateBalance.ts b/src/pages/Background/lib/fetchAndUpdateBalance.ts index 464d3e3..f109adc 100644 --- a/src/pages/Background/lib/fetchAndUpdateBalance.ts +++ b/src/pages/Background/lib/fetchAndUpdateBalance.ts @@ -82,7 +82,13 @@ const fetchAndUpdateBalance = async ({ // critical balance toast("Balance is critically low"); if (sf && sfSigner) { - cleanUpStreams({ sf, sfToken, sfSigner, all: true }); + cleanUpStreams({ + sf, + sfToken, + sfSigner, + all: true, + mmSigner: mmProvider.getSigner(), + }); } return; } diff --git a/src/pages/Background/lib/updateRateSetting.ts b/src/pages/Background/lib/updateRateSetting.ts index 4dddd7a..8960f01 100644 --- a/src/pages/Background/lib/updateRateSetting.ts +++ b/src/pages/Background/lib/updateRateSetting.ts @@ -2,7 +2,7 @@ import { storage } from "@extend-chrome/storage"; import { PayRates, RateSettings } from "../../shared/types"; import { BigNumber } from "ethers"; -const updateRateSetting = ({ +const updateRateSetting = async ({ oldKey, newKey, rateAmt, @@ -16,7 +16,7 @@ const updateRateSetting = ({ storage.local.set(({ settings }: { settings: RateSettings }) => { delete settings[oldKey]; settings[newKey] = { rateAmount: rateAmt, payWhen }; - return settings; + return { settings }; }); }; diff --git a/src/pages/Content/index.ts b/src/pages/Content/index.ts index 4832fab..ac63d69 100644 --- a/src/pages/Content/index.ts +++ b/src/pages/Content/index.ts @@ -24,22 +24,3 @@ if (monetizationTag) { }); } } - -try { - const port = chrome.runtime.connect({ name: "content-script" }); - const onPortDisconnect = () => { - try { - console.log(chrome.runtime.lastError); - setTimeout(() => { - if (!chrome.runtime?.id) { - document.body.insertAdjacentHTML( - "afterend", - "" - ); - document.getElementById("cobweb-removed-link")?.click(); - } - }, 1000); - } catch {} - }; - port.onDisconnect.addListener(onPortDisconnect); -} catch {} diff --git a/src/pages/Popup/CobwebInfo.tsx b/src/pages/Popup/CobwebInfo.tsx index 160d228..903c1c5 100644 --- a/src/pages/Popup/CobwebInfo.tsx +++ b/src/pages/Popup/CobwebInfo.tsx @@ -70,12 +70,14 @@ const CobwebInfo = () => { message: APPROVE_AMT, options: { depositAmt: approveAmt }, }); + setApproveAmtShow(false); }; const approveFull = () => { chrome.runtime.sendMessage({ message: APPROVE_FULL, }); + setApproveAmtShow(false); }; return ( diff --git a/src/pages/Popup/ListSettings.tsx b/src/pages/Popup/ListSettings.tsx index 54fda0b..0428450 100644 --- a/src/pages/Popup/ListSettings.tsx +++ b/src/pages/Popup/ListSettings.tsx @@ -2,7 +2,7 @@ import React, { useEffect } from "react"; import { useChromeStorageLocal } from "use-chrome-storage"; import { useState } from "react"; import { PayRates, Rate, RateSettings, Stream } from "../shared/types"; -import { BigNumber, utils } from "ethers"; +import { BigNumber, constants, utils } from "ethers"; import fallbackRate from "../shared/fallbackRate"; import TokenInput from "./components/TokenInput"; import Setting from "./components/Setting"; @@ -147,12 +147,14 @@ const ListSettings = () => { }} >

- {verifySignature(key) ?? "[invalid Cobweb Tag]"} :{" "} + {verifySignature(key) ?? "[invalid Cobweb Tag]"}:{" "} - {(+utils.formatUnits(value.rateAmount)).toFixed( - 4 - )} - ETH per second + {BigNumber.from(value.rateAmount) !== + constants.Zero + ? (+utils.formatUnits( + value.rateAmount + )).toFixed(4) + " ETH per second" + : "[blocked]"} {" "}

diff --git a/src/pages/Popup/ListStreamsIn.tsx b/src/pages/Popup/ListStreamsIn.tsx deleted file mode 100644 index b88052a..0000000 --- a/src/pages/Popup/ListStreamsIn.tsx +++ /dev/null @@ -1,60 +0,0 @@ -import React, { useEffect, useState } from "react"; -import { useChromeStorageLocal } from "use-chrome-storage"; -import { GraphQlStream } from "../shared/types"; -import { getStreamsDeepIn } from "./lib/getStreams"; -import StreamComponent from "./components/StreamComponent"; -import CobwebPage from "./components/CobwebPage"; -import { toast } from "../shared/toast"; -import ToastHandler from "./components/ToastHandler"; - -const ListStreamsIn = () => { - const [mmAddress, , ,]: [string, any, any, any] = useChromeStorageLocal( - "extend-chrome/storage__local--address", - "" - ); - const [streams, setStreams] = useState>([]); - - useEffect(() => { - const getStreamsRes = async () => { - try { - const res = await getStreamsDeepIn(mmAddress); - if (!res) { - throw new Error("Expected streams"); - } else { - setStreams(res); - } - } catch { - toast("Could not fetch streams"); - } - }; - - if (!mmAddress) { - return; - } - - getStreamsRes(); - }, [mmAddress]); - - return ( - <> - - <> -

Streams In

-
-
- {streams.length ? ( - streams.map((stream: GraphQlStream) => ( - - )) - ) : ( -

No streams found.

- )} -
- -
- - - ); -}; - -export default ListStreamsIn; diff --git a/src/pages/Popup/ListStreamsOut.tsx b/src/pages/Popup/ListStreamsOut.tsx index 053e332..e5541ab 100644 --- a/src/pages/Popup/ListStreamsOut.tsx +++ b/src/pages/Popup/ListStreamsOut.tsx @@ -24,6 +24,7 @@ const ListStreamsOut = () => { if (!res) { throw new Error("Expected streams"); } else { + console.log(res); setStreams(res); } } catch { diff --git a/src/pages/Popup/Popup.tsx b/src/pages/Popup/Popup.tsx index 9b16b3f..c95b652 100644 --- a/src/pages/Popup/Popup.tsx +++ b/src/pages/Popup/Popup.tsx @@ -9,7 +9,7 @@ import { CHECK_METAMASK, } from "../shared/events"; import { useChromeStorageLocal } from "use-chrome-storage"; -import { PayRates, Stream } from "../shared/types"; +import { Rate, PayRates, Stream } from "../shared/types"; import Setting from "./components/Setting"; import DropdownModal from "./components/DropdownModal"; import BackgroundBox from "./components/BackgroundBox"; @@ -18,6 +18,7 @@ import { getRate } from "../Background/lib/getRate"; import Onboarding from "./components/OnboardingCarousel"; import ToastHandler from "./components/ToastHandler"; import BalanceDisplay from "./components/BalanceDisplay"; +import fallbackRate from "../shared/fallbackRate"; import "bootstrap-icons/font/bootstrap-icons.css"; // @ts-expect-error @@ -73,11 +74,13 @@ const Popup = () => { useChromeStorageLocal("extend-chrome/storage__local--streams", []); const [tabId, setTabId] = useState(0); - const [url, setUrl] = useState(""); - const [rate, setRate] = useState({ - rateAmount: constants.Zero, - payWhen: PayRates.ANY, - }); + const [defaultRate, , ,]: [Rate, any, any, any] = useChromeStorageLocal( + "extend-chrome/storage__local--defaultRate", + fallbackRate + ); + const [rate, setRate] = useState(defaultRate); + + const [currentStream, setCurrentStream] = useState(null); useEffect(() => { try { @@ -86,20 +89,14 @@ const Popup = () => { return; } setTabId(tabs[0].id ?? 0); - setUrl(tabs[0].url ?? tabs[0].pendingUrl ?? ""); - setRate( - (await getRate(url)) ?? { - rateAmount: constants.Zero, - payWhen: PayRates.ANY, - } - ); + if (currentStream) { + setRate((await getRate(currentStream?.recipient)) ?? defaultRate); + } }); } catch (e) { toast("Couldn't get current tab rate"); } - }, [url]); - - const [currentStream, setCurrentStream] = useState(null); + }, [currentStream]); useEffect(() => { setCurrentStream( @@ -137,10 +134,12 @@ const Popup = () => { oldKey, newKey, rateAmt, + payWhen, }: { oldKey: string; newKey: string; rateAmt: BigNumber; + payWhen: PayRates; }) => { if (!currentStream) { toast("Couldn't find stream"); @@ -154,17 +153,19 @@ const Popup = () => { oldKey, newKey, rateAmt, + payWhen, }, }); chrome.runtime.sendMessage({ message: UPDATE_STREAM, options: { + from: address, rateAmount: rateAmt, to: currentStream.recipient, tabId, - url, }, }); + setRate({ rateAmount: rateAmt, payWhen }); } catch { toast("Could not update settings"); } @@ -244,6 +245,7 @@ const Popup = () => { '' } > + ~ {ethers.utils.formatUnits( streamedUntilNow(currentStream).sub( streamedUntilNow(currentStream).mod(1e12) @@ -292,16 +294,6 @@ const Popup = () => {
- {rate.rateAmount === constants.Zero ? ( - - ) : null} - ) : null} ) : null} - {!onBlur ? ( - - ) : null}
{value.payWhen === PayRates.BLOCKED ? ( @@ -92,14 +85,15 @@ const Setting = ({ + ) : null}
{value.payWhen !== PayRates.BLOCKED ? ( <> @@ -139,7 +151,7 @@ const Setting = ({ onChange={() => setSetting({ oldKey: skey, - newKey: currentKey, + newKey: skey, rateAmt: currentRateAmt, payWhen: PayRates.ANY, }) @@ -164,7 +176,7 @@ const Setting = ({ onChange={() => setSetting({ oldKey: skey, - newKey: currentKey, + newKey: skey, rateAmt: currentRateAmt, payWhen: PayRates.FOCUS, }) @@ -190,8 +202,8 @@ const Setting = ({ onChange={() => setSetting({ oldKey: skey, - newKey: currentKey, - rateAmt: currentRateAmt, + newKey: skey, + rateAmt: constants.Zero, payWhen: PayRates.BLOCKED, }) } diff --git a/src/pages/Popup/components/StreamComponent.tsx b/src/pages/Popup/components/StreamComponent.tsx index 3d2d5f4..176df4f 100644 --- a/src/pages/Popup/components/StreamComponent.tsx +++ b/src/pages/Popup/components/StreamComponent.tsx @@ -28,27 +28,29 @@ const StreamComponent = ({ >

' } > {" "} - {(+ethers.utils.formatUnits(stream.streamedUntilUpdatedAt)).toFixed(4)} + {(+ethers.utils.formatUnits(stream.streamedUntilUpdatedAt)).toFixed( + 4 + )}{" "} {stream.token.name}

{" "} - {isIn ? "from" : "to"}{" "} + {!isIn ? "from" : "to"}{" "} {stream.addressInOut},{" "} {stream.userData ? "on " : null} {stream.userData ? ( diff --git a/src/pages/Popup/components/ToastHandler.tsx b/src/pages/Popup/components/ToastHandler.tsx index 310b75d..7bb522d 100644 --- a/src/pages/Popup/components/ToastHandler.tsx +++ b/src/pages/Popup/components/ToastHandler.tsx @@ -21,7 +21,10 @@ const ToastHandler = () => { }); return ( -

+
{toasts.map((toast) => (
} /> } /> } /> - } /> } /> } /> diff --git a/src/pages/Popup/lib/getStreams.ts b/src/pages/Popup/lib/getStreams.ts index 2aae6fa..d8dc5d8 100644 --- a/src/pages/Popup/lib/getStreams.ts +++ b/src/pages/Popup/lib/getStreams.ts @@ -2,48 +2,6 @@ import { BigNumber } from "ethers"; import { gql, ApolloClient, InMemoryCache } from "@apollo/client"; import { GraphQlStream } from "../../shared/types"; -const getStreamsDeepIn = async (address: string) => { - const client = new ApolloClient({ - uri: "https://api.thegraph.com/subgraphs/name/superfluid-finance/protocol-v1-goerli", - cache: new InMemoryCache(), - }); - const QUERY = gql` - query GetStreams($address: Bytes!) { - streams(where: { receiver: $address }) { - id - sender - token { - decimals - name - } - streamedUntilUpdatedAt - updatedAtTimestamp - } - } - `; - const result = await client.query< - { - streams: Array; - }, - { address: string } - >({ - query: QUERY, - variables: { address }, - }); - return (result as any).data.streams.map((stream: any) => { - return { - id: stream.id, - streamedUntilUpdatedAt: BigNumber.from(stream.streamedUntilUpdatedAt), - addressInOut: stream.sender, - updatedAtTimestamp: new Date(Number(stream.updatedAtTimestamp * 1000)), - token: { - decimals: Number(stream.token.decimals), - name: stream.token.name, - }, - }; - }) as GraphQlStream[]; -}; - const getStreamsDeepOut = async (address: string) => { const client = new ApolloClient({ uri: "https://api.thegraph.com/subgraphs/name/superfluid-finance/protocol-v1-goerli", @@ -53,10 +11,12 @@ const getStreamsDeepOut = async (address: string) => { query GetStreams($address: Bytes!) { streams(where: { sender: $address }) { id - receiver + receiver { + id + } token { decimals - name + symbol } streamedUntilUpdatedAt updatedAtTimestamp @@ -74,16 +34,16 @@ const getStreamsDeepOut = async (address: string) => { }); return (result as any).data.streams.map((stream: any) => { return { - id: Number(stream.id), + id: stream.id, streamedUntilUpdatedAt: BigNumber.from(stream.streamedUntilUpdatedAt), - addressInOut: stream.receiver, + addressInOut: stream.receiver.id, updatedAtTimestamp: new Date(Number(stream.updatedAtTimestamp * 1000)), token: { decimals: Number(stream.token.decimals), - name: stream.token.name, + name: stream.token.symbol, }, }; }) as GraphQlStream[]; }; -export { getStreamsDeepIn, getStreamsDeepOut }; +export { getStreamsDeepOut }; diff --git a/src/pages/shared/events.ts b/src/pages/shared/events.ts index f425b78..4d68be2 100644 --- a/src/pages/shared/events.ts +++ b/src/pages/shared/events.ts @@ -5,7 +5,6 @@ export const CREATE_STREAM = "streams/create"; export const UPDATE_STREAM = "streams/update"; export const BLOCK_TAG = "settings/block"; export const UPDATE_SETTING = "settings/update"; -export const EDIT_CURRENT_STREAM = "streams/patch"; export const FETCH_BALANCE = "user/fetch-balance"; export const APPROVE_AMT = "user/approve-amt"; export const APPROVE_FULL = "user/approve-full"; diff --git a/worker/src/index.ts b/worker/src/index.ts index 24edbd2..3f764bd 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -60,12 +60,12 @@ const worker = { ); } - const params = new URLSearchParams(request.url); + const params = new URLSearchParams(new URL(request.url).search); const identifier = params.get("identifier"); const address = params.get("address"); if (identifier && address && ethers.utils.isAddress(address)) { - await env.COBWEB_KV.put(identifier, address); + await env.COBWEB_KV.put(address.toLowerCase(), identifier); const total = await env.COBWEB_KV.get("total"); if (!total) { await env.COBWEB_KV.put("total", String(100)); @@ -159,10 +159,10 @@ const worker = { }; const returnUserInformation = async (): Promise => { - const params = new URLSearchParams(request.url); + const params = new URLSearchParams(new URL(request.url).search); const address = params.get("address"); if (address) { - const valid = await env.COBWEB_KV.get(address); + const valid = (await env.COBWEB_KV.get(address.toLowerCase())) !== null; if (env.ENVIRONMENT === "dev") { logger("Requested " + address + ", is " + valid, "GET"); } @@ -176,7 +176,7 @@ const worker = { }; const requestNewUser = async (): Promise => { - const params = new URLSearchParams(request.url); + const params = new URLSearchParams(new URL(request.url).search); const address = params.get("address"); if (address) { const valid = await env.COBWEB_KV.get(address); @@ -194,6 +194,7 @@ const worker = { ], attachments: [], }), + headers: { "Content-Type": "application/json" }, }); if (env.ENVIRONMENT === "dev") { logger("Sent request for " + address + ".", "VERIF"); @@ -217,13 +218,20 @@ const worker = { logger("Request URL:" + request.url, "REQ"); } - const url = new URL(request.url); - if (url.pathname === "/add") { - return addNewUser(); - } else if (url.pathname === "/request") { - return requestNewUser(); - } else { - return returnUserInformation(); + try { + const url = new URL(request.url); + if (url.pathname === "/add") { + return addNewUser(); + } else if (url.pathname === "/request") { + return requestNewUser(); + } else { + return returnUserInformation(); + } + } catch { + return new Response(JSON.stringify({ error: "Unknown error" }), { + ...HEADERS, + status: 500, + }); } }, };