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

feat: optimistic updates #3

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
19 changes: 14 additions & 5 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ function AppContent() {

// Fetch and subscribe to the beast
const beast = useBeast(client);
const warrior = useWarrior(client, address);
const thingBalances = useThingBalances(client);
const { warrior, optimisticallyUpdateWarrior } = useWarrior(client, address);
const { balances, optimisticallyUpdateBalance } = useThingBalances(client);

// Create particles for the background
useEffect(() => {
Expand Down Expand Up @@ -179,6 +179,16 @@ function AppContent() {
return;
}

const unclaimedTokens = warrior.unclaimed_tokens;
optimisticallyUpdateWarrior({
...warrior,
unclaimed_tokens: 0n,
});
optimisticallyUpdateBalance({
account: address,
amount: unclaimedTokens,
});

try {
await account.execute_from_outside([
{
Expand All @@ -187,7 +197,6 @@ function AppContent() {
contractAddress: ACTIONS_ADDRESS,
},
]);

toast.success(`Claimed ${formatEth(warrior.unclaimed_tokens)} $THING`);
} catch (error) {
toast.error("Failed to claim tokens");
Expand All @@ -210,7 +219,7 @@ function AppContent() {
>
{username ? (
<>
{username} ({`${formatEth(thingBalances[address])} $THING`})
{username} ({`${formatEth(balances[address])} $THING`})
</>
) : (
'CLEAR'
Expand Down Expand Up @@ -311,7 +320,7 @@ function AppContent() {
{showLeaderboard && (
<Leaderboard
client={client}
balances={thingBalances}
balances={balances}
onClose={() => setShowLeaderboard(false)}
/>
)}
Expand Down
24 changes: 18 additions & 6 deletions src/hooks/useThingBalances.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ export function useThingBalances(client?: ToriiClient) {
const updateBalance = (balanceData: any) => {
setBalances((prevBalances) => {
const newBalances = { ...prevBalances };
newBalances[balanceData.account.value] = BigInt('0x' + balanceData.amount.value);
newBalances[balanceData.account?.value ?? balanceData.account] = BigInt(
"0x" + (balanceData.amount?.value ?? balanceData.amount)
);
return newBalances;
});
};
Expand All @@ -33,19 +35,29 @@ export function useThingBalances(client?: ToriiClient) {
return;
}

setBalances(prevBalances => {
setBalances((prevBalances) => {
const newBalances = { ...prevBalances };
Object.values(entities).forEach(entity => {
Object.values(entities).forEach((entity) => {
const balanceData = entity["beastslayers-ERC20BalanceModel"] as any;
newBalances[balanceData.account.value] = BigInt('0x' + balanceData.amount.value);
newBalances[balanceData.account.value] = BigInt(
"0x" + balanceData.amount.value
);
});
return newBalances;
});
};

const subscribeToBalance = async () => {
subscription.current = await client.onEntityUpdated(
[{ Keys: { keys: [undefined, undefined], models: ["beastslayers-ERC20BalanceModel"], pattern_matching: "FixedLen" } }],
[
{
Keys: {
keys: [undefined, undefined],
models: ["beastslayers-ERC20BalanceModel"],
pattern_matching: "FixedLen",
},
},
],
(_hashedKeys, models) => {
const updatedBalance = models["beastslayers-ERC20BalanceModel"];
if (updatedBalance) {
Expand All @@ -59,5 +71,5 @@ export function useThingBalances(client?: ToriiClient) {
subscribeToBalance();
}, [client]);

return balances;
return { balances, optimisticallyUpdateBalance: updateBalance };
}
21 changes: 14 additions & 7 deletions src/hooks/useWarrior.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,13 @@ export function useWarrior(client?: ToriiClient, address?: string) {
});
const subscription = useRef<any>();


const updateWarrior = (warriorData: any) => {
setWarrior((oldWarrior) => {
const mappedWarrior = {
address: warriorData.address.value,
level: warriorData.level.value,
score: warriorData.score.value,
unclaimed_tokens: BigInt('0x' +warriorData.unclaimed_tokens.value),
address: warriorData.address?.value ?? warriorData.address,
level: warriorData.level?.value ?? warriorData.level,
score: warriorData.score?.value ?? warriorData.score,
unclaimed_tokens: BigInt("0x" + warriorData.unclaimed_tokens?.value) ?? warriorData.unclaimed_tokens,
};

if (mappedWarrior.level > (oldWarrior?.level || 0)) {
Expand Down Expand Up @@ -65,7 +64,15 @@ export function useWarrior(client?: ToriiClient, address?: string) {

const subscribeToWarrior = async () => {
subscription.current = await client.onEntityUpdated(
[{ Keys: { keys: [address], models: ["beastslayers-Warrior"], pattern_matching: "FixedLen" } }],
[
{
Keys: {
keys: [address],
models: ["beastslayers-Warrior"],
pattern_matching: "FixedLen",
},
},
],
(_hashedKeys, models) => {
const updatedWarrior = models["beastslayers-Warrior"];
if (updatedWarrior) {
Expand All @@ -79,5 +86,5 @@ export function useWarrior(client?: ToriiClient, address?: string) {
subscribeToWarrior();
}, [client, address]);

return warrior;
return { warrior, optimisticallyUpdateWarrior: updateWarrior };
}