diff --git a/packages/examples/README.md b/packages/examples/README.md index 539956b241..1c6eeee985 100644 --- a/packages/examples/README.md +++ b/packages/examples/README.md @@ -88,6 +88,8 @@ The following is a list of the snaps in this directory. - [**`packages/preinstalled`**](./packages/preinstalled): This snap demonstrates preinstalled snaps, i.e., snaps that are installed in the MetaMask extension by default. +- [**`packages/send-flow`**](./packages/send-flow): This snap demonstrates + a simple send flow using custom UI. - [**`packages/wasm`**](./packages/wasm): This snap demonstrates how to use WebAssembly in a snap. diff --git a/packages/examples/packages/send-flow/.depcheckrc.json b/packages/examples/packages/send-flow/.depcheckrc.json new file mode 100644 index 0000000000..15d64e734b --- /dev/null +++ b/packages/examples/packages/send-flow/.depcheckrc.json @@ -0,0 +1,17 @@ +{ + "ignore-patterns": ["dist", "coverage"], + "ignores": [ + "@lavamoat/allow-scripts", + "@lavamoat/preinstall-always-fail", + "@metamask/auto-changelog", + "@metamask/eslint-*", + "@types/*", + "@typescript-eslint/*", + "eslint-config-*", + "eslint-plugin-*", + "prettier-plugin-packagejson", + "ts-node", + "typedoc", + "typescript" + ] +} diff --git a/packages/examples/packages/send-flow/.eslintrc.js b/packages/examples/packages/send-flow/.eslintrc.js new file mode 100644 index 0000000000..2d3d56ab04 --- /dev/null +++ b/packages/examples/packages/send-flow/.eslintrc.js @@ -0,0 +1,21 @@ +module.exports = { + extends: ['../../.eslintrc.js'], + + parserOptions: { + tsconfigRootDir: __dirname, + }, + + overrides: [ + { + files: ['*.ts', '*.tsx'], + rules: { + '@typescript-eslint/no-shadow': [ + 'error', + { + allow: ['Text'], + }, + ], + }, + }, + ], +}; diff --git a/packages/examples/packages/send-flow/CHANGELOG.md b/packages/examples/packages/send-flow/CHANGELOG.md new file mode 100644 index 0000000000..720e00537e --- /dev/null +++ b/packages/examples/packages/send-flow/CHANGELOG.md @@ -0,0 +1,10 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +[Unreleased]: https://github.com/MetaMask/snaps/ diff --git a/packages/examples/packages/send-flow/LICENSE.APACHE2 b/packages/examples/packages/send-flow/LICENSE.APACHE2 new file mode 100644 index 0000000000..1cdad6a8b4 --- /dev/null +++ b/packages/examples/packages/send-flow/LICENSE.APACHE2 @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2024 Consensys Software Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/examples/packages/send-flow/LICENSE.MIT0 b/packages/examples/packages/send-flow/LICENSE.MIT0 new file mode 100644 index 0000000000..3a4d3cb295 --- /dev/null +++ b/packages/examples/packages/send-flow/LICENSE.MIT0 @@ -0,0 +1,16 @@ +MIT No Attribution + +Copyright 2024 Consensys Software Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/examples/packages/send-flow/README.md b/packages/examples/packages/send-flow/README.md new file mode 100644 index 0000000000..dd699dcc92 --- /dev/null +++ b/packages/examples/packages/send-flow/README.md @@ -0,0 +1,19 @@ +# `@metamask/send-flow-example-snap` + +This snap demonstrates a simple send flow built with Snaps custom UI. + +## Snap usage + +### `onRpcRequest` + +This snap exposes an `onRpcRequest` handler, which supports the following +JSON-RPC methods: + +- `dialog`: Create a `snap_dialog` with the send flow. + +### `onHomePage` + +The snap exposes an `onHomePage` handler, which shows the send flow. + +For more information, you can refer to +[the end-to-end tests](./src/index.test.tsx). diff --git a/packages/examples/packages/send-flow/jest.config.js b/packages/examples/packages/send-flow/jest.config.js new file mode 100644 index 0000000000..d73c99b9a2 --- /dev/null +++ b/packages/examples/packages/send-flow/jest.config.js @@ -0,0 +1,36 @@ +const deepmerge = require('deepmerge'); + +const baseConfig = require('../../../../jest.config.base'); + +module.exports = deepmerge(baseConfig, { + preset: '@metamask/snaps-jest', + + // Since `@metamask/snaps-jest` runs in the browser, we can't collect + // coverage information. + collectCoverage: false, + + // This is required for the tests to run inside the `MetaMask/snaps` + // repository. You don't need this in your own project. + moduleNameMapper: { + '^@metamask/(.+)/jsx-dev-runtime': [ + '/../../../$1/jsx-dev-runtime', + '/../../../../node_modules/@metamask/$1/jsx-dev-runtime', + '/node_modules/@metamask/$1/jsx-dev-runtime', + ], + '^@metamask/(.+)/jsx': [ + '/../../../$1/src/jsx', + '/../../../../node_modules/@metamask/$1/jsx', + '/node_modules/@metamask/$1/jsx', + ], + '^@metamask/(.+)/node$': [ + '/../../../$1/src/node', + '/../../../../node_modules/@metamask/$1/node', + '/node_modules/@metamask/$1/node', + ], + '^@metamask/(.+)$': [ + '/../../../$1/src', + '/../../../../node_modules/@metamask/$1', + '/node_modules/@metamask/$1', + ], + }, +}); diff --git a/packages/examples/packages/send-flow/package.json b/packages/examples/packages/send-flow/package.json new file mode 100644 index 0000000000..d30deb1114 --- /dev/null +++ b/packages/examples/packages/send-flow/package.json @@ -0,0 +1,74 @@ +{ + "name": "@metamask/send-flow-example-snap", + "version": "0.0.0", + "description": "MetaMask example Snap demonstrating a send flow with UI components.", + "repository": { + "type": "git", + "url": "https://github.com/MetaMask/snaps.git" + }, + "license": "(MIT-0 OR Apache-2.0)", + "sideEffects": false, + "main": "./dist/bundle.js", + "files": [ + "dist/", + "snap.manifest.json" + ], + "scripts": { + "build": "mm-snap build", + "build:clean": "yarn clean && yarn build", + "changelog:update": "../../../../scripts/update-changelog.sh @metamask/send-flow-example-snap", + "changelog:validate": "../../../../scripts/validate-changelog.sh @metamask/send-flow-example-snap", + "clean": "rimraf \"dist\"", + "lint": "yarn lint:eslint && yarn lint:misc --check && yarn changelog:validate && yarn lint:dependencies", + "lint:ci": "yarn lint", + "lint:dependencies": "depcheck", + "lint:eslint": "eslint . --cache --ext js,ts,jsx,tsx", + "lint:fix": "yarn lint:eslint --fix && yarn lint:misc --write", + "lint:misc": "prettier --no-error-on-unmatched-pattern --loglevel warn \"**/*.json\" \"**/*.md\" \"**/*.html\" \"!CHANGELOG.md\" \"!snap.manifest.json\" --ignore-path ../../../../.gitignore", + "publish:preview": "yarn npm publish --tag preview", + "start": "mm-snap watch", + "test": "yarn test:e2e", + "test:e2e": "jest" + }, + "dependencies": { + "@metamask/rpc-errors": "^6.3.1", + "@metamask/snaps-sdk": "workspace:^" + }, + "devDependencies": { + "@jest/globals": "^29.5.0", + "@lavamoat/allow-scripts": "^3.0.4", + "@metamask/auto-changelog": "^3.4.4", + "@metamask/eslint-config": "^12.1.0", + "@metamask/eslint-config-jest": "^12.1.0", + "@metamask/eslint-config-nodejs": "^12.1.0", + "@metamask/eslint-config-typescript": "^12.1.0", + "@metamask/snaps-cli": "workspace:^", + "@metamask/snaps-jest": "workspace:^", + "@swc/core": "1.3.78", + "@swc/jest": "^0.2.26", + "@typescript-eslint/eslint-plugin": "^5.42.1", + "@typescript-eslint/parser": "^6.21.0", + "deepmerge": "^4.2.2", + "depcheck": "^1.4.7", + "eslint": "^8.27.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-import": "^2.26.0", + "eslint-plugin-jest": "^27.1.5", + "eslint-plugin-jsdoc": "^41.1.2", + "eslint-plugin-n": "^15.7.0", + "eslint-plugin-prettier": "^4.2.1", + "eslint-plugin-promise": "^6.1.1", + "jest": "^29.0.2", + "prettier": "^2.8.8", + "prettier-plugin-packagejson": "^2.5.2", + "ts-node": "^10.9.1", + "typescript": "~5.3.3" + }, + "engines": { + "node": "^18.16 || >=20" + }, + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + } +} diff --git a/packages/examples/packages/send-flow/snap.config.ts b/packages/examples/packages/send-flow/snap.config.ts new file mode 100644 index 0000000000..371496203a --- /dev/null +++ b/packages/examples/packages/send-flow/snap.config.ts @@ -0,0 +1,14 @@ +import type { SnapConfig } from '@metamask/snaps-cli'; +import { resolve } from 'path'; + +const config: SnapConfig = { + input: resolve(__dirname, 'src/index.tsx'), + server: { + port: 8070, + }, + stats: { + buffer: false, + }, +}; + +export default config; diff --git a/packages/examples/packages/send-flow/snap.manifest.json b/packages/examples/packages/send-flow/snap.manifest.json new file mode 100644 index 0000000000..59d3cbf1c3 --- /dev/null +++ b/packages/examples/packages/send-flow/snap.manifest.json @@ -0,0 +1,27 @@ +{ + "version": "0.0.0", + "description": "MetaMask example snap demonstrating a send flow with UI components.", + "proposedName": "Send flow Example Snap", + "repository": { + "type": "git", + "url": "https://github.com/MetaMask/snaps.git" + }, + "source": { + "shasum": "cw0v0wyDRw/bPiyDVlfHhJS1pnKkCul3eh7VheiaHIM=", + "location": { + "npm": { + "filePath": "dist/bundle.js", + "packageName": "@metamask/send-flow-example-snap", + "registry": "https://registry.npmjs.org/" + } + } + }, + "initialPermissions": { + "endowment:rpc": { + "dapps": true + }, + "snap_dialog": {}, + "endowment:page-home": {} + }, + "manifestVersion": "0.1" +} diff --git a/packages/examples/packages/send-flow/src/components/AccountSelector.tsx b/packages/examples/packages/send-flow/src/components/AccountSelector.tsx new file mode 100644 index 0000000000..1d99e07070 --- /dev/null +++ b/packages/examples/packages/send-flow/src/components/AccountSelector.tsx @@ -0,0 +1,54 @@ +import { + Card, + Field, + Selector, + SelectorOption, + type SnapComponent, +} from '@metamask/snaps-sdk/jsx'; + +import type { Account } from '../types'; +import { truncate } from '../utils'; + +/** + * The props for the {@link AccountSelector} component. + * + * @property selectedAccount - The currently selected account. + * @property accounts - The available accounts. + */ +export type AccountSelectorProps = { + selectedAccount: string; + accounts: Account[]; +}; + +/** + * A component that shows the account selector. + * + * @param props - The component props. + * @param props.selectedAccount - The currently selected account. + * @param props.accounts - The available accounts. + * @returns The AccountSelector component. + */ +export const AccountSelector: SnapComponent = ({ + selectedAccount, + accounts, +}) => ( + + + {accounts.map(({ name, address, balance, icon }) => ( + + + + ))} + + +); diff --git a/packages/examples/packages/send-flow/src/components/SendFlow.tsx b/packages/examples/packages/send-flow/src/components/SendFlow.tsx new file mode 100644 index 0000000000..cf8d6740d3 --- /dev/null +++ b/packages/examples/packages/send-flow/src/components/SendFlow.tsx @@ -0,0 +1,77 @@ +import type { SnapComponent } from '@metamask/snaps-sdk/jsx'; +import { Box, Container } from '@metamask/snaps-sdk/jsx'; + +import type { Account, Currency } from '../types'; +import { SendFlowFooter } from './SendFlowFooter'; +import { SendFlowHeader } from './SendFlowHeader'; +import { SendForm } from './SendForm'; +import { TransactionSummary } from './TransactionSummary'; + +/** + * The props for the {@link SendFlow} component. + * + * @property accounts - The available accounts. + * @property selectedAccount - The currently selected account. + * @property selectedCurrency - The selected currency to display. + * @property total - The total cost of the transaction. + * @property fees - The fees for the transaction. + * @property displayClearIcon - Whether to display the clear icon or not. + * @property flushToAddress - Whether to flush the address field or not. + * @property errors - The form errors. + */ +export type SendFlowProps = { + accounts: Account[]; + selectedAccount: string; + selectedCurrency: 'BTC' | '$'; + total: Currency; + fees: Currency; + displayClearIcon: boolean; + flushToAddress?: boolean; + errors?: { + amount?: string; + to?: string; + }; +}; + +/** + * A send flow component, which shows the user a form to send funds to another. + * + * @param props - The component props. + * @param props.accounts - The available accounts. + * @param props.selectedAccount - The currently selected account. + * @param props.selectedCurrency - The selected currency to display. + * @param props.total - The total cost of the transaction. + * @param props.errors - The form errors. + * @param props.fees - The fees for the transaction. + * @param props.displayClearIcon - Whether to display the clear icon or not. + * @param props.flushToAddress - Whether to flush the address field or not. + * @returns The SendFlow component. + */ +export const SendFlow: SnapComponent = ({ + accounts, + selectedAccount, + selectedCurrency, + total, + fees, + displayClearIcon, + flushToAddress, + errors, +}) => { + return ( + + + + + + + + + ); +}; diff --git a/packages/examples/packages/send-flow/src/components/SendFlowFooter.tsx b/packages/examples/packages/send-flow/src/components/SendFlowFooter.tsx new file mode 100644 index 0000000000..4e5d3e20fc --- /dev/null +++ b/packages/examples/packages/send-flow/src/components/SendFlowFooter.tsx @@ -0,0 +1,12 @@ +import { Button, Footer, type SnapComponent } from '@metamask/snaps-sdk/jsx'; + +/** + * A component that shows the send flow footer. + * + * @returns The SendFlowFooter component. + */ +export const SendFlowFooter: SnapComponent = () => ( +
+ +
+); diff --git a/packages/examples/packages/send-flow/src/components/SendFlowHeader.tsx b/packages/examples/packages/send-flow/src/components/SendFlowHeader.tsx new file mode 100644 index 0000000000..ad6c62fb5b --- /dev/null +++ b/packages/examples/packages/send-flow/src/components/SendFlowHeader.tsx @@ -0,0 +1,19 @@ +import type { SnapComponent } from '@metamask/snaps-sdk/jsx'; +import { Box, Button, Heading, Icon } from '@metamask/snaps-sdk/jsx'; + +/** + * A component that shows the send flow header. + * + * @returns The SendFlowHeader component. + */ +export const SendFlowHeader: SnapComponent = () => ( + + + Send + + +); diff --git a/packages/examples/packages/send-flow/src/components/SendForm.tsx b/packages/examples/packages/send-flow/src/components/SendForm.tsx new file mode 100644 index 0000000000..c7901400f3 --- /dev/null +++ b/packages/examples/packages/send-flow/src/components/SendForm.tsx @@ -0,0 +1,89 @@ +import { + Box, + Button, + Field, + Form, + Icon, + Image, + Input, + Text, + type SnapComponent, +} from '@metamask/snaps-sdk/jsx'; + +import btcIcon from '../images/btc.svg'; +import jazzicon3 from '../images/jazzicon3.svg'; +import type { Account, SendFormErrors } from '../types'; +import { AccountSelector } from './AccountSelector'; + +/** + * The props for the {@link SendForm} component. + * + * @property selectedAccount - The currently selected account. + * @property accounts - The available accounts. + * @property errors - The form errors. + * @property selectedCurrency - The selected currency to display. + * @property displayClearIcon - Whether to display the clear icon or not. + * @property flushToAddress - Whether to flush the address field or not. + */ +export type SendFormProps = { + selectedAccount: string; + accounts: Account[]; + errors?: SendFormErrors; + selectedCurrency: 'BTC' | '$'; + displayClearIcon: boolean; + flushToAddress?: boolean; +}; + +/** + * A component that shows the send form. + * + * @param props - The component props. + * @param props.selectedAccount - The currently selected account. + * @param props.accounts - The available accounts. + * @param props.errors - The form errors. + * @param props.selectedCurrency - The selected currency to display. + * @param props.displayClearIcon - Whether to display the clear icon or not. + * @param props.flushToAddress - Whether to flush the address field or not. + * @returns The SendForm component. + */ +export const SendForm: SnapComponent = ({ + selectedAccount, + accounts, + errors, + selectedCurrency, + displayClearIcon, + flushToAddress, +}) => ( +
+ + + + + + + + {selectedCurrency} + + + + + + + + + {displayClearIcon && ( + + + + )} + + +); diff --git a/packages/examples/packages/send-flow/src/components/TransactionSummary.tsx b/packages/examples/packages/send-flow/src/components/TransactionSummary.tsx new file mode 100644 index 0000000000..ef4901413f --- /dev/null +++ b/packages/examples/packages/send-flow/src/components/TransactionSummary.tsx @@ -0,0 +1,51 @@ +import { + Row, + Section, + Text, + Value, + type SnapComponent, +} from '@metamask/snaps-sdk/jsx'; + +import type { Currency } from '../types'; + +/** + * The props for the {@link TransactionSummary} component. + * + * @property fees - The fees for the transaction. + * @property total - The total cost of the transaction. + */ +export type TransactionSummaryProps = { + fees: Currency; + total: Currency; +}; + +/** + * A component that shows the transaction summary. + * + * @param props - The component props. + * @param props.fees - The fees for the transaction. + * @param props.total - The total cost of the transaction. + * @returns The TransactionSummary component. + */ +export const TransactionSummary: SnapComponent = ({ + fees, + total, +}) => ( +
+ + + + + 30m + + + + +
+); diff --git a/packages/examples/packages/send-flow/src/components/index.ts b/packages/examples/packages/send-flow/src/components/index.ts new file mode 100644 index 0000000000..109408cfd6 --- /dev/null +++ b/packages/examples/packages/send-flow/src/components/index.ts @@ -0,0 +1 @@ +export * from './SendFlow'; diff --git a/packages/examples/packages/send-flow/src/data.ts b/packages/examples/packages/send-flow/src/data.ts new file mode 100644 index 0000000000..4b821fb503 --- /dev/null +++ b/packages/examples/packages/send-flow/src/data.ts @@ -0,0 +1,26 @@ +import jazzicon1 from './images/jazzicon1.svg'; +import jazzicon2 from './images/jazzicon2.svg'; +import type { Account } from './types'; + +/** + * Example accounts data. + */ +export const accounts: Record = { + bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh: { + name: 'My Bitcoin Account', + address: 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh', + balance: { amount: 1.8, fiat: 92000 }, + icon: jazzicon1, + }, + bc1pmpg8yzpty4xgp497qdydkcqt90zz68n48wzwm757vk8nrlkat99q272xm3: { + name: 'Savings Account', + address: 'bc1pmpg8yzpty4xgp497qdydkcqt90zz68n48wzwm757vk8nrlkat99q272xm3', + balance: { amount: 2.5, fiat: 150000 }, + icon: jazzicon2, + }, +}; + +/** + * Example accounts data as an array. + */ +export const accountsArray = Object.values(accounts); diff --git a/packages/examples/packages/send-flow/src/images/btc.svg b/packages/examples/packages/send-flow/src/images/btc.svg new file mode 100644 index 0000000000..f5889766e2 --- /dev/null +++ b/packages/examples/packages/send-flow/src/images/btc.svg @@ -0,0 +1,12 @@ + + + + + + + + + diff --git a/packages/examples/packages/send-flow/src/images/jazzicon1.svg b/packages/examples/packages/send-flow/src/images/jazzicon1.svg new file mode 100644 index 0000000000..c7cc308bb7 --- /dev/null +++ b/packages/examples/packages/send-flow/src/images/jazzicon1.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/packages/examples/packages/send-flow/src/images/jazzicon2.svg b/packages/examples/packages/send-flow/src/images/jazzicon2.svg new file mode 100644 index 0000000000..b00299acb0 --- /dev/null +++ b/packages/examples/packages/send-flow/src/images/jazzicon2.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/packages/examples/packages/send-flow/src/images/jazzicon3.svg b/packages/examples/packages/send-flow/src/images/jazzicon3.svg new file mode 100644 index 0000000000..c43767a6d7 --- /dev/null +++ b/packages/examples/packages/send-flow/src/images/jazzicon3.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/packages/examples/packages/send-flow/src/index.test.tsx b/packages/examples/packages/send-flow/src/index.test.tsx new file mode 100644 index 0000000000..568c7b5a2d --- /dev/null +++ b/packages/examples/packages/send-flow/src/index.test.tsx @@ -0,0 +1,26 @@ +import { expect } from '@jest/globals'; +import { installSnap } from '@metamask/snaps-jest'; + +describe('onRpcRequest', () => { + it('throws an error if the requested method does not exist', async () => { + const { request } = await installSnap(); + + const response = await request({ + method: 'foo', + }); + + expect(response).toRespondWithError({ + code: -32601, + message: 'The method does not exist / is not available.', + stack: expect.any(String), + data: { + method: 'foo', + cause: null, + }, + }); + }); + + describe('display', () => { + it.todo('shows a custom dialog with the SendFlow interface'); + }); +}); diff --git a/packages/examples/packages/send-flow/src/index.tsx b/packages/examples/packages/send-flow/src/index.tsx new file mode 100644 index 0000000000..6334ab90a8 --- /dev/null +++ b/packages/examples/packages/send-flow/src/index.tsx @@ -0,0 +1,154 @@ +import { rpcErrors } from '@metamask/rpc-errors'; +import type { + OnHomePageHandler, + OnUserInputHandler, +} from '@metamask/snaps-sdk'; +import { + UserInputEventType, + type OnRpcRequestHandler, +} from '@metamask/snaps-sdk'; + +import { SendFlow } from './components'; +import { accountsArray, accounts } from './data'; +import type { SendFormState, SendFlowContext } from './types'; +import { formValidation, generateSendFlow } from './utils'; + +/** + * Handle incoming JSON-RPC requests from the dapp, sent through the + * `wallet_invokeSnap` method. This handler handles one method: + * + * - `display`: Display a dialog with the SendFlow interface. + * + * @param params - The request parameters. + * @param params.request - The JSON-RPC request object. + * @returns The JSON-RPC response. + * @see https://docs.metamask.io/snaps/reference/exports/#onrpcrequest + */ +export const onRpcRequest: OnRpcRequestHandler = async ({ request }) => { + switch (request.method) { + case 'display': { + const interfaceId = await generateSendFlow({ + accountsArray, + accounts, + fees: { amount: 1.0001, fiat: 1.23 }, + }); + + return await snap.request({ + method: 'snap_dialog', + params: { + id: interfaceId, + }, + }); + } + + default: + throw rpcErrors.methodNotFound({ + data: { + method: request.method, + }, + }); + } +}; + +/** + * Handle incoming home page requests from the MetaMask clients. + * + * @returns The interface ID for the send flow. + * @see https://docs.metamask.io/snaps/reference/exports/#onhomepage + */ +export const onHomePage: OnHomePageHandler = async () => { + const interfaceId = await generateSendFlow({ + accountsArray, + accounts, + fees: { amount: 1.0001, fiat: 1.23 }, + }); + + return { id: interfaceId }; +}; + +/** + * Handle incoming user events coming from the Snap interface. + * + * @param params - The event parameters. + * @param params.id - The Snap interface ID where the event was fired. + * @param params.event - The event object containing the event type, name and + * value. + * @param params.context - The interface context. + * @see https://docs.metamask.io/snaps/reference/exports/#onuserinput + */ +export const onUserInput: OnUserInputHandler = async ({ + event, + id, + context, +}) => { + const { selectedCurrency, fees } = context as SendFlowContext; + + const state = await snap.request({ + method: 'snap_getInterfaceState', + params: { id }, + }); + + const sendForm = state.sendForm as SendFormState; + + const formErrors = formValidation(sendForm, context as SendFlowContext); + + const total = { + amount: Number(sendForm.amount ?? 0) + fees.amount, + fiat: 250 + fees.fiat, + }; + + if (event.type === UserInputEventType.InputChangeEvent) { + switch (event.name) { + case 'amount': + case 'to': + case 'accountSelector': { + await snap.request({ + method: 'snap_updateInterface', + params: { + id, + ui: ( + + ), + }, + }); + + break; + } + default: + break; + } + } else if (event.type === UserInputEventType.ButtonClickEvent) { + switch (event.name) { + case 'clear': + await snap.request({ + method: 'snap_updateInterface', + params: { + id, + ui: ( + + ), + }, + }); + break; + default: + break; + } + } +}; diff --git a/packages/examples/packages/send-flow/src/types.ts b/packages/examples/packages/send-flow/src/types.ts new file mode 100644 index 0000000000..08b340749f --- /dev/null +++ b/packages/examples/packages/send-flow/src/types.ts @@ -0,0 +1,62 @@ +/** + * The state of the send form. + * + * @property to - The receiving address. + * @property amount - The amount to send. + * @property accountSelector - The selected account. + */ +export type SendFormState = { + to: string; + amount: string; + accountSelector: string; +}; + +/** + * The form errors. + * + * @property to - The error for the receiving address. + * @property amount - The error for the amount. + */ +export type SendFormErrors = { + to?: string; + amount?: string; +}; + +/** + * An Account of the send flow interface. + * + * @property name - The name of the account. + * @property address - The address of the account. + * @property balance - The balance of the account. + * @property icon - The icon of the account. + */ +export type Account = { + name: string; + address: string; + balance: Currency; + icon: string; +}; + +/** + * A currency value. + * + * @property amount - The amount in the selected currency. + * @property fiat - The amount in fiat currency. + */ +export type Currency = { + amount: number; + fiat: number; +}; + +/** + * The context of the send flow interface. + * + * @property accounts - The available accounts. + * @property selectedCurrency - The selected currency. + * @property fees - The fees for the transaction. + */ +export type SendFlowContext = { + accounts: Record; + selectedCurrency: 'BTC' | '$'; + fees: Currency; +}; diff --git a/packages/examples/packages/send-flow/src/utils.tsx b/packages/examples/packages/send-flow/src/utils.tsx new file mode 100644 index 0000000000..75021dd5a6 --- /dev/null +++ b/packages/examples/packages/send-flow/src/utils.tsx @@ -0,0 +1,91 @@ +import { SendFlow } from './components'; +import type { + Account, + Currency, + SendFlowContext, + SendFormErrors, + SendFormState, +} from './types'; + +export type GenerateSendFlowParams = { + accountsArray: Account[]; + accounts: Record; + fees: Currency; +}; + +/** + * Generate the send flow. + * + * @param params - The parameters for the send form. + * @param params.accountsArray - The available accounts as an array. + * @param params.accounts - The available accounts. + * @param params.fees - The fees for the transaction. + * @returns The interface ID. + */ +export async function generateSendFlow({ + accountsArray, + accounts, + fees, +}: GenerateSendFlowParams) { + return await snap.request({ + method: 'snap_createInterface', + params: { + ui: ( + + ), + context: { + accounts, + selectedCurrency: 'BTC', + fees, + }, + }, + }); +} + +/** + * Validate the send form. + * + * @param formState - The state of the send form. + * @param context - The context of the interface. + * @returns The form errors. + */ +export function formValidation( + formState: SendFormState, + context: SendFlowContext, +): SendFormErrors { + const errors: Partial = {}; + + if (formState.to === 'invalid address') { + errors.to = 'Invalid address'; + } + + if ( + formState.amount && + Number(formState.amount) > + context.accounts[formState.accountSelector].balance.amount + ) { + errors.amount = 'Insufficient funds'; + } + + return errors; +} + +/** + * Truncate a string to a given length. + * + * @param str - The string to truncate. + * @param length - The number of characters to truncate the string to. + * @returns The truncated string. + */ +export function truncate(str: string, length: number): string { + return str.length > length + ? `${str.slice(0, 5)}...${str.slice(str.length - 5, str.length)}` + : str; +} diff --git a/packages/examples/packages/send-flow/tsconfig.json b/packages/examples/packages/send-flow/tsconfig.json new file mode 100644 index 0000000000..7f1d10e498 --- /dev/null +++ b/packages/examples/packages/send-flow/tsconfig.json @@ -0,0 +1,26 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "baseUrl": "./", + "jsx": "react-jsxdev", + "paths": { + "@metamask/*/jsx": ["../../../*/src/jsx"], + "@metamask/*/jsx-dev-runtime": ["../../../*/src/jsx"], + "@metamask/*": ["../../../*/src"] + }, + "module": "ES2020", + "moduleResolution": "Node10" + }, + "include": ["src", "snap.config.ts"], + "references": [ + { + "path": "../../../snaps-sdk" + }, + { + "path": "../../../snaps-jest" + }, + { + "path": "../../../snaps-cli" + } + ] +} diff --git a/packages/test-snaps/package.json b/packages/test-snaps/package.json index 27993a3ef6..362148ebbf 100644 --- a/packages/test-snaps/package.json +++ b/packages/test-snaps/package.json @@ -53,6 +53,7 @@ "@metamask/network-example-snap": "workspace:^", "@metamask/notification-example-snap": "workspace:^", "@metamask/preinstalled-example-snap": "workspace:^", + "@metamask/send-flow-example-snap": "workspace:^", "@metamask/signature-insights-example-snap": "workspace:^", "@metamask/snaps-utils": "workspace:^", "@metamask/utils": "^9.2.1", diff --git a/packages/test-snaps/src/features/snaps/index.ts b/packages/test-snaps/src/features/snaps/index.ts index 8a9cd37b01..c80978a40d 100644 --- a/packages/test-snaps/src/features/snaps/index.ts +++ b/packages/test-snaps/src/features/snaps/index.ts @@ -26,3 +26,4 @@ export * from './transaction-insights'; export * from './signature-insights'; export * from './updates'; export * from './wasm'; +export * from './send-flow'; diff --git a/packages/test-snaps/src/features/snaps/send-flow/SendFlow.tsx b/packages/test-snaps/src/features/snaps/send-flow/SendFlow.tsx new file mode 100644 index 0000000000..f2435cc0f7 --- /dev/null +++ b/packages/test-snaps/src/features/snaps/send-flow/SendFlow.tsx @@ -0,0 +1,42 @@ +import { logError } from '@metamask/snaps-utils'; +import type { FunctionComponent } from 'react'; +import { Button } from 'react-bootstrap'; + +import { useInvokeMutation } from '../../../api'; +import { Result, Snap } from '../../../components'; +import { getSnapId } from '../../../utils'; +import { + SEND_FLOW_SNAP_ID, + SEND_FLOW_SNAP_PORT, + SEND_FLOW_VERSION, +} from './constants'; + +export const SendFlow: FunctionComponent = () => { + const [invokeSnap, { isLoading, data }] = useInvokeMutation(); + const snapId = getSnapId(SEND_FLOW_SNAP_ID, SEND_FLOW_SNAP_PORT); + + const handleSubmitDisplay = () => { + invokeSnap({ + snapId, + method: 'display', + }).catch(logError); + }; + + return ( + + + + + {JSON.stringify(data, null, 2)} + + + ); +}; diff --git a/packages/test-snaps/src/features/snaps/send-flow/constants.ts b/packages/test-snaps/src/features/snaps/send-flow/constants.ts new file mode 100644 index 0000000000..6daf5e2c96 --- /dev/null +++ b/packages/test-snaps/src/features/snaps/send-flow/constants.ts @@ -0,0 +1,5 @@ +import packageJson from '@metamask/send-flow-example-snap/package.json'; + +export const SEND_FLOW_SNAP_ID = 'npm:@metamask/send-flow-example-snap'; +export const SEND_FLOW_SNAP_PORT = 8070; +export const SEND_FLOW_VERSION = packageJson.version; diff --git a/packages/test-snaps/src/features/snaps/send-flow/index.ts b/packages/test-snaps/src/features/snaps/send-flow/index.ts new file mode 100644 index 0000000000..109408cfd6 --- /dev/null +++ b/packages/test-snaps/src/features/snaps/send-flow/index.ts @@ -0,0 +1 @@ +export * from './SendFlow'; diff --git a/yarn.lock b/yarn.lock index 2d92ee1d09..de94908be5 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5421,6 +5421,43 @@ __metadata: languageName: node linkType: hard +"@metamask/send-flow-example-snap@workspace:^, @metamask/send-flow-example-snap@workspace:packages/examples/packages/send-flow": + version: 0.0.0-use.local + resolution: "@metamask/send-flow-example-snap@workspace:packages/examples/packages/send-flow" + dependencies: + "@jest/globals": "npm:^29.5.0" + "@lavamoat/allow-scripts": "npm:^3.0.4" + "@metamask/auto-changelog": "npm:^3.4.4" + "@metamask/eslint-config": "npm:^12.1.0" + "@metamask/eslint-config-jest": "npm:^12.1.0" + "@metamask/eslint-config-nodejs": "npm:^12.1.0" + "@metamask/eslint-config-typescript": "npm:^12.1.0" + "@metamask/rpc-errors": "npm:^6.3.1" + "@metamask/snaps-cli": "workspace:^" + "@metamask/snaps-jest": "workspace:^" + "@metamask/snaps-sdk": "workspace:^" + "@swc/core": "npm:1.3.78" + "@swc/jest": "npm:^0.2.26" + "@typescript-eslint/eslint-plugin": "npm:^5.42.1" + "@typescript-eslint/parser": "npm:^6.21.0" + deepmerge: "npm:^4.2.2" + depcheck: "npm:^1.4.7" + eslint: "npm:^8.27.0" + eslint-config-prettier: "npm:^8.5.0" + eslint-plugin-import: "npm:^2.26.0" + eslint-plugin-jest: "npm:^27.1.5" + eslint-plugin-jsdoc: "npm:^41.1.2" + eslint-plugin-n: "npm:^15.7.0" + eslint-plugin-prettier: "npm:^4.2.1" + eslint-plugin-promise: "npm:^6.1.1" + jest: "npm:^29.0.2" + prettier: "npm:^2.8.8" + prettier-plugin-packagejson: "npm:^2.5.2" + ts-node: "npm:^10.9.1" + typescript: "npm:~5.3.3" + languageName: unknown + linkType: soft + "@metamask/signature-insights-example-snap@workspace:^, @metamask/signature-insights-example-snap@workspace:packages/examples/packages/signature-insights": version: 0.0.0-use.local resolution: "@metamask/signature-insights-example-snap@workspace:packages/examples/packages/signature-insights" @@ -6291,6 +6328,7 @@ __metadata: "@metamask/notification-example-snap": "workspace:^" "@metamask/preinstalled-example-snap": "workspace:^" "@metamask/providers": "npm:^17.1.2" + "@metamask/send-flow-example-snap": "workspace:^" "@metamask/signature-insights-example-snap": "workspace:^" "@metamask/snaps-utils": "workspace:^" "@metamask/utils": "npm:^9.2.1"