From 7763b19ab3b80cc242ddbed194474af0d5715a24 Mon Sep 17 00:00:00 2001 From: Onyewuchi Emeka Date: Tue, 27 Aug 2024 05:03:31 +0100 Subject: [PATCH 1/3] refactor: optimize counter increment logic and notification handling - Refactored showToastOrAlert to showNotification for better clarity. - Improved async/await usage with consistent error handling using try/catch. - Added detailed logging for missing program or counterAddress. - Cleaned up and grouped logic for better readability and maintainability. - Ensured balance checks and airdrop requests are well-handled during transactions. --- .../courses/mobile/intro-to-solana-mobile.md | 79 +++++++++++-------- 1 file changed, 48 insertions(+), 31 deletions(-) diff --git a/content/courses/mobile/intro-to-solana-mobile.md b/content/courses/mobile/intro-to-solana-mobile.md index 0f8b33b21..106967c3b 100644 --- a/content/courses/mobile/intro-to-solana-mobile.md +++ b/content/courses/mobile/intro-to-solana-mobile.md @@ -1008,11 +1008,27 @@ export function CounterView() { const { program, counterAddress } = useProgram(); const [counter, setCounter] = useState(); - // Fetch Counter Info useEffect(() => { - if (!program || !counterAddress) return; + if (!program || !counterAddress) { + console.log("Missing dependencies:", { + program: !!program ? "Program Loaded" : "Program Not loaded", + counterAddress: !!counterAddress + ? "Counter Address Loaded" + : "Counter Address Not loaded", + }); + return; + } - program.account.counter.fetch(counterAddress).then(setCounter); + const fetchCounter = async () => { + try { + const counterData = await program.account.counter.fetch(counterAddress); + setCounter(counterData); + } catch (error) { + console.error("Failed to fetch counter:", error); + } + }; + + fetchCounter(); const subscriptionId = connection.onAccountChange( counterAddress, @@ -1023,8 +1039,8 @@ export function CounterView() { accountInfo.data, ); setCounter(data); - } catch (e) { - console.log("account decoding error: " + e); + } catch (error) { + console.error("Account decoding error:", error); } }, ); @@ -1109,62 +1125,63 @@ export function CounterButton() { const { connection } = useConnection(); const [isTransactionInProgress, setIsTransactionInProgress] = useState(false); - const showToastOrAlert = (message: string) => { - if (Platform.OS === "android") { - ToastAndroid.show(message, ToastAndroid.SHORT); - } else { - Alert.alert(message); - } + const showNotification = (message: string) => { + Platform.OS === "android" + ? ToastAndroid.show(message, ToastAndroid.SHORT) + : Alert.alert(message); }; const incrementCounter = () => { - if (!program || !counterAddress) return; + if (!program || !counterAddress) { + console.log("Missing program or counterAddress."); + return; + } + + if (isTransactionInProgress) return; - if (!isTransactionInProgress) { + try { setIsTransactionInProgress(true); - transact(async (wallet: Web3MobileWallet) => { + await transact(async (wallet: Web3MobileWallet) => { const authResult = await authorizeSession(wallet); - const latestBlockhashResult = await connection.getLatestBlockhash(); + const { blockhash, lastValidBlockHeight } = + await connection.getLatestBlockhash(); - const ix = await program.methods + const incrementInstruction = await program.methods .increment() .accounts({ counter: counterAddress, user: authResult.publicKey }) .instruction(); const balance = await connection.getBalance(authResult.publicKey); - console.log( `Wallet ${authResult.publicKey} has a balance of ${balance}`, ); - // When on Devnet you may want to transfer SOL manually per session, due to Devnet's airdrop rate limit const minBalance = LAMPORTS_PER_SOL / 1000; - if (balance < minBalance) { console.log( - `requesting airdrop for ${authResult.publicKey} on ${connection.rpcEndpoint}`, + `Requesting airdrop for ${authResult.publicKey} on ${connection.rpcEndpoint}`, ); await connection.requestAirdrop(authResult.publicKey, minBalance * 2); } const transaction = new Transaction({ - ...latestBlockhashResult, feePayer: authResult.publicKey, - }).add(ix); + blockhash, + lastValidBlockHeight, + }).add(incrementInstruction); + const signature = await wallet.signAndSendTransactions({ transactions: [transaction], }); - showToastOrAlert(`Transaction successful! ${signature}`); - }) - .catch(e => { - console.log(e); - showToastOrAlert(`Error: ${JSON.stringify(e)}`); - }) - .finally(() => { - setIsTransactionInProgress(false); - }); + showNotification(`Transaction successful! ${signature}`); + }); + } catch (error) { + console.error("Transaction failed:", error); + showNotification(`Error: ${JSON.stringify(error)}`); + } finally { + setIsTransactionInProgress(false); } }; From 887109e17285a54630a38116776038406c52bde4 Mon Sep 17 00:00:00 2001 From: Onyewuchi Emeka Date: Wed, 4 Sep 2024 21:26:36 +0100 Subject: [PATCH 2/3] chore(): fixed PR issues --- content/courses/mobile/intro-to-solana-mobile.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/content/courses/mobile/intro-to-solana-mobile.md b/content/courses/mobile/intro-to-solana-mobile.md index 106967c3b..aa84e6bed 100644 --- a/content/courses/mobile/intro-to-solana-mobile.md +++ b/content/courses/mobile/intro-to-solana-mobile.md @@ -1011,13 +1011,14 @@ export function CounterView() { useEffect(() => { if (!program || !counterAddress) { console.log("Missing dependencies:", { - program: !!program ? "Program Loaded" : "Program Not loaded", - counterAddress: !!counterAddress + program: Boolean(program) ? "Program Loaded" : "Program Not loaded", + counterAddress: Boolean(counterAddress) ? "Counter Address Loaded" : "Counter Address Not loaded", }); return; } + }); const fetchCounter = async () => { try { @@ -1126,9 +1127,11 @@ export function CounterButton() { const [isTransactionInProgress, setIsTransactionInProgress] = useState(false); const showNotification = (message: string) => { - Platform.OS === "android" - ? ToastAndroid.show(message, ToastAndroid.SHORT) - : Alert.alert(message); + if (Platform.OS === "android") { + ToastAndroid.show(message, ToastAndroid.SHORT); + } else { + Alert.alert(message); + } }; const incrementCounter = () => { From a9991cd5aa53aca89752bd38736b5e71e66ca8cb Mon Sep 17 00:00:00 2001 From: Onyewuchi Emeka Date: Thu, 12 Sep 2024 22:44:27 +0100 Subject: [PATCH 3/3] fix(): changed function name to ensure better clarity --- content/courses/mobile/intro-to-solana-mobile.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/content/courses/mobile/intro-to-solana-mobile.md b/content/courses/mobile/intro-to-solana-mobile.md index aa84e6bed..50d8c4cee 100644 --- a/content/courses/mobile/intro-to-solana-mobile.md +++ b/content/courses/mobile/intro-to-solana-mobile.md @@ -1126,7 +1126,7 @@ export function CounterButton() { const { connection } = useConnection(); const [isTransactionInProgress, setIsTransactionInProgress] = useState(false); - const showNotification = (message: string) => { + const showMessage = (message: string) => { if (Platform.OS === "android") { ToastAndroid.show(message, ToastAndroid.SHORT); } else { @@ -1178,11 +1178,11 @@ export function CounterButton() { transactions: [transaction], }); - showNotification(`Transaction successful! ${signature}`); + showMessage(`Transaction successful! ${signature}`); }); } catch (error) { console.error("Transaction failed:", error); - showNotification(`Error: ${JSON.stringify(error)}`); + showMessage(`Error: ${JSON.stringify(error)}`); } finally { setIsTransactionInProgress(false); }