Skip to content

Commit

Permalink
add account selector component and error printing to all examples
Browse files Browse the repository at this point in the history
  • Loading branch information
ASAPSegfault committed Feb 7, 2024
1 parent 3a59a72 commit 320a3e7
Show file tree
Hide file tree
Showing 9 changed files with 223 additions and 25 deletions.
23 changes: 23 additions & 0 deletions age/front/react/src/App.css
Original file line number Diff line number Diff line change
Expand Up @@ -148,4 +148,27 @@ button:disabled {
font-weight: bold;
text-align: center;
margin: 2rem;
}

.account-select-container {
display: flex;
flex-direction: column;
align-items: flex-start;
padding: 10px;
}

.account-select-label {
margin-bottom: 8px;
font-weight: bold;
}

.account-select-dropdown {
padding: 8px;
border-radius: 4px;
border: 1px solid #ccc;
outline: none;
width: 100%;
max-width: 300px; /* Adjust based on your layout */
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
cursor: pointer;
}
38 changes: 32 additions & 6 deletions age/front/react/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
const CONTRACT_ADDRESS =
"AS12S1xuDVdpTMGhs19iBo3HXRQqZZaFzSF1hkz1RdF5YxqqVvTnb";
const coins = 0.1;
const minGas = 2100000
const operationDelayNotice =
"If there's no change, please wait a few seconds before clicking again. Confirmation of the operation may take up to 16 seconds.";
const errorMessageNotEnoughBalance = `You need a minimum of ${coins} MAS to set the age.`;
Expand All @@ -25,13 +26,23 @@ enum Provider {
function App() {
const [client, setClient] = useState<Client>();
const [provider, setProvider] = useState<Provider>();
const [account, setAccount] = useState<IAccount>();
const [selectedAccount, setSelectedAccount] = useState<IAccount>();
const [accounts, setAccounts] = useState<IAccount[]>([]);
const [lastOpId, setLastOpId] = useState<string>();
const [ageResult, setAgeResult] = useState<string>();
const [inputAge, setInputAge] = useState<number>(0);
const [inputName, setInputName] = useState<string>();
const [errorMessage, setErrorMessage] = useState<any>();

const selectAccount = async (account: IAccount) => {
if (!provider) return;
const providersList = await providers(true, 10000);
const selectedProvider = providersList.find(p => p.name() === provider);
if (!selectedProvider) return;
setClient(await ClientFactory.fromWalletProvider(selectedProvider, account));
setSelectedAccount(account); // Update the selected account
};

const initialize = async (providerName: Provider) => {
setErrorMessage(null);
const providersList = await providers(true, 10000);
Expand All @@ -56,7 +67,8 @@ function App() {
await ClientFactory.fromWalletProvider(selectedProvider, accounts[0])
);
setProvider(providerName);
setAccount(accounts[0]);
setAccounts(accounts)
setSelectedAccount(accounts[0]);
};

useEffect(() => {
Expand All @@ -76,7 +88,7 @@ function App() {
targetAddress: CONTRACT_ADDRESS,
functionName: "changeAge",
parameter: args,
maxGas: BigInt(1000000),
maxGas: BigInt(minGas),
coins: fromMAS(coins),
fee: BigInt(0),
});
Expand All @@ -97,7 +109,7 @@ function App() {
}
try {
let res = await client.smartContracts().readSmartContract({
maxGas: BigInt(1000000),
maxGas: BigInt(minGas),
targetAddress: CONTRACT_ADDRESS,
targetFunction: "getAge",
parameter: new Args().addString(inputName).serialize(),
Expand All @@ -117,12 +129,26 @@ function App() {
initialize(providerName);
}}
/>
{account && (
{selectedAccount && (
<div className="wrapper">
<h1 className="messageToDisplay">Age Example: React</h1>
<div>
<div className="account-select-container flex w-full gap-4 justify-center items-center">
<label htmlFor="account-selector" className="account-select-label">Select Your Account</label>
<select
id="account-selector"
className="account-select-dropdown"
onChange={(e) => selectAccount(accounts[parseInt(e.target.value)])}
>
{accounts.map((account, index) => (
<option value={index} key={account.address()}>
Account {account.name()} : {account.address().substring(0, 6)}...{account.address().substring(account.address().length - 4)}
</option>
))}
</select>
</div>
<InfoWrapper
address={account.address()}
address={selectedAccount.address()}
provider={provider || ""}
lastOpId={lastOpId}
/>
Expand Down
27 changes: 27 additions & 0 deletions blog/front/react/src/components/AccountSelector.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { useWeb3 } from "../context/web3Context";
import "../css/AccountSelector.css";

export const AccountSelect = () => {
const { accounts, selectAccount } = useWeb3();

if (!accounts || accounts.length === 0) {
return <div>No accounts available</div>;
}

return (
<div className="account-select-container flex w-full gap-4 justify-center items-center">
<label htmlFor="account-selector" className="account-select-label">Select Your Account</label>
<select
id="account-selector"
className="account-select-dropdown"
onChange={(e) => selectAccount(accounts[parseInt(e.target.value)])}
>
{accounts.map((account, index) => (
<option value={index} key={account.address()}>
Account {account.name()} : {account.address().substring(0, 6)}...{account.address().substring(account.address().length - 4)}
</option>
))}
</select>
</div>
);
};
20 changes: 19 additions & 1 deletion blog/front/react/src/components/AddPost.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export const AddPost = ({ fetchPosts }: { fetchPosts: () => void }) => {
const [content, setContent] = useState("");
const [author, setAuthor] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");

const handleSubmit = async () => {
setLoading(true);
Expand Down Expand Up @@ -46,7 +47,11 @@ export const AddPost = ({ fetchPosts }: { fetchPosts: () => void }) => {
console.log("Post not added");
}
} catch (error) {
console.log(error);
const errorMessage = error instanceof Error ? error.message : "An unknown error occurred";
setError(errorMessage);
setTimeout(() => {
setError("");
}, 10000);
} finally {
await fetchPosts();
setLoading(false);
Expand Down Expand Up @@ -139,6 +144,19 @@ export const AddPost = ({ fetchPosts }: { fetchPosts: () => void }) => {
);
}

if (error) {
return (
<div>
<div className="flex flex-col w-full items-start px-4 lg:px-14 underline underline-offset-4 font-Poppins font-bold text-lg text-primary hover:text-primary-focus">
<button onClick={() => setOpen(true)}>Add Post</button>
</div>
<div className="flex flex-col justify-center items-center p-4 text-left text-red-500">
{error}
</div>
</div>
)
}

return (
<div className="flex flex-col w-full items-start px-4 lg:px-14 underline underline-offset-4 font-Poppins font-bold text-lg text-primary hover:text-primary-focus">
<button onClick={() => setOpen(true)}>Add Post</button>
Expand Down
4 changes: 3 additions & 1 deletion blog/front/react/src/components/body.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@ import { Post } from "../const/post";
import { useWeb3 } from "../context/web3Context";
import { getPosts } from "../web3Call/posts";
import { ProviderInfo } from "./ProviderInfo";
import { AccountSelect } from "./AccountSelector";

export default function Body() {
const [posts, setPosts] = useState<Post[]>([]);
const { client } = useWeb3();
const { client, accounts } = useWeb3();
const [loading, setLoading] = useState(false);

useEffect(() => {
Expand All @@ -35,6 +36,7 @@ export default function Body() {
<div className="body flex-col justify-center align-middle">
<div className="flex-col">
<ProviderSelect />
{accounts && (<AccountSelect />)}
<ProviderInfo />
{client && (
<>
Expand Down
25 changes: 20 additions & 5 deletions blog/front/react/src/context/web3Context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ import { Provider } from "../const";
const Web3Context = createContext<
| {
client?: IClient;
account?: IAccount;
selectedAccount?: IAccount;
accounts?: IAccount[];
provider?: Provider;
providerAddress?: string;
providerName?: string;
initialize: (providerName: Provider) => void;
selectAccount: (acccount: IAccount) => void;
errorMessage?: string;
}
| undefined
Expand All @@ -22,9 +24,10 @@ type TabProviderProps = {

export const Web3Provider: FC<TabProviderProps> = ({ children }) => {
const [client, setClient] = useState<IClient>();
const [account, setAccount] = useState<IAccount>();
const [accounts, setAccounts] = useState<IAccount[]>([]);
const [selectedAccount, setSelectedAccount] = useState<IAccount>();
const [provider, setProvider] = useState<Provider>();
const providerAddress = account?.address() || "";
const providerAddress = selectedAccount?.address() || "";
const providerName = provider || "";
const [errorMessage, setErrorMessage] = useState<string>("");

Expand Down Expand Up @@ -52,22 +55,34 @@ export const Web3Provider: FC<TabProviderProps> = ({ children }) => {
await ClientFactory.fromWalletProvider(selectedProvider, accounts[0])
);
setProvider(providerName);
setAccount(accounts[0]);
setAccounts(accounts)
setSelectedAccount(accounts[0]);
};

useEffect(() => {
initialize(Provider.MASSASTATION);
}, []);

const selectAccount = async (account: IAccount) => {
if (!provider) return;
const providersList = await providers(true, 10000);
const selectedProvider = providersList.find(p => p.name() === provider);
if (!selectedProvider) return;
setClient(await ClientFactory.fromWalletProvider(selectedProvider, account));
setSelectedAccount(account);
};

return (
<Web3Context.Provider
value={{
client,
account,
accounts,
selectedAccount,
provider,
providerAddress,
providerName,
initialize,
selectAccount,
errorMessage,
}}
>
Expand Down
22 changes: 22 additions & 0 deletions blog/front/react/src/css/AccountSelector.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
.account-select-container {
display: flex;
flex-direction: column;
align-items: flex-start;
padding: 10px;
}

.account-select-label {
margin-bottom: 8px;
font-weight: bold;
}

.account-select-dropdown {
padding: 8px;
border-radius: 4px;
border: 1px solid #ccc;
outline: none;
width: 100%;
max-width: 300px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
cursor: pointer;
}
28 changes: 28 additions & 0 deletions helloworld/front/react/src/App.css
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,32 @@

.message-display {
margin-left: 20px; /* Adjust the left margin as needed */
}

.account-select-container {
display: flex;
flex-direction: column;
align-items: flex-start;
padding: 10px;
}

.account-select-label {
margin-bottom: 8px;
font-weight: bold;
}

.account-select-dropdown {
padding: 8px;
border-radius: 4px;
border: 1px solid #ccc;
outline: none;
width: 100%;
max-width: 300px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
cursor: pointer;
}

.error {
color: red;
text-align: center;
}
Loading

0 comments on commit 320a3e7

Please sign in to comment.