Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use beta-5 wallet connector UI #41

Merged
merged 7 commits into from
Feb 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4,018 changes: 492 additions & 3,526 deletions app/package-lock.json

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,17 @@
"dependencies": {
"@emotion/react": "^11.11.0",
"@emotion/styled": "^11.11.0",
"@fuel-ui/css": "^0.21",
"@fuel-wallet/react": "^0.13",
"@fuel-wallet/sdk": "^0.13",
"@fuel-ui/css": "^0.23",
"@fuel-wallet/react": "^0.15.2",
"@fuel-wallet/sdk": "^0.15.2",
"@mui/base": "^5.0.0-beta.2",
"@mui/icons-material": "^5.11.16",
"@mui/lab": "^5.0.0-alpha.46",
"@mui/material": "^5.13.2",
"@tanstack/react-query": "^4.24.9",
"ace-builds": "^1.22.0",
"ansicolor": "^1.1.100",
"fuels": "^0.69",
"fuels": "^0.74",
"react": "^18.2.0",
"react-ace": "^10.1.0",
"react-dom": "^18.2.0",
Expand Down
6 changes: 5 additions & 1 deletion app/src/features/editor/hooks/useCompile.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import styled from '@emotion/styled';
import ansicolor from 'ansicolor';
import React, { useState, useEffect } from 'react';
import { saveAbi, saveBytecode, saveStorageSlots } from '../../../utils/localStorage';
import {
saveAbi,
saveBytecode,
saveStorageSlots,
} from '../../../utils/localStorage';
import { CopyableHex } from '../../../components/shared';
import { Toolchain } from '../components/ToolchainDropdown';

Expand Down
2 changes: 1 addition & 1 deletion app/src/features/interact/hooks/useContract.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useQuery } from '@tanstack/react-query';
import { useWallet } from '../../toolbar/hooks/useWallet';
import { useWallet } from '@fuel-wallet/react';
import { Contract, Interface } from 'fuels';
import { loadAbi } from '../../../utils/localStorage';

Expand Down
48 changes: 21 additions & 27 deletions app/src/features/toolbar/components/ActionToolbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@ import { DeployState } from '../../../utils/types';
import { DeploymentButton } from './DeploymentButton';
import CompileButton from './CompileButton';
import SecondaryButton from '../../../components/SecondaryButton';
import { useFuel } from '@fuel-wallet/react';
import { loadAbi, loadBytecode, loadStorageSlots } from '../../../utils/localStorage';
import {
loadAbi,
loadBytecode,
loadStorageSlots,
} from '../../../utils/localStorage';

export interface ActionToolbarProps {
deployState: DeployState;
Expand All @@ -29,8 +32,6 @@ function ActionToolbar({
setDrawerOpen,
updateLog,
}: ActionToolbarProps) {
const { fuel } = useFuel();

return (
<div
style={{
Expand All @@ -44,28 +45,17 @@ function ActionToolbar({
disabled={isCompiled === true || deployState === DeployState.DEPLOYING}
tooltip='Compile sway code'
/>
{!fuel ? (
<SecondaryButton
header={true}
onClick={() =>
window.open('https://wallet.fuel.network/docs/install/', '_blank')
}
text='INSTALL'
tooltip={'Install the fuel wallet to deploy contracts'}
/>
) : (
<DeploymentButton
abi={loadAbi()}
bytecode={loadBytecode()}
storageSlots={loadStorageSlots()}
isCompiled={isCompiled}
setContractId={setContractId}
deployState={deployState}
setDeployState={setDeployState}
setDrawerOpen={setDrawerOpen}
updateLog={updateLog}
/>
)}
<DeploymentButton
abi={loadAbi()}
bytecode={loadBytecode()}
storageSlots={loadStorageSlots()}
isCompiled={isCompiled}
setContractId={setContractId}
deployState={deployState}
setDeployState={setDeployState}
setDrawerOpen={setDrawerOpen}
updateLog={updateLog}
/>
<SecondaryButton
header={true}
onClick={() => setDrawerOpen(!drawerOpen)}
Expand All @@ -80,7 +70,11 @@ function ActionToolbar({
<SecondaryButton
header={true}
onClick={() =>
window.open('https://docs.fuel.network/docs/sway', '_blank', 'noreferrer')
window.open(
'https://docs.fuel.network/docs/sway',
'_blank',
'noreferrer'
)
}
text='DOCS'
tooltip={'Open documentation for Sway in a new tab'}
Expand Down
44 changes: 30 additions & 14 deletions app/src/features/toolbar/components/DeploymentButton.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import React, { useCallback, useMemo } from 'react';
import { DeployState } from '../../../utils/types';
import { useDeployContract } from '../hooks/useDeployContract';
import {
DeployContractData,
useDeployContract,
} from '../hooks/useDeployContract';
import SecondaryButton from '../../../components/SecondaryButton';
import { ButtonSpinner } from '../../../components/shared';
import { useProvider } from '@fuel-wallet/react';
import { useConnectIfNotAlready } from '../hooks/useConnectIfNotAlready';

interface DeploymentButtonProps {
abi: string;
Expand All @@ -28,9 +31,7 @@ export function DeploymentButton({
setDrawerOpen,
updateLog,
}: DeploymentButtonProps) {
const { provider } = useProvider();

const networkUrl = provider?.url;
const { connectIfNotAlready, isConnected } = useConnectIfNotAlready();

const handleError = useCallback(
(error: Error) => {
Expand All @@ -41,13 +42,13 @@ export function DeploymentButton({
);

const handleSuccess = useCallback(
(data: any) => {
({ contractId, networkUrl }: DeployContractData) => {
setDeployState(DeployState.DEPLOYED);
setContractId(data);
setContractId(contractId);
setDrawerOpen(true);
updateLog(`Contract was successfully deployed to ${networkUrl}`);
},
[setContractId, setDeployState, setDrawerOpen, updateLog, networkUrl]
[setContractId, setDeployState, setDrawerOpen, updateLog]
);

const deployContractMutation = useDeployContract(
Expand All @@ -56,17 +57,32 @@ export function DeploymentButton({
storageSlots,
handleError,
handleSuccess,
updateLog,
// Only attempt to fetch the wallet after the deploy button has been clicked. This prevents
// the wallet from opening when the page first loads.
deployState === DeployState.NOT_DEPLOYED
updateLog
);

const onDeployClick = useCallback(async () => {
const handleDeploy = useCallback(async () => {
updateLog(`Deploying contract...`);
setDeployState(DeployState.DEPLOYING);
deployContractMutation.mutate();
}, [deployContractMutation, setDeployState, updateLog]);
}, [updateLog, setDeployState, deployContractMutation]);

const handleConnectionFailed = useCallback(
async () => handleError(new Error('Failed to connect to wallet.')),
[handleError]
);

const onDeployClick = useCallback(async () => {
if (!isConnected) {
updateLog(`Connecting to wallet...`);
}
await connectIfNotAlready(handleDeploy, handleConnectionFailed);
}, [
isConnected,
updateLog,
connectIfNotAlready,
handleDeploy,
handleConnectionFailed,
]);

const { isDisabled, tooltip } = useMemo(() => {
switch (deployState) {
Expand Down
43 changes: 43 additions & 0 deletions app/src/features/toolbar/hooks/useConnectIfNotAlready.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { useConnectUI, useWallet } from '@fuel-wallet/react';
import { useCallback, useMemo, useEffect, useRef } from 'react';

export function useConnectIfNotAlready() {
const connectedCallbackRef = useRef<(() => Promise<void>) | null>(null);
const failedCallbackRef = useRef<(() => Promise<void>) | null>(null);
const { connect, isError, isConnecting } = useConnectUI();
const { wallet } = useWallet();
const isConnected = useMemo(() => !!wallet, [wallet]);

const connectIfNotAlready = useCallback(
(
connectedCallback: () => Promise<void>,
failedCallback: () => Promise<void>
) => {
connectedCallbackRef.current = connectedCallback;
failedCallbackRef.current = failedCallback;

if (!isConnected && !isConnecting) {
connect();
} else {
connectedCallback();
}
},
[connect, isConnected, isConnecting]
);

useEffect(() => {
if (connectedCallbackRef.current && isConnected) {
connectedCallbackRef.current();
connectedCallbackRef.current = null;
}
}, [isConnected, connectedCallbackRef]);

useEffect(() => {
if (failedCallbackRef.current && isError) {
failedCallbackRef.current();
failedCallbackRef.current = null;
}
}, [isError, failedCallbackRef]);

return { connectIfNotAlready, isConnected };
}
49 changes: 30 additions & 19 deletions app/src/features/toolbar/hooks/useDeployContract.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,28 @@
import { ContractFactory, JsonAbi, StorageSlot } from 'fuels';
import { useMutation } from '@tanstack/react-query';
import { useWallet } from './useWallet';
import { useFuel, useWallet } from '@fuel-wallet/react';

const DEPLOYMENT_TIMEOUT_MS = 120000;

export interface DeployContractData {
contractId: string;
networkUrl: string;
}

export function useDeployContract(
abi: string,
bytecode: string,
storageSlots: string,
onError: (error: any) => void,
onSuccess: (data: any) => void,
updateLog: (entry: string) => void,
isDisabled: boolean
updateLog: (entry: string) => void
) {
const { wallet, isLoading: walletIsLoading } = useWallet(isDisabled);
const { wallet, isLoading: walletIsLoading } = useWallet();
const { fuel } = useFuel();

const mutation = useMutation(
async () => {
const network = await fuel.currentNetwork();
if (!wallet) {
if (walletIsLoading) {
updateLog('Connecting to wallet...');
Expand All @@ -25,22 +31,27 @@ export function useDeployContract(
}
}

const contractIdPromise = new Promise(async (resolve, reject) => {
const contractFactory = new ContractFactory(
bytecode,
JSON.parse(abi) as JsonAbi,
wallet
);
const resultPromise = new Promise(
async (resolve: (data: DeployContractData) => void, reject) => {
const contractFactory = new ContractFactory(
bytecode,
JSON.parse(abi) as JsonAbi,
wallet
);

try {
const contract = await contractFactory.deployContract({
storageSlots: JSON.parse(storageSlots) as StorageSlot[],
});
resolve(contract.id.toB256());
} catch (error) {
reject(error);
try {
const contract = await contractFactory.deployContract({
storageSlots: JSON.parse(storageSlots) as StorageSlot[],
});
resolve({
contractId: contract.id.toB256(),
networkUrl: network.url,
});
} catch (error) {
reject(error);
}
}
});
);

const timeoutPromise = new Promise((_resolve, reject) =>
setTimeout(
Expand All @@ -56,7 +67,7 @@ export function useDeployContract(
)
);

return await Promise.race([contractIdPromise, timeoutPromise]);
return await Promise.race([resultPromise, timeoutPromise]);
},
{
// Retry once if the wallet is still loading.
Expand Down
36 changes: 0 additions & 36 deletions app/src/features/toolbar/hooks/useWallet.ts

This file was deleted.

Loading