diff --git a/README.md b/README.md index 8acec32..618bcd3 100644 --- a/README.md +++ b/README.md @@ -2,20 +2,29 @@ # svelte-web3 -web3.js 1.2.9 as a Svelte store. +import web3.js as a store for Svelte or Sapper. -## Installation +## Svelte and Sapper installation + +1. add the `svelte-web3` package ```bash npm i svelte-web3 ``` -## Basic Usage +2. add the web3.js library in the main HTML page (`public/index.html` in Svelte and `src/template.html` in Sapper) + +```html + + +``` + +## Svelte and Sapper basic usage Import the `ethStore` main connection helper and needed derived Svelte stores (see list below): ```js -import { ethStore, web3, selectedAccount, connected } from 'svelte-web3'; +import { ethStore, web3, selectedAccount, connected } from 'svelte-web3' ``` To enable connection to the current window provider: @@ -30,8 +39,24 @@ To enable connection using an url string: ethStore.setProvider('') ``` -If connection is successful, you can access the instantiated web3.js with the current window provider -using the `$` svelte store syntax : +Please note that if your code is running in SSR context (like with +Sapper), you can only call `setBrowserProvider` and `setProvider` in +browser context for example using `onMount` or as an handler of a +client-side event : + +```js + onMount( + async () => { + console.log('Connecting to Ethereum Testnet Görli...') + ethStore.setProvider('https://rpc.slock.it/goerli') + }) +``` + +In SSR context, the stores are defined but no connection has been +instanciated. + +If a connection is successful, you can access the instantiated web3.js +with the current window provider using the `$` svelte store syntax : ```js $web3.eth.getBalance() @@ -50,8 +75,10 @@ Svelte stores are automatically updated when network or the selected account cha Please see the file `example/App.svelte` for more usage information to start a transaction and concrete usage of stores. -## Demo/Example +## Svelte example (based on rollup template) -```bash -npm run example -``` +Please check `example/svelte-app-template-web3` in github. + +## Sapper example (ased on webpack template) + +Please check `example/sapper-app-template-web3` in github. diff --git a/example/main.js b/example/main.js deleted file mode 100644 index 5ef7a8e..0000000 --- a/example/main.js +++ /dev/null @@ -1,11 +0,0 @@ -import App from './App.svelte' - -const app = new App({ - target: document.body, - props: { - name: 'Svelte + Web3', - tipAddres: '0x834356a88C66897FA0A05a61964a91A607956ee3', - } -}); - -export default app diff --git a/example/rollup.config.js b/example/rollup.config.js deleted file mode 100644 index 13a2396..0000000 --- a/example/rollup.config.js +++ /dev/null @@ -1,48 +0,0 @@ -import svelte from 'rollup-plugin-svelte'; -import resolve from '@rollup/plugin-node-resolve'; -import commonjs from '@rollup/plugin-commonjs'; -import livereload from 'rollup-plugin-livereload'; - -const watch = process.env.ROLLUP_WATCH; - -export default { - input: 'example/main.js', - output: { - name: 'app', - sourcemap: true, - format: 'iife', - file: 'public/build/bundle.js' - }, - plugins: [ - svelte({ - css: css => { - css.write('public/build/bundle.css'); - } - }), - resolve({ - dedupe: ['svelte'] - }), - commonjs(), - serve(), - watch && livereload('public'), - ], - watch: { - clearScreen: false - } -}; - -function serve() { - let started = false; - - return { - writeBundle() { - if (!started) { - started = true; - require('child_process').spawn('npm', ['run', 'start-example'], { - stdio: ['ignore', 'inherit', 'inherit'], - shell: true - }); - } - } - }; -} diff --git a/example/sapper-app-template-web3/.gitignore b/example/sapper-app-template-web3/.gitignore new file mode 100644 index 0000000..f220e37 --- /dev/null +++ b/example/sapper-app-template-web3/.gitignore @@ -0,0 +1,5 @@ +.DS_Store +/node_modules/ +/src/node_modules/@sapper/ +yarn-error.log +/__sapper__/ diff --git a/example/sapper-app-template-web3/README.md b/example/sapper-app-template-web3/README.md new file mode 100644 index 0000000..8dc7474 --- /dev/null +++ b/example/sapper-app-template-web3/README.md @@ -0,0 +1,157 @@ +# sapper-template + +The default template for setting up a [Sapper](https://github.com/sveltejs/sapper) project. Can use either Rollup or webpack as bundler. + + +## Getting started + + +### Using `degit` + +To create a new Sapper project based on Rollup locally, run + +```bash +npx degit "sveltejs/sapper-template#rollup" my-app +``` + +For a webpack-based project, instead run + +```bash +npx degit "sveltejs/sapper-template#webpack" my-app +``` + +[`degit`](https://github.com/Rich-Harris/degit) is a scaffolding tool that lets you create a directory from a branch in a repository. + +Replace `my-app` with the path where you wish to create the project. + + +### Using GitHub templates + +Alternatively, you can create the new project as a GitHub repository using GitHub's template feature. + +Go to either [sapper-template-rollup](https://github.com/sveltejs/sapper-template-rollup) or [sapper-template-webpack](https://github.com/sveltejs/sapper-template-webpack) and click on "Use this template" to create a new project repository initialized by the template. + + +### Running the project + +Once you have created the project, install dependencies and run the project in development mode: + +```bash +cd my-app +npm install # or yarn +npm run dev +``` + +This will start the development server on [localhost:3000](http://localhost:3000). Open it and click around. + +You now have a fully functional Sapper project! To get started developing, consult [sapper.svelte.dev](https://sapper.svelte.dev). + +### Using TypeScript + +By default, the template uses plain JavaScript. If you wish to use TypeScript instead, you need some changes to the project: + + * Add `typescript` as well as typings as dependences in `package.json` + * Configure the bundler to use [`svelte-preprocess`](https://github.com/sveltejs/svelte-preprocess) and transpile the TypeScript code. + * Add a `tsconfig.json` file + * Update the project code to TypeScript + +The template comes with a script that will perform these changes for you by running + +```bash +node scripts/setupTypeScript.js +``` + +`@sapper` dependencies are resolved through `src/node_modules/@sapper`, which is created during the build. You therefore need to run or build the project once to avoid warnings about missing dependencies. + +The script does not support webpack at the moment. + +## Directory structure + +Sapper expects to find two directories in the root of your project — `src` and `static`. + + +### src + +The [src](src) directory contains the entry points for your app — `client.js`, `server.js` and (optionally) a `service-worker.js` — along with a `template.html` file and a `routes` directory. + + +#### src/routes + +This is the heart of your Sapper app. There are two kinds of routes — *pages*, and *server routes*. + +**Pages** are Svelte components written in `.svelte` files. When a user first visits the application, they will be served a server-rendered version of the route in question, plus some JavaScript that 'hydrates' the page and initialises a client-side router. From that point forward, navigating to other pages is handled entirely on the client for a fast, app-like feel. (Sapper will preload and cache the code for these subsequent pages, so that navigation is instantaneous.) + +**Server routes** are modules written in `.js` files, that export functions corresponding to HTTP methods. Each function receives Express `request` and `response` objects as arguments, plus a `next` function. This is useful for creating a JSON API, for example. + +There are three simple rules for naming the files that define your routes: + +* A file called `src/routes/about.svelte` corresponds to the `/about` route. A file called `src/routes/blog/[slug].svelte` corresponds to the `/blog/:slug` route, in which case `params.slug` is available to the route +* The file `src/routes/index.svelte` (or `src/routes/index.js`) corresponds to the root of your app. `src/routes/about/index.svelte` is treated the same as `src/routes/about.svelte`. +* Files and directories with a leading underscore do *not* create routes. This allows you to colocate helper modules and components with the routes that depend on them — for example you could have a file called `src/routes/_helpers/datetime.js` and it would *not* create a `/_helpers/datetime` route. + + +#### src/node_modules/images + +Images added to `src/node_modules/images` can be imported into your code using `import 'images/'`. They will be given a dynamically generated filename containing a hash, allowing for efficient caching and serving the images on a CDN. + +See [`index.svelte`](src/routes/index.svelte) for an example. + + +#### src/node_modules/@sapper + +This directory is managed by Sapper and generated when building. It contains all the code you import from `@sapper` modules. + + +### static + +The [static](static) directory contains static assets that should be served publicly. Files in this directory will be available directly under the root URL, e.g. an `image.jpg` will be available as `/image.jpg`. + +The default [service-worker.js](src/service-worker.js) will preload and cache these files, by retrieving a list of `files` from the generated manifest: + +```js +import { files } from '@sapper/service-worker'; +``` + +If you have static files you do not want to cache, you should exclude them from this list after importing it (and before passing it to `cache.addAll`). + +Static files are served using [sirv](https://github.com/lukeed/sirv). + + +## Bundler configuration + +Sapper uses Rollup or webpack to provide code-splitting and dynamic imports, as well as compiling your Svelte components. With webpack, it also provides hot module reloading. As long as you don't do anything daft, you can edit the configuration files to add whatever plugins you'd like. + + +## Production mode and deployment + +To start a production version of your app, run `npm run build && npm start`. This will disable live reloading, and activate the appropriate bundler plugins. + +You can deploy your application to any environment that supports Node 10 or above. As an example, to deploy to [Vercel Now](https://vercel.com) when using `sapper export`, run these commands: + +```bash +npm install -g vercel +vercel +``` + +If your app can't be exported to a static site, you can use the [vercel-sapper](https://github.com/thgh/vercel-sapper) builder. You can find instructions on how to do so in its [README](https://github.com/thgh/vercel-sapper#basic-usage). + + +## Using external components + +When using Svelte components installed from npm, such as [@sveltejs/svelte-virtual-list](https://github.com/sveltejs/svelte-virtual-list), Svelte needs the original component source (rather than any precompiled JavaScript that ships with the component). This allows the component to be rendered server-side, and also keeps your client-side app smaller. + +Because of that, it's essential that the bundler doesn't treat the package as an *external dependency*. You can either modify the `external` option under `server` in [rollup.config.js](rollup.config.js) or the `externals` option in [webpack.config.js](webpack.config.js), or simply install the package to `devDependencies` rather than `dependencies`, which will cause it to get bundled (and therefore compiled) with your app: + +```bash +npm install -D @sveltejs/svelte-virtual-list +``` + +## Troubleshooting + +Using Windows and WSL2? + +If your project lives outside the WSL root directory, [this limitation](https://github.com/microsoft/WSL/issues/4169) is known to cause live-reloading to fail. See [this issue](https://github.com/sveltejs/sapper/issues/1150) for details. + +## Bugs and feedback + +Sapper is in early development, and may have the odd rough edge here and there. Please be vocal over on the [Sapper issue tracker](https://github.com/sveltejs/sapper/issues). diff --git a/example/sapper-app-template-web3/package.json b/example/sapper-app-template-web3/package.json new file mode 100644 index 0000000..9cbef84 --- /dev/null +++ b/example/sapper-app-template-web3/package.json @@ -0,0 +1,25 @@ +{ + "name": "TODO", + "description": "TODO", + "version": "0.0.1", + "scripts": { + "dev": "sapper dev", + "build": "sapper build", + "export": "sapper export", + "start": "node __sapper__/build" + }, + "dependencies": { + "compression": "^1.7.1", + "polka": "next", + "svelte-web3": "^1.3.4", + "sirv": "^1.0.0" + }, + "devDependencies": { + "sapper": "^0.28.0", + "svelte": "^3.17.3", + "file-loader": "^6.0.0", + "svelte-loader": "^2.9.0", + "webpack": "^4.7.0", + "webpack-modules": "^1.0.0" + } +} diff --git a/example/sapper-app-template-web3/scripts/setupTypeScript.js b/example/sapper-app-template-web3/scripts/setupTypeScript.js new file mode 100644 index 0000000..68e5b56 --- /dev/null +++ b/example/sapper-app-template-web3/scripts/setupTypeScript.js @@ -0,0 +1,306 @@ +/** + * Run this script to convert the project to TypeScript. This is only guaranteed to work + * on the unmodified default template; if you have done code changes you are likely need + * to touch up the generated project manually. + */ + +// @ts-check +const fs = require('fs'); +const path = require('path'); +const { argv } = require('process'); + +const projectRoot = argv[2] || path.join(__dirname, '..'); + +const isRollup = fs.existsSync(path.join(projectRoot, "rollup.config.js")); + +function warn(message) { + console.warn('Warning: ' + message); +} + +function replaceInFile(fileName, replacements) { + if (fs.existsSync(fileName)) { + let contents = fs.readFileSync(fileName, 'utf8'); + let hadUpdates = false; + + replacements.forEach(([from, to]) => { + const newContents = contents.replace(from, to); + + const isAlreadyApplied = typeof to !== 'string' || contents.includes(to); + + if (newContents !== contents) { + contents = newContents; + hadUpdates = true; + } else if (!isAlreadyApplied) { + warn(`Wanted to update "${from}" in ${fileName}, but did not find it.`); + } + }); + + if (hadUpdates) { + fs.writeFileSync(fileName, contents); + } else { + console.log(`${fileName} had already been updated.`); + } + } else { + warn(`Wanted to update ${fileName} but the file did not exist.`); + } +} + +function createFile(fileName, contents) { + if (fs.existsSync(fileName)) { + warn(`Wanted to create ${fileName}, but it already existed. Leaving existing file.`); + } else { + fs.writeFileSync(fileName, contents); + } +} + +function addDepsToPackageJson() { + const pkgJSONPath = path.join(projectRoot, 'package.json'); + const packageJSON = JSON.parse(fs.readFileSync(pkgJSONPath, 'utf8')); + packageJSON.devDependencies = Object.assign(packageJSON.devDependencies, { + ...(isRollup ? { '@rollup/plugin-typescript': '^6.0.0' } : { 'ts-loader': '^8.0.4' }), + '@tsconfig/svelte': '^1.0.10', + '@types/compression': '^1.7.0', + '@types/node': '^14.11.1', + '@types/polka': '^0.5.1', + 'svelte-check': '^1.0.46', + 'svelte-preprocess': '^4.3.0', + tslib: '^2.0.1', + typescript: '^4.0.3' + }); + + // Add script for checking + packageJSON.scripts = Object.assign(packageJSON.scripts, { + validate: 'svelte-check --ignore src/node_modules/@sapper' + }); + + // Write the package JSON + fs.writeFileSync(pkgJSONPath, JSON.stringify(packageJSON, null, ' ')); +} + +function changeJsExtensionToTs(dir) { + const elements = fs.readdirSync(dir, { withFileTypes: true }); + + for (let i = 0; i < elements.length; i++) { + if (elements[i].isDirectory()) { + changeJsExtensionToTs(path.join(dir, elements[i].name)); + } else if (elements[i].name.match(/^[^_]((?!json).)*js$/)) { + fs.renameSync(path.join(dir, elements[i].name), path.join(dir, elements[i].name).replace('.js', '.ts')); + } + } +} + +function updateSingleSvelteFile({ view, vars, contextModule }) { + replaceInFile(path.join(projectRoot, 'src', `${view}.svelte`), [ + [/(?:/gm, (m, attrs) => ``], + ...(vars ? vars.map(({ name, type }) => [`export let ${name};`, `export let ${name}: ${type};`]) : []), + ...(contextModule ? contextModule.map(({ js, ts }) => [js, ts]) : []) + ]); +} + +// Switch the *.svelte file to use TS +function updateSvelteFiles() { + [ + { + view: 'components/Nav', + vars: [{ name: 'segment', type: 'string' }] + }, + { + view: 'routes/_layout', + vars: [{ name: 'segment', type: 'string' }] + }, + { + view: 'routes/_error', + vars: [ + { name: 'status', type: 'number' }, + { name: 'error', type: 'Error' } + ] + }, + { + view: 'routes/blog/index', + vars: [{ name: 'posts', type: '{ slug: string; title: string, html: any }[]' }], + contextModule: [ + { + js: '.then(r => r.json())', + ts: '.then((r: { json: () => any; }) => r.json())' + }, + { + js: '.then(posts => {', + ts: '.then((posts: { slug: string; title: string, html: any }[]) => {' + } + ] + }, + { + view: 'routes/blog/[slug]', + vars: [{ name: 'post', type: '{ slug: string; title: string, html: any }' }] + } + ].forEach(updateSingleSvelteFile); +} + +function updateRollupConfig() { + // Edit rollup config + replaceInFile(path.join(projectRoot, 'rollup.config.js'), [ + // Edit imports + [ + /'rollup-plugin-terser';\n(?!import sveltePreprocess)/, + `'rollup-plugin-terser'; +import sveltePreprocess from 'svelte-preprocess'; +import typescript from '@rollup/plugin-typescript'; +` + ], + // Edit inputs + [ + /(?`, `self.addEventListener('activate', (event: ExtendableEvent) =>`], + [`self.addEventListener('install', event =>`, `self.addEventListener('install', (event: ExtendableEvent) =>`], + [`addEventListener('fetch', event =>`, `addEventListener('fetch', (event: FetchEvent) =>`], + ]); +} + +function createTsConfig() { + const tsconfig = `{ + "extends": "@tsconfig/svelte/tsconfig.json", + "compilerOptions": { + "lib": ["DOM", "ES2017", "WebWorker"] + }, + "include": ["src/**/*", "src/node_modules/**/*"], + "exclude": ["node_modules/*", "__sapper__/*", "static/*"] + }`; + + createFile(path.join(projectRoot, 'tsconfig.json'), tsconfig); +} + +// Adds the extension recommendation +function configureVsCode() { + const dir = path.join(projectRoot, '.vscode'); + + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir); + } + + createFile(path.join(projectRoot, '.vscode', 'extensions.json'), `{"recommendations": ["svelte.svelte-vscode"]}`); +} + +function deleteThisScript() { + fs.unlinkSync(path.join(__filename)); + + // Check for Mac's DS_store file, and if it's the only one left remove it + const remainingFiles = fs.readdirSync(path.join(__dirname)); + if (remainingFiles.length === 1 && remainingFiles[0] === '.DS_store') { + fs.unlinkSync(path.join(__dirname, '.DS_store')); + } + + // Check if the scripts folder is empty + if (fs.readdirSync(path.join(__dirname)).length === 0) { + // Remove the scripts folder + fs.rmdirSync(path.join(__dirname)); + } +} + +console.log(`Adding TypeScript with ${isRollup ? "Rollup" : "webpack" }...`); + +addDepsToPackageJson(); + +changeJsExtensionToTs(path.join(projectRoot, 'src')); + +updateSvelteFiles(); + +if (isRollup) { + updateRollupConfig(); +} else { + updateWebpackConfig(); +} + +updateServiceWorker(); + +createTsConfig(); + +configureVsCode(); + +// Delete this script, but not during testing +if (!argv[2]) { + deleteThisScript(); +} + +console.log('Converted to TypeScript.'); + +if (fs.existsSync(path.join(projectRoot, 'node_modules'))) { + console.log(` +Next: +1. run 'npm install' again to install TypeScript dependencies +2. run 'npm run build' for the @sapper imports in your project to work +`); +} diff --git a/example/sapper-app-template-web3/src/ambient.d.ts b/example/sapper-app-template-web3/src/ambient.d.ts new file mode 100644 index 0000000..ec71cae --- /dev/null +++ b/example/sapper-app-template-web3/src/ambient.d.ts @@ -0,0 +1,39 @@ +/** + * These declarations tell TypeScript that we allow import of images, e.g. + * ``` + + + + ``` + */ +declare module "*.gif" { + const value: string; + export = value; +} + +declare module "*.jpg" { + const value: string; + export = value; +} + +declare module "*.jpeg" { + const value: string; + export = value; +} + +declare module "*.png" { + const value: string; + export = value; +} + +declare module "*.svg" { + const value: string; + export = value; +} + +declare module "*.webp" { + const value: string; + export = value; +} diff --git a/example/sapper-app-template-web3/src/client.js b/example/sapper-app-template-web3/src/client.js new file mode 100644 index 0000000..cec9172 --- /dev/null +++ b/example/sapper-app-template-web3/src/client.js @@ -0,0 +1,5 @@ +import * as sapper from '@sapper/app'; + +sapper.start({ + target: document.querySelector('#sapper') +}); \ No newline at end of file diff --git a/example/sapper-app-template-web3/src/components/Nav.svelte b/example/sapper-app-template-web3/src/components/Nav.svelte new file mode 100644 index 0000000..38f8dbc --- /dev/null +++ b/example/sapper-app-template-web3/src/components/Nav.svelte @@ -0,0 +1,61 @@ + + + + + diff --git a/example/sapper-app-template-web3/src/routes/_error.svelte b/example/sapper-app-template-web3/src/routes/_error.svelte new file mode 100644 index 0000000..320e587 --- /dev/null +++ b/example/sapper-app-template-web3/src/routes/_error.svelte @@ -0,0 +1,40 @@ + + + + + + {status} + + +

{status}

+ +

{error.message}

+ +{#if dev && error.stack} +
{error.stack}
+{/if} diff --git a/example/sapper-app-template-web3/src/routes/_layout.svelte b/example/sapper-app-template-web3/src/routes/_layout.svelte new file mode 100644 index 0000000..8432299 --- /dev/null +++ b/example/sapper-app-template-web3/src/routes/_layout.svelte @@ -0,0 +1,22 @@ + + + + +