Skip to content

Commit

Permalink
Improved Snap code and flow
Browse files Browse the repository at this point in the history
  • Loading branch information
Montoya committed Apr 2, 2024
1 parent 61f7bc6 commit c05d83c
Show file tree
Hide file tree
Showing 9 changed files with 131 additions and 50 deletions.
30 changes: 13 additions & 17 deletions packages/site/src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -135,10 +135,7 @@ const Index = () => {
params: {
snapId: defaultSnapOrigin,
request: {
method: 'setLxpAddress',
params: {
lxpAddress: lxpAddressValue,
},
method: 'watchLxpAddress',
},
},
});
Expand Down Expand Up @@ -299,15 +296,11 @@ const Index = () => {
)}
<Card
content={{
title: 'Get LXP Address',
description: `${
snapLxpAddress
? truncateAddress(snapLxpAddress)
: 'Check the wallet address linked to your LXP'
}`,
title: 'Set LXP Address',
description: 'Please enter the wallet address where you hold LXP.',
button: (
<GetLxpAddressButton
onClick={handleGetLxpAddress}
<SetLxpAddressButton
onClick={handleSetLxpAddress}
disabled={!state.installedSnap}
/>
),
Expand All @@ -316,12 +309,15 @@ const Index = () => {
/>
<Card
content={{
title: 'Set LXP Address',
description: 'Please enter the wallet address holding your LXP',
input: <LxpAddressInput onChangeHandler={setLxpAddressValue} />,
title: 'Get LXP Address',
description: `${
snapLxpAddress
? truncateAddress(snapLxpAddress)
: 'Check the wallet address linked to your LXP.'
}`,
button: (
<SetLxpAddressButton
onClick={handleSetLxpAddress}
<GetLxpAddressButton
onClick={handleGetLxpAddress}
disabled={!state.installedSnap}
/>
),
Expand Down
12 changes: 10 additions & 2 deletions packages/snap/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,23 @@
"one": "There is {count} active LXP activation"
},
"lxpAddress": {
"heading": "LXP wallet address",
"heading": "Linea XP wallet address",
"prompt": "Please enter the wallet address linked to your LXP"
},
"nextSteps": {
"heading": "Thank you for installing the LXP Snap",
"body": "Next, set your address with the [companion site](https://lxp-snap.linea.build/) to track your Linea XP balance. At any time you can open the Snaps menu and click on LXP to view your balance, Proof of Humanity status, and current activations."
},
"noAddress": {
"toSetText": "To view your LXP balance and POH status,",
"toSetLink": "first set your address"
},
"help": "LXP earned in activations may not arrive in your wallet until the activation is complete.",
"viewBalance": "View balance on Lineascan",
"completePOH": "Complete Proof of Humanity",
"exploreAll": "Explore All Linea Activations"
"exploreAll": "Explore All Linea Activations",
"errors": {
"heading": "Error",
"invalidLxpAddress": "{address} is not a valid address. Please try again."
}
}
12 changes: 10 additions & 2 deletions packages/snap/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,23 @@
"one": "Hay {count} activacion de LXP activa"
},
"lxpAddress": {
"heading": "Cuenta que usas para LXP",
"heading": "Cuenta que usas para Linea XP",
"prompt": "Ingresa tu cuenta para ver tu balance"
},
"nextSteps": {
"heading": "Gracias por instalar LXP Snap",
"body": "Para ver tu balance de LXP y estado de POH, [ingresa tu cuenta por el sitio web](https://lxp-snap.linea.build/). A cualquier tiempo puedes abrir el menu y seleccionar el Snap para ver tu balance, estado de POH, y activaciones de LXP activas."
},
"noAddress": {
"toSetText": "Para ver tu balance de LXP y estado de POH,",
"toSetLink": "primero ingresa tu cuenta"
},
"help": "Es posible que LXP obtenido en activaciones no llegue a su cuenta hasta que se complete la activación.",
"viewBalance": "Ve tu balance de LXP en Lineascan",
"completePOH": "Verfica tu estado de POH",
"exploreAll": "Explora todas las activaciones"
"exploreAll": "Explora todas las activaciones",
"errors": {
"heading": "Error",
"invalidLxpAddress": "{address} no es una cuenta valido. Por favor, inténtelo de nuevo más tarde."
}
}
12 changes: 10 additions & 2 deletions packages/snap/locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,23 @@
"one": "Il y a {count} activation LXP active"
},
"lxpAddress": {
"heading": "fr-LXP wallet address",
"heading": "fr-Linea XP wallet address",
"prompt": "fr-Please enter the wallet address linked to your LXP"
},
"nextSteps": {
"heading": "fr-Thank you for installing the LXP Snap",
"body": "fr-Next, set your address with the [companion site](https://lxp-snap.linea.build/) to track your Linea XP balance. At any time you can open the Snaps menu and click on LXP to view your balance, Proof of Humanity status, and current activations."
},
"noAddress": {
"toSetText": "fr-To view your LXP balance and POH status,",
"toSetLink": "fr-first set your address"
},
"help": "fr-LXP earned in activations may not arrive in your wallet until the activation is complete.",
"viewBalance": "fr-View balance on Lineascan",
"completePOH": "fr-Complete Proof of Humanity",
"exploreAll": "fr-Explore All Linea Activations"
"exploreAll": "fr-Explore All Linea Activations",
"errors": {
"heading": "fr-Error",
"invalidLxpAddress": "fr-{address} is not a valid address. Please try again."
}
}
2 changes: 1 addition & 1 deletion packages/snap/snap.manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"url": "https://github.com/Consensys/lxp-snap"
},
"source": {
"shasum": "UoOlIKigX7EpEbieg+P2xZDlsiq2m64xQSWSjVQEk2o=",
"shasum": "J7CKoYhgYm7nmRgfcnLRzWRRcavzXQvpyUlJ+oA/AlI=",
"location": {
"npm": {
"filePath": "dist/bundle.js",
Expand Down
59 changes: 37 additions & 22 deletions packages/snap/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,42 +12,35 @@ import {
getPohStatus,
registerAddress,
} from './service';
import { renderMainUi, renderPromptLxpAddress } from './ui';
import { renderMainUi, renderPromptLxpAddress, renderPromptLxpAddressError, renderPromptNextSteps } from './ui';

Check failure on line 15 in packages/snap/src/index.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint

Replace `·renderMainUi,·renderPromptLxpAddress,·renderPromptLxpAddressError,·renderPromptNextSteps·` with `⏎··renderMainUi,⏎··renderPromptLxpAddress,⏎··renderPromptLxpAddressError,⏎··renderPromptNextSteps,⏎`
import { getChainId, getState, loadCaptions, setState } from './utils';

export const onInstall: OnInstallHandler = async () => {
await loadCaptions(true);
const lxpAddress = await snap.request({
await snap.request({
method: 'snap_dialog',
params: await renderPromptLxpAddress(),
params: await renderPromptNextSteps(),
});

if (lxpAddress) {
const lxpAddressStr = lxpAddress as `0x${string}`;
if (isValidHexAddress(lxpAddressStr)) {
await setState({
lxpAddress: lxpAddressStr,
});
} else {
console.error(`${lxpAddressStr} is not a valid address`);
}
}
};

export const onUpdate: OnUpdateHandler = async () => {
await loadCaptions(true);
};

export const onHomePage: OnHomePageHandler = async () => {
await loadCaptions(true);
const chainId = await getChainId();
const snapState = await getState();
await loadCaptions();

Check failure on line 32 in packages/snap/src/index.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint

Delete `··`
/* make calls in parallel */

Check failure on line 33 in packages/snap/src/index.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint

Delete `·`
const [chainId, snapState] = await Promise.all([getChainId(), getState()]);

Check failure on line 34 in packages/snap/src/index.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint

Delete `·`

const myAccount = snapState.lxpAddress as string;
const myLxpBalance = myAccount
? await getLxpBalanceForAddress(myAccount, chainId)
: 0;
const myPohStatus = myAccount ? await getPohStatus(myAccount) : false;
const activations = await getCurrentActivations();

Check failure on line 37 in packages/snap/src/index.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint

Delete `··`
/* make calls in parallel */
const [myLxpBalance, myPohStatus, activations] = await Promise.all([
getLxpBalanceForAddress(myAccount, chainId),
getPohStatus(myAccount),
getCurrentActivations(),
]);

Check failure on line 43 in packages/snap/src/index.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint

Delete `·`

await setState({
myLxpBalance,
Expand Down Expand Up @@ -90,6 +83,28 @@ export const onRpcRequest: OnRpcRequestHandler = async ({ request }) => {
return registerAddress(signature, payload);
}

case 'watchLxpAddress': {

Check failure on line 86 in packages/snap/src/index.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint

Delete `·`
await loadCaptions();
const lxpAddress = await snap.request({
method: 'snap_dialog',
params: await renderPromptLxpAddress(),
});

if (lxpAddress) {
const lxpAddressStr = lxpAddress as `0x${string}`;
if (isValidHexAddress(lxpAddressStr)) {
await setState({
lxpAddress: lxpAddressStr,
});
} else {
await snap.request({
method: 'snap_dialog',
params: await renderPromptLxpAddressError(lxpAddressStr),
});
}
}
}

default:
throw new Error('Method not found.');
}
Expand Down
8 changes: 8 additions & 0 deletions packages/snap/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ export type Captions = {
heading: string;
prompt: string;
};
nextSteps: {
heading: string;
body: string;
};
noAddress: {
toSetText: string;
toSetLink: string;
Expand All @@ -28,6 +32,10 @@ export type Captions = {
viewBalance: string;
completePOH: string;
exploreAll: string;
errors: {
heading: string,
invalidLxpAddress: string;
};
};

export type Tag = {
Expand Down
41 changes: 39 additions & 2 deletions packages/snap/src/ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {

import banner from '../img/banner.svg';
import { getState, truncateString } from './utils';
import { error } from '@metamask/snaps-cli/dist/types/utils';

/**
* Render the main UI.
Expand Down Expand Up @@ -94,8 +95,8 @@ export async function renderMainUi(myAccount: string) {
}

/**
* Render the UI in the onInstall hook.
* @returns DialogParams UI for onInstall.
* Render the UI in the onRpcRequest for setting a watch address.
* @returns DialogParams UI for onRpcRequest dialog.
*/
export async function renderPromptLxpAddress() {
const snapState = await getState();
Expand All @@ -110,3 +111,39 @@ export async function renderPromptLxpAddress() {
placeholder: '0x123...',
} as DialogParams;
}

/**
* Render the UI in the onInstall hook.
* @returns DialogParams UI for onInstall.
*/
export async function renderPromptNextSteps() {
const snapState = await getState();
const captions = snapState?.captions;

return {
type: 'alert',
content: panel([
heading(captions?.nextSteps.heading as string),
text(captions?.nextSteps.body as string),
]),
} as DialogParams;
}

/**
* Render the UI in the onRpcRequest for setting a watch address when an invalid address is provided.
* @returns DialogParams UI for onRpcRequest error dialog.
*/
export async function renderPromptLxpAddressError(lxpAddressStr:string) {
const snapState = await getState();
const captions = snapState?.captions;

const errorMsg = captions?.errors.invalidLxpAddress.replace('{address}', lxpAddressStr);

return {
type: 'alert',
content: panel([
heading(captions?.errors.heading as string),
text(errorMsg),
]),
} as DialogParams;
}
5 changes: 3 additions & 2 deletions packages/snap/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,13 @@ export async function setState(state: SnapState): Promise<void> {
* @returns The current chain ID.
*/
export async function getChainId() {
const chainId = await ethereum.request<string>({
let chainId = await ethereum.request<string>({
method: 'eth_chainId',
});

if (!chainId) {
throw new Error('Something went wrong while getting the chain ID.');
console.error('Something went wrong while getting the chain ID.');
chainId = '1';
}

return chainId;
Expand Down

0 comments on commit c05d83c

Please sign in to comment.