Skip to content

Commit

Permalink
Merge pull request #206 from polywrap/release/dev
Browse files Browse the repository at this point in the history
Release Feb 20th
  • Loading branch information
dOrgJelli committed Feb 20, 2024
2 parents cf46438 + 6ba083c commit c3b073b
Show file tree
Hide file tree
Showing 10 changed files with 141 additions and 82 deletions.
26 changes: 18 additions & 8 deletions web/app/s/[id]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Disclaimer from "@/components/Disclaimer";
import RealtimeLogs from "@/components/RealtimeLogs";
import Strategy from "@/components/Strategy";
import NoResultsFound from "@/components/NoResultsFound";
import {
StrategiesWithProjects,
Application,
Expand Down Expand Up @@ -107,12 +108,21 @@ export default async function StrategyPage({
const uniqueNetworks = Array.from(
new Set(strategies.map((x) => x.networks).flat())
);
return (
<Strategy
fetchedStrategies={strategies}
prompt={run.data.prompt}
runId={run.data.id}
networks={uniqueNetworks}
/>
);

if (strategies.length > 0) {
return (
<Strategy
fetchedStrategies={strategies}
prompt={run.data.prompt}
runId={run.data.id}
networks={uniqueNetworks}
/>
);
} else {
return (
<NoResultsFound
prompt={run.data.prompt}
/>
);
}
}
1 change: 1 addition & 0 deletions web/components/Button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ const Button = ({
return (
<Popover className='relative'>
<Popover.Button
disabled={disabled}
className={clsx(
"text-shadow-md relative inline-flex items-center justify-center space-x-2 rounded-full border-2 transition-all duration-500",
hierarchyClasses[hierarchy],
Expand Down
58 changes: 58 additions & 0 deletions web/components/NoResultsFound.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
"use client";

import { useState } from "react";
import TextField from "./TextField";
import { useRouter } from "next/navigation";
import useSession from "@/hooks/useSession";
import { startRun } from "@/app/actions";
import ChatInputButton from "./ChatInputButton";

export default function NoResultsFound(props: {
prompt: string;
}) {
const [currentPrompt, setCurrentPrompt] = useState<string>(props.prompt);
const [isRegenerating, setIsRegenerating] = useState(false);
const { data: session } = useSession();
const router = useRouter();

async function regenerateStrat(prompt: string) {
setIsRegenerating(true);
if (!session) {
throw new Error("User needs to have a session");
}
const response = await startRun(prompt, session.supabaseAccessToken);
router.push(`/s/${response.runId}`);
setIsRegenerating(false);
}

return (
<>
<div className='flex justify-center py-10 px-6 flex-grow flex-column'>
<div className='flex flex-col mx-auto max-w-wrapper w-full space-y-4'>
<TextField
label={`No results found for ${props.prompt}, try again...`}
value={currentPrompt}
onChange={(e) => setCurrentPrompt(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !!currentPrompt) {
regenerateStrat(currentPrompt);
}
}}
rightAdornment={
<ChatInputButton
running={isRegenerating}
message={currentPrompt}
regenerate
handleSend={async () => {
if (currentPrompt) {
await regenerateStrat(currentPrompt);
}
}}
/>
}
/>
</div>
</div>
</>
)
}
12 changes: 2 additions & 10 deletions web/components/RealtimeLogs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,7 @@ export default function RealtimeLogs(props: {
});
const progressInformation = useProgressTime(
Object.values(STEP_TIME_ESTS),
sortedLogsWithSteps,
props.run.prompt
sortedLogsWithSteps
);

const supabase = createSupabaseBrowserClient(
Expand All @@ -73,17 +72,10 @@ export default function RealtimeLogs(props: {
},
(payload) => {
if (payload.new.status === "ERRORED") {
router.refresh();
setHasErrored(true);
return;
}

if (
payload.new.step_name === "SYNTHESIZE_RESULTS" &&
payload.new.status === "COMPLETED"
) {
router.refresh();
}
router.refresh();
}
)
.subscribe();
Expand Down
2 changes: 1 addition & 1 deletion web/components/Strategy.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ export default function Strategy(props: {
</div>
<Button
disabled={
selectedStrategiesLength === 0 || amount === "0" || amount === ""
selectedStrategiesLength === 0 || amount === "0" || amount === "" || isTransactionPending
}
onClick={executeTransaction}>
{isTransactionPending ? (
Expand Down
14 changes: 11 additions & 3 deletions web/components/StrategyTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,12 @@ const InputWithTooltip = forwardRef(
)
);

declare global {
interface Window {
getSelection: () => Selection | null;
}
}

function WeightInput({
selected,
index,
Expand Down Expand Up @@ -106,7 +112,10 @@ export function StrategyTable(props: StrategiesHandler & { network: NetworkName
.filter((s) => !s.disabled)
.some((s) => s.selected);

function openProjectDetails(strategy: StrategyInformation) {
function openProjectDetails(strategy: StrategyInformation){
// Do not open the project details if the user is trying to select the project
if (window.getSelection()?.type === "Range") return;

setShowStrategyDetails({
show: true,
strategy,
Expand Down Expand Up @@ -155,7 +164,6 @@ export function StrategyTable(props: StrategiesHandler & { network: NetworkName
);
};


return (
<>
<div className='space-y-2'>
Expand Down Expand Up @@ -188,7 +196,7 @@ export function StrategyTable(props: StrategiesHandler & { network: NetworkName
className={clsx(
"bg-indigo-50 border-2 border-indigo-300 hover:bg-white transition-colors duration-200 w-full rounded-2xl shadow-sm hover:shadow-lg shadow-primary-shadow/20 p-4 col-span-12 space-y-3 cursor-pointer"
)}
onClick={() => openProjectDetails(entry)}>
onClick={(e) => openProjectDetails(entry)}>
<div className='grid gap-4 grid-cols-12'>
<div className='flex space-x-4 items-center w-full col-span-12 md:col-span-6'>
<div
Expand Down
2 changes: 1 addition & 1 deletion web/components/TimeRemaining.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ function formatTime(seconds: number) {
const roundedSeconds = Math.round(seconds);
const minutes = Math.floor(roundedSeconds / 60);
const secs = roundedSeconds % 60;
const timeRemaining = seconds ? `${minutes}:${secs.toString().padStart(2, "0")}` : "1:40"
const timeRemaining = seconds ? `${minutes}:${secs.toString().padStart(2, "0")}` : "1:10"
return `Estimated time: ~${timeRemaining}`
}

Expand Down
34 changes: 21 additions & 13 deletions web/hooks/useDonation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,18 +38,20 @@ export function useDonation() {
setIsTransactionPending(true);

const { network: selectedNetwork, token: selectedToken, donations } = plan;
const filteredDonations = donations.filter((d) => Number(d.amount) > 0);

const token = getTokensForNetwork(selectedNetwork).find(
(t) => t.name == selectedToken.name
);

if (!token) {
throw new Error(`Token with name: ${selectedToken} is not valid`);
}
const amounts = donations.map((d) => Number(d.amount));
const amounts = filteredDonations.map((d) => Number(d.amount));
console.log(plan, amounts, signer, token);
try {
await splitTransferFunds(
donations.map((d) => d.recipient),
filteredDonations.map((d) => d.recipient),
amounts,
signer,
selectedNetwork,
Expand Down Expand Up @@ -97,17 +99,23 @@ export function useDonation() {
amount: string,
network: NetworkName
) => {
const ethersProvider = new ethers.providers.Web3Provider(
wallet.provider,
"any"
);
const signer = ethersProvider.getSigner();
const tokenContract = new ethers.Contract(token.address, ERC20_ABI, signer);

const contractAddress = DISPERSE_CONTRACT_ADDRESSES[network];
const amountInDecimals = ethers.utils.parseUnits(amount.toString(), token.decimals);
const approveTx = await tokenContract.approve(contractAddress, amountInDecimals);
await approveTx.wait(1);
setIsTransactionPending(true);

try {
const ethersProvider = new ethers.providers.Web3Provider(
wallet.provider,
"any"
);
const signer = ethersProvider.getSigner();
const tokenContract = new ethers.Contract(token.address, ERC20_ABI, signer);

const contractAddress = DISPERSE_CONTRACT_ADDRESSES[network];
const amountInDecimals = ethers.utils.parseUnits(amount.toString(), token.decimals);
const approveTx = await tokenContract.approve(contractAddress, amountInDecimals);
await approveTx.wait(1);
} finally {
setIsTransactionPending(false);
}
};

return {
Expand Down
66 changes: 24 additions & 42 deletions web/hooks/useProgressTime.ts
Original file line number Diff line number Diff line change
@@ -1,74 +1,56 @@
import { Tables } from "@/supabase/dbTypes";
import { COMPLETED_TEXTS } from "@/utils/logs";
import { useState, useEffect } from "react";

export function useProgressTime(
stepTimes: number[],
logs: Array<Tables<"logs">>,
prompt: string,
logs: Array<Tables<"logs">>
) {
const [startTime] = useState(Date.now());
const [startTime, setStartTime] = useState(Date.now());
const [progressInformation, setProgressInformation] = useState({
logs,
time: 0,
progress: 0,
});

// Capture the start time when the hook is first called or when stepTimes or currentStep changes
const totalTime = stepTimes.reduce((a, b) => a + b, 0);
let currentStep = logs.findIndex(
(x) => x.status === "IN_PROGRESS"
);

useEffect(() => {
const totalTime = stepTimes.reduce((a, b) => a + b, 0);
setStartTime(Date.now())
}, [currentStep])

useEffect(() => {
const intervalId = setInterval(function () {
const now = Date.now();
const secondsFromStart = (now - startTime) / 1000; // Convert ms to seconds
let currentStep = progressInformation.logs.findIndex(
(x) => x.status === "IN_PROGRESS"
);
const elapsedTimeSinceStart = (now - startTime) / 1000; // Convert ms to seconds

if (elapsedTimeSinceStart > stepTimes[currentStep]) {
return
}

const elapsedTimeInSteps = stepTimes
.slice(0, currentStep + 1)
.slice(0, currentStep)
.reduce((a, b) => a + b, 0);

const timeRemaining = Math.max(totalTime - secondsFromStart, 0);

const progress = (secondsFromStart / totalTime) * 100;
if (timeRemaining <= 1) {
clearInterval(intervalId);
return;
}
const totalElapsedTime = elapsedTimeSinceStart + elapsedTimeInSteps;

if (
secondsFromStart > elapsedTimeInSteps &&
stepTimes.length > currentStep &&
currentStep !== -1
) {
setProgressInformation(({ logs }) => {
const newLogs = [...logs];
newLogs[currentStep].status = "COMPLETED";
newLogs[currentStep].value = COMPLETED_TEXTS[newLogs[currentStep].step_name]
if (currentStep === 0) {
newLogs[currentStep].value += " to " + prompt
}
const timeRemaining = Math.max(totalTime - totalElapsedTime, 0); // Prevent negative time
const progress = (totalElapsedTime / totalTime) * 100;

if (stepTimes.length > currentStep + 1) {
newLogs[currentStep + 1].status = "IN_PROGRESS";
}
return {
time: timeRemaining,
progress: progress,
logs: newLogs,
};
});
return;
if (timeRemaining < 1) {
return
}

setProgressInformation((i) => ({
...i,
time: timeRemaining,
progress: progress,
}));

}, 1000);
return () => clearInterval(intervalId);
}, [stepTimes]);
}, [stepTimes, currentStep]);

return progressInformation;
}
8 changes: 4 additions & 4 deletions web/utils/logs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ export const STEPS_ORDER: Record<StepName, number> = {
}

export const STEP_TIME_ESTS: Record<StepName, number> = {
FETCH_PROJECTS: 30,
EVALUATE_PROJECTS: 30,
ANALYZE_FUNDING: 30,
SYNTHESIZE_RESULTS: 10
FETCH_PROJECTS: 35,
EVALUATE_PROJECTS: 15,
ANALYZE_FUNDING: 5,
SYNTHESIZE_RESULTS: 15
}

0 comments on commit c3b073b

Please sign in to comment.