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

intro-to-solana-mobile.md - refactor: optimize counter increment logic and notification handling #355

Closed
Changes from 2 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
72 changes: 46 additions & 26 deletions content/courses/mobile/intro-to-solana-mobile.md
Original file line number Diff line number Diff line change
Expand Up @@ -1008,11 +1008,28 @@ export function CounterView() {
const { program, counterAddress } = useProgram();
const [counter, setCounter] = useState<CounterAccount>();

// Fetch Counter Info
useEffect(() => {
if (!program || !counterAddress) return;
if (!program || !counterAddress) {
console.log("Missing dependencies:", {
program: Boolean(program) ? "Program Loaded" : "Program Not loaded",
counterAddress: Boolean(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,
Expand All @@ -1023,8 +1040,8 @@ export function CounterView() {
accountInfo.data,
);
setCounter(data);
} catch (e) {
console.log("account decoding error: " + e);
} catch (error) {
console.error("Account decoding error:", error);
}
},
);
Expand Down Expand Up @@ -1109,7 +1126,7 @@ export function CounterButton() {
const { connection } = useConnection();
const [isTransactionInProgress, setIsTransactionInProgress] = useState(false);

const showToastOrAlert = (message: string) => {
const showNotification = (message: string) => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This does not show notifications.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this does show notification. can you please elaborate on this review

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does it create one of these?

image

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It creates these instead:
alert_example_ios
alert_example_android

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's not a 'notification' then. The word notification has a very specific meaning on mobile. Please change the function name.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changed to showMessage()

if (Platform.OS === "android") {
ToastAndroid.show(message, ToastAndroid.SHORT);
} else {
Expand All @@ -1118,53 +1135,56 @@ export function CounterButton() {
};

const incrementCounter = () => {
if (!program || !counterAddress) return;
if (!program || !counterAddress) {
console.log("Missing program or counterAddress.");
return;
}

if (!isTransactionInProgress) {
if (isTransactionInProgress) return;

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);
mikemaccana marked this conversation as resolved.
Show resolved Hide resolved
}
};

Expand Down
Loading