From cc428045a3edf48d448fd375e5df2184cd08511b Mon Sep 17 00:00:00 2001 From: Mujahid Khan <106528609+mujahidkay@users.noreply.github.com> Date: Fri, 27 Sep 2024 04:14:04 +0500 Subject: [PATCH 1/5] chore: update package.json --- package.json | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 99e39b693..c7c7fb322 100644 --- a/package.json +++ b/package.json @@ -11,8 +11,8 @@ "test": "ava", "lint-fix": "yarn lint --fix", "lint": "eslint 'snippets/**/*.js'", - "format": "prettier --write '**/*.md' --config .prettierrc.json", - "lint:format": "prettier --check '**/*.md' --config .prettierrc.json", + "format": "node scripts/markdown-js-snippets-linter.mjs 'main/**/*.md' --fix && prettier --write '**/*.md' --config .prettierrc.json", + "lint:format": "node scripts/markdown-js-snippets-linter.mjs 'main/**/*.md' && prettier --check '**/*.md' --config .prettierrc.json", "build": "exit 0" }, "packageManager": "yarn@4.4.0", @@ -65,6 +65,7 @@ "eslint-plugin-import": "^2.26.0", "eslint-plugin-jsdoc": "^35.1.2", "eslint-plugin-prettier": "^5.2.1", + "glob": "^10.4.3", "import-meta-resolve": "^2.2.1", "prettier": "^3.3.3", "ses": "^1.8.0", From 9941bb1aa197b632674d3d4fbdc50ffffa53659f Mon Sep 17 00:00:00 2001 From: Mujahid Khan <106528609+mujahidkay@users.noreply.github.com> Date: Fri, 27 Sep 2024 04:14:15 +0500 Subject: [PATCH 2/5] chore: update yarn.lock --- yarn.lock | 70 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/yarn.lock b/yarn.lock index 8d35ea6e9..b43510fdb 100644 --- a/yarn.lock +++ b/yarn.lock @@ -264,6 +264,7 @@ __metadata: eslint-plugin-import: "npm:^2.26.0" eslint-plugin-jsdoc: "npm:^35.1.2" eslint-plugin-prettier: "npm:^5.2.1" + glob: "npm:^10.4.3" import-meta-resolve: "npm:^2.2.1" prettier: "npm:^3.3.3" ses: "npm:^1.8.0" @@ -5348,6 +5349,22 @@ __metadata: languageName: node linkType: hard +"glob@npm:^10.4.3": + version: 10.4.5 + resolution: "glob@npm:10.4.5" + dependencies: + foreground-child: "npm:^3.1.0" + jackspeak: "npm:^3.1.2" + minimatch: "npm:^9.0.4" + minipass: "npm:^7.1.2" + package-json-from-dist: "npm:^1.0.0" + path-scurry: "npm:^1.11.1" + bin: + glob: dist/esm/bin.mjs + checksum: 10c0/19a9759ea77b8e3ca0a43c2f07ecddc2ad46216b786bb8f993c445aee80d345925a21e5280c7b7c6c59e860a0154b84e4b2b60321fea92cd3c56b4a7489f160e + languageName: node + linkType: hard + "glob@npm:^7.1.3, glob@npm:^7.1.6": version: 7.1.7 resolution: "glob@npm:7.1.7" @@ -6043,6 +6060,19 @@ __metadata: languageName: node linkType: hard +"jackspeak@npm:^3.1.2": + version: 3.4.3 + resolution: "jackspeak@npm:3.4.3" + dependencies: + "@isaacs/cliui": "npm:^8.0.2" + "@pkgjs/parseargs": "npm:^0.11.0" + dependenciesMeta: + "@pkgjs/parseargs": + optional: true + checksum: 10c0/6acc10d139eaefdbe04d2f679e6191b3abf073f111edf10b1de5302c97ec93fffeb2fdd8681ed17f16268aa9dd4f8c588ed9d1d3bffbbfa6e8bf897cbb3149b9 + languageName: node + linkType: hard + "jessie.js@npm:^0.3.4": version: 0.3.4 resolution: "jessie.js@npm:0.3.4" @@ -6243,6 +6273,13 @@ __metadata: languageName: node linkType: hard +"lru-cache@npm:^10.2.0": + version: 10.4.3 + resolution: "lru-cache@npm:10.4.3" + checksum: 10c0/ebd04fbca961e6c1d6c0af3799adcc966a1babe798f685bb84e6599266599cd95d94630b10262f5424539bc4640107e8a33aa28585374abf561d30d16f4b39fb + languageName: node + linkType: hard + "lru-cache@npm:^6.0.0": version: 6.0.0 resolution: "lru-cache@npm:6.0.0" @@ -6479,6 +6516,15 @@ __metadata: languageName: node linkType: hard +"minimatch@npm:^9.0.4": + version: 9.0.5 + resolution: "minimatch@npm:9.0.5" + dependencies: + brace-expansion: "npm:^2.0.1" + checksum: 10c0/de96cf5e35bdf0eab3e2c853522f98ffbe9a36c37797778d2665231ec1f20a9447a7e567cb640901f89e4daaa95ae5d70c65a9e8aa2bb0019b6facbc3c0575ed + languageName: node + linkType: hard + "minimist@npm:^1.2.0, minimist@npm:^1.2.3, minimist@npm:^1.2.5, minimist@npm:^1.2.6": version: 1.2.6 resolution: "minimist@npm:1.2.6" @@ -6560,6 +6606,13 @@ __metadata: languageName: node linkType: hard +"minipass@npm:^7.1.2": + version: 7.1.2 + resolution: "minipass@npm:7.1.2" + checksum: 10c0/b0fd20bb9fb56e5fa9a8bfac539e8915ae07430a619e4b86ff71f5fc757ef3924b23b2c4230393af1eda647ed3d75739e4e0acb250a6b1eb277cf7f8fe449557 + languageName: node + linkType: hard + "minisearch@npm:^6.3.0": version: 6.3.0 resolution: "minisearch@npm:6.3.0" @@ -6975,6 +7028,13 @@ __metadata: languageName: node linkType: hard +"package-json-from-dist@npm:^1.0.0": + version: 1.0.0 + resolution: "package-json-from-dist@npm:1.0.0" + checksum: 10c0/e3ffaf6ac1040ab6082a658230c041ad14e72fabe99076a2081bb1d5d41210f11872403fc09082daf4387fc0baa6577f96c9c0e94c90c394fd57794b66aa4033 + languageName: node + linkType: hard + "parent-module@npm:^1.0.0": version: 1.0.1 resolution: "parent-module@npm:1.0.1" @@ -7043,6 +7103,16 @@ __metadata: languageName: node linkType: hard +"path-scurry@npm:^1.11.1": + version: 1.11.1 + resolution: "path-scurry@npm:1.11.1" + dependencies: + lru-cache: "npm:^10.2.0" + minipass: "npm:^5.0.0 || ^6.0.2 || ^7.0.0" + checksum: 10c0/32a13711a2a505616ae1cc1b5076801e453e7aae6ac40ab55b388bb91b9d0547a52f5aaceff710ea400205f18691120d4431e520afbe4266b836fadede15872d + languageName: node + linkType: hard + "path-to-regexp@npm:0.1.7": version: 0.1.7 resolution: "path-to-regexp@npm:0.1.7" From cac45a30820decfcd35122ce09715245e14151e6 Mon Sep 17 00:00:00 2001 From: Mujahid Khan <106528609+mujahidkay@users.noreply.github.com> Date: Fri, 27 Sep 2024 04:14:30 +0500 Subject: [PATCH 3/5] lint: update prettier config --- .prettierrc.json | 1 - 1 file changed, 1 deletion(-) diff --git a/.prettierrc.json b/.prettierrc.json index 95d6e1268..2ef00902e 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -2,7 +2,6 @@ "printWidth": 80, "tabWidth": 2, "useTabs": false, - "semi": false, "singleQuote": true, "proseWrap": "preserve", "trailingComma": "none", From e8cb88e308faf37f869cd6ed3c0f221f2d1efaa4 Mon Sep 17 00:00:00 2001 From: Mujahid Khan <106528609+mujahidkay@users.noreply.github.com> Date: Fri, 27 Sep 2024 04:15:06 +0500 Subject: [PATCH 4/5] lint: add custom linter script --- scripts/markdown-js-snippets-linter.mjs | 237 ++++++++++++++++++++++++ 1 file changed, 237 insertions(+) create mode 100644 scripts/markdown-js-snippets-linter.mjs diff --git a/scripts/markdown-js-snippets-linter.mjs b/scripts/markdown-js-snippets-linter.mjs new file mode 100644 index 000000000..123e56606 --- /dev/null +++ b/scripts/markdown-js-snippets-linter.mjs @@ -0,0 +1,237 @@ +import { promises as fs } from 'fs'; +import { glob } from 'glob'; + + +const extractJsSnippets = (markdownContent) => { + const pattern = /```(?:js|javascript)\n([\s\S]*?)```/g; + const matches = []; + let match; + while ((match = pattern.exec(markdownContent)) !== null) { + const startLine = markdownContent.slice(0, match.index).split('\n').length; + matches.push({ + content: match[1], + start: match.index, + end: match.index + match[0].length, + startLine: startLine, + language: match[0].startsWith('```javascript') ? 'javascript' : 'js' + }); + } + return matches; +}; + +const checkSemicolonsAndEllipsis = (code, startLine) => { + const lines = code.split('\n'); + const issues = []; + let openBrackets = 0; + let openParens = 0; + let openSquareBrackets = 0; + let inMultiLineComment = false; + + const isJSDocOrComment = (line) => { + return line.trim().startsWith('*') || + line.trim().startsWith('/**') || + line.trim().startsWith('*/') || + line.trim().startsWith('//'); + }; + + const isStatementEnd = (line, nextLine) => { + const strippedLine = line.replace(/\/\/.*$/, '').trim(); + const strippedNextLine = nextLine ? nextLine.replace(/\/\/.*$/, '').trim() : ''; + return strippedLine && + !strippedLine.endsWith('{') && + !strippedLine.endsWith('}') && + !strippedLine.endsWith(':') && + !strippedLine.endsWith(',') && + !strippedLine.endsWith('(') && + !strippedLine.endsWith('.') && + !strippedLine.endsWith('?') && + !strippedLine.endsWith('=') && + !strippedLine.endsWith('&&') && + !strippedLine.endsWith('||') && + !strippedLine.endsWith('=>') && + !strippedLine.startsWith('else') && + !strippedLine.startsWith('catch') && + !strippedLine.startsWith('finally') && + !strippedNextLine.trim().startsWith('.') && + !strippedNextLine.trim().startsWith('(') && + !strippedNextLine.trim().startsWith('.then') && + !strippedNextLine.trim().startsWith('.catch') && + !strippedNextLine.trim().startsWith('.finally') && + openBrackets === 0 && + openParens === 0 && + openSquareBrackets === 0; + }; + + const shouldHaveSemicolon = (line, nextLine) => { + const strippedLine = line.replace(/\/\/.*$/, '').trim(); + return (strippedLine.startsWith('const ') || + strippedLine.startsWith('let ') || + strippedLine.startsWith('var ') || + strippedLine.includes('=') || + /\bawait\b/.test(strippedLine) || + (/^[a-zA-Z_$][a-zA-Z0-9_$]*(\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$/.test(strippedLine) && !strippedLine.endsWith('.')) || + (/^[a-zA-Z_$][a-zA-Z0-9_$]*\[[0-9]+\]$/.test(strippedLine))) && + isStatementEnd(line, nextLine); + }; + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + const nextLine = i < lines.length - 1 ? lines[i + 1] : null; + + if (line.includes('/*')) inMultiLineComment = true; + if (line.includes('*/')) { + inMultiLineComment = false; + continue; + } + if (inMultiLineComment || isJSDocOrComment(line)) continue; + + openBrackets += (line.match(/\{/g) || []).length - (line.match(/\}/g) || []).length; + openParens += (line.match(/\(/g) || []).length - (line.match(/\)/g) || []).length; + openSquareBrackets += (line.match(/\[/g) || []).length - (line.match(/\]/g) || []).length; + + const codeWithoutComment = line.replace(/\/\/.*$/, '').trim(); + + // Check for standalone '...' + if (codeWithoutComment === '...') { + issues.push({ + line: startLine + i, + original: line.trim(), + fixed: '// ...', + type: 'ellipsis' + }); + } else if (shouldHaveSemicolon(line, nextLine) && !codeWithoutComment.endsWith(';')) { + issues.push({ + line: startLine + i, + original: line.trim(), + fixed: `${codeWithoutComment};${line.includes('//') ? ' ' + line.split('//')[1] : ''}`, + type: 'semicolon' + }); + } + } + + return issues; +}; + + +const lintMarkdownFile = async (filePath, fix = false) => { + try { + const content = await fs.readFile(filePath, 'utf8'); + const jsSnippets = extractJsSnippets(content); + let fixedContent = content; + const allIssues = []; + + for (let i = jsSnippets.length - 1; i >= 0; i--) { + const snippet = jsSnippets[i]; + const issues = checkSemicolonsAndEllipsis(snippet.content, snippet.startLine); + allIssues.push(...issues.map(issue => ({ ...issue, snippet: i + 1 }))); + + if (fix) { + const fixedLines = snippet.content.split('\n'); + issues.forEach(issue => { + const lineIndex = issue.line - snippet.startLine; + fixedLines[lineIndex] = issue.fixed; + }); + const fixedSnippet = fixedLines.join('\n'); + fixedContent = fixedContent.slice(0, snippet.start) + + '```js\n' + fixedSnippet + '```' + + fixedContent.slice(snippet.end); + } + } + + // Count ```javascript instances + const javascriptCount = (content.match(/```javascript/g) || []).length; + + // Replace all ```javascript with ```js + if (fix) { + fixedContent = fixedContent.replace(/```javascript/g, '```js'); + } + + if (fix && (allIssues.length > 0 || content !== fixedContent)) { + await fs.writeFile(filePath, fixedContent, 'utf8'); + } + + return { + filePath, + issues: allIssues, + fixedContent: fix ? fixedContent : null, + javascriptCount: javascriptCount + }; + } catch (error) { + console.error(`Error processing file ${filePath}: ${error.message}`); + return { filePath, issues: [], error: error.message }; + } +}; +const processFiles = async (globPattern, fix = false) => { + try { + const files = await glob(globPattern); + if (files.length === 0) { + console.error('No files found matching the pattern.'); + process.exit(1); + } + + let totalIssues = 0; + let totalJavascriptInstances = 0; + let hasErrors = false; + + for (const file of files) { + const { issues, error, javascriptCount } = await lintMarkdownFile(file, fix); + if (error) { + console.error(`\nError in file ${file}:`); + console.error(error); + hasErrors = true; + } else { + if (issues.length > 0) { + console.error(`\nFound ${issues.length} error(s) in ${file}:`); + issues.forEach(issue => { + console.error(`\nSnippet ${issue.snippet}, Line ${issue.line}:`); + console.error(`Original: ${issue.original}`); + console.error(`${fix ? 'Fixed: ' : 'Suggested:'} ${issue.fixed}`); + }); + totalIssues += issues.length; + hasErrors = true; + } + if (javascriptCount > 0) { + console.error(`\nFound ${javascriptCount} instance(s) of \`\`\`javascript in ${file}`); + totalJavascriptInstances += javascriptCount; + hasErrors = true; + } + } + } + + if (totalIssues > 0 || totalJavascriptInstances > 0) { + console.error(`\nTotal errors found: ${totalIssues}`); + console.error(`Total \`\`\`javascript instances found: ${totalJavascriptInstances}`); + if (fix) { + console.log("All matching files have been updated with the necessary changes."); + } else { + console.error("Run with --fix to automatically fix these errors and replace \`\`\`javascript with \`\`\`js."); + } + } else { + console.log("No errors found in any of the matching files."); + } + + if (hasErrors && !fix) { + process.exit(1); + } + } catch (error) { + console.error(`Error processing files: ${error.message}`); + process.exit(1); + } +}; + +const main = async () => { + if (process.argv.length < 3 || process.argv.length > 4) { + console.error("Usage: node linter.js [--fix]"); + process.exit(1); + } + + const globPattern = process.argv[2]; + const fix = process.argv.includes('--fix'); + + await processFiles(globPattern, fix); +}; + +main().catch(error => { + console.error(`Unhandled error: ${error.message}`); + process.exit(1); +}); From fcb738e080b02590669b6c04a9d786512d72c466 Mon Sep 17 00:00:00 2001 From: Mujahid Khan <106528609+mujahidkay@users.noreply.github.com> Date: Fri, 27 Sep 2024 04:15:27 +0500 Subject: [PATCH 5/5] lint: inline snippets --- CONTRIBUTING.md | 8 +- main/e2e-testing.md | 30 +++---- main/glossary/index.md | 12 +-- main/guides/coreeval/permissions.md | 4 +- main/guides/coreeval/proposal.md | 46 +++++----- main/guides/getting-started/deploying.md | 2 +- ...sell-concert-tickets-contract-explainer.md | 28 +++--- .../swaparoo-how-to-swap-assets-explainer.md | 52 +++++------ .../swaparoo-making-a-payment-explainer.md | 6 +- .../ui-tutorial/agoric-provider.md | 16 ++-- .../ui-tutorial/connect-wallet.md | 32 +++---- .../ui-tutorial/making-an-offer.md | 42 ++++----- .../ui-tutorial/querying-vstorage.md | 18 ++-- .../getting-started/ui-tutorial/starting.md | 18 ++-- main/guides/governance/index.md | 78 ++++++++-------- main/guides/integration/name-services.md | 16 ++-- main/guides/js-programming/far.md | 6 +- main/guides/js-programming/hardened-js.md | 38 ++++---- main/guides/js-programming/notifiers.md | 44 ++++----- .../orchestration/getting-started/api.md | 44 ++++----- .../contract-walkthrough/cross-chain-swap.md | 86 +++++++++--------- .../cross-chain-unbond.md | 42 ++++----- .../getting-started/key-concepts.md | 32 +++---- main/guides/wallet/index.md | 6 +- main/guides/zoe/actual-contracts/PSM.md | 12 +-- main/guides/zoe/contract-requirements.md | 16 ++-- main/guides/zoe/contract-upgrade.md | 78 ++++++++-------- main/guides/zoe/contract-walkthru.md | 4 +- main/guides/zoe/contracts/atomic-swap.md | 52 +++++------ .../zoe/contracts/constantProductAMM.md | 42 ++++----- main/guides/zoe/contracts/covered-call.md | 58 ++++++------ .../zoe/contracts/second-price-auction.md | 50 +++++------ main/guides/zoe/contracts/simple-exchange.md | 61 +++++++------ main/guides/zoe/offer-enforcement.md | 28 +++--- main/guides/zoe/price-authority.md | 4 +- main/guides/zoe/proposal.md | 4 +- main/guides/zoe/pub-to-storage.md | 20 ++--- main/reference/ertp-api/amount-math.md | 90 +++++++++---------- main/reference/ertp-api/brand.md | 6 +- main/reference/ertp-api/ertp-data-types.md | 6 +- main/reference/ertp-api/issuer.md | 90 ++++++++++--------- main/reference/ertp-api/mint.md | 13 +-- main/reference/ertp-api/payment.md | 4 +- main/reference/ertp-api/purse.md | 56 ++++++------ main/reference/repl/networking.md | 20 ++--- main/reference/repl/timerServices.md | 2 +- main/reference/vstorage-ref.md | 14 +-- main/reference/zoe-api/price-authority.md | 30 +++---- main/reference/zoe-api/ratio-math.md | 52 +++++------ main/reference/zoe-api/user-seat.md | 2 +- main/reference/zoe-api/zcfseat.md | 30 +++---- main/reference/zoe-api/zoe-contract-facet.md | 38 ++++---- main/reference/zoe-api/zoe-data-types.md | 8 +- main/reference/zoe-api/zoe-helpers.md | 52 +++++------ main/reference/zoe-api/zoe.md | 46 +++++----- 55 files changed, 852 insertions(+), 842 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b01b2bf3b..525c11c0e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -107,7 +107,7 @@ module.exports = { themeConfig: { sidebar: 'auto' } -} +}; ``` Or, add a config entry, either as part of a group or as an individual page. @@ -133,7 +133,7 @@ module.exports = { } ] } -} +}; ``` ## Writing Links @@ -564,8 +564,8 @@ export default ({ router }) => { path: '/getting-started/agoric-cli-guide.html', redirect: '/guides/agoric-cli/' } - ]) -} + ]); +}; ``` The general format should be self-explanatory. However, there are two things you need to know that aren't apparent diff --git a/main/e2e-testing.md b/main/e2e-testing.md index 6871f2821..a42a094d8 100644 --- a/main/e2e-testing.md +++ b/main/e2e-testing.md @@ -40,8 +40,8 @@ Before you start writing your E2E tests, you'll need to create a configuration f Inside `synpress.config.js`, you'll set the `baseUrl` property within the e2e configuration. This tells Cypress where to find your DApp during testing. Here's an example configuration: ```js -const baseConfig = require('@agoric/synpress/synpress.config') -const { defineConfig } = require('cypress') +const baseConfig = require('@agoric/synpress/synpress.config'); +const { defineConfig } = require('cypress'); module.exports = defineConfig({ ...baseConfig, @@ -49,7 +49,7 @@ module.exports = defineConfig({ ...baseConfig.e2e, baseUrl: 'http://localhost:5173' } -}) +}); ``` In this example, `baseUrl` is set to `http://localhost:5173`. Make sure to replace this with the actual URL where your DApp is running. @@ -69,7 +69,7 @@ Navigate to your project's `tests/e2e` directory and create a new file named `su After creating your `support.js` file, make sure to include the following import statement: ```js -import '@agoric/synpress/support/index' +import '@agoric/synpress/support/index'; ``` This import is essential because it brings in the necessary functionalities from `@agoric/synpress` to interact with the Keplr wallet within your e2e tests. Without it, your tests won't be able to leverage the features provided by `@agoric/synpress` for Keplr integration. @@ -86,8 +86,8 @@ You use `describe` blocks to group related tests together, and `it` blocks to de describe('User Login', () => { it('should login with valid credentials', () => { // Test steps for login functionality - }) -}) + }); +}); ``` ### Test 1: Setting Up Keplr Wallet @@ -96,9 +96,9 @@ describe('User Login', () => { it('should setup a Keplr wallet', () => { cy.setupWallet({ secretWords: 'KEPLR_MNEMONIC' - }) - cy.visit('/') -}) + }); + cy.visit('/'); +}); ``` This test case simulates setting up a Keplr wallet for your tests, using the `cy.setupWallet` method. Make sure to replace `KEPLR_MNEMONIC` with a 24-word mnemonic phrase. The `setupWallet` method creates a wallet based on the provided mnemonic phrase, which can then be used throughout your test suite. @@ -109,9 +109,9 @@ After setting up the wallet, we visit the root path (`/`) of the DApp using `cy. ```js it('should accept connection with wallet', () => { - cy.contains('Connect Wallet').click() - cy.acceptAccess() -}) + cy.contains('Connect Wallet').click(); + cy.acceptAccess(); +}); ``` This test simulates a user connecting their Keplr wallet to your DApp. `cy.contains('Connect Wallet')` searches for an element containing the text `Connect Wallet` on the webpage and triggers a click event. `cy.acceptAccess` simulates accepting Keplr wallet access for your DApp. @@ -120,9 +120,9 @@ This test simulates a user connecting their Keplr wallet to your DApp. `cy.conta ```js it('should confirm make an offer transaction', () => { - cy.contains('Make an Offer').click() - cy.confirmTransaction() -}) + cy.contains('Make an Offer').click(); + cy.confirmTransaction(); +}); ``` This test simulates transaction Signing on your DApp. `cy.contains('Make an Offer')` searches for an element containing the text `Make an Offer` and triggers a click event. `cy.confirmTransaction` simulates confirming a transaction. diff --git a/main/glossary/index.md b/main/glossary/index.md index 94eaffb0c..21428a868 100644 --- a/main/glossary/index.md +++ b/main/glossary/index.md @@ -141,10 +141,10 @@ and the [ERTP API's Brand section](/reference/ertp-api/brand). Before a contract can be installed on Zoe, its source code must be bundled. This is done by: ```js -import bundleSource from '@endo/bundle-source' +import bundleSource from '@endo/bundle-source'; const atomicSwapBundle = await bundleSource( require.resolve('@agoric/zoe/src/contracts/atomicSwap') -) +); ``` The installation operation returns an `installation`, which is an object with a single @@ -153,7 +153,7 @@ In most cases, the bundle contains a base64-encoded zip file that you can extract for review. ```js -const { endoZipBase64 } = await E(installation).getBundle() +const { endoZipBase64 } = await E(installation).getBundle(); ``` ```sh @@ -296,10 +296,10 @@ A _facet_ is an object that exposes an API or particular view of some larger ent You can make any number of facets of an entity. In JavaScript, you often make a facet that forwards method calls: ```js -import { Far } from '@endo/far' +import { Far } from '@endo/far'; const facet = Far('FacetName', { myMethod: (...args) => oldObject.method(...args) -}) +}); ``` Two Agoric uses are: @@ -550,7 +550,7 @@ const myProposal = harden({ give: { Asset: AmountMath.make(quatloosBrand, 4n) }, want: { Price: AmountMath.make(moolaBrand, 15n) }, exit: { onDemand: null } -}) +}); ``` `give` and `want` each associate [Keywords](#keyword) defined by the contract with corresponding [Amounts](#amount) describing respectively what will be given and what is being requested in exchange. diff --git a/main/guides/coreeval/permissions.md b/main/guides/coreeval/permissions.md index c4a00cfc9..251df205f 100644 --- a/main/guides/coreeval/permissions.md +++ b/main/guides/coreeval/permissions.md @@ -25,9 +25,9 @@ export const permit = harden({ instance: { produce: { [contractName]: true } }, issuer: { consume: { IST: true }, produce: { Ticket: true } }, brand: { consume: { IST: true }, produce: { Ticket: true } } -}) +}); -export const main = startSellConcertTicketsContract +export const main = startSellConcertTicketsContract; ``` ## Selected BootstrapPowers diff --git a/main/guides/coreeval/proposal.md b/main/guides/coreeval/proposal.md index 6afe36706..5264c2d71 100644 --- a/main/guides/coreeval/proposal.md +++ b/main/guides/coreeval/proposal.md @@ -19,15 +19,15 @@ After some preliminaries, ... ```js // @ts-check -import { allValues } from './objectTools.js' +import { allValues } from './objectTools.js'; import { AmountMath, installContract, startContract -} from './platform-goals/start-contract.js' +} from './platform-goals/start-contract.js'; -const { Fail } = assert -const IST_UNIT = 1_000_000n +const { Fail } = assert; +const IST_UNIT = 1_000_000n; export const makeInventory = (brand, baseUnit) => { return { @@ -43,14 +43,14 @@ export const makeInventory = (brand, baseUnit) => { tradePrice: AmountMath.make(brand, baseUnit * 1n), maxTickets: 3n } - } -} + }; +}; export const makeTerms = (brand, baseUnit) => { return { inventory: makeInventory(brand, baseUnit) - } -} + }; +}; /** * @typedef {{ @@ -66,7 +66,7 @@ export const makeTerms = (brand, baseUnit) => { ... the function for deploying the contract is `startSellConcertTicketsContract`: ```js -const contractName = 'sellConcertTickets' +const contractName = 'sellConcertTickets'; /** * Core eval script to start contract @@ -75,23 +75,23 @@ const contractName = 'sellConcertTickets' * @param {*} config */ export const startSellConcertTicketsContract = async (powers, config) => { - console.log('core eval for', contractName) + console.log('core eval for', contractName); const { // must be supplied by caller or template-replaced bundleID = Fail`no bundleID` - } = config?.options?.[contractName] ?? {} + } = config?.options?.[contractName] ?? {}; const installation = await installContract(powers, { name: contractName, bundleID - }) + }); const ist = await allValues({ brand: powers.brand.consume.IST, issuer: powers.issuer.consume.IST - }) + }); - const terms = makeTerms(ist.brand, 1n * IST_UNIT) + const terms = makeTerms(ist.brand, 1n * IST_UNIT); await startContract(powers, { name: contractName, @@ -101,10 +101,10 @@ export const startSellConcertTicketsContract = async (powers, config) => { terms }, issuerNames: ['Ticket'] - }) + }); - console.log(contractName, '(re)started') -} + console.log(contractName, '(re)started'); +}; ``` A `BootstrapPowers` object is composed of several _promise spaces_. @@ -137,12 +137,12 @@ export const installContract = async ( { consume: { zoe }, installation: { produce: produceInstallation } }, { name, bundleID } ) => { - const installation = await E(zoe).installBundleID(bundleID) - produceInstallation[name].reset() - produceInstallation[name].resolve(installation) - console.log(name, 'installed as', bundleID.slice(0, 8)) - return installation -} + const installation = await E(zoe).installBundleID(bundleID); + produceInstallation[name].reset(); + produceInstallation[name].resolve(installation); + console.log(name, 'installed as', bundleID.slice(0, 8)); + return installation; +}; ``` This `installation` promise space is linked to the `E(agoricNames).lookup('installation')` NameHub: when you call `produce[name].resolve(value)` on the installation promise space, it triggers an update in the NameHub. The update associates the provided name with the provided value so that `E(agoricNames).lookup('installation', name)` is a promise for `value`. diff --git a/main/guides/getting-started/deploying.md b/main/guides/getting-started/deploying.md index 40b527786..b5a7445d8 100644 --- a/main/guides/getting-started/deploying.md +++ b/main/guides/getting-started/deploying.md @@ -58,7 +58,7 @@ file `ui/public/conf/installationConstants.js` with contents like: export default { CONTRACT_NAME: 'fungibleFaucet', INSTALLATION_BOARD_ID: '1456154132' -} +}; ``` The board provides a unique ID per object, in this case diff --git a/main/guides/getting-started/sell-concert-tickets-contract-explainer.md b/main/guides/getting-started/sell-concert-tickets-contract-explainer.md index b5ac214e7..92610affc 100644 --- a/main/guides/getting-started/sell-concert-tickets-contract-explainer.md +++ b/main/guides/getting-started/sell-concert-tickets-contract-explainer.md @@ -33,7 +33,7 @@ const inventory = { tradePrice: AmountMath.make(istBrand, n), maxTickets: n } -} +}; ``` Our contract takes the provided `inventory` object as a parameter to initiate the process. @@ -49,8 +49,8 @@ In our example, tickets are non-fungible and can have duplicates, meaning there ```js -const ticketMint = await zcf.makeZCFMint('Ticket', AssetKind.COPY_BAG) -const { brand: ticketBrand } = ticketMint.getIssuerRecord() +const ticketMint = await zcf.makeZCFMint('Ticket', AssetKind.COPY_BAG); +const { brand: ticketBrand } = ticketMint.getIssuerRecord(); ``` Once our asset is defined, we will mint our inventory at the start of our the smart contract and allocate it to our `inventorySeat` object. @@ -69,14 +69,14 @@ const inventoryBag = makeCopyBag( ticket, maxTickets ]) -) +); const toMint = { Tickets: { brand: ticketBrand, value: inventoryBag } -} -const inventorySeat = ticketMint.mintGains(toMint) +}; +const inventorySeat = ticketMint.mintGains(toMint); ``` ## Trading Tickets @@ -85,7 +85,7 @@ Customers who wish to purchase event tickets first [make an invitation](https:// ```js const makeTradeInvitation = () => - zcf.makeInvitation(tradeHandler, 'buy tickets', undefined, proposalShape) + zcf.makeInvitation(tradeHandler, 'buy tickets', undefined, proposalShape); ``` Here you can see two important parameters: @@ -94,9 +94,9 @@ Here you can see two important parameters: ```js const tradeHandler = buyerSeat => { - const { give, want } = buyerSeat.getProposal() + const { give, want } = buyerSeat.getProposal(); // ... checks and transfers -} +}; ``` - **proposalShape** (Optional): This object outlines the necessary and permissible elements of each [proposal](https://docs.agoric.com/reference/zoe-api/zoe-contract-facet.html#proposal-shapes). Here is the proposal shape for this contract. @@ -106,7 +106,7 @@ const proposalShape = harden({ give: { Price: AmountShape }, want: { Tickets: { brand: ticketBrand, value: M.bag() } }, exit: M.any() -}) +}); ``` ## Trade Handler @@ -115,20 +115,20 @@ The `tradeHandler` function begins by checking to see if there are enough ticket ```js AmountMath.isGTE(inventorySeat.getCurrentAllocation().Tickets, want.Tickets) || - Fail`Not enough inventory, ${q(want.Tickets)} wanted` + Fail`Not enough inventory, ${q(want.Tickets)} wanted`; ``` Next, the total price is calcualted using `bagPrice`: ```js -const totalPrice = bagPrice(want.Tickets.value, inventory) +const totalPrice = bagPrice(want.Tickets.value, inventory); ``` After that, a check is made to ensure the offered price is sufficient: ```js AmountMath.isGTE(give.Price, totalPrice) || - Fail`Total price is ${q(totalPrice)}, but ${q(give.Price)} was given` + Fail`Total price is ${q(totalPrice)}, but ${q(give.Price)} was given`; ``` Finally, `atomicRearrange` can be called to exchange the requested tickets for the required payment: @@ -142,7 +142,7 @@ atomicRearrange( // tickets from inventory to buyer [inventorySeat, buyerSeat, want] ]) -) +); ``` Take a complete look at this example code in our [Github repository](https://github.com/Agoric/dapp-agoric-basics/blob/main/contract/src/sell-concert-tickets.contract.js). diff --git a/main/guides/getting-started/swaparoo-how-to-swap-assets-explainer.md b/main/guides/getting-started/swaparoo-how-to-swap-assets-explainer.md index 57d770648..df3a18429 100644 --- a/main/guides/getting-started/swaparoo-how-to-swap-assets-explainer.md +++ b/main/guides/getting-started/swaparoo-how-to-swap-assets-explainer.md @@ -11,10 +11,10 @@ Let's take a look at how this contract works: The contract retrieves the `feeIssuer` from the Zoe service, which is an issuer for the stable token used for fees. It creates a `feeSeat` and a `feeShape` based on the `feeAmount` specified in the contract terms. ```js -const stableIssuer = await E(zcf.getZoeService()).getFeeIssuer() -const feeBrand = await E(stableIssuer).getBrand() -const { zcfSeat: feeSeat } = zcf.makeEmptySeatKit() -const feeShape = makeNatAmountShape(feeBrand, feeAmount.value) +const stableIssuer = await E(zcf.getZoeService()).getFeeIssuer(); +const feeBrand = await E(stableIssuer).getBrand(); +const { zcfSeat: feeSeat } = zcf.makeEmptySeatKit(); +const feeShape = makeNatAmountShape(feeBrand, feeAmount.value); ``` ## Making the First Invitation @@ -23,24 +23,24 @@ The `makeFirstInvitation` function is called with an array of issuers. It verifi ```js const makeFirstInvitation = issuers => { - mustMatch(issuers, M.arrayOf(IssuerShape)) + mustMatch(issuers, M.arrayOf(IssuerShape)); for (const i of issuers) { if (!Object.values(zcf.getTerms().issuers).includes(i)) { - zcf.saveIssuer(i, `Issuer${(issuerNumber += 1)}`) + zcf.saveIssuer(i, `Issuer${(issuerNumber += 1)}`); } } const proposalShape = M.splitRecord({ give: M.splitRecord({ Fee: feeShape }) - }) + }); const firstInvitation = zcf.makeInvitation( makeSecondInvitation, 'create a swap', undefined, proposalShape - ) - return firstInvitation -} + ); + return firstInvitation; +}; ``` ## Making the Second Invitation @@ -49,15 +49,15 @@ When the first party accepts the invitation, the `makeSecondInvitation` function ```js const makeSecondInvitation = async (firstSeat, offerArgs) => { - mustMatch(offerArgs, harden({ addr: M.string() })) - const { addr: secondPartyAddress } = offerArgs + mustMatch(offerArgs, harden({ addr: M.string() })); + const { addr: secondPartyAddress } = offerArgs; const secondDepositFacet = await E(depositFacetFromAddr).lookup( secondPartyAddress, 'depositFacet' - ) + ); // ... -} +}; ``` From there a second invitation is created with an offer handler that checks if the second party's proposal matches the first party's want. If it does, it calls the `swapWithFee` function to perform the asset swap and collect the fee. @@ -66,17 +66,17 @@ From there a second invitation is created with an offer handler that checks if t const secondSeatOfferHandler = secondSeat => { if (!matches(secondSeat.getProposal(), makeSecondProposalShape(want1))) { // Handle mismatched proposals - return + return; } - return swapWithFee(zcf, firstSeat, secondSeat, feeSeat, feeAmount) -} + return swapWithFee(zcf, firstSeat, secondSeat, feeSeat, feeAmount); +}; const secondSeatInvitation = await zcf.makeInvitation( secondSeatOfferHandler, 'matchOffer', { give: give1, want: want1 } -) +); ``` ## Performing the swap @@ -85,7 +85,7 @@ The `swapWithFee` function uses the `atomicRearrange` function from Zoe to perfo ```js export const swapWithFee = (zcf, firstSeat, secondSeat, feeSeat, feeAmount) => { - const { Fee: _, ...firstGive } = firstSeat.getProposal().give + const { Fee: _, ...firstGive } = firstSeat.getProposal().give; atomicRearrange( zcf, @@ -94,12 +94,12 @@ export const swapWithFee = (zcf, firstSeat, secondSeat, feeSeat, feeAmount) => { [secondSeat, firstSeat, secondSeat.getProposal().give], [firstSeat, feeSeat, { Fee: feeAmount }] ]) - ) + ); - firstSeat.exit() - secondSeat.exit() - return 'success' -} + firstSeat.exit(); + secondSeat.exit(); + return 'success'; +}; ``` ## Collecting fees @@ -109,9 +109,9 @@ The contract also provides a `creatorFacet` with a `makeCollectFeesInvitation` m ```js const creatorFacet = Far('Creator', { makeCollectFeesInvitation() { - return makeCollectFeesInvitation(zcf, feeSeat, feeBrand, 'Fee') + return makeCollectFeesInvitation(zcf, feeSeat, feeBrand, 'Fee'); } -}) +}); ``` ## Video Walkthrough diff --git a/main/guides/getting-started/swaparoo-making-a-payment-explainer.md b/main/guides/getting-started/swaparoo-making-a-payment-explainer.md index b934ef2c7..815eb76aa 100644 --- a/main/guides/getting-started/swaparoo-making-a-payment-explainer.md +++ b/main/guides/getting-started/swaparoo-making-a-payment-explainer.md @@ -10,11 +10,11 @@ Let's take a look at the following code snippet from the Swaparoo contract: const secondDepositFacet = await E(depositFacetFromAddr).lookup( secondPartyAddress, 'depositFacet' -) +); -await E(secondDepositFacet).receive(secondSeatInvitation) +await E(secondDepositFacet).receive(secondSeatInvitation); -return 'invitation sent' +return 'invitation sent'; ``` ## Step-by-Step Explanation diff --git a/main/guides/getting-started/ui-tutorial/agoric-provider.md b/main/guides/getting-started/ui-tutorial/agoric-provider.md index 666303df0..ab140fb1d 100644 --- a/main/guides/getting-started/ui-tutorial/agoric-provider.md +++ b/main/guides/getting-started/ui-tutorial/agoric-provider.md @@ -35,14 +35,14 @@ Put the provider in the root of your application by editing `App.tsx`. We can al The end result should look something like this: ```tsx -import { AgoricProvider, ConnectWalletButton } from '@agoric/react-components' -import { wallets } from 'cosmos-kit' -import { ThemeProvider, useTheme } from '@interchain-ui/react' -import './App.css' -import '@agoric/react-components/dist/style.css' +import { AgoricProvider, ConnectWalletButton } from '@agoric/react-components'; +import { wallets } from 'cosmos-kit'; +import { ThemeProvider, useTheme } from '@interchain-ui/react'; +import './App.css'; +import '@agoric/react-components/dist/style.css'; function App() { - const { themeClass } = useTheme() + const { themeClass } = useTheme(); return (
@@ -67,10 +67,10 @@ function App() {
- ) + ); } -export default App +export default App; ``` You may have noticed the `defaultChainName` prop points to a local chain. This assumes diff --git a/main/guides/getting-started/ui-tutorial/connect-wallet.md b/main/guides/getting-started/ui-tutorial/connect-wallet.md index 550415d9f..c3982eaaa 100644 --- a/main/guides/getting-started/ui-tutorial/connect-wallet.md +++ b/main/guides/getting-started/ui-tutorial/connect-wallet.md @@ -21,10 +21,10 @@ showing the user's IST balance. Create a new file, `src/Purses.tsx`, where you'll write a component for rendering purse balances. ```tsx -import { useAgoric } from '@agoric/react-components' +import { useAgoric } from '@agoric/react-components'; const Purses = () => { - const { walletConnection } = useAgoric() + const { walletConnection } = useAgoric(); return (
@@ -40,10 +40,10 @@ const Purses = () => { 'No wallet connected.' )}
- ) -} + ); +}; -export default Purses +export default Purses; ``` Then, in `App.tsx` render the component inside the `AgoricProvider`, below the @@ -68,13 +68,13 @@ We'll access the purse data from the `useAgoric` hook. First, we'll create a new since we'll need to render another purse for the NFTs later on. Create a new file, `src/hooks.ts` ```ts -import { useAgoric } from '@agoric/react-components' +import { useAgoric } from '@agoric/react-components'; export const usePurse = (brandPetname: string) => { - const { purses } = useAgoric() + const { purses } = useAgoric(); - return purses?.find(p => p.brandPetname === brandPetname) -} + return purses?.find(p => p.brandPetname === brandPetname); +}; ``` This provides a utility for looking up a user's purse by name. Notice how it accesses `purses` from `useAgoric()`. @@ -92,13 +92,13 @@ yarn add -D @agoric/web-components@0.16.0 Then, in `Purses.tsx`, we can put it all together to render the IST balance: ```tsx -import { useAgoric } from '@agoric/react-components' -import { usePurse } from './hooks' -import { stringifyAmountValue } from '@agoric/web-components' +import { useAgoric } from '@agoric/react-components'; +import { usePurse } from './hooks'; +import { stringifyAmountValue } from '@agoric/web-components'; const Purses = () => { - const { walletConnection } = useAgoric() - const istPurse = usePurse('IST') + const { walletConnection } = useAgoric(); + const istPurse = usePurse('IST'); return (
@@ -122,8 +122,8 @@ const Purses = () => { 'No wallet connected.' )}
- ) -} + ); +}; ``` When the app rebuilds, you should see the real IST balance appear below "Purses". Now you're able diff --git a/main/guides/getting-started/ui-tutorial/making-an-offer.md b/main/guides/getting-started/ui-tutorial/making-an-offer.md index 975952025..ec0bc26fe 100644 --- a/main/guides/getting-started/ui-tutorial/making-an-offer.md +++ b/main/guides/getting-started/ui-tutorial/making-an-offer.md @@ -14,7 +14,7 @@ the Items they want. There's 3 types of items available for sale in the contract creating an array to list them in `Trade.tsx`: ```ts -const allItems = ['scroll', 'map', 'potion'] +const allItems = ['scroll', 'map', 'potion']; ``` Next, add another component to `Trade.tsx` for letting the user choose the amount of each item in the offer: @@ -26,10 +26,10 @@ const Item = ({ onChange, inputStep }: { - label: string - value: number | string - onChange: React.ChangeEventHandler - inputStep?: string + label: string; + value: number | string; + onChange: React.ChangeEventHandler; + inputStep?: string; }) => (

{label}

@@ -44,7 +44,7 @@ const Item = ({ className="input" />
-) +); ``` And add some styles to `App.css`: @@ -168,26 +168,26 @@ Recall the `useContract` hook you added to your `Trade` component previously. No brands and instance from that to submit the offer: ```ts -const { brands, instance } = useContract() +const { brands, instance } = useContract(); ``` Next, get the `makeOffer` function from the `useAgoric()` hook: ```ts -const { makeOffer } = useAgoric() +const { makeOffer } = useAgoric(); ``` Now, create a function to submit the offer. For more details on how this works, see [making an offer](../../getting-started/explainer-how-to-make-an-offer.md): ```ts -import { makeCopyBag } from '@agoric/store' +import { makeCopyBag } from '@agoric/store'; // Inside your 'Trade' component: const submitOffer = () => { - assert(brands && instance && makeOffer) - const value = makeCopyBag(Object.entries(choices)) - const want = { Items: { brand: brands.Item, value } } - const give = { Price: { brand: brands.IST, value: giveValue } } + assert(brands && instance && makeOffer); + const value = makeCopyBag(Object.entries(choices)); + const want = { Items: { brand: brands.Item, value } }; + const give = { Price: { brand: brands.IST, value: giveValue } }; makeOffer( { @@ -198,19 +198,19 @@ const submitOffer = () => { { give, want }, undefined, (update: { status: string; data?: unknown }) => { - console.log('UPDATE', update) + console.log('UPDATE', update); if (update.status === 'error') { - alert(`Offer error: ${update.data}`) + alert(`Offer error: ${update.data}`); } if (update.status === 'accepted') { - alert('Offer accepted') + alert('Offer accepted'); } if (update.status === 'refunded') { - alert('Offer rejected') + alert('Offer rejected'); } } - ) -} + ); +}; ``` For specifics on how offers work, see [Specifying Offers](../../getting-started/contract-rpc.md#specifying-offers). The `makeOffer` function allows you to specify an @@ -227,7 +227,7 @@ And add the type to `vite-env.d.ts`: ```ts declare module '@agoric/store' { - export const makeCopyBag + export const makeCopyBag; } ``` @@ -237,7 +237,7 @@ Now, simply add a button to submit the offer: { !!(brands && instance && makeOffer && istPurse) && ( - ) + ); } ``` diff --git a/main/guides/getting-started/ui-tutorial/querying-vstorage.md b/main/guides/getting-started/ui-tutorial/querying-vstorage.md index 1d2f99523..e06ddb3f3 100644 --- a/main/guides/getting-started/ui-tutorial/querying-vstorage.md +++ b/main/guides/getting-started/ui-tutorial/querying-vstorage.md @@ -14,7 +14,7 @@ to use the RPC endpoints we added earlier. Example: ```ts -const { chainStorageWatcher } = useAgoric() +const { chainStorageWatcher } = useAgoric(); ``` ## Querying Vstorage @@ -29,10 +29,10 @@ Create a new file, `src/Trade.tsx`: const Trade = () => { return (
TODO - Create inputs for submitting an offer.
- ) -} + ); +}; -export default Trade +export default Trade; ``` And add some styling for it in `App.css` while we're at it: @@ -120,18 +120,18 @@ and emits updates when the data on-chain changes. For more details about vstorag Next, go ahead and add this hook to the `Trade` component you made before this: ```tsx -import { useContract } from './hooks' +import { useContract } from './hooks'; const Trade = () => { // Don't do anything with brands or instances yet. - useContract() + useContract(); return (
TODO - Create inputs for submitting an offer.
- ) -} + ); +}; -export default Trade +export default Trade; ``` You should now see the `brands` and `instances` being logged to the console. See if you diff --git a/main/guides/getting-started/ui-tutorial/starting.md b/main/guides/getting-started/ui-tutorial/starting.md index 7755a5c5e..466eb8ac9 100644 --- a/main/guides/getting-started/ui-tutorial/starting.md +++ b/main/guides/getting-started/ui-tutorial/starting.md @@ -35,30 +35,30 @@ yarn add -D buffer Now, create a new file `src/installSesLockdown.ts`: ```typescript -import 'ses' // adds lockdown, harden, and Compartment -import '@endo/eventual-send/shim.js' // adds support needed by E -import { Buffer } from 'buffer' +import 'ses'; // adds lockdown, harden, and Compartment +import '@endo/eventual-send/shim.js'; // adds support needed by E +import { Buffer } from 'buffer'; -const consoleTaming = import.meta.env.DEV ? 'unsafe' : 'safe' +const consoleTaming = import.meta.env.DEV ? 'unsafe' : 'safe'; lockdown({ errorTaming: 'unsafe', overrideTaming: 'severe', consoleTaming -}) +}); -Error.stackTraceLimit = Infinity +Error.stackTraceLimit = Infinity; -globalThis.Buffer = Buffer +globalThis.Buffer = Buffer; // @ts-expect-error Add process to context for cosmos-kit -globalThis.process = { env: import.meta.env } +globalThis.process = { env: import.meta.env }; ``` And at the top of `src/main.tsx` import the new file: ```typescript -import './installSesLockdown.ts' +import './installSesLockdown.ts'; ``` Restart your app and it should load as before without errors. Now, the app is running with Hardened JS enabled and we're ready to continue. diff --git a/main/guides/governance/index.md b/main/guides/governance/index.md index 27797e817..e40ab42b9 100644 --- a/main/guides/governance/index.md +++ b/main/guides/governance/index.md @@ -27,7 +27,7 @@ const paramTypes = harden( /** @type {const} */ ({ Fee: ParamTypes.AMOUNT }) -) +); ``` ## Reusing Contracts for Electorate, Election Manager @@ -52,17 +52,17 @@ to [publish values of the parameters to vstorage](../zoe/pub-to-storage). import { handleParamGovernance } from '@agoric/governance/src/contractHelper.js'; export const start = async (zcf, privateArgs, baggage) => { -... + // ... const { publicMixin, makeDurableGovernorFacet, params } = await handleParamGovernance( zcf, privateArgs.initialPoserInvitation, paramTypes, privateArgs.storageNode, - privateArgs.marshaller, + privateArgs.marshaller ); -... -} + // ... +}; ``` We get back @@ -73,22 +73,22 @@ We get back ```js export const start = async (zcf, privateArgs, baggage) => { -... + // ... const publicFacet = Far('Public', { makeFirstInvitation, - ...publicMixin, + ...publicMixin }); const limitedCreatorFacet = Far('Creator', { makeCollectFeesInvitation() { return makeCollectFeesInvitation(zcf, feeSeat, feeBrand, 'Fee'); - }, + } }); const { governorFacet } = makeDurableGovernorFacet( baggage, - limitedCreatorFacet, + limitedCreatorFacet ); return harden({ publicFacet, creatorFacet: governorFacet }); -} +}; ``` ## Starting a Governed Contract via its Governor @@ -121,9 +121,9 @@ using `v0-accept-charter` to identify this offer: ```js test.serial('Voter0 accepts charter, committee invitations', async t => { -... + // ... await victor.acceptCharterInvitation('v0-accept-charter'); -... + // ... }); ``` @@ -136,8 +136,8 @@ referring back to `v0-accept-charter` as `charterAcceptOfferId`: ```js const makeVoter = (t, wallet, wellKnown) => { -... - const putQuestion = async (offerId, params, deadline) => { + // ... + const putQuestion = async (offerId, params, deadline) => { const instance = await wellKnown.instance[contractName]; // swaparoo instance handle const path = { paramPath: { key: 'governedParams' } }; @@ -146,17 +146,17 @@ const makeVoter = (t, wallet, wellKnown) => { /** @type {import('@agoric/smart-wallet/src/offers.js').OfferSpec} */ const offer = { - id: offerId, - invitationSpec: { - source: 'continuing', - previousOffer: NonNullish(charterAcceptOfferId), - invitationMakerName: 'VoteOnParamChange', - }, - offerArgs, - proposal: {}, + id: offerId, + invitationSpec: { + source: 'continuing', + previousOffer: NonNullish(charterAcceptOfferId), + invitationMakerName: 'VoteOnParamChange' + }, + offerArgs, + proposal: {} }; return doOffer(offer); - }; + }; }; ``` @@ -164,14 +164,14 @@ The `offerArgs` include a deadline and details of the params to change: ```js test.serial('vote to change swap fee', async t => { -... + // ... const targetFee = IST(50n, 100n); // 50 / 100 = 0.5 IST const changes = { Fee: targetFee }; -... + // ... const deadline = BigInt(new Date(2024, 6, 1, 9, 10).valueOf() / 1000); const result = await victor.putQuestion('proposeToSetFee', changes, deadline); t.log('question is posed', result); -... + // ... }); ``` @@ -182,9 +182,9 @@ using `v0-join-committee` to identify this offer: ```js test.serial('Voter0 accepts charter, committee invitations', async t => { -... + // ... await victor.acceptCommitteeInvitation('v0-join-committee', 0); -... + // ... }); ``` @@ -193,7 +193,7 @@ referring back to `v0-join-committee` as `committeeOfferId`: ```js const makeVoter = (t, wallet, wellKnown) => { -... + // ... const vote = async (offerId, details, position) => { const chosenPositions = [details.positions[position]]; @@ -204,13 +204,13 @@ const makeVoter = (t, wallet, wellKnown) => { source: 'continuing', previousOffer: NonNullish(committeeOfferId), invitationMakerName: 'makeVoteInvitation', - invitationArgs: harden([chosenPositions, details.questionHandle]), + invitationArgs: harden([chosenPositions, details.questionHandle]) }, - proposal: {}, + proposal: {} }; return doOffer(offer); }; -... + // ... }; ``` @@ -219,12 +219,14 @@ published to vstorage. ```js test.serial('vote to change swap fee', async t => { -... - const details = await vstorage.get(`published.committee.swaparoo.latestQuestion`); + // ... + const details = await vstorage.get( + `published.committee.swaparoo.latestQuestion` + ); t.is(details.electionType, 'param_change'); const voteResult = await victor.vote('voteToSetFee', details, 0); t.log('victor voted:', voteResult); -... + // ... }); ``` @@ -233,11 +235,11 @@ carried. It instructs the swaparoo contract to change the fee. ```js test.serial('vote to change swap fee', async t => { -... + // ... const swapPub = E(zoe).getPublicFacet( - swapPowers.instance.consume[contractName], + swapPowers.instance.consume[contractName] ); -... + // ... const after = await E(swapPub).getAmount('Fee'); t.deepEqual(after, targetFee); }); diff --git a/main/guides/integration/name-services.md b/main/guides/integration/name-services.md index 30de12b67..c55ada090 100644 --- a/main/guides/integration/name-services.md +++ b/main/guides/integration/name-services.md @@ -13,14 +13,14 @@ Well-known names are chosen by [BLD staker governance](https://community.agoric. To look up well-known objects, such as the BLD brand: ```js -const brandHub = E(agoricNames).lookup('brand') -const bldBrand = await E(brandHub).lookup('BLD') +const brandHub = E(agoricNames).lookup('brand'); +const bldBrand = await E(brandHub).lookup('BLD'); ``` or, equivalently: ```js -const bldBrand = await E(agoricNames).lookup('brand', 'BLD') +const bldBrand = await E(agoricNames).lookup('brand', 'BLD'); ``` `agoricNames` is a _NameHub_. In general, `E(hub).lookup(key1, key2, ...rest)` is equivalent @@ -40,12 +40,12 @@ Adding or updating an entry requires access to the corresponding _NameAdmin_ fac one of its descendants - most likely as part of [permissioned contract deployment](../coreeval/). For example: ```js -const { instance } = await E(zoe).startInstance(lemonadeStand) +const { instance } = await E(zoe).startInstance(lemonadeStand); const { brands: { Lemonade: lemonadeBrand } -} = await E(zoe).getTerms(instance) -const brandAdmin = E(agoricNamesAdmin).lookupAdmin('brand') -await E(brandAdmin).update('Lemonade', lemonadeBrand) +} = await E(zoe).getTerms(instance); +const brandAdmin = E(agoricNamesAdmin).lookupAdmin('brand'); +await E(brandAdmin).update('Lemonade', lemonadeBrand); ``` ### agoricNames in vstorage @@ -103,7 +103,7 @@ We can then save the id in a file or send it in email to someone else, and they can look up the object: ```js -const instance = await E(board).getValue('board023423') +const instance = await E(board).getValue('board023423'); ``` See also: [marshalling amounts and instance](../getting-started/contract-rpc#marshalling-amounts-and-instances) diff --git a/main/guides/js-programming/far.md b/main/guides/js-programming/far.md index 853b9af4d..b8e80fe03 100644 --- a/main/guides/js-programming/far.md +++ b/main/guides/js-programming/far.md @@ -57,9 +57,9 @@ All Passables must be hardened. Consider what might happen if we had a remote `i some pass-by-copy data that we passed to it: ```js -let amount1 = { brand: brand1, value: 10n } -await E(item).setPrice(amount1) // Throws an error, but let's imagine it doesn't. -amount1.value = 20n +let amount1 = { brand: brand1, value: 10n }; +await E(item).setPrice(amount1); // Throws an error, but let's imagine it doesn't. +amount1.value = 20n; ``` Now `amount1` is supposedly both in the local and the remote vat, but the `value` diff --git a/main/guides/js-programming/hardened-js.md b/main/guides/js-programming/hardened-js.md index 8092d5c4a..b13c4d403 100644 --- a/main/guides/js-programming/hardened-js.md +++ b/main/guides/js-programming/hardened-js.md @@ -317,14 +317,14 @@ are only for lint tools and do not have any effect at runtime: /** @param {number} init */ const makeCounter = init => { - let value = init + let value = init; return { incr: () => { - value += 1 - return value + value += 1; + return value; } - } -} + }; +}; ``` If we're not careful, our clients can cause us to misbehave: @@ -385,11 +385,11 @@ in [Higher-order Smart Contracts across Chains](https://www.youtube.com/watch?v= ```js const makeMint = () => { - const ledger = makeWeakMap() + const ledger = makeWeakMap(); const issuer = harden({ makeEmptyPurse: () => mint.makePurse(0) - }) + }); const mint = harden({ makePurse: initialBalance => { @@ -398,21 +398,21 @@ const makeMint = () => { getBalance: () => ledger.get(purse), deposit: (amount, src) => { - Nat(ledger.get(purse) + Nat(amount)) - ledger.set(src, Nat(ledger.get(src) - amount)) - ledger.set(purse, ledger.get(purse) + amount) + Nat(ledger.get(purse) + Nat(amount)); + ledger.set(src, Nat(ledger.get(src) - amount)); + ledger.set(purse, ledger.get(purse) + amount); }, withdraw: amount => { - const newPurse = issuer.makeEmptyPurse() - newPurse.deposit(amount, purse) - return newPurse + const newPurse = issuer.makeEmptyPurse(); + newPurse.deposit(amount, purse); + return newPurse; } - }) - ledger.set(purse, initialBalance) - return purse + }); + ledger.set(purse, initialBalance); + return purse; } - }) + }); - return mint -} + return mint; +}; ``` diff --git a/main/guides/js-programming/notifiers.md b/main/guides/js-programming/notifiers.md index a91d6b043..1eaa289a3 100644 --- a/main/guides/js-programming/notifiers.md +++ b/main/guides/js-programming/notifiers.md @@ -35,10 +35,10 @@ element (i.e., `updater` or `publication`) produces the async iteration which is consumed using each pair’s second element (i.e., `notifier` or `subscription`). ```js -import { makeNotifierKit } from '@agoric/notifier' -import { makeSubscriptionKit } from '@agoric/notifier' -const { updater, notifier } = makeNotifierKit() -const { publication, subscription } = makeSubscriptionKit() +import { makeNotifierKit } from '@agoric/notifier'; +import { makeSubscriptionKit } from '@agoric/notifier'; +const { updater, notifier } = makeNotifierKit(); +const { publication, subscription } = makeSubscriptionKit(); ``` The key difference between the two is @@ -186,11 +186,11 @@ Let’s look at a subscription example. We have three characters: Paula the publ First we create a publication/subscription pair with `makeSubscriptionKit()`. Paula publishes an iteration with the non-final sequence 'a', 'b' and 'done' as its completion value. ```js -const { publication, subscription } = makeSubscriptionKit() +const { publication, subscription } = makeSubscriptionKit(); // Paula the publisher says -publication.updateState('a') -publication.updateState('b') -publication.finish('done') +publication.updateState('a'); +publication.updateState('b'); +publication.finish('done'); ``` Remember, a `SubscriptionKit` is lossless. It conveys all of an async iteration’s non-final values, as well as the final value. @@ -208,14 +208,14 @@ the code won’t know what the completion value actually was “done”, “comp const consume = async subscription => { try { for await (const val of subscription) { - console.log('non-final-value', val) + console.log('non-final-value', val); } - console.log('the iteration finished') + console.log('the iteration finished'); } catch (reason) { - console.log('the iteration failed', reason) + console.log('the iteration failed', reason); } -} -consume(subscription) +}; +consume(subscription); // Eventually prints: // non-final-value a // non-final-value b @@ -229,8 +229,8 @@ const observer = harden({ updateState: val => console.log('non-final-value', val), finish: completion => console.log('finished', completion), fail: reason => console.log('failed', reason) -}) -observeIteration(subscription, observer) +}); +observeIteration(subscription, observer); // Eventually prints: // non-final-value a // non-final-value b @@ -244,7 +244,7 @@ losslessly convey termination. Let's say the subscription example above started with the following instead of `makeSubscriptionKit()`. ```js -const { updater, notifier } = makeNotifierKit() +const { updater, notifier } = makeNotifierKit(); ``` If we then renamed `publication` to `updater` and `subscription` to `notifier` @@ -292,12 +292,12 @@ remote reference to an `AsyncIterable` at Paula's site. Alice has to make an replace her call to `consume(subscription)` with: ```js -import { makeSubscription } from '@agoric/notifier' +import { makeSubscription } from '@agoric/notifier'; const localSubscription = makeSubscription( E(subscription).getSharableSubsciptionInternals() -) -consume(localSubscription) +); +consume(localSubscription); ``` The code above uses a SubscriptionKit. NotifierKits have a similar pair of a @@ -310,9 +310,9 @@ making a new local pair and plugging them together with `observeIteration`. ```js const { publication: adapterPublication, subscription: adapterSubscription } = - makeSubscriptionKit() -observeIteration(subscription, adapterPublication) -consume(adapterSubscription) + makeSubscriptionKit(); +observeIteration(subscription, adapterPublication); +consume(adapterSubscription); ``` This works when subscription is a reference to a `AsyncIterable`. If Alice only diff --git a/main/guides/orchestration/getting-started/api.md b/main/guides/orchestration/getting-started/api.md index 1a1cc0502..47ffb1271 100644 --- a/main/guides/orchestration/getting-started/api.md +++ b/main/guides/orchestration/getting-started/api.md @@ -12,32 +12,32 @@ The [`Orchestrator`](https://agoric-sdk.pages.dev/interfaces/_agoric_orchestrati Retrieves the chain information and provides access to chain-specific methods. See [getChain](https://agoric-sdk.pages.dev/interfaces/_agoric_orchestration.Orchestrator#getChain). -```javascript -const chain = await orchestrator.getChain('chainName') +```js +const chain = await orchestrator.getChain('chainName'); ``` ### makeLocalAccount Creates a new `LocalChainAccount`. See [makeLocalAccount](https://agoric-sdk.pages.dev/interfaces/_agoric_orchestration.Orchestrator#makeLocalAccount). -```javascript -const localAccount = await orchestrator.makeLocalAccount() +```js +const localAccount = await orchestrator.makeLocalAccount(); ``` ### getBrandInfo Returns information about a `denom`, including the equivalent local Brand, the chain where the denom is held, and the chain that issues the corresponding asset. See [getBrandInfo](https://agoric-sdk.pages.dev/interfaces/_agoric_orchestration.Orchestrator#getBrandInfo). -```javascript -const brandInfo = orchestrator.getBrandInfo('denom') +```js +const brandInfo = orchestrator.getBrandInfo('denom'); ``` ### asAmount Converts a denom amount to an `Amount` with a brand. See [asAmount](https://agoric-sdk.pages.dev/interfaces/_agoric_orchestration.Orchestrator#asAmount). -```javascript -const amount = orchestrator.asAmount({ denom: 'uatom', value: 1000n }) +```js +const amount = orchestrator.asAmount({ denom: 'uatom', value: 1000n }); ``` ## OrchestrationAccount @@ -48,54 +48,54 @@ An [`OrchestrationAccount`](https://agoric-sdk.pages.dev/types/_agoric_orchestra Retrieves the address of the account on the remote chain. See [getAddress](https://agoric-sdk.pages.dev/interfaces/_agoric_orchestration.OrchestrationAccountI#getAddress). -```javascript -const address = await orchestrationAccount.getAddress() +```js +const address = await orchestrationAccount.getAddress(); ``` ### getBalances Returns an array of amounts for every balance in the account. See [getBalances](https://agoric-sdk.pages.dev/interfaces/_agoric_orchestration.OrchestrationAccountI#getBalances). -```javascript -const balances = await orchestrationAccount.getBalances() +```js +const balances = await orchestrationAccount.getBalances(); ``` ### getBalance Retrieves the balance of a specific denom for the account. See [getBalance](https://agoric-sdk.pages.dev/interfaces/_agoric_orchestration.OrchestrationAccountI#getBalance). -```javascript -const balance = await orchestrationAccount.getBalance('uatom') +```js +const balance = await orchestrationAccount.getBalance('uatom'); ``` ### send Transfers an amount to another account on the same chain. The promise settles when the transfer is complete. See [send](https://agoric-sdk.pages.dev/interfaces/_agoric_orchestration.OrchestrationAccountI#send). -```javascript -await orchestrationAccount.send(receiverAddress, amount) +```js +await orchestrationAccount.send(receiverAddress, amount); ``` ### transfer Transfers an amount to another account, typically on another chain. The promise settles when the transfer is complete. See [transfer](https://agoric-sdk.pages.dev/interfaces/_agoric_orchestration.OrchestrationAccountI#transfer). -```javascript -await orchestrationAccount.transfer(amount, destinationAddress) +```js +await orchestrationAccount.transfer(amount, destinationAddress); ``` ### transferSteps Transfers an amount to another account in multiple steps. The promise settles when the entire path of the transfer is complete. See [transferSteps](https://agoric-sdk.pages.dev/interfaces/_agoric_orchestration.OrchestrationAccountI#transferSteps). -```javascript -await orchestrationAccount.transferSteps(amount, transferMsg) +```js +await orchestrationAccount.transferSteps(amount, transferMsg); ``` ### deposit Deposits payment from Zoe to the account. For remote accounts, an IBC Transfer will be executed to transfer funds there. -```javascript -await orchestrationAccount.deposit(payment) +```js +await orchestrationAccount.deposit(payment); ``` diff --git a/main/guides/orchestration/getting-started/contract-walkthrough/cross-chain-swap.md b/main/guides/orchestration/getting-started/contract-walkthrough/cross-chain-swap.md index d0ed83ce6..a093fc545 100644 --- a/main/guides/orchestration/getting-started/contract-walkthrough/cross-chain-swap.md +++ b/main/guides/orchestration/getting-started/contract-walkthrough/cross-chain-swap.md @@ -8,14 +8,14 @@ ## Imports -```javascript -import { StorageNodeShape } from '@agoric/internal' -import { TimerServiceShape } from '@agoric/time' -import { withdrawFromSeat } from '@agoric/zoe/src/contractSupport/zoeHelpers.js' -import { deeplyFulfilled } from '@endo/marshal' -import { M, objectMap } from '@endo/patterns' -import { orcUtils } from '../utils/orc.js' -import { withOrchestration } from '../utils/start-helper.js' +```js +import { StorageNodeShape } from '@agoric/internal'; +import { TimerServiceShape } from '@agoric/time'; +import { withdrawFromSeat } from '@agoric/zoe/src/contractSupport/zoeHelpers.js'; +import { deeplyFulfilled } from '@endo/marshal'; +import { M, objectMap } from '@endo/patterns'; +import { orcUtils } from '../utils/orc.js'; +import { withOrchestration } from '../utils/start-helper.js'; ``` Importing Shapes and Utilities: @@ -29,7 +29,7 @@ Importing Shapes and Utilities: ## Type Imports -```javascript +```js /** * @import {Orchestrator, IcaAccount, CosmosValidatorAddress} from '../types.js' * @import {TimerService} from '@agoric/time'; @@ -46,7 +46,7 @@ This includes type information to help with TypeScript or JSDoc annotations, whi ## `stakeAndSwapFn` Offer Handler -```javascript +```js /** * @param {Orchestrator} orch * @param {object} ctx @@ -57,7 +57,7 @@ This includes type information to help with TypeScript or JSDoc annotations, whi * @param {CosmosValidatorAddress} offerArgs.validator */ const stakeAndSwapFn = async (orch, { zcf }, seat, offerArgs) => { - ... +// ... ``` Function Parameters: @@ -67,43 +67,43 @@ Function Parameters: - `seat`: The seat representing the contract's position in the offer. - `offerArgs`: Arguments provided with the offer, including staked amount and validator address. -```javascript -const { give } = seat.getProposal() +```js +const { give } = seat.getProposal(); ``` Extracts the `give` part of the proposal from the seat. This includes what the user is offering to the contract. -```javascript -const omni = await orch.getChain('omniflixhub') -const agoric = await orch.getChain('agoric') +```js +const omni = await orch.getChain('omniflixhub'); +const agoric = await orch.getChain('agoric'); ``` Retrieves chain objects for omniflixhub (a remote chain) and agoric (the local chain) chains using the orchestrator. -```javascript +```js const [omniAccount, localAccount] = await Promise.all([ omni.makeAccount(), agoric.makeAccount() -]) +]); ``` Creates accounts on both omniflixhub and agoric chains concurrently. -```javascript -const omniAddress = omniAccount.getAddress() +```js +const omniAddress = omniAccount.getAddress(); ``` Retrieves the address of the omniAccount. ## Depositing and Exiting -```javascript +```js // deposit funds from user seat to LocalChainAccount -const payments = await withdrawFromSeat(zcf, seat, give) +const payments = await withdrawFromSeat(zcf, seat, give); await deeplyFulfilled( objectMap(payments, payment => localAccount.deposit(payment)) -) -seat.exit() +); +seat.exit(); ``` ### Withdraw Funds @@ -120,7 +120,7 @@ The seat exits the offer, completing the offer being handled. ## Building and Executing Swap Instructions -```javascript +```js // build swap instructions with orcUtils library const transferMsg = orcUtils.makeOsmosisSwap({ destChain: 'omniflixhub', @@ -128,7 +128,7 @@ const transferMsg = orcUtils.makeOsmosisSwap({ amountIn: give.Stable, brandOut: '...', slippage: 0.03 -}) +}); ``` Parameters include destination chain, destination address, input amount, output brand, and slippage tolerance. In the `give` keyword record, the `Stable` keyword is expected to have the assets to trade. @@ -137,13 +137,13 @@ Parameters include destination chain, destination address, input amount, output Carries out the swap instructions using the results of `orcUtils.makeOsmosisSwap` above. -```javascript +```js await localAccount .transferSteps(give.Stable, transferMsg) .then(_txResult => omniAccount.delegate(offerArgs.validator, offerArgs.staked) ) - .catch(e => console.error(e)) + .catch(e => console.error(e)); ``` Transfers the stablecoins according to the swap instructions. On `transferSteps` being resolves, we delegate the staked amount to the specified validator on the omniflixhub chain. @@ -152,7 +152,7 @@ We log any errors that occur during the process. ## Declaring `privateArgs` shape, and upgradeability -```javascript +```js /** @type {ContractMeta} */ export const meta = { privateArgsShape: { @@ -164,21 +164,21 @@ export const meta = { timerService: M.or(TimerServiceShape, null) }, upgradability: 'canUpgrade' -} -harden(meta) +}; +harden(meta); ``` This defines the shape of private arguments and the contract’s upgradability, and `harden` ensures that the metadata object is immutable. ## `makeNatAmountShape` function -```javascript +```js /** * @param {Brand} brand must be a 'nat' brand, not checked * @param {NatValue} [min] */ export const makeNatAmountShape = (brand, min) => - harden({ brand, value: min ? M.gte(min) : M.nat() }) + harden({ brand, value: min ? M.gte(min) : M.nat() }); ``` Utility function to create a shape for amounts of the specified fungible brand. If a minimum value is provided, ensures the amount is greater than or equal to it. @@ -187,7 +187,7 @@ Utility function to create a shape for amounts of the specified fungible brand. The `contract` function when wrapped inside `withOrchestration` defines the [`start` function](#start-function) which is the entry point of the contract. The contract exports a `start` function [below](#start-function). It is merely a convention/convenience that we define a more abstract `contract` function here and pass it to `withOrchestration`. The arguments of this function are `zcf`, `privateAge`, `zone`, and `tools` for orchestration. -```javascript +```js /** * Orchestration contract to be wrapped by withOrchestration for Zoe * @@ -208,15 +208,15 @@ const contract = async (zcf, privateArgs, zone, { orchestrate }) => { ## Getting brands from Contract Terms -```javascript -const { brands } = zcf.getTerms() +```js +const { brands } = zcf.getTerms(); ``` This retrieves the brands specified in the contract terms. ## Handler for swap and stake offers -```javascript +```js /** deprecated historical example */ /** * @type {OfferHandler< @@ -224,14 +224,14 @@ This retrieves the brands specified in the contract terms. * { staked: Amount<'nat'>; validator: CosmosValidatorAddress } * >} */ -const swapAndStakeHandler = orchestrate('LSTTia', { zcf }, stakeAndSwapFn) +const swapAndStakeHandler = orchestrate('LSTTia', { zcf }, stakeAndSwapFn); ``` `swapAndStakeHandler` defines the offer handler for the swap and stake operation using [`stakeAndSwapFn` function](#stakeandswapfn-offer-handler). ## Make Invitation and Create `publicFacet` -```javascript +```js const publicFacet = zone.exo('publicFacet', undefined, { makeSwapAndStakeInvitation() { return zcf.makeInvitation( @@ -243,17 +243,17 @@ const publicFacet = zone.exo('publicFacet', undefined, { want: {}, // XXX ChainAccount Ownable? exit: M.any() }) - ) + ); } -}) +}); ``` Defines the `publicFacet` for the contract, which includes the method to make an `invitation` for users to swap stablecoins for TIA and stake, and returns the hardened public facet. Defining `publicFacet` with `zone.exo` makes it [remotely accessible](/glossary/#exo) and persistent through contract upgrades with a [durable `zone`](/glossary/#zone). ## `start` Function -```javascript -export const start = withOrchestration(contract) +```js +export const start = withOrchestration(contract); ``` Defines the `start` function of the contract that is returned by a call to `withOrchestration` with [`contract` function](#contract-function) as a parameter. In essence `contract` function is the entry point or `start` function of this contract with some orchestration setup. diff --git a/main/guides/orchestration/getting-started/contract-walkthrough/cross-chain-unbond.md b/main/guides/orchestration/getting-started/contract-walkthrough/cross-chain-unbond.md index a3f34e830..d6d3d6e85 100644 --- a/main/guides/orchestration/getting-started/contract-walkthrough/cross-chain-unbond.md +++ b/main/guides/orchestration/getting-started/contract-walkthrough/cross-chain-unbond.md @@ -8,9 +8,9 @@ ## Imports -```javascript -import { M } from '@endo/patterns' -import { withOrchestration } from '../utils/start-helper.js' +```js +import { M } from '@endo/patterns'; +import { withOrchestration } from '../utils/start-helper.js'; ``` - `M`: Imported from @endo/patterns, provides pattern-matching utilities. @@ -18,7 +18,7 @@ import { withOrchestration } from '../utils/start-helper.js' ## JSDoc Annotations for Type Information -```javascript +```js /** * @import {Orchestrator, IcaAccount, CosmosValidatorAddress} from '../types.js' * @import {TimerService} from '@agoric/time'; @@ -36,7 +36,7 @@ This includes type information annotations to help with TypeScript or JSDoc, mak ## `unbondAndLiquidStakeFn` Function -```javascript +```js /** * @param {Orchestrator} orch * @param {object} ctx @@ -45,7 +45,7 @@ This includes type information annotations to help with TypeScript or JSDoc, mak * @param {undefined} _offerArgs */ const unbondAndLiquidStakeFn = async (orch, { zcf }, _seat, _offerArgs) => { - ... +// ... ``` ### Function Parameters @@ -57,9 +57,9 @@ const unbondAndLiquidStakeFn = async (orch, { zcf }, _seat, _offerArgs) => { ## Interacting with Chains -```javascript -const omni = await orch.getChain('omniflixhub') -const omniAccount = await omni.makeAccount() +```js +const omni = await orch.getChain('omniflixhub'); +const omniAccount = await omni.makeAccount(); ``` ### Get Chain @@ -72,9 +72,9 @@ Creates an account on the omniflixhub chain. ## Interaction with Stride Chain -```javascript -const stride = await orch.getChain('stride') -const strideAccount = await stride.makeAccount() +```js +const stride = await orch.getChain('stride'); +const strideAccount = await stride.makeAccount(); ``` ### Get Chain @@ -89,7 +89,7 @@ Creates an account on the stride chain. The `contract` function when wrapped inside `withOrchestration` defines the [`start` function](#start-function) which is the entry point of the contract. The contract exports a `start` function [below](#start-function). It is merely a convention/convenience that we define a more abstract `contract` function here and pass it to `withOrchestration`. The arguments of this function are `zcf`, `privateAge`, `zone`, and `tools` for orchestration. -```javascript +```js /** * Orchestration contract to be wrapped by withOrchestration for Zoe * @@ -117,13 +117,13 @@ const contract = async (zcf, privateArgs, zone, { orchestrate }) => { ## Offer Handler for Unbond and Liquid Stake -```javascript +```js /** @type {OfferHandler} */ const unbondAndLiquidStake = orchestrate( 'LSTTia', { zcf }, unbondAndLiquidStakeFn -) +); ``` ### Offer Handler @@ -132,7 +132,7 @@ Defines the offer handler for the unbond and liquid stake operation using [`unbo ## Make Invitation and Create `publicFacet` -```javascript +```js const publicFacet = zone.exo('publicFacet', undefined, { makeUnbondAndLiquidStakeInvitation() { return zcf.makeInvitation( @@ -145,19 +145,19 @@ const publicFacet = zone.exo('publicFacet', undefined, { want: {}, // XXX ChainAccount Ownable? exit: M.any() }) - ) + ); } -}) +}); -return harden({ publicFacet }) +return harden({ publicFacet }); ``` Defines the `publicFacet` for the contract, which includes the method to make an `invitation`, and returns the hardened public facet. Defining `publicFacet` with `zone.exo` makes it [remotely accessible](/glossary/#exo) and persistent through contract upgrades with a [durable `zone`](/glossary/#zone). ## `start` Function -```javascript -export const start = withOrchestration(contract) +```js +export const start = withOrchestration(contract); ``` Defines the `start` function of the contract that is returned by a call to `withOrchestration` with [`contract` function](#contract-function) as a parameter. In essence `contract` function is the entry point or `start` function of this contract with some orchestration setup. diff --git a/main/guides/orchestration/getting-started/key-concepts.md b/main/guides/orchestration/getting-started/key-concepts.md index 222c9e7c3..735e7d060 100644 --- a/main/guides/orchestration/getting-started/key-concepts.md +++ b/main/guides/orchestration/getting-started/key-concepts.md @@ -20,9 +20,9 @@ For a detailed explanation of these access control rules, see [Access Control wi This sample is taken from one of the [example contracts](https://github.com/Agoric/agoric-sdk/blob/master/packages/orchestration/src/examples/swapExample.contract.js) -```javascript +```js const stakeAndSwapFn = async (orch, ...) => { -... +// ... const omni = await orch.getChain('omniflixhub'); const agoric = await orch.getChain('agoric'); @@ -34,7 +34,7 @@ const stakeAndSwapFn = async (orch, ...) => { const omniAddress = omniAccount.getAddress(); // deposit funds from user seat to LocalChainAccount -... +// ... const transferMsg = orcUtils.makeOsmosisSwap({ ... }); try { @@ -53,18 +53,18 @@ The `makeChainHub` utility manages the connections and metadata for various bloc It simplifies accessing and interacting with multiple chains, providing a unified interface for the orchestration logic to manage cross-chain operations effectively. ChainHub also allows dynamic registration and use of chain and connection information. -```javascript -const chainHub = makeChainHub(remotePowers.agoricNames) +```js +const chainHub = makeChainHub(remotePowers.agoricNames); // Register a new chain with its information -chainHub.registerChain(chainKey, chainInfo) +chainHub.registerChain(chainKey, chainInfo); // Register a connection between the Agoric chain and the new chain chainHub.registerConnection( agoricChainInfo.chainId, chainInfo.chainId, connectionInfo -) +); ``` In this example, `chainHub` is used to register a new chain and establish a connection between the Agoric chain and the newly registered chain. @@ -77,8 +77,8 @@ Orchestration accounts are a key concept in the Agoric Orchestration API, repres - `getAddress` retrieves the address of the account on the remote chain. -```javascript -const address = await orchestrationAccount.getAddress() +```js +const address = await orchestrationAccount.getAddress(); ``` **2. Balance Management** @@ -86,9 +86,9 @@ const address = await orchestrationAccount.getAddress() - `getBalances` returns an array of amounts for every balance in the account. - `getBalance` retrieves the balance of a specific denom for the account. -```javascript -const balances = await orchestrationAccount.getBalances() -const balance = await orchestrationAccount.getBalance('uatom') +```js +const balances = await orchestrationAccount.getBalances(); +const balance = await orchestrationAccount.getBalance('uatom'); ``` **3. Funds Transfer** @@ -97,10 +97,10 @@ const balance = await orchestrationAccount.getBalance('uatom') - `transfer` transfers an amount to another account, typically on another chain. - `transferSteps` transfers an amount in multiple steps, handling complex transfer paths. -```javascript -await orchestrationAccount.send(receiverAddress, amount) -await orchestrationAccount.transfer(amount, destinationAddress) -await orchestrationAccount.transferSteps(amount, transferMsg) +```js +await orchestrationAccount.send(receiverAddress, amount); +await orchestrationAccount.transfer(amount, destinationAddress); +await orchestrationAccount.transferSteps(amount, transferMsg); ``` To see the function the Orchestration API exposes, see [Orchestration API](/guides/orchestration/getting-started/api.html) diff --git a/main/guides/wallet/index.md b/main/guides/wallet/index.md index ecbc0fb5e..e0ee22272 100644 --- a/main/guides/wallet/index.md +++ b/main/guides/wallet/index.md @@ -86,19 +86,19 @@ walletSend({ type: 'walletSuggestInstallation', petname: 'Installation', boardId: INSTALLATION_BOARD_ID -}) +}); // Our issuer will default to something like `FungibleFaucet.Instance`. walletSend({ type: 'walletSuggestInstance', petname: 'Instance', boardId: INSTANCE_BOARD_ID -}) +}); // Our issuer will default to something like `FungibleFaucet.Token`. walletSend({ type: 'walletSuggestIssuer', petname: 'Token', boardId: TOKEN_ISSUER_BOARD_ID -}) +}); ``` ## The Agoric Board diff --git a/main/guides/zoe/actual-contracts/PSM.md b/main/guides/zoe/actual-contracts/PSM.md index 39107af07..90f165e7e 100644 --- a/main/guides/zoe/actual-contracts/PSM.md +++ b/main/guides/zoe/actual-contracts/PSM.md @@ -35,7 +35,7 @@ To create an offer to swap external stable tokens for IST tokens, do the followi 1. Create an invitation using the makeWantMintedInvitation method. ```js - const myInvitation = E(publicFacet).makeWantMintedInvitation() + const myInvitation = E(publicFacet).makeWantMintedInvitation(); ``` 2. Create Amounts for the external stable tokens you want to trade and for the IST tokens you want to receive. @@ -60,7 +60,7 @@ To create an offer to swap external stable tokens for IST tokens, do the followi 4. Create a payment record containing the external stable tokens you’re trading to the PSM. ```js - const myPaymentRecord = { In: anchorPayment } + const myPaymentRecord = { In: anchorPayment }; ``` 5. Create the offer, remembering to harden the proposal & payment record. @@ -70,7 +70,7 @@ To create an offer to swap external stable tokens for IST tokens, do the followi myInvitation, harden(myProposal), harden(myPaymentRecord) - ) + ); ``` ### Swapping IST Tokens for External Stable Tokens @@ -80,7 +80,7 @@ To create an offer to swap IST tokens for external stable tokens, do the followi 1. Create an invitation using the makeGiveMintedInvitation method. ```js - const myInvitation = E(publicFacet).makeGiveMintedInvitation() + const myInvitation = E(publicFacet).makeGiveMintedInvitation(); ``` 2. Create Amounts for the IST tokens you want to trade and for the external stable @@ -101,9 +101,9 @@ const myProposal = harden({ ` 4. Create and harden a payment record containing the IST tokens you’re trading to the PSM. ```js - const myPaymentRecord = harden({ In: mintedPayment }) + const myPaymentRecord = harden({ In: mintedPayment }); ``` 5. Create the offer. ```js - const seat = E(zoe).offer(myInvitation, myProposal, myPaymentRecord) + const seat = E(zoe).offer(myInvitation, myProposal, myPaymentRecord); ``` diff --git a/main/guides/zoe/contract-requirements.md b/main/guides/zoe/contract-requirements.md index ea3598d07..50ea34b5a 100644 --- a/main/guides/zoe/contract-requirements.md +++ b/main/guides/zoe/contract-requirements.md @@ -49,10 +49,10 @@ to pass in any arguments that should not be part of the public terms. ```js const start = (zcf, privateArgs) => { - ... + // ... // your code here return harden({ creatorFacet, creatorInvitation, publicFacet }); -} +}; harden(start); export { start }; ``` @@ -90,7 +90,7 @@ Use `zcf.makeInvitation()` to create the first party's `invitation`: const creatorInvitation = zcf.makeInvitation( makeMatchingInvitation, 'firstOffer' -) +); ``` `makeMatchingInvitation()` creates the second `invitation`. @@ -103,7 +103,7 @@ const matchingSeatInvitation = zcf.makeInvitation( asset: give.Asset, price: want.Price } -) +); ``` The third argument (which is optional and wasn't needed for the first `invitation`) says @@ -119,10 +119,10 @@ match, they each get back what they brought to the exchange, and it's still over ```js const matchingSeatOfferHandler = matchingSeat => { - const swapResult = swap(zcf, firstSeat, matchingSeat) - zcf.shutdown() - return swapResult -} + const swapResult = swap(zcf, firstSeat, matchingSeat); + zcf.shutdown(); + return swapResult; +}; ``` If you study other contracts, you'll see they all have this basic format. Depending diff --git a/main/guides/zoe/contract-upgrade.md b/main/guides/zoe/contract-upgrade.md index 61a8eef62..33d15056d 100644 --- a/main/guides/zoe/contract-upgrade.md +++ b/main/guides/zoe/contract-upgrade.md @@ -72,25 +72,25 @@ between incarnations in a way that preserves identity of objects as seen from other vats: ```js -let rooms +let rooms; if (!baggage.has('rooms')) { // initial incarnation: create the object - rooms = makeScalarBigMapStore('rooms', { durable: true }) - baggage.init('rooms', rooms) + rooms = makeScalarBigMapStore('rooms', { durable: true }); + baggage.init('rooms', rooms); } else { // subsequent incarnation: use the object from the initial incarnation - rooms = baggage.get('rooms') + rooms = baggage.get('rooms'); } ``` The `provide` function supports a concise idiom for this find-or-create pattern: ```js -import { provide } from '@agoric/vat-data' +import { provide } from '@agoric/vat-data'; const rooms = provide(baggage, 'rooms', () => makeScalarBigMapStore('rooms', { durable: true }) -) +); ``` The `zone` API is a convenient way to manage durability. Its store methods integrate the `provide` pattern: @@ -133,12 +133,12 @@ Now we have all the parts of an upgradable contract. We can then upgrade it to have another method: ```js - const makeRoom = zone.exoClass('Room', RoomI, (id) => ({ id, value: 0 }), { - ... - clear(delta) { - this.state.value = 0; - }, - }); +const makeRoom = zone.exoClass('Room', RoomI, id => ({ id, value: 0 }), { + // ... + clear(delta) { + this.state.value = 0; + } +}); ``` The interface guard also needs updating. @@ -146,8 +146,8 @@ The interface guard also needs updating. ```js const RoomI = M.interface('Room', { - ... - clear: M.call().returns(), + // ... + clear: M.call().returns() }); ``` @@ -179,14 +179,14 @@ Define all exo classes/kits before any incoming method calls from other vats -- baggage is a MapStore that provides a way to preserve the state and behavior of objects between [smart contract upgrades](https://docs.agoric.com/guides/zoe/contract-upgrade) in a way that preserves the identity of objects as seen from other [vats](#vat). In the provided contract, baggage is used to ensure that the state of various components is maintained even after the contract is upgraded. -```javascript +```js export const start = async (zcf, privateArgs, baggage) => { - ... + // ... const { accountsStorageNode } = await provideAll(baggage, { - accountsStorageNode: () => E(storageNode).makeChildNode('accounts'), + accountsStorageNode: () => E(storageNode).makeChildNode('accounts') }); - ... -} + // ... +}; ``` ### Exo @@ -195,7 +195,7 @@ An Exo object is an exposed Remotable object with methods (aka a [Far](/glossary This [@endo/exo](https://github.com/endojs/endo/tree/master/packages/exo) package defines the APIs for making Exo objects, and for defining ExoClasses and ExoClassKits for making Exo objects. -```javascript +```js const publicFacet = zone.exo( 'StakeAtom', M.interface('StakeAtomI', { @@ -204,20 +204,20 @@ const publicFacet = zone.exo( }), { async makeAccount() { - trace('makeAccount') - const holder = await makeAccountKit() - return holder + trace('makeAccount'); + const holder = await makeAccountKit(); + return holder; }, makeAccountInvitationMaker() { - trace('makeCreateAccountInvitation') + trace('makeCreateAccountInvitation'); return zcf.makeInvitation(async seat => { - seat.exit() - const holder = await makeAccountKit() - return holder.asContinuingOffer() - }, 'wantStakingAccount') + seat.exit(); + const holder = await makeAccountKit(); + return holder.asContinuingOffer(); + }, 'wantStakingAccount'); } } -) +); ``` ### Zones @@ -226,40 +226,40 @@ Each [Zone](/glossary/#zone) provides an API that allows the allocation of [Exo See [SwingSet vat upgrade documentation](https://github.com/Agoric/agoric-sdk/tree/master/packages/SwingSet/docs/vat-upgrade.md) for more example use of the zone API. -```javascript +```js const zone = makeDurableZone(baggage); -... -zone.subZone('vows') +// ... +zone.subZone('vows'); ``` ### Durable Zone A zone specifically designed for durability, allowing the contract to persist its state across upgrades. This is critical for maintaining the continuity and reliability of the contract’s operations. -```javascript -const zone = makeDurableZone(baggage) +```js +const zone = makeDurableZone(baggage); ``` ### Vow Tools See [Vow](/glossary/#vow); These tools handle promises and asynchronous operations within the contract. `prepareVowTools` prepares the necessary utilities to manage these asynchronous tasks, ensuring that the contract can handle complex workflows that involve waiting for events or responses from other chains. -```javascript +```js const vowTools = prepareVowTools(zone.subZone('vows')); -... +// ... const makeLocalOrchestrationAccountKit = prepareLocalChainAccountKit( zone, makeRecorderKit, zcf, privateArgs.timerService, vowTools, - makeChainHub(privateArgs.agoricNames), + makeChainHub(privateArgs.agoricNames) ); -... +// ... const makeCosmosOrchestrationAccount = prepareCosmosOrchestrationAccount( zone, makeRecorderKit, vowTools, - zcf, + zcf ); ``` diff --git a/main/guides/zoe/contract-walkthru.md b/main/guides/zoe/contract-walkthru.md index a14634464..9eaa4c6df 100644 --- a/main/guides/zoe/contract-walkthru.md +++ b/main/guides/zoe/contract-walkthru.md @@ -80,7 +80,7 @@ The test starts by using `makeZoeKitForTest` to set up zoe for testing: <<< @/../snippets/zoe/contracts/test-bundle-source.js#importZoeForTest ```js -const { zoeService: zoe } = makeZoeKitForTest() +const { zoeService: zoe } = makeZoeKitForTest(); ``` ::: @@ -199,7 +199,7 @@ alicePurse.deposit(moneyPayment); Then we pass the contract instance and the purse to our code for `alice`: ```js -await alice(t, zoe, instance, alicePurse) +await alice(t, zoe, instance, alicePurse); ``` Alice starts by using the `instance` to get the contract's `publicFacet` and `terms` from Zoe: diff --git a/main/guides/zoe/contracts/atomic-swap.md b/main/guides/zoe/contracts/atomic-swap.md index 4d392abc5..bc2341e2d 100644 --- a/main/guides/zoe/contracts/atomic-swap.md +++ b/main/guides/zoe/contracts/atomic-swap.md @@ -29,11 +29,11 @@ can create a swap instance for this particular transaction. const issuerKeywordRecord = harden({ Asset: moolaIssuer, Price: simoleanIssuer -}) +}); const { creatorInvitation } = await E(zoe).startInstance( atomicSwapInstallation, issuerKeywordRecord -) +); ``` Then Alice escrows her offer with Zoe. She passes in two @@ -52,14 +52,14 @@ In this case, Alice's exit rule is `onDemand`, meaning she can exit the contract instance at any time. ```js -const threeMoola = AmountMath.make(moolaBrand, 3) +const threeMoola = AmountMath.make(moolaBrand, 3); const aliceProposal = harden({ give: { Asset: threeMoola }, want: { Price: AmountMath.make(simoleanBrand, 7) }, exit: { onDemand: null } -}) +}); -const alicePayment = await E(aliceMoolaPurse).withdraw(threeMoola) +const alicePayment = await E(aliceMoolaPurse).withdraw(threeMoola); ``` For Alice to escrow with Zoe, she needs to use her invitation. @@ -71,14 +71,14 @@ const aliceSeat = await E(zoe).offer( creatorInvitation, aliceProposal, harden({ Asset: alicePayment }) -) +); ``` This first offer's outcome is an invitation Alice can send to anyone she wants. In this example, she sends it to Bob. ```js -const invitationP = aliceSeat.getOfferResult() +const invitationP = aliceSeat.getOfferResult(); ``` Bob examines the invitation's details to see if they match Alice's claims @@ -86,26 +86,26 @@ about it. ```js secondary style2 const { installation: bobInstallation, instance } = - E(zoe).getInvitationDetails(invitationP) -const bobIssuers = E(zoe).getIssuers(instance) + E(zoe).getInvitationDetails(invitationP); +const bobIssuers = E(zoe).getIssuers(instance); -const bobExclusiveInvitation = await invitationIssuer.claim(invitationP) +const bobExclusiveInvitation = await invitationIssuer.claim(invitationP); const bobInvitationValue = await E(zoe).getInvitationDetails( bobExclusiveInvitation -) +); // Bob verifies the invitation. -assert(bobInstallation === atomicSwapInstallation, details`wrong contract`) -assert(bobIssuers.Asset === moolaIssuer, details`unexpected Asset issuer`) -assert(bobIssuers.Price === simoleanIssuer, details`unexpected Price issuer`) +assert(bobInstallation === atomicSwapInstallation, details`wrong contract`); +assert(bobIssuers.Asset === moolaIssuer, details`unexpected Asset issuer`); +assert(bobIssuers.Price === simoleanIssuer, details`unexpected Price issuer`); assert( AmountMath.isEqual(bobInvitationValue.asset, moola(3)), details`wrong asset` -) +); assert( AmountMath.isEqual(bobInvitationValue.price, simoleans(7)), details`wrong price` -) +); ``` Bob decides to exercise the invitation, and to escrow his payments. He then @@ -114,20 +114,20 @@ But Bob has written his proposal to match Alice's (notice that the `give` and `want` clauses are reversed from Alice's proposal): ```js secondary style2 -const sevenSimoleans = AmountMath.make(simoleanBrand, 7n) +const sevenSimoleans = AmountMath.make(simoleanBrand, 7n); const bobProposal = harden({ want: { Asset: AmountMath.make(moolaBrand, 3n) }, give: { Price: sevenSimoleans }, exit: { onDemand: null } -}) +}); -const bobPayment = await E(bobSimoleansPurse).withdraw(sevenSimoleans) +const bobPayment = await E(bobSimoleansPurse).withdraw(sevenSimoleans); // Bob escrows with zoe and makes an offer const bobSeat = await E(zoe).offer( bobExclusiveInvitation, bobProposal, harden({ Price: bobPayment }) -) +); ``` Bob has made his offer, so the contract executes. Since Alice @@ -136,16 +136,16 @@ and Bob's offers match, Alice's payouts resolve. She uses her payout to find out if Zoe returned some of it. ```js -const aliceAssetPayout = await aliceSeat.getPayout('Asset') -const alicePricePayout = await aliceSeat.getPayout('Price') -const moolaRefundAmount = aliceMoolaPurse.deposit(aliceAssetPayout) -const simoleanGainAmount = aliceSimoleansPurse.deposit(alicePricePayout) +const aliceAssetPayout = await aliceSeat.getPayout('Asset'); +const alicePricePayout = await aliceSeat.getPayout('Price'); +const moolaRefundAmount = aliceMoolaPurse.deposit(aliceAssetPayout); +const simoleanGainAmount = aliceSimoleansPurse.deposit(alicePricePayout); ``` Bob's payout is also available. Since he already knows what Alice's offer was, he doesn't need to look for a simolean refund. ```js secondary style2 -const bobAssetPayout = await bobSeat.getPayout('Asset') -const bobMoolaGainAmount = bobMoolaPurse.deposit(bobAssetPayout) +const bobAssetPayout = await bobSeat.getPayout('Asset'); +const bobMoolaGainAmount = bobMoolaPurse.deposit(bobAssetPayout); ``` diff --git a/main/guides/zoe/contracts/constantProductAMM.md b/main/guides/zoe/contracts/constantProductAMM.md index 326f13941..02181aef3 100644 --- a/main/guides/zoe/contracts/constantProductAMM.md +++ b/main/guides/zoe/contracts/constantProductAMM.md @@ -69,7 +69,7 @@ amountOut of the result.) const quote = E(publicFacet).getOutputPrice( AmountMath.make(BLDBrand, 275n), AmountMath.makeEmpty(ATMBrand) -) +); ``` Let's assume the quote says she needs to provide 216 ATM. Sara believes the @@ -85,15 +85,15 @@ back. const saraProposal = harden({ want: { Out: AmountMath.make(BLDBrand, 275n) }, give: { In: AmountMath.make(atmBrand, 220n) } -}) +}); -const swapInvitation = await E(publicFacet).makeSwapOutInvitation() +const swapInvitation = await E(publicFacet).makeSwapOutInvitation(); const atmPayment = harden({ In: saraAtmPurse.withdraw(AmountMath.make(atmBrand, 220n)) -}) +}); -const saraSeat = await E(zoe).offer(swapInvitation, saraProposal, atmPayment) -const saraResult = await saraSeat.getOfferResult() +const saraSeat = await E(zoe).offer(swapInvitation, saraProposal, atmPayment); +const saraResult = await saraSeat.getOfferResult(); ``` If the result is `Swap successfully completed.`, she got the BLD for 220 ATM @@ -101,11 +101,11 @@ or less (she'll want to deposit any refund). Otherwise the market price moved ag her, and she'll have to check the price again and make another offer. ```js -const BLDProceeds = await E(saraSeat).getPayout('In') -const atmRefund = await E(saraSeat).getPayout('Out') +const BLDProceeds = await E(saraSeat).getPayout('In'); +const atmRefund = await E(saraSeat).getPayout('Out'); -const BLDProceedsAmount = E(saraBLDPurse).deposit(BLDProceeds) -E(saraAtmPurse).deposit(atmRefund) +const BLDProceedsAmount = E(saraBLDPurse).deposit(BLDProceeds); +E(saraAtmPurse).deposit(atmRefund); ``` ### Creating a New Pool @@ -117,7 +117,7 @@ on which to decide how much liquidity to create, so the liquidity amount equals amount of the central token in the offer. ```js -const BLDLiquidityIssuer = await E(publicFacet).addPool(BLDIssuer, 'BLD') +const BLDLiquidityIssuer = await E(publicFacet).addPool(BLDIssuer, 'BLD'); ``` Alice sees that the current rate in the external market is 2 BLD for each @@ -130,18 +130,18 @@ const aliceProposal = harden({ Secondary: AmountMath.make(BLDBrand, 100n), Central: AmountMath.make(ISTBrand, 50n) } -}) +}); const alicePayments = { Secondary: aliceBLDPayment, Central: aliceISTPayment -} +}; -const aliceAddLiquidityInvitation = E(publicFacet).makeAddLiquidityInvitation() +const aliceAddLiquidityInvitation = E(publicFacet).makeAddLiquidityInvitation(); const addLiquiditySeat = await E(zoe).offer( aliceAddLiquidityInvitation, aliceProposal, alicePayments -) +); ``` ### Adding Liquidity to an Existing Pool @@ -157,9 +157,9 @@ Bob calls `getPoolAllocation()` to find the relative levels. Let's say the answe that the current ratio is 1234 BLD to 1718 IST. ```js -const BLDPoolAlloc = E(publicFacet).getPoolAllocation(BLDBrand) -const ISTValue = BLDPoolAlloc.Central.value -const BLDValue = BLDPoolAlloc.secondary.value +const BLDPoolAlloc = E(publicFacet).getPoolAllocation(BLDBrand); +const ISTValue = BLDPoolAlloc.Central.value; +const BLDValue = BLDPoolAlloc.secondary.value; ``` Now he can add liquidity. The price ratio changes when anyone trades with the pool, @@ -177,14 +177,14 @@ const bobProposal = harden({ }, want: { Liquidity: AmountMath.make(liquidityBrand, 0n) }, exit: { onDemand: null } -}) +}); const bobPayments = { Central: bobISTPayment, Secondary: bobBLDPayment -} +}; -const seat = await E(zoe).offer(addLiquidityInvite, bobProposal, bobPayments) +const seat = await E(zoe).offer(addLiquidityInvite, bobProposal, bobPayments); ``` ## Governance diff --git a/main/guides/zoe/contracts/covered-call.md b/main/guides/zoe/contracts/covered-call.md index 6b7413fa1..52d75b90c 100644 --- a/main/guides/zoe/contracts/covered-call.md +++ b/main/guides/zoe/contracts/covered-call.md @@ -95,25 +95,25 @@ issuerKeywordRecord to specify the issuers to be used with each keyword. const issuerKeywordRecord = harden({ UnderlyingAsset: moolaIssuer, StrikePrice: simoleanIssuer -}) +}); const { creatorInvitation } = await E(zoe).startInstance( coveredCallInstallation, issuerKeywordRecord -) +); ``` Then Alice creates a proposal, and escrows the funds she is depositing. ```js -const threeMoola = AmountMath.make(moolaBrand, 3n) +const threeMoola = AmountMath.make(moolaBrand, 3n); const aliceProposal = harden({ give: { UnderlyingAsset: threeMoola }, want: { StrikePrice: AmountMath.make(simoleanBrand, 7n) }, exit: { afterDeadline: { deadline: 1599856578n, timer: chainTimer } } -}) +}); -const alicePayment = { UnderlyingAsset: aliceMoolaPurse.withdraw(threeMoola) } +const alicePayment = { UnderlyingAsset: aliceMoolaPurse.withdraw(threeMoola) }; ``` Alice makes an offer and gets a seat. @@ -123,9 +123,9 @@ const aliceSeat = await E(zoe).offer( creatorInvitation, aliceProposal, alicePayment -) +); -const coveredCall = aliceSeat.getOfferResult() +const coveredCall = aliceSeat.getOfferResult(); ``` The offerResult obtained from the seat is a zoe invitation that serves as the @@ -135,8 +135,8 @@ who can either exercise the call option or sell it in another contract, say, an atomic swap: ```js -const invitationIssuer = E(zoe).getInvitationIssuer() -const bobExclOption = await invitationIssuer.claim(coveredCall) +const invitationIssuer = E(zoe).getInvitationIssuer(); +const bobExclOption = await invitationIssuer.claim(coveredCall); ``` Let's imagine that Bob wants to sell the invitation. He can start a swap @@ -146,11 +146,11 @@ instance to trade this invitation for bucks. const swapIssuerKeywordRecord = harden({ Asset: invitationIssuer, Price: bucksR.issuer -}) +}); const bobSwapSeat = await E(zoe).startInstance( swapInstallation, swapIssuerKeywordRecord -) +); ``` Bob specifies that he wants to swap the invitation for 1 buck, and escrows @@ -161,16 +161,16 @@ share. const bobProposalSwap = harden({ give: { Asset: invitationIssuer.getAmountOf(bobExclOption) }, want: { Price: bucks(1) } -}) +}); -const bobPayments = harden({ Asset: bobExclOption }) +const bobPayments = harden({ Asset: bobExclOption }); const bobSwapSeat = await E(zoe).offer( bobSwapInvitation, bobProposalSwap, bobPayments -) +); -const daveSwapInvitation = bobSwapSeat.getOfferResult() +const daveSwapInvitation = bobSwapSeat.getOfferResult(); ``` ## Buying An Option @@ -184,13 +184,13 @@ what the invitation can be used for. ```js const { installation: daveSwapInstall, instance } = - await E(zoe).getInvitationDetails(daveSwapInvitation) -const daveSwapIssuers = await E(zoe).getIssuers(instance) + await E(zoe).getInvitationDetails(daveSwapInvitation); +const daveSwapIssuers = await E(zoe).getIssuers(instance); // Dave does some checks -assert(daveSwapInstall === swapInstallation, details`wrong installation`) -assert(daveIssuers.Asset === moolaIssuer, details`unexpected Asset issuer`) -assert(daveIssuers.Price === simoleanIssuer, details`unexpected Price issuer`) +assert(daveSwapInstall === swapInstallation, details`wrong installation`); +assert(daveIssuers.Asset === moolaIssuer, details`unexpected Asset issuer`); +assert(daveIssuers.Price === simoleanIssuer, details`unexpected Price issuer`); ``` Dave can safely proceed with the swap because he knows that if Bob has lied @@ -201,15 +201,15 @@ Dave escrows his 1 buck with Zoe and forms his proposal. const daveSwapProposal = harden({ want: { Asset: optionAmount }, give: { Price: bucks(1) } -}) +}); -const daveSwapPayments = harden({ Price: daveBucksPayment }) +const daveSwapPayments = harden({ Price: daveBucksPayment }); const daveSwapSeat = await E(zoe).offer( daveSwapInvitation, daveSwapProposal, daveSwapPayments -) +); ``` ## Exercising the Option @@ -219,23 +219,23 @@ option by submitting an offer that pays the required exercise price in exchange for the underlying asset: ```js -const daveOption = await daveSwapSeat.getPayout('Asset') +const daveOption = await daveSwapSeat.getPayout('Asset'); const daveCoveredCallProposal = harden({ want: { UnderlyingAsset: AmountMath.make(moolaBrand, 3n) }, give: { StrikePrice: AmountMath.make(simoleanBrand, 7n) } -}) +}); const daveCoveredCallPayments = harden({ StrikePrice: daveSimoleanPayment -}) +}); const daveCallSeat = await E(zoe).offer( daveOption, daveCoveredCallProposal, daveCoveredCallPayments -) +); -const daveMoolaPayout = await daveCallSeat.getPayout('UnderlyingAsset') -await daveMoolaPurse.deposit(daveMoolaPayout) +const daveMoolaPayout = await daveCallSeat.getPayout('UnderlyingAsset'); +await daveMoolaPurse.deposit(daveMoolaPayout); ``` diff --git a/main/guides/zoe/contracts/second-price-auction.md b/main/guides/zoe/contracts/second-price-auction.md index 1bfe09dc4..ac6c3d586 100644 --- a/main/guides/zoe/contracts/second-price-auction.md +++ b/main/guides/zoe/contracts/second-price-auction.md @@ -46,14 +46,14 @@ installation.) const issuerKeywordRecord = harden({ Asset: moolaIssuer, Bid: simoleanIssuer -}) +}); -const terms = harden({ numBidsAllowed: 3 }) +const terms = harden({ numBidsAllowed: 3 }); const { creatorInvitation } = await E(zoe).startInstance( installation, issuerKeywordRecord, terms -) +); ``` She can put something up for auction by escrowing it with Zoe, so she provides a @@ -67,17 +67,17 @@ const aliceProposal = harden({ give: { Asset: AmountMath.make(moolaBrand, 1n) }, want: { Bid: AmountMath.make(simoleanBrand, 3n) }, exit: { waived: null } -}) +}); -const alicePayments = { Asset: aliceMoolaPayment } +const alicePayments = { Asset: aliceMoolaPayment }; const aliceSeat = await E(zoe).offer( creatorInvitation, aliceProposal, alicePayments -) -const invitationMaker = await E(aliceSeat).getOfferResult() -const bobInvitation = E(invitationMaker).makeBidInvitation() +); +const invitationMaker = await E(aliceSeat).getOfferResult(); +const bobInvitation = E(invitationMaker).makeBidInvitation(); ``` Now Alice can share the counterparty invitation with her friends and see if there are @@ -87,19 +87,19 @@ he expects. He can also check that the item up for sale is what he wants by comp the issuers. ```js -const invitationIssuer = await E(zoe).getInvitationIssuer() -const bobExclusiveInvitation = await invitationIssuer.claim(bobInvitation) +const invitationIssuer = await E(zoe).getInvitationIssuer(); +const bobExclusiveInvitation = await invitationIssuer.claim(bobInvitation); const { installation: bobInstallation, instance } = await E( zoe -).getInvitationDetails(bobExclusiveInvitation) -const bobIssuers = await E(zoe).getIssuers(instance) +).getInvitationDetails(bobExclusiveInvitation); +const bobIssuers = await E(zoe).getIssuers(instance); assert( bobInstallation === secondPriceAuctionInstallation, details`wrong installation` -) -assert(bobIssuers.Asset === moolaIssuer, details`wrong issuer`) +); +assert(bobIssuers.Asset === moolaIssuer, details`wrong issuer`); ``` Bob decides to join the contract and makes an offer: @@ -108,15 +108,15 @@ Bob decides to join the contract and makes an offer: const bobProposal = harden({ give: { Bid: AmountMath.make(simoleanBrand, 11n) }, want: { Asset: AmountMath.make(moolaBrand, 1n) } -}) +}); -const bobPayments = { Bid: bobSimoleanPayment } +const bobPayments = { Bid: bobSimoleanPayment }; const bobSeat = await E(zoe).offer( bobExclusiveInvitation, bobProposal, bobPayments -) +); ``` Since multiple parties may want to participate in the auction, let's say that Carol and Dave also decide to bid in the same way @@ -128,19 +128,19 @@ Bob gets the 1 moola that was up for auction as well as a refund of 4 simoleans (11-7), and Carol and Dave get a full refund. ```js -const aliceAssetPayout = await aliceSeat.getPayout('Asset') -const moolaRefundAmount = aliceMoolaPurse.deposit(aliceAssetPayout) +const aliceAssetPayout = await aliceSeat.getPayout('Asset'); +const moolaRefundAmount = aliceMoolaPurse.deposit(aliceAssetPayout); -const alicePricePayout = await aliceSeat.getPayout('Price') -const simoleanGainAmount = aliceSimPurse.deposit(alicePricePayout) +const alicePricePayout = await aliceSeat.getPayout('Price'); +const simoleanGainAmount = aliceSimPurse.deposit(alicePricePayout); ``` Bob's payouts are also available. ```js -const bobAssetPayout = await bobSeat.getPayout('Asset') -const bobMoolaGainAmount = bobMoolaPurse.deposit(bobAssetPayout) +const bobAssetPayout = await bobSeat.getPayout('Asset'); +const bobMoolaGainAmount = bobMoolaPurse.deposit(bobAssetPayout); -const bobPricePayout = await bobSeat.getPayout('Price') -const bobSimoleanRefundAmount = bobSimoleanPurse.deposit(bobPricePayout) +const bobPricePayout = await bobSeat.getPayout('Price'); +const bobSimoleanRefundAmount = bobSimoleanPurse.deposit(bobPricePayout); ``` diff --git a/main/guides/zoe/contracts/simple-exchange.md b/main/guides/zoe/contracts/simple-exchange.md index eb7998c86..528f03ad5 100644 --- a/main/guides/zoe/contracts/simple-exchange.md +++ b/main/guides/zoe/contracts/simple-exchange.md @@ -45,10 +45,12 @@ The `publicFacet` is returned when the contract is started. const { publicFacet } = await E(zoe).startInstance(installation, { Asset: moolaIssuer, Price: simoleanIssuer -}) -const simpleExchangeInvitation = await E(publicFacet).makeInvitation() -const { instance } = await E(zoe).getInvitationDetails(simpleExchangeInvitation) -const aliceInvitation = await E(publicFacet).makeInvitation() +}); +const simpleExchangeInvitation = await E(publicFacet).makeInvitation(); +const { instance } = await E(zoe).getInvitationDetails( + simpleExchangeInvitation +); +const aliceInvitation = await E(publicFacet).makeInvitation(); ``` ## Adding an Order @@ -61,9 +63,9 @@ const aliceSellOrderProposal = harden({ give: { Asset: AmountMath.make(moolaBrand, 3n) }, want: { Price: AmountMath.make(simoleanBrand, 4n) }, exit: { onDemand: null } -}) +}); -const alicePayment = { Asset: aliceMoolaPayment } +const alicePayment = { Asset: aliceMoolaPayment }; ``` Alice escrows her payment with Zoe to add her sell order to the exchange. @@ -73,7 +75,7 @@ const aliceSeat = await E(zoe).offer( aliceInvitation, aliceSellOrderProposal, alicePayment -) +); ``` ## Buying an Order @@ -83,13 +85,13 @@ offer. It sounds like a good deal to him, so he checks the installation with Zoe and sees the exchange is trading what he expects: ```js -const bobInvitation = E(publicFacet).makeInvitation() -const invitationIssuer = E(zoe).getInvitationIssuer() -const bobExclusiveInvitation = E(invitationIssuer).claim(bobInvitation) +const bobInvitation = E(publicFacet).makeInvitation(); +const invitationIssuer = E(zoe).getInvitationIssuer(); +const bobExclusiveInvitation = E(invitationIssuer).claim(bobInvitation); const { instance, installation } = await E(zoe).getInvitationDetails( bobExclusiveInvitation -) -const bobIssuers = await E(zoe).getIssuers(instance) +); +const bobIssuers = await E(zoe).getIssuers(instance); ``` Bob verifies the information is what he expects. He compares the @@ -97,9 +99,12 @@ installation he gets from the invitation with a canonical link he found in a public directory he trusts. ```js -assert(installation === simpleExchangeInstallation, details`wrong installation`) -assert(bobIssuers.Asset === moolaIssuer, details`wrong Asset issuer`) -assert(bobIssuers.Price === simoleanIssuer, details`wrong Price issuer`) +assert( + installation === simpleExchangeInstallation, + details`wrong installation` +); +assert(bobIssuers.Asset === moolaIssuer, details`wrong Asset issuer`); +assert(bobIssuers.Price === simoleanIssuer, details`wrong Price issuer`); ``` Bob has checked that everything is in order, so he fulfills the buy order: @@ -109,18 +114,18 @@ const bobBuyOrderProposal = harden({ give: { Price: AmountMath.make(simoleanBrand, 7n) }, want: { Asset: AmountMath.make(moolaBrand, 3n) }, exit: { onDemand: null } -}) +}); const bobSimPayment = await E(bobSimoleanPurse).withdraw( AmountMath(simoleanBrand, 7n) -) -const bobPayments = { Price: bobSimPayment } +); +const bobPayments = { Price: bobSimPayment }; const bobSeat = await E(zoe).offer( bobExclusiveInvitation, bobBuyOrderProposal, bobPayments -) +); ``` ## Payout @@ -130,19 +135,19 @@ resolves to a promise for payment. For Bob: ```js const { Asset: bobAssetPayoutP, Price: bobPricePayoutP } = - await bobSeat.getPayouts() -const bobAssetPayout = await bobAssetPayoutP -const bobMoolaGainAmount = await E(bobMoolaPurse).deposit(bobAssetPayout) -const bobPricePayout = await bobPricePayoutP -const bobSimGainAmount = await E(bobSimPurse).deposit(bobPricePayout) + await bobSeat.getPayouts(); +const bobAssetPayout = await bobAssetPayoutP; +const bobMoolaGainAmount = await E(bobMoolaPurse).deposit(bobAssetPayout); +const bobPricePayout = await bobPricePayoutP; +const bobSimGainAmount = await E(bobSimPurse).deposit(bobPricePayout); ``` Alice gets her payouts the same way. (The choice between `getPayouts()` and `getPayout(keyword)` is based on which is more convenient in each circumstance). ```js -const aliceAssetPayout = await aliceSeat.getPayout('Asset') -const aliceMoolaGainAmount = aliceMoolaPurse.deposit(aliceAssetPayout) -const alicePricePayout = await aliceSeat.getPayout('Price') -const aliceSimGainAmount = aliceSimPurse.deposit(alicePricePayout) +const aliceAssetPayout = await aliceSeat.getPayout('Asset'); +const aliceMoolaGainAmount = aliceMoolaPurse.deposit(aliceAssetPayout); +const alicePricePayout = await aliceSeat.getPayout('Price'); +const aliceSimGainAmount = aliceSimPurse.deposit(alicePricePayout); ``` diff --git a/main/guides/zoe/offer-enforcement.md b/main/guides/zoe/offer-enforcement.md index f250027b1..8c8ccd5e0 100644 --- a/main/guides/zoe/offer-enforcement.md +++ b/main/guides/zoe/offer-enforcement.md @@ -100,22 +100,22 @@ It only does one thing, and it's pretty useless—it gives you back what you ```js const start = zcf => { const refund = seat => { - seat.exit() - return `The offer was accepted` - } - const makeRefundInvitation = () => zcf.makeInvitation(refund, 'getRefund') + seat.exit(); + return `The offer was accepted`; + }; + const makeRefundInvitation = () => zcf.makeInvitation(refund, 'getRefund'); const publicFacet = Far('publicFacet', { makeInvitation: makeRefundInvitation - }) + }); - const creatorInvitation = makeRefundInvitation() + const creatorInvitation = makeRefundInvitation(); - return harden({ creatorInvitation, publicFacet }) -} + return harden({ creatorInvitation, publicFacet }); +}; -harden(start) -export { start } +harden(start); +export { start }; ``` Whenever we create a new object or array, we recursively @@ -190,10 +190,10 @@ both parties. Finally, `matchingSeatOfferHandler()` shuts down the contract. ```js const matchingSeatOfferHandler = matchingSeat => { - const swapResult = swap(zcf, firstSeat, matchingSeat) - zcf.shutdown() - return swapResult -} + const swapResult = swap(zcf, firstSeat, matchingSeat); + zcf.shutdown(); + return swapResult; +}; ``` Now let's put it together. The final step of `makeMatchingInvitation()` diff --git a/main/guides/zoe/price-authority.md b/main/guides/zoe/price-authority.md index e135deacf..37ac1a530 100644 --- a/main/guides/zoe/price-authority.md +++ b/main/guides/zoe/price-authority.md @@ -18,7 +18,7 @@ official `priceQuotes`. A `priceQuote` is a record with an amount and a payment, where the amount is also the current balance of the payment: ```js -const { quoteAmount, quotePayment } = priceQuote +const { quoteAmount, quotePayment } = priceQuote; ``` Because these are ERTP amounts and payments, they have issuers. And @@ -31,7 +31,7 @@ mint associated with the quoteIssuer by using the `quoteIssuer` to obtain the `quoteAmount` of the `quotePayment`: ```js -const verifiedQuoteAmount = await E(quoteIssuer).getAmountOf(quotePayment) +const verifiedQuoteAmount = await E(quoteIssuer).getAmountOf(quotePayment); ``` Once you have a `quoteAmount` (or a `verifiedQuoteAmount`), you can extract the diff --git a/main/guides/zoe/proposal.md b/main/guides/zoe/proposal.md index 0d3626c4b..77b0bd08e 100644 --- a/main/guides/zoe/proposal.md +++ b/main/guides/zoe/proposal.md @@ -33,7 +33,7 @@ const myProposal = harden({ give: { Asset: AmountMath.make(quatloosBrand, 4n) }, want: { Price: AmountMath.make(moolaBrand, 15n) }, exit: { onDemand: null } -}) +}); ``` **give** and **want** use [Keywords](/reference/zoe-api/zoe-data-types#keyword) defined by the contract. @@ -73,7 +73,7 @@ or rejected or the assets are reassigned to another offer. const payments = { Asset: quatloosPayment, Price: moolaPayment -} +}; ``` ## Offer Arguments diff --git a/main/guides/zoe/pub-to-storage.md b/main/guides/zoe/pub-to-storage.md index 292969c7e..f77407428 100644 --- a/main/guides/zoe/pub-to-storage.md +++ b/main/guides/zoe/pub-to-storage.md @@ -12,8 +12,8 @@ In [Adding Parameter Governance to a Contract](../governance/#adding-parameter-g In [dapp-agoric-basics](https://github.com/Agoric/dapp-agoric-basics), the `startSwapContract` uses 2 [permitted deployment capabilities](../coreeval/permissions), `chainStorage` and `board` and uses them to make the `privateArgs`: ```js -const marshaller = await E(board).getPublishingMarshaller() -const storageNode = await E(chainStorage).makeChildNode(contractName) +const marshaller = await E(board).getPublishingMarshaller(); +const storageNode = await E(chainStorage).makeChildNode(contractName); ``` A `Marshaller` is parameterized by functions for mapping unforgeable object identities to plain data slot references and back. Using the [board](../integration/name-services#the-board-publishing-under-arbitrary-names) name service gives consistent slot references across contracts. @@ -104,7 +104,7 @@ a `RecorderKit` using [prepareRecorderKitMakers](/reference/zoe-api/zoe-helpers# const { makeRecorderKit } = prepareRecorderKitMakers( baggage, privateArgs.marshaller -) +); ``` The contract gets `baggage`, along with `privateArgs` when it starts in @@ -122,14 +122,14 @@ The contract gets `baggage`, along with `privateArgs` when it starts in * @param {Baggage} baggage */ export const prepare = async (zcf, privateArgs, baggage) => { - ... + // ... }; ``` The reserve uses its `StorageNode` and makes a child to get `metricsNode`: ```js -const metricsNode = await E(storageNode).makeChildNode('metrics') +const metricsNode = await E(storageNode).makeChildNode('metrics'); ``` The `marshaller` is used to serialize data structures such as `MetricsNotification` above. @@ -140,9 +140,9 @@ To start `assetReserve`, the [setupReserve](https://github.com/Agoric/agoric-sdk the two relevant `privateArgs`, `marshaller` and `storageNode`: ```js -const STORAGE_PATH = 'reserve' -const storageNode = await E(storageNode).makeChildNode(STORAGE_PATH) -const marshaller = await E(board).getReadonlyMarshaller() +const STORAGE_PATH = 'reserve'; +const storageNode = await E(storageNode).makeChildNode(STORAGE_PATH); +const marshaller = await E(board).getReadonlyMarshaller(); ``` The `setupReserve` function gets `chainStorage` and `board` deployment capabilities passed in: @@ -152,8 +152,8 @@ export const setupReserve = async ({ consume: { board, chainStorage, - ... +// ... }, -... +// ... }) => { ... }; ``` diff --git a/main/reference/ertp-api/amount-math.md b/main/reference/ertp-api/amount-math.md index 9f6cc6eb1..969757a53 100644 --- a/main/reference/ertp-api/amount-math.md +++ b/main/reference/ertp-api/amount-math.md @@ -26,7 +26,7 @@ not equal, an error is thrown and no changes are made. Creates an **Amount** from a given **Brand** and **AmountValue**. ```js -const bid = AmountMath.make(quatloosBrand, 300n) +const bid = AmountMath.make(quatloosBrand, 300n); ``` ## AmountMath.coerce(brand, allegedAmount) @@ -39,7 +39,7 @@ Verifies that an **Amount** is for the specified _brand_ and returns an equivale If the **Amount** is not for the specified **Brand**, an error is thrown. ```js -const verifiedAmount = AmountMath.coerce(quatloosBrand, bid) +const verifiedAmount = AmountMath.coerce(quatloosBrand, bid); ``` ## AmountMath.getValue(brand, amount) @@ -51,10 +51,10 @@ const verifiedAmount = AmountMath.coerce(quatloosBrand, bid) Returns the **AmountValue** from the given **Amount**. ```js -const quatloos123 = AmountMath.make(quatloosBrand, 123n) +const quatloos123 = AmountMath.make(quatloosBrand, 123n); // Returns 123n -AmountMath.getValue(quatloosBrand, quatloos123) +AmountMath.getValue(quatloosBrand, quatloos123); ``` ## AmountMath.makeEmpty(brand, assetKind) @@ -70,7 +70,7 @@ on whether the _assetKind_ is **AssetKind.NAT** (`0n`), **AssetKind.COPY_SET** ( ```js // Returns an amount with 0n as its value -const empty = AmountMath.makeEmpty(quatloosBrand, AssetKind.NAT) +const empty = AmountMath.makeEmpty(quatloosBrand, AssetKind.NAT); ``` ## AmountMath.makeEmptyFromAmount(amount) @@ -82,9 +82,9 @@ Returns an empty **Amount** for the **Brand** of the _amount_ parameter. ```js // bid = { brand: quatloosBrand, value: 300n } -const bid = AmountMath.make(quatloosBrand, 300n) +const bid = AmountMath.make(quatloosBrand, 300n); // Returns { brand: quatloosBrand, value: 0n } -const zeroQuatloos = AmountMath.makeEmptyFromAmount(bid) +const zeroQuatloos = AmountMath.makeEmptyFromAmount(bid); ``` ## AmountMath.isEmpty(amount, brand?) @@ -98,14 +98,14 @@ Returns **true** if the **Amount** is empty. Otherwise returns **false**. If the optional _brand_ argument doesn't match the **Amount**'s **Brand**, an error is thrown. ```js -const empty = AmountMath.makeEmpty(quatloosBrand, AssetKind.NAT) -const quatloos1 = AmountMath.make(quatloosBrand, 1n) +const empty = AmountMath.makeEmpty(quatloosBrand, AssetKind.NAT); +const quatloos1 = AmountMath.make(quatloosBrand, 1n); // Returns true -const result = AmountMath.isEmpty(empty) +const result = AmountMath.isEmpty(empty); // Returns false -const result = AmountMath.isEmpty(quatloos1) +const result = AmountMath.isEmpty(quatloos1); ``` ## AmountMath.isGTE(leftAmount, rightAmount, brand?) @@ -126,20 +126,20 @@ kind of **AmountMath**. For example, { 'seat 1', 'seat 2' } is considered greater than { 'seat 2' } because the former is a strict superset of the latter. ```js -const empty = AmountMath.makeEmpty(quatloosBrand, AssetKind.NAT) -const quatloos5 = AmountMath.make(quatloosBrand, 5n) -const quatloos10 = AmountMath.make(quatloosBrand, 10n) +const empty = AmountMath.makeEmpty(quatloosBrand, AssetKind.NAT); +const quatloos5 = AmountMath.make(quatloosBrand, 5n); +const quatloos10 = AmountMath.make(quatloosBrand, 10n); // Returns true -AmountMath.isGTE(quatloos5, empty) +AmountMath.isGTE(quatloos5, empty); // Returns false -AmountMath.isGTE(empty, quatloos5, quatloosBrand) +AmountMath.isGTE(empty, quatloos5, quatloosBrand); // Returns true -AmountMath.isGTE(quatloos10, quatloos5) +AmountMath.isGTE(quatloos10, quatloos5); // Returns false -AmountMath.isGTE(quatloos5, quatloos10) +AmountMath.isGTE(quatloos5, quatloos10); // Returns true -AmountMath.isGTE(quatloos5, quatloos5) +AmountMath.isGTE(quatloos5, quatloos5); ``` ## AmountMath.isEqual(leftAmount, rightAmount, brand?) @@ -163,19 +163,19 @@ unequal to { 'seat 2' } because the number of elements differ. { 'seat 1' } is considered unequal to { 'seat 2' } because the elements do not match. ```js -const empty = AmountMath.makeEmpty(quatloosBrand, AssetKind.NAT) -const quatloos5 = AmountMath.make(quatloosBrand, 5n) -const quatloos5b = AmountMath.make(quatloosBrand, 5n) -const quatloos10 = AmountMath.make(quatloosBrand, 10n) +const empty = AmountMath.makeEmpty(quatloosBrand, AssetKind.NAT); +const quatloos5 = AmountMath.make(quatloosBrand, 5n); +const quatloos5b = AmountMath.make(quatloosBrand, 5n); +const quatloos10 = AmountMath.make(quatloosBrand, 10n); // Returns true -AmountMath.isEqual(quatloos10, quatloos10) +AmountMath.isEqual(quatloos10, quatloos10); // Returns true -AmountMath.isEqual(quatloos5, quatloos5b) +AmountMath.isEqual(quatloos5, quatloos5b); // Returns false -AmountMath.isEqual(quatloos10, quatloos5) +AmountMath.isEqual(quatloos10, quatloos5); // Returns false -AmountMath.isEqual(empty, quatloos10) +AmountMath.isEqual(empty, quatloos10); ``` ## AmountMath.add(leftAmount, rightAmount, brand?) @@ -198,13 +198,13 @@ If one of _leftAmount_ or _rightAmount_ is empty, this method returns an **Amoun If both are empty, this method returns an empty **Amount**. ```js -import { AssetKind, makeIssuerKit, AmountMath } from '@agoric/ertp' -const { brand: myItemsBrand } = makeIssuerKit('myItems', AssetKind.COPY_SET) -const listAmountA = AmountMath.make(myItemsBrand, ['1', '2', '4']) -const listAmountB = AmountMath.make(myItemsBrand, ['3']) +import { AssetKind, makeIssuerKit, AmountMath } from '@agoric/ertp'; +const { brand: myItemsBrand } = makeIssuerKit('myItems', AssetKind.COPY_SET); +const listAmountA = AmountMath.make(myItemsBrand, ['1', '2', '4']); +const listAmountB = AmountMath.make(myItemsBrand, ['3']); // Returns an amount whose value is ['1', '2', '4', '3'] -const combinedList = AmountMath.add(listAmountA, listAmountB) +const combinedList = AmountMath.add(listAmountA, listAmountB); ``` ## AmountMath.subtract(leftAmount, rightAmount, brand?) @@ -228,17 +228,17 @@ If _rightAmount_ is empty, this method returns _leftAmount_. If both arguments a empty, this method returns an empty **Amount**. ```js -import { AssetKind, makeIssuerKit, AmountMath } from '@agoric/ertp' -const { brand: myItemsBrand } = makeIssuerKit('myItems', AssetKind.COPY_SET) -const listAmountA = AmountMath.make(myItemsBrand, ['1', '2', '4']) -const listAmountB = AmountMath.make(myItemsBrand, ['3']) -const listAmountC = AmountMath.make(myItemsBrand, ['2']) +import { AssetKind, makeIssuerKit, AmountMath } from '@agoric/ertp'; +const { brand: myItemsBrand } = makeIssuerKit('myItems', AssetKind.COPY_SET); +const listAmountA = AmountMath.make(myItemsBrand, ['1', '2', '4']); +const listAmountB = AmountMath.make(myItemsBrand, ['3']); +const listAmountC = AmountMath.make(myItemsBrand, ['2']); // Returns ['1', '4'] -const subtractedList = AmountMath.subtract(listAmountA, listAmountC) +const subtractedList = AmountMath.subtract(listAmountA, listAmountC); // Throws an error -const badList = AmountMath.subtract(listAmountA, listAmountB) +const badList = AmountMath.subtract(listAmountA, listAmountB); ``` ## AmountMath.min(x, y, brand?) @@ -255,11 +255,11 @@ Both **Amount** arguments must have the same **Brand**. If the optional _brand_ argument doesn't match the **Amount**s' **Brand**, an error is thrown. ```js -const smallerAmount = AmountMath.make(quatloosBrand, 5n) -const largerAmount = AmountMath.make(quatloosBrand, 10n) +const smallerAmount = AmountMath.make(quatloosBrand, 5n); +const largerAmount = AmountMath.make(quatloosBrand, 10n); // Returns an amount equivalent to smallerAmount -const comparisonResult = AmountMath.min(smallerAmount, largerAmount) +const comparisonResult = AmountMath.min(smallerAmount, largerAmount); ``` ## AmountMath.max(x, y, brand?) @@ -276,11 +276,11 @@ Both **Amount** arguments must have the same **Brand**. If the optional _brand_ argument doesn't match the **Amount**s' **Brand**, an error is thrown. ```js -const smallerAmount = AmountMath.make(quatloosBrand, 5n) -const largerAmount = AmountMath.make(quatloosBrand, 10n) +const smallerAmount = AmountMath.make(quatloosBrand, 5n); +const largerAmount = AmountMath.make(quatloosBrand, 10n); // Returns an amount equivalent to largerAmount -const comparisonResult = AmountMath.max(smallerAmount, largerAmount) +const comparisonResult = AmountMath.max(smallerAmount, largerAmount); ``` ## Related Methods diff --git a/main/reference/ertp-api/brand.md b/main/reference/ertp-api/brand.md index b8957fdbe..c3757799d 100644 --- a/main/reference/ertp-api/brand.md +++ b/main/reference/ertp-api/brand.md @@ -29,7 +29,7 @@ an **Issuer**. The claim should be cross-checked using the **Issuer's** [**anIssuer.getBrand()**](./issuer#anissuer-getbrand) method for mutual agreement. ```js -const isIssuer = brand.isMyIssuer(issuer) +const isIssuer = brand.isMyIssuer(issuer); ``` ## aBrand.getAllegedName() @@ -50,7 +50,7 @@ _Quatloos_ **Issuer**. The alleged name is just a human readable string which is helpful for debugging. ```js -const name = brand.getAllegedName() +const name = brand.getAllegedName(); ``` ## aBrand.getDisplayInfo() @@ -66,7 +66,7 @@ the smallest denomination used for financial accounting (e.g., displaying in dollars rather than cents). ```js -const quatloosDisplay = quatloosBrand.getDisplayInfo() +const quatloosDisplay = quatloosBrand.getDisplayInfo(); ``` ## aBrand.getAmountShape() diff --git a/main/reference/ertp-api/ertp-data-types.md b/main/reference/ertp-api/ertp-data-types.md index 029a20162..7e1b53a14 100644 --- a/main/reference/ertp-api/ertp-data-types.md +++ b/main/reference/ertp-api/ertp-data-types.md @@ -61,9 +61,9 @@ Use **[makeIssuerKit()](./issuer#makeissuerkit-allegedname-assetkind-displayinfo your contract uses. See the **[Issuer](./issuer)** documentation for details on how to use this method. ```js -import { AssetKind, makeIssuerKit } from '@agoric/ertp' -makeIssuerKit('quatloos') // Defaults to AssetKind.NAT and undefined DisplayInfo -makeIssuerKit('kitties', AssetKind.COPY_SET) // Defaults to undefined DisplayInfo +import { AssetKind, makeIssuerKit } from '@agoric/ertp'; +makeIssuerKit('quatloos'); // Defaults to AssetKind.NAT and undefined DisplayInfo +makeIssuerKit('kitties', AssetKind.COPY_SET); // Defaults to undefined DisplayInfo ``` ## DisplayInfo diff --git a/main/reference/ertp-api/issuer.md b/main/reference/ertp-api/issuer.md index 0d840041a..09c7de706 100644 --- a/main/reference/ertp-api/issuer.md +++ b/main/reference/ertp-api/issuer.md @@ -53,9 +53,9 @@ with however many properties are required to describe the asset. This object set _valueShape's_ properties of the asset's **[AmountShape](./ertp-data-types#amountshape)**. ```js -import { AssetKind, makeIssuerKit } from '@agoric/ertp' -makeIssuerKit('quatloos') // Defaults to AssetKind.NAT -makeIssuerKit('title', AssetKind.COPY_SET) +import { AssetKind, makeIssuerKit } from '@agoric/ertp'; +makeIssuerKit('quatloos'); // Defaults to AssetKind.NAT +makeIssuerKit('title', AssetKind.COPY_SET); ``` ```js @@ -63,22 +63,22 @@ const { issuer: quatloosIssuer, mint: quatloosMint, brand: quatloosBrand -} = makeIssuerKit('quatloos') +} = makeIssuerKit('quatloos'); // This is merely an amount, describing assets, not minting assets -const quatloos2 = AmountMath.make(quatloosBrand, 2n) +const quatloos2 = AmountMath.make(quatloosBrand, 2n); const { issuer: titleIssuer, mint: titleMint, brand: titleBrand -} = makeIssuerKit('propertyTitle') +} = makeIssuerKit('propertyTitle'); // These are merely amounts describing digital assets, not minting assets. -const cornerProperty = AmountMath.make(propertyTitleBrand, ['1292826']) -const adjacentProperty = AmountMath.make(propertyTitleBrand, ['1028393']) +const cornerProperty = AmountMath.make(propertyTitleBrand, ['1292826']); +const adjacentProperty = AmountMath.make(propertyTitleBrand, ['1028393']); const combinedProperty = AmountMath.make(propertyTitleBrand, [ '1292826', '1028393' -]) +]); ``` ## anIssuer.getAllegedName() @@ -101,8 +101,8 @@ or not such a name is already in use. The alleged name is just a human readable string which is helpful for debugging. ```js -const { issuer: quatloosIssuer } = makeIssuerKit('quatloos') -const quatloosIssuerAllegedName = quatloosIssuer.getAllegedName() +const { issuer: quatloosIssuer } = makeIssuerKit('quatloos'); +const quatloosIssuerAllegedName = quatloosIssuer.getAllegedName(); // quatloosIssuerAllegedName === 'quatloos' ``` @@ -115,10 +115,10 @@ Returns the kind of the **Issuer**'s asset. The **AssetKind** specifies what kind of values are used in **[Amounts](./ertp-data-types#amount)** for this **Issuer**. ```js -const { issuer: quatloosIssuer } = makeIssuerKit('quatloos') -quatloosIssuer.getAssetKind() // Returns 'nat', also known as AssetKind.NAT, the default value. -const { issuer: moolaIssuer } = makeIssuerKit('moola', AssetKind.COPY_SET) -moolaIssuer.getAssetKind() // Returns 'copy_set', also known as 'AssetKind.COPY_SET' +const { issuer: quatloosIssuer } = makeIssuerKit('quatloos'); +quatloosIssuer.getAssetKind(); // Returns 'nat', also known as AssetKind.NAT, the default value. +const { issuer: moolaIssuer } = makeIssuerKit('moola', AssetKind.COPY_SET); +moolaIssuer.getAssetKind(); // Returns 'copy_set', also known as 'AssetKind.COPY_SET' ``` ## anIssuer.getAmountOf(payment) @@ -135,11 +135,11 @@ const { issuer: quatloosIssuer, mint: quatloosMint, brand: quatloosBrand -} = makeIssuerKit('quatloos') +} = makeIssuerKit('quatloos'); const quatloosPayment = quatloosMint.mintPayment( AmountMath.make(quatloosBrand, 100n) -) -quatloosIssuer.getAmountOf(quatloosPayment) // returns an amount of 100 Quatloos +); +quatloosIssuer.getAmountOf(quatloosPayment); // returns an amount of 100 Quatloos ``` ## anIssuer.getBrand() @@ -153,8 +153,8 @@ an **Issuer** alone. Fake digital assets and amounts can use another **Issuer's* ```js const { issuer: quatloosIssuer, brand: quatloosBrand } = - makeIssuerKit('quatloos') -const quatloosBrand = quatloosIssuer.getBrand() + makeIssuerKit('quatloos'); +const quatloosBrand = quatloosIssuer.getBrand(); // brand === quatloosBrand ``` @@ -165,8 +165,8 @@ const quatloosBrand = quatloosIssuer.getBrand() Makes and returns an empty **Purse** that holds assets of the **[Brand](./brand)** associated with the **Issuer**. ```js -const { issuer: quatloosIssuer } = makeIssuerKit('quatloos') -const quatloosPurse = quatloosIssuer.makeEmptyPurse() +const { issuer: quatloosIssuer } = makeIssuerKit('quatloos'); +const quatloosPurse = quatloosIssuer.makeEmptyPurse(); ``` ## **anIssuer.burn(payment, optAmount?)** @@ -192,12 +192,12 @@ const { issuer: quatloosIssuer, mint: quatloosMint, brand: quatloosBrand -} = makeIssuerKit('quatloos') -const amountToBurn = AmountMath.make(quatloosBrand, 10n) -const paymentToBurn = quatloosMint.mintPayment(amountToBurn) +} = makeIssuerKit('quatloos'); +const amountToBurn = AmountMath.make(quatloosBrand, 10n); +const paymentToBurn = quatloosMint.mintPayment(amountToBurn); // burntAmount should equal 10 Quatloos -const burntAmount = quatloosIssuer.burn(paymentToBurn, amountToBurn) +const burntAmount = quatloosIssuer.burn(paymentToBurn, amountToBurn); ``` ## anIssuer.isLive(payment) @@ -233,11 +233,11 @@ const { issuer: quatloosIssuer, mint: quatloosMint, brand: quatloosBrand -} = makeIssuerKit('quatloos') -const amountExpectedToTransfer = AmountMath.make(quatloosBrand, 2n) -const originalPayment = quatloosMint.mintPayment(amountExpectedToTransfer) +} = makeIssuerKit('quatloos'); +const amountExpectedToTransfer = AmountMath.make(quatloosBrand, 2n); +const originalPayment = quatloosMint.mintPayment(amountExpectedToTransfer); -const newPayment = quatloosIssuer.claim(originalPayment, amountToTransfer) +const newPayment = quatloosIssuer.claim(originalPayment, amountToTransfer); ``` ## anIssuer.combine(paymentsArray, optTotalAmount?) @@ -262,15 +262,15 @@ const { issuer: quatloosIssuer, mint: quatloosMint, brand: quatloosBrand -} = makeIssuerKit('quatloos') +} = makeIssuerKit('quatloos'); // Create an array of 100 payments of 1 quatloo each -const payments = [] +const payments = []; for (let i = 0; i < 100; i += 1) { - payments.push(quatloosMint.mintPayment(AmountMath.make(quatloosBrand, 1n))) + payments.push(quatloosMint.mintPayment(AmountMath.make(quatloosBrand, 1n))); } // combinedPayment equals 100 -const combinedPayment = quatloosIssuer.combine(payments) +const combinedPayment = quatloosIssuer.combine(payments); ``` ## anIssuer.split(payment, paymentAmountA) @@ -294,13 +294,15 @@ const { issuer: quatloosIssuer, mint: quatloosMint, brand: quatloosBrand -} = makeIssuerKit('quatloos') -const oldPayment = quatloosMint.mintPayment(AmountMath.make(quatloosBrand, 20n)) +} = makeIssuerKit('quatloos'); +const oldPayment = quatloosMint.mintPayment( + AmountMath.make(quatloosBrand, 20n) +); // After the split, paymentA has 5 quatloos and paymentB has 15. const [paymentA, paymentB] = quatloosIssuer.split( oldPayment, AmountMath.make(quatloosBrand, 5n) -) +); ``` ## anIssuer.splitMany(payment, amountArray) @@ -324,23 +326,23 @@ const { issuer: quatloosIssuer, mint: quatloosMint, brand: quatloosBrand -} = makeIssuerKit('quatloos') +} = makeIssuerKit('quatloos'); const oldPayment = quatloosMint.mintPayment( AmountMath.make(quatloosBrand, 100n) -) -const goodAmounts = Array(10).fill(AmountMath.make(quatloosBrand, 10n)) +); +const goodAmounts = Array(10).fill(AmountMath.make(quatloosBrand, 10n)); -const arrayOfNewPayments = quatloosIssuer.splitMany(oldPayment, goodAmounts) +const arrayOfNewPayments = quatloosIssuer.splitMany(oldPayment, goodAmounts); // The total amount in the amountArray must equal the original payment amount // Set original amount to 1000n -const payment = quatloosMint.mintPayment(AmountMath.make(quatloosBrand, 1000n)) +const payment = quatloosMint.mintPayment(AmountMath.make(quatloosBrand, 1000n)); // Total amounts in badAmounts equal 20n, when it should equal 1000n -const badAmounts = Array(2).fill(AmountMath.make(quatloosBrand, 10n)) +const badAmounts = Array(2).fill(AmountMath.make(quatloosBrand, 10n)); // 20n does not equal 1000n, so throws error -quatloosIssuer.splitMany(payment, badAmounts) +quatloosIssuer.splitMany(payment, badAmounts); ``` ::: diff --git a/main/reference/ertp-api/mint.md b/main/reference/ertp-api/mint.md index 420ffc684..b15dfdd59 100644 --- a/main/reference/ertp-api/mint.md +++ b/main/reference/ertp-api/mint.md @@ -16,11 +16,12 @@ Returns the **Issuer** uniquely associated with this **Mint**. From its creation in an unchangeable one-to-one relationship with a particular **Issuer**. ```js -const { issuer: quatloosIssuer, mint: quatloosMint } = makeIssuerKit('quatloos') -const quatloosMintIssuer = quatloosMint.getIssuer() +const { issuer: quatloosIssuer, mint: quatloosMint } = + makeIssuerKit('quatloos'); +const quatloosMintIssuer = quatloosMint.getIssuer(); // Returns true -issuer === quatloosMintIssuer +issuer === quatloosMintIssuer; ``` ## aMint.mintPayment(newAmount) @@ -37,11 +38,11 @@ const { issuer: quatloosIssuer, mint: quatloosMint, brand: quatloosBrand -} = makeIssuerKit('quatloos') +} = makeIssuerKit('quatloos'); -const quatloos1000 = amountMath.make(quatloosBrand, 1000n) +const quatloos1000 = amountMath.make(quatloosBrand, 1000n); // newPayment will have a balance of 1000 Quatloos -const newPayment = quatloosMint.mintPayment(quatloos1000) +const newPayment = quatloosMint.mintPayment(quatloos1000); ``` ::: tip Important diff --git a/main/reference/ertp-api/payment.md b/main/reference/ertp-api/payment.md index 52104c2ec..bc63f5544 100644 --- a/main/reference/ertp-api/payment.md +++ b/main/reference/ertp-api/payment.md @@ -43,9 +43,9 @@ should be treated with suspicion and verified elsewhere. Any successful operation by an **Issuer** on a **Payment** verifies it. ```js -const payment = quatloosMint.mintPayment(AmountMath.make(quatloosBrand, 10n)) +const payment = quatloosMint.mintPayment(AmountMath.make(quatloosBrand, 10n)); // Should return 'quatloos' -const allegedBrand = payment.getAllegedBrand() +const allegedBrand = payment.getAllegedBrand(); ``` ## Related Methods diff --git a/main/reference/ertp-api/purse.md b/main/reference/ertp-api/purse.md index 1cbc3f4b1..7a31c8492 100644 --- a/main/reference/ertp-api/purse.md +++ b/main/reference/ertp-api/purse.md @@ -19,8 +19,8 @@ method on the **[Issuer](./issuer)** associated with the **Brand** of assets you new **Purse** to hold. ```js -const { issuer: quatloosIssuer } = makeIssuerKit('quatloos') -const quatloosPurse = quatloosIssuer.makeEmptyPurse() +const { issuer: quatloosIssuer } = makeIssuerKit('quatloos'); +const quatloosPurse = quatloosIssuer.makeEmptyPurse(); ``` You change a **Purse**'s balance by calling either @@ -59,13 +59,13 @@ Returns a lossy notifier for changes to this **Purse**'s balance. For more detai see [Notifiers](/guides/js-programming/notifiers). ```js -const notifier = purse.getCurrentAmountNotifier() -let nextUpdate = notifier.getUpdateSince() +const notifier = purse.getCurrentAmountNotifier(); +let nextUpdate = notifier.getUpdateSince(); const checkNotifier = async () => { - const { value: balance, updateCount } = await nextUpdate - nextUpdate = notifier.getUpdateSince(updateCount) -} + const { value: balance, updateCount } = await nextUpdate; + nextUpdate = notifier.getUpdateSince(updateCount); +}; ``` ## aPurse.deposit(payment, optAmount?) @@ -94,19 +94,19 @@ const { issuer: quatloosIssuer, mint: quatloosMint, brand: quatloosBrand -} = makeIssuerKit('quatloos') -const quatloosPurse = quatloosIssuer.makeEmptyPurse() -const payment = quatloosMint.mintPayment(AmountMath.make(quatloosBrand, 123n)) -const quatloos123 = AmountMath.make(quatloosBrand, 123n) +} = makeIssuerKit('quatloos'); +const quatloosPurse = quatloosIssuer.makeEmptyPurse(); +const payment = quatloosMint.mintPayment(AmountMath.make(quatloosBrand, 123n)); +const quatloos123 = AmountMath.make(quatloosBrand, 123n); // Deposit a payment for 123 Quatloos into the Purse. -const depositAmountA = quatloosPurse.deposit(payment, quatloos123) +const depositAmountA = quatloosPurse.deposit(payment, quatloos123); const secondPayment = quatloosMint.mintPayment( AmountMath.make(quatloosBrand, 100n) -) +); // Throws error -const depositAmountB = quatloosPurse.deposit(secondPayment, quatloos123) +const depositAmountB = quatloosPurse.deposit(secondPayment, quatloos123); ``` ## aPurse.withdraw(amount) @@ -122,21 +122,21 @@ But as soon as the message is processed, the value is gone from the **Purse**. ```js // Create a Purse and give it a balance of 10 Quatloos -const { issuer, mint, brand } = makeIssuerKit('quatloos') -const purse = issuer.makeEmptyPurse() -const payment = mint.mintPayment(AmountMath.make(brand, 10n)) -const quatloos10 = AmountMath.make(brand, 10n) -purse.deposit(payment, quatloos10) +const { issuer, mint, brand } = makeIssuerKit('quatloos'); +const purse = issuer.makeEmptyPurse(); +const payment = mint.mintPayment(AmountMath.make(brand, 10n)); +const quatloos10 = AmountMath.make(brand, 10n); +purse.deposit(payment, quatloos10); // Withdraw an amount of 3 from the Purse -const quatloos3 = AmountMath.make(brand, 3n) -const withdrawalPayment = purse.withdraw(quatloos3) +const quatloos3 = AmountMath.make(brand, 3n); +const withdrawalPayment = purse.withdraw(quatloos3); // The balance of the withdrawal payment is 3 Quatloos -issuer.getAmountOf(withdrawalPayment) +issuer.getAmountOf(withdrawalPayment); // The new balance of the Purse is 7 Quatloos -purse.getCurrentAmount() +purse.getCurrentAmount(); ``` ## aPurse.getAllegedBrand() @@ -148,7 +148,7 @@ indicating what kind of digital asset the **Purse** purports to hold. This can i **Purse**'s **Brand** if the **Purse** was made by a trusted **[Issuer](./issuer)** using **[anIssuer.makeEmptyPurse()](./issuer#anissuer-makeemptypurse)**. ```js -const purseBrand = quatloosPurse.getAllegedBrand() +const purseBrand = quatloosPurse.getAllegedBrand(); ``` ## aPurse.getDepositFacet() @@ -163,11 +163,11 @@ This makes it a safe way to let other people send you **Payments**. You can only deposit a **Payment** into a **DepositFacet** that's the same **[Brand](./brand)** as the original **Purse**. ```js -const depositOnlyFacet = purse.getDepositFacet() +const depositOnlyFacet = purse.getDepositFacet(); // Give depositOnlyFacet to someone else. Anyone with a deposit facet reference can tell it to receive // a payment, thus depositing the payment assets in the Purse associated with the deposit facet. -depositOnlyFacet.receive(payment) +depositOnlyFacet.receive(payment); ``` Once you have created a **DepositFacet**, there is one method you can call @@ -191,9 +191,9 @@ If the optional argument _optAmount_ does not equal the balance of _payment_, or if _payment_ is an unresolved promise, this method throws an error. ```js -const depositOnlyFacet = purse.getDepositFacet() +const depositOnlyFacet = purse.getDepositFacet(); // Give depositOnlyFacet to someone else. Anyone with a deposit facet reference can tell it to receive // a payment, thus depositing the payment assets in the Purse associated with the deposit facet. -depositOnlyFacet.receive(payment) +depositOnlyFacet.receive(payment); ``` diff --git a/main/reference/repl/networking.md b/main/reference/repl/networking.md index 16e32d1ac..07fad12fd 100644 --- a/main/reference/repl/networking.md +++ b/main/reference/repl/networking.md @@ -50,10 +50,10 @@ You must also prepare a `ConnectionHandler` object to manage the connection you' Then you will call the `connect()` method on your local `Port`. This will return a `Promise` that will fire with a new `Connection` object, on which you can send data. Your `ConnectionHandler` will be notified about the new channel, and will receive inbound data from the other side. ```js -const remoteEndpoint = `/ibc-hop/${hopName}/ibc-port/${portName}/ordered/${version}` +const remoteEndpoint = `/ibc-hop/${hopName}/ibc-port/${portName}/ordered/${version}`; E(home.ibcport[0]) .connect(remoteEndpoint, connectionHandler) - .then(conn => doSomethingWithConnection(conn)) + .then(conn => doSomethingWithConnection(conn)); ``` ## Opening a Listening Port and Accepting an Inbound Connection @@ -66,12 +66,12 @@ To get a listening port, you need a `NetworkInterface` object (such as the one o // Ask for a random allocation - ends with a slash E(home.network) .bind('/ibc-port/') - .then(port => usePort(port)) + .then(port => usePort(port)); // or ask for a specific port name E(home.network) .bind('/ibc-port/my-cool-port-name') - .then(port => usePort(port)) + .then(port => usePort(port)); ``` IBC has named "hops" (what they call "Connections" in the IBC spec) which each carry data between two specific chains. These hops are different from the connections described in this document. When you bind a port like `/ibc-port/$PORT` without specifying the "hop", any IBC chain can initiate a connection to this port. @@ -81,7 +81,7 @@ You can ask the `Port` object this returns for its local address, which is espec ```js E(port) .getLocalAddress() - .then(localAddress => useIt(localAddress)) + .then(localAddress => useIt(localAddress)); ``` Once the port is bound, you must call `addListener()` to mark it as ready for inbound connections. You must provide this with a `ListenHandler` object, which has methods to react to listening events. As with `ConnectionHandler`, these methods are all optional. @@ -94,7 +94,7 @@ Once the port is bound, you must call `addListener()` to mark it as ready for in Once your `ChannelHandler` is prepared, call `addListener()`: ```js -port.addListener(handler).then(() => console.log('listener is active')) +port.addListener(handler).then(() => console.log('listener is active')); ``` `onAccept()` is the most important method. It is called with a `remote` endpoint, which tells you the address of the `Port` at the other end, where someone else called `connect()`. You can use this to decide if you want to accept the connection, or what sort of authority to exercise in response to messages arriving therein. @@ -108,7 +108,7 @@ The Networking API (at least for IBC) provides a "record pipe", in which each pa Once you have a `Connection` object, you send data by calling its `send()` method: ```js -connection.send('data') +connection.send('data'); ``` `send()` returns a Promise for the ACK data sent by the other side of the connection, which is represented in the same way as inbound data for `onReceive()`. @@ -134,7 +134,7 @@ It is recommended to avoid ACK data where possible. When a given Connection has ceased to be useful, you should close it: ```js -connection.close() +connection.close(); ``` This initiates a shutdown. The `ConnectionHandler` on both sides will eventually see their `onClose()` methods be called, with a `reason`. It will allow them to distinguish an intentional `onClose()` (`reason` is `undefined`) from some error condition. @@ -144,7 +144,7 @@ This initiates a shutdown. The `ConnectionHandler` on both sides will eventually When you no longer wish to receive connections on a port, you can remove the listener: ```js -port.removeListener(handler).then(() => console.log('removed')) +port.removeListener(handler).then(() => console.log('removed')); ``` You must provide the handler you added, to enable the future ability to have multiple listeners on the same port. @@ -156,7 +156,7 @@ Note that if you want to listen on this port again, you can just call `port.addL Removing a listener doesn't release the port address to make it available for other `bind()` requests. You can call: ```js -port.revoke() +port.revoke(); ``` to completely deallocate the port, remove all listeners, close all pending connections, and release its address. diff --git a/main/reference/repl/timerServices.md b/main/reference/repl/timerServices.md index 4365b3612..3846220b5 100644 --- a/main/reference/repl/timerServices.md +++ b/main/reference/repl/timerServices.md @@ -13,7 +13,7 @@ The timer service lets you: For testing, use ```js -import buildManualTimer from '@agoric/zoe/tools/manualTimer.js' +import buildManualTimer from '@agoric/zoe/tools/manualTimer.js'; ``` See package [@agoric/time](https://agoric-sdk.pages.dev/modules/_agoric_time) for details. diff --git a/main/reference/vstorage-ref.md b/main/reference/vstorage-ref.md index 4218b4628..5e2030124 100644 --- a/main/reference/vstorage-ref.md +++ b/main/reference/vstorage-ref.md @@ -50,7 +50,7 @@ agoricNames contains several other NameHubs. See also [agoricNames](https://docs.agoric.com/guides/integration/name-services.html#agoricnames-agoricnamesadmin-well-known-names). ```js -;['brand', 'installation', 'instance', 'issuer', 'oracleBrand', 'vbankAsset'] +['brand', 'installation', 'instance', 'issuer', 'oracleBrand', 'vbankAsset']; ``` ## vstorage: well known contracts @@ -172,7 +172,7 @@ The data at this key are the entries of the NameHub. Here we show the object com ```js { -... +// ... 'ibc/42225F147137DDEB5FEF0F1D0A92F2AD57557AFA2C4D6F30B21E0D983001C002': { brand: Object @Alleged: stATOM brand#board00990 {}, denom: 'ibc/42225F147137DDEB5FEF0F1D0A92F2AD57557AFA2C4D6F30B21E0D983001C002', @@ -184,7 +184,7 @@ The data at this key are the entries of the NameHub. Here we show the object com issuerName: 'stATOM', proposedName: 'stATOM', }, -... +// ... 'ibc/BA313C4A19DFBF943586C0387E6B11286F9E416B4DD27574E6909CABE0E342FA': { brand: Object @Alleged: ATOM brand#board05557 {}, denom: 'ibc/BA313C4A19DFBF943586C0387E6B11286F9E416B4DD27574E6909CABE0E342FA', @@ -196,7 +196,7 @@ The data at this key are the entries of the NameHub. Here we show the object com issuerName: 'ATOM', proposedName: 'ATOM', }, -... +// ... ubld: { brand: Object @Alleged: BLD brand#board0566 {}, denom: 'ubld', @@ -228,7 +228,7 @@ The keys under `published.boardAux` are board IDs. Here we show a handful. ```js -;['board00282', 'board0074', 'board01744'] +['board00282', 'board0074', 'board01744']; ``` The data are auxiliary info about objects in the board; @@ -308,11 +308,11 @@ Here we show a handful. See also: [Smart Wallet VStorage Topics](/guides/getting-started/contract-rpc#smart-wallet-vstorage-topics) ```js -;[ +[ 'agoric1890064p6j3xhzzdf8daknd6kpvhw766ds8flgw', 'agoric1ee9hr0jyrxhy999y755mp862ljgycmwyp4pl7q', 'agoric1enwuyn2hzyyvt39x87tk9rhlkpqtyv9haj7mgs' -] +]; ``` The `.current` child has current wallet status. For example: diff --git a/main/reference/zoe-api/price-authority.md b/main/reference/zoe-api/price-authority.md index cf76201ac..cd2811aa6 100644 --- a/main/reference/zoe-api/price-authority.md +++ b/main/reference/zoe-api/price-authority.md @@ -22,7 +22,7 @@ given _brandIn_/_brandOut_ pair. const quoteIssuer = await E(PriceAuthority).getQuoteIssuer( collateralKit.brand, loanKit.brand -) +); ``` ## E(PriceAuthority).getTimerService(brandIn, brandOut) @@ -38,7 +38,7 @@ given _brandIn_/_brandOut_ pair. const myTimer = E(PriceAuthority).getTimerService( collateral.brand, loanKit.brand -) +); ``` ## E(PriceAuthority).makeQuoteNotifier(amountIn, brandOut) @@ -51,7 +51,7 @@ Be notified of the latest **PriceQuotes** for a given _amountIn_. The issuing rate may be very different between **PriceAuthorities**. ```js -const myNotifier = E(PriceAuthority).makeQuoteNotifier(quatloos100, usdBrand) +const myNotifier = E(PriceAuthority).makeQuoteNotifier(quatloos100, usdBrand); ``` ## E(PriceAuthority).quoteGiven(amountIn, brandOut) @@ -63,7 +63,7 @@ const myNotifier = E(PriceAuthority).makeQuoteNotifier(quatloos100, usdBrand) Gets a quote on-demand corresponding to _amountIn_. ```js -const quote = await E(PriceAuthority).quoteGiven(moola500, quatloosBrand) +const quote = await E(PriceAuthority).quoteGiven(moola500, quatloosBrand); ``` ## E(PriceAuthority).quoteWanted(brandIn, amountOut) @@ -75,7 +75,7 @@ const quote = await E(PriceAuthority).quoteGiven(moola500, quatloosBrand) Gets a quote on-demand corresponding to _amountOut_. ```js -const quote = await E(PriceAuthority).quoteWanted(quatloosBrand, moola500) +const quote = await E(PriceAuthority).quoteWanted(quatloosBrand, moola500); ``` ## E(PriceAuthority).quoteAtTime(deadline, amountIn, brandOut) @@ -93,7 +93,7 @@ const priceQuoteOnThisAtTime = E(PriceAuthority).quoteAtTime( 7n, quatloosAmount34, usdBrand -) +); ``` ## E(PriceAuthority).quoteWhenGT(amountIn, amountOutLimit) @@ -108,7 +108,7 @@ Resolves when a **PriceQuote** of _amountIn_ exceeds _amountOutLimit_. const quote = E(PriceAuthority).quoteWhenGT( AmountMath.make(brands.In, 29n), AmountMath.make(brands.Out, 974n) -) +); ``` ## E(PriceAuthority).quoteWhenGTE(amountIn, amountOutLimit) @@ -123,7 +123,7 @@ Resolves when a **PriceQuote** of _amountIn_ reaches or exceeds _amountOutLimit_ const quote = E(PriceAuthority).quoteWhenGTE( AmountMath.make(brands.In, 29n), AmountMath.make(brands.Out, 974n) -) +); ``` ## E(PriceAuthority).quoteWhenLT(amountIn, amountOutLimit) @@ -138,7 +138,7 @@ Resolves when a **PriceQuote** of _amountIn_ drops below _amountOutLimit_. const quote = E(PriceAuthority).quoteWhenLT( AmountMath.make(brands.In, 29n), AmountMath.make(brands.Out, 974n) -) +); ``` ## E(PriceAuthority).quoteWhenLTE(amountIn, amountOutLimit) @@ -153,7 +153,7 @@ Resolves when a **PriceQuote** of _amountIn_ reaches or drops below _amountOutLi const quote = E(PriceAuthority).quoteWhenLTE( AmountMath.make(brands.In, 29n), AmountMath.make(brands.Out, 974n) -) +); ``` ## E(PriceAuthority).mutableQuoteWhenGT(amountIn, amountOutLimit) @@ -168,7 +168,7 @@ Resolves when a **PriceQuote** of _amountIn_ exceeds _amountOutLimit_. const quote = E(PriceAuthority).mutableQuoteWhenGT( AmountMath.make(brands.In, 29n), AmountMath.make(brands.Out, 974n) -) +); ``` ## E(PriceAuthority).mutableQuoteWhenGTE(amountIn, amountOutLimit) @@ -184,7 +184,7 @@ _amountOutLimit_. const quote = E(PriceAuthority).mutableQuoteWhenGTE( AmountMath.make(brands.In, 29n), AmountMath.make(brands.Out, 974n) -) +); ``` ## E(PriceAuthority).mutableQuoteWhenLT(amountIn, amountOutLimit) @@ -200,7 +200,7 @@ _amountOutLimit_. const quote = E(PriceAuthority).mutableQuoteWhenLT( AmountMath.make(brands.In, 29n), AmountMath.make(brands.Out, 974n) -) +); ``` ## E(PriceAuthority).mutableQuoteWhenLTE(amountIn, amountOutLimit) @@ -216,7 +216,7 @@ _amountOutLimit_. const quote = E(PriceAuthority).mutableQuoteWhenLTE( AmountMath.make(brands.In, 29n), AmountMath.make(brands.Out, 974n) -) +); ``` ## MutableQuote @@ -243,7 +243,7 @@ A **PriceQuote** is an **Amount**-**Payment** pair, where the **Amount** is also balance of the **Payment**. ```js -const { quoteAmount, quotePayment } = priceQuote +const { quoteAmount, quotePayment } = priceQuote; ``` **PriceQuotes** are returned in two forms: diff --git a/main/reference/zoe-api/ratio-math.md b/main/reference/zoe-api/ratio-math.md index 792e5086b..da626357b 100644 --- a/main/reference/zoe-api/ratio-math.md +++ b/main/reference/zoe-api/ratio-math.md @@ -18,7 +18,7 @@ Throws messages for errors: - **Parameter must be a Ratio record, but ${ratio} has ${q(name)}** ```js -assertIsRatio(aRatio) +assertIsRatio(aRatio); ``` ## makeRatio(numerator, numeratorBrand, denominator?, denominatorBrand?) @@ -35,9 +35,9 @@ By default, the _denominator_ is 100n (i.e., the **Ratio** is a percent). ```js // Use default values to create a ratio of 50 / 100 Quatloos -const ratio = makeRatio(50n, quatloosBrand) +const ratio = makeRatio(50n, quatloosBrand); // Specify all values to create a ratio of 75 Quatloos / 4 Moolas (the current exchange rate) -const ratio = makeRatio(75n, quatloosBrand, 4n, moolasBrand) +const ratio = makeRatio(75n, quatloosBrand, 4n, moolasBrand); ``` ## makeRatioFromAmounts(numeratorAmount, denominatorAmount) @@ -51,9 +51,9 @@ of two **Amounts**. The _numeratorAmount_ is the **Ratio's** numerator and the _denominatorAmount_ is the **Ratio's** denominator. ```js -const fiftyCents = AmountMath.make(centsBrand, 50n) -const dollar = AmountMath.make(centsBrand, 100n) -const halfADollar = makeRatioFromAmounts(fiftyCents, dollar) +const fiftyCents = AmountMath.make(centsBrand, 50n); +const dollar = AmountMath.make(centsBrand, 100n); +const halfADollar = makeRatioFromAmounts(fiftyCents, dollar); ``` ## floorMultiplyBy(amount, ratio) @@ -87,10 +87,10 @@ Throws errors with messages: ratio.denominator.brand_)}\*: The amount and ratio's denominator must have the same brand. ```js -const exchangeRatio = makeRatio(3n, swissFrancBrand, 5n, dollarBrand) -const dollars47 = AmountMath.make(dollarBrand, 47n) +const exchangeRatio = makeRatio(3n, swissFrancBrand, 5n, dollarBrand); +const dollars47 = AmountMath.make(dollarBrand, 47n); // Returns an amount of 28 Swiss francs -const exchange = floorMultiplyBy(dollars47, exchangeRatio) +const exchange = floorMultiplyBy(dollars47, exchangeRatio); ``` ## ceilMultiplyBy(amount, ratio) @@ -124,10 +124,10 @@ Throws errors with messages: ratio.denominator.brand**: The amount and ratio's denominator must have the same brand. ```js -const exchangeRatio = makeRatio(3n, swissFrancBrand, 5n, dollarBrand) -const dollars47 = AmountMath.make(dollarBrand, 47n) +const exchangeRatio = makeRatio(3n, swissFrancBrand, 5n, dollarBrand); +const dollars47 = AmountMath.make(dollarBrand, 47n); // Returns an amount of 29 Swiss francs -const exchange = ceilMultiplyBy(dollars47, exchangeRatio) +const exchange = ceilMultiplyBy(dollars47, exchangeRatio); ``` ## multiplyBy(amount, ratio) @@ -160,10 +160,10 @@ Throws errors with messages: ratio.denominator.brand**: The amount and ratio's denominator must have the same brand. ```js -const exchangeRatio = makeRatio(3n, swissFrancBrand, 5n, dollarBrand) -const dollars47 = AmountMath.make(dollarBrand, 47n) +const exchangeRatio = makeRatio(3n, swissFrancBrand, 5n, dollarBrand); +const dollars47 = AmountMath.make(dollarBrand, 47n); // Returns an amount of 28 Swiss francs -const exchange = multiplyBy(dollars47, exchangeRatio) +const exchange = multiplyBy(dollars47, exchangeRatio); ``` ## floorDivideBy(amount, ratio) @@ -195,10 +195,10 @@ Throws errors with messages: amount and ratio's numerator must have the same brand. ```js -const exchangeRatio = makeRatio(3n, swissFrancBrand, 5n, dollarBrand) -const dollars47 = AmountMath.make(dollarBrand, 47n) +const exchangeRatio = makeRatio(3n, swissFrancBrand, 5n, dollarBrand); +const dollars47 = AmountMath.make(dollarBrand, 47n); // Returns an amount of 78 dollars -const exchange = floorDivideBy(dollars47, exchangeRatio) +const exchange = floorDivideBy(dollars47, exchangeRatio); ``` ## ceilDivideBy(amount, ratio) @@ -230,10 +230,10 @@ Throws errors with messages: amount and ratio's numerator must have the same brand. ```js -const exchangeRatio = makeRatio(3n, swissFrancBrand, 5n, dollarBrand) -const dollars47 = AmountMath.make(dollarBrand, 47n) +const exchangeRatio = makeRatio(3n, swissFrancBrand, 5n, dollarBrand); +const dollars47 = AmountMath.make(dollarBrand, 47n); // Returns an amount of 79 dollars -const exchange = ceilDivideBy(dollars47, exchangeRatio) +const exchange = ceilDivideBy(dollars47, exchangeRatio); ``` ## divideBy(amount, ratio) @@ -265,10 +265,10 @@ Throws errors with messages: amount and ratio's numerator must have the same brand. ```js -const exchangeRatio = makeRatio(3n, swissFrancBrand, 5n, dollarBrand) -const dollars47 = AmountMath.make(dollarBrand, 47n) +const exchangeRatio = makeRatio(3n, swissFrancBrand, 5n, dollarBrand); +const dollars47 = AmountMath.make(dollarBrand, 47n); // Returns an amount of 78 dollars -const exchange = divideBy(dollars47, exchangeRatio) +const exchange = divideBy(dollars47, exchangeRatio); ``` ## invertRatio(ratio) @@ -280,9 +280,9 @@ Returns a **Ratio** such that the _ratio_ argument's numerator is the returned v denominator and the _ratio_ argument's denominator is the returned value's numerator. ```js -const exchangeRatio = makeRatio(3n, swissFrancBrand, 5n, usDollarBrand) +const exchangeRatio = makeRatio(3n, swissFrancBrand, 5n, usDollarBrand); // Returns a ratio of 5 US dollars / 3 swiss Francs -const invertedRatio = invertRatio(exchangeRatio) +const invertedRatio = invertRatio(exchangeRatio); ``` ## addRatios(left, right) diff --git a/main/reference/zoe-api/user-seat.md b/main/reference/zoe-api/user-seat.md index 539bd53d5..527722fdb 100644 --- a/main/reference/zoe-api/user-seat.md +++ b/main/reference/zoe-api/user-seat.md @@ -42,7 +42,7 @@ get what they asked for or Zoe ensures they get back their deposit. Example: ```js -const { want, give, exit } = sellerSeat.getProposal() +const { want, give, exit } = sellerSeat.getProposal(); ``` ## E(UserSeat).getPayouts() diff --git a/main/reference/zoe-api/zcfseat.md b/main/reference/zoe-api/zcfseat.md index 9dcb9fbb1..da2e1a7a4 100644 --- a/main/reference/zoe-api/zcfseat.md +++ b/main/reference/zoe-api/zcfseat.md @@ -32,7 +32,7 @@ contract that they are entering when they make an offer. See - Example: ```js -const { want, give, exit } = sellerSeat.getProposal() +const { want, give, exit } = sellerSeat.getProposal(); ``` ## aZCFSeat.exit(completion) @@ -63,7 +63,7 @@ Any other still open seats or outstanding promises and the contract instance con Agoric recommends you exit a seat with an error as follows ```js -throw seat.fail(Error('you did it wrong')) +throw seat.fail(Error('you did it wrong')); ``` ## aZCFSeat.hasExited() @@ -173,14 +173,14 @@ of the allocation. For example, if we start with a new, empty, allocation: ```js // Make an empty seat. -const { zcfSeat: zcfSeat1 } = zcf.makeEmptySeatKit() +const { zcfSeat: zcfSeat1 } = zcf.makeEmptySeatKit(); // The allocation is currently empty, i.e. `{}` -const stagedAllocation = zcfSeat1.getStagedAllocation() -const empty = AmountMath.makeEmpty(brand, AssetKind.NAT) +const stagedAllocation = zcfSeat1.getStagedAllocation(); +const empty = AmountMath.makeEmpty(brand, AssetKind.NAT); // Try to incrementBy empty. This succeeds, and the keyword is added // with an empty amount. -zcfSeat1.incrementBy({ IST: empty }) -t.deepEqual(zcfSeat1.getStagedAllocation(), { IST: empty }) +zcfSeat1.incrementBy({ IST: empty }); +t.deepEqual(zcfSeat1.getStagedAllocation(), { IST: empty }); ``` While this incremented the allocation by an empty amount, any amount would have been added to the @@ -209,13 +209,13 @@ cases to look at; when the corresponding amount to subtract is empty and when it ```js // Make an empty seat. -const { zcfSeat: zcfSeat1 } = zcf.makeEmptySeatKit() +const { zcfSeat: zcfSeat1 } = zcf.makeEmptySeatKit(); // The allocation is currently {} -const stagedAllocation = zcfSeat1.getStagedAllocation() -const empty = AmountMath.makeEmpty(brand, AssetKind.NAT) +const stagedAllocation = zcfSeat1.getStagedAllocation(); +const empty = AmountMath.makeEmpty(brand, AssetKind.NAT); // decrementBy empty does not throw, and does not add a keyword -zcfSeat1.decrementBy({ IST: empty }) -t.deepEqual(zcfSeat1.getStagedAllocation(), {}) +zcfSeat1.decrementBy({ IST: empty }); +t.deepEqual(zcfSeat1.getStagedAllocation(), {}); ``` The result here is **not** to add the **Keyword** to the allocation. It wasn't there to begin with, and @@ -229,11 +229,11 @@ However, decrementing a non-empty amount from an empty allocation has a differen ```js // Make an empty seat. -const { zcfSeat: zcfSeat1 } = zcf.makeEmptySeatKit() +const { zcfSeat: zcfSeat1 } = zcf.makeEmptySeatKit(); // The allocation is currently {} -const stagedAllocation = zcfSeat1.getStagedAllocation() +const stagedAllocation = zcfSeat1.getStagedAllocation(); // decrementBy throws for a keyword that does not exist on the stagedAllocation and a non-empty amount -zcfSeat1.decrementBy({ IST: runFee }) +zcfSeat1.decrementBy({ IST: runFee }); ``` It throws an error because you cannot subtract something from nothing. So trying to decrement an empty diff --git a/main/reference/zoe-api/zoe-contract-facet.md b/main/reference/zoe-api/zoe-contract-facet.md index 6403c0fda..b04484588 100644 --- a/main/reference/zoe-api/zoe-contract-facet.md +++ b/main/reference/zoe-api/zoe-contract-facet.md @@ -67,9 +67,9 @@ The following demonstrates **zcf.makeZCFMint**: calls to the resulting **ZCFMint** are synchronous. ```js -const mySynchronousMint = await zcf.makeZCFMint('MyToken', AssetKind.COPY_SET) -const { brand, issuer } = mySynchronousMint.getIssuerRecord() -mySynchronousMint.mintGains({ myKeyword: amount }, seat) +const mySynchronousMint = await zcf.makeZCFMint('MyToken', AssetKind.COPY_SET); +const { brand, issuer } = mySynchronousMint.getIssuerRecord(); +mySynchronousMint.mintGains({ myKeyword: amount }, seat); ``` ## zcf.getInvitationIssuer() @@ -79,7 +79,7 @@ mySynchronousMint.mintGains({ myKeyword: amount }, seat) Returns the **InvitationIssuer** for the Zoe instance. ```js -const invitationIssuer = await zcf.getInvitationIssuer() +const invitationIssuer = await zcf.getInvitationIssuer(); ``` ## zcf.saveIssuer(issuer, keyword) @@ -101,7 +101,7 @@ associated with the **Issuer** value of the record: **IssuerRecord.brand** and **IssuerRecord.issuer**. ```js -await zcf.saveIssuer(secondaryIssuer, keyword) +await zcf.saveIssuer(secondaryIssuer, keyword); ``` @@ -148,7 +148,7 @@ Patterns are often constructed using the For example, when making a covered call, to express that the offering party can't cancel: ```js -import { M } from '@endo/patterns' +import { M } from '@endo/patterns'; const waivedExitProposalShape = M.splitRecord( // required properties @@ -157,13 +157,13 @@ const waivedExitProposalShape = M.splitRecord( { give: M.record(), want: M.record() }, // unknown properties M.record() -) +); const creatorInvitation = zcf.makeInvitation( makeCallOption, 'makeCallOption', undefined, waivedExitProposalShape -) +); ``` Full details are in the [@endo/patterns](https://endojs.github.io/endo/modules/_endo_patterns.html) package. Here's a handy reference: @@ -226,7 +226,7 @@ particular view or API of an object; there may be multiple such facets per object) a **ZCFSeat** and a **UserSeat**. ```js -const { zcfSeat: mySeat } = zcf.makeEmptySeatKit() +const { zcfSeat: mySeat } = zcf.makeEmptySeatKit(); ``` ## zcf.getInstance() @@ -257,7 +257,7 @@ Returns the **Issuer** of the _brand_ argument. Returns the **AssetKind** associated with the _brand_ argument. ```js -const quatloosAssetKind = zcf.getAssetKind(quatloosBrand) +const quatloosAssetKind = zcf.getAssetKind(quatloosBrand); ``` ## zcf.stopAcceptingOffers() @@ -289,7 +289,7 @@ other outstanding promises are closed with a generic 'vat terminated' message. ```js -zcf.shutdown() +zcf.shutdown(); ``` ## zcf.shutdownWithFailure(reason) @@ -309,7 +309,7 @@ other outstanding promises are closed with the relevant error message. ```js -zcf.shutdownWithFailure() +zcf.shutdownWithFailure(); ``` ## zcf.getTerms() @@ -338,7 +338,7 @@ to **zcf**, and **zcf** already knows what instance is running. So in contract c a user side, with access to Zoe Service, you use **E(zoe).getTerms()**. ```js -const { brands, issuers, maths, terms } = zcf.getTerms() +const { brands, issuers, maths, terms } = zcf.getTerms(); ``` ## zcf.getZoeService() @@ -350,8 +350,8 @@ the contract code as well. ```js // Making an offer to another contract instance in the contract. -const zoeService = zcf.getZoeService() -E(zoeService).offer(creatorInvitation, proposal, paymentKeywordRecord) +const zoeService = zcf.getZoeService(); +E(zoeService).offer(creatorInvitation, proposal, paymentKeywordRecord); ``` ## zcf.assertUniqueKeyword(keyword) @@ -364,7 +364,7 @@ and could be used as a new **Brand** to make an **Issuer**. Throws an appropriat a valid **Keyword**, or is not unique. ```js -zcf.assertUniqueKeyword(keyword) +zcf.assertUniqueKeyword(keyword); ``` ## zcf.setOfferFilter(strings) @@ -437,9 +437,9 @@ rights are unchanged. - **reallocating must be done over two or more seats** ```js -sellerSeat.incrementBy(buyerSeat.decrementBy({ Money: providedMoney })) -buyerSeat.incrementBy(sellerSeat.decrementBy({ Items: wantedItems })) -zcf.reallocate(buyerSeat, sellerSeat) +sellerSeat.incrementBy(buyerSeat.decrementBy({ Money: providedMoney })); +buyerSeat.incrementBy(sellerSeat.decrementBy({ Items: wantedItems })); +zcf.reallocate(buyerSeat, sellerSeat); ``` **Note**: This method has been deprecated. Use **[atomicRearrange()](./#atomicrearrange-transfers)** instead. diff --git a/main/reference/zoe-api/zoe-data-types.md b/main/reference/zoe-api/zoe-data-types.md index b81dbcf0f..ce11fc578 100644 --- a/main/reference/zoe-api/zoe-data-types.md +++ b/main/reference/zoe-api/zoe-data-types.md @@ -11,8 +11,8 @@ For example, if a seat expected to be paid 5 _Quatloos_ and 3 _Widgets_ after su ```js { - Quatloos: 5n - Widgets: 3n + Quatloos: 5n; + Widgets: 3n; } ``` @@ -81,10 +81,10 @@ Subtypes further constrain property values (for example, an Users submit their **payments** as **KeywordRecords**: ```js -const aFistfulOfQuatloos = AmountMath.make(quatloosBrand, 1000n) +const aFistfulOfQuatloos = AmountMath.make(quatloosBrand, 1000n); const paymentKeywordRecord = { Asset: quatloosPurse.withdraw(aFistfulOfQuatloos) -} +}; ``` ## ParsableNumber diff --git a/main/reference/zoe-api/zoe-helpers.md b/main/reference/zoe-api/zoe-helpers.md index e95ebd0b1..2d348fc0d 100644 --- a/main/reference/zoe-api/zoe-helpers.md +++ b/main/reference/zoe-api/zoe-helpers.md @@ -12,7 +12,7 @@ following imports the two ZoeHelper functions **[assertIssuerKeywords()](#assert import { assertIssuerKeywords, assertProposalShape -} from '@agoric/zoe/src/contractSupport/index.js' +} from '@agoric/zoe/src/contractSupport/index.js'; ``` ## atomicRearrange(zcf, transfers) @@ -108,10 +108,10 @@ The function throws an error if incorrect or extra **Keywords** are passed in, or if there are **Keywords** missing. The **Keyword** order is irrelevant. ```js -import { assertIssuerKeywords } from '@agoric/zoe/src/contractSupport/index.js' +import { assertIssuerKeywords } from '@agoric/zoe/src/contractSupport/index.js'; // Proposals for this contract instance use keywords 'Asset' and 'Price' -assertIssuerKeywords(zcf, harden(['Asset', 'Price'])) +assertIssuerKeywords(zcf, harden(['Asset', 'Price'])); ``` ## satisfies(zcf, seat, update) @@ -136,13 +136,13 @@ It then calls **satisfiedBy()** on both orders of the two **seats**. If both sat it does a swap on them. ```js -import { satisfies } from '@agoric/zoe/src/contractSupport/index.js' +import { satisfies } from '@agoric/zoe/src/contractSupport/index.js'; const satisfiedBy = (xSeat, ySeat) => - satisfies(zcf, xSeat, ySeat.getCurrentAllocation()) + satisfies(zcf, xSeat, ySeat.getCurrentAllocation()); if (satisfiedBy(offer, seat) && satisfiedBy(seat, offer)) { - swap(zcf, seat, offer) + swap(zcf, seat, offer); } ``` @@ -172,9 +172,9 @@ wants 3 Quatloos, **seat** A retains 2 Quatloos. If the swap fails, no assets transfer, and both _leftSeat_ and _rightSeat_ are exited. ```js -import { swap } from '@agoric/zoe/src/contractSupport.js' +import { swap } from '@agoric/zoe/src/contractSupport.js'; -swap(zcf, firstSeat, secondSeat) +swap(zcf, firstSeat, secondSeat); ``` ## swapExact(zcf, leftSeat, rightSeat) @@ -206,9 +206,9 @@ Once the contract has been completed, please check your payout**. If the swap fails, no assets transfer, and both _leftSeat_ and _rightSeat_ are exited. ```js -import { swapExact } from '@agoric/zoe/src/contractSupport/index.js' +import { swapExact } from '@agoric/zoe/src/contractSupport/index.js'; -const swapMsg = swapExact(zcf, zcfSeatA, zcfSeatB) +const swapMsg = swapExact(zcf, zcfSeatA, zcfSeatB); ``` ## fitProposalShape(seat, proposalShape) @@ -242,17 +242,17 @@ and **give** should be **null**; the **exit** clause should specify a rule with these expectations, that **proposal** is rejected (and refunded). ```js -import { assertProposalShape } from '@agoric/zoe/src/contractSupport/index.js' +import { assertProposalShape } from '@agoric/zoe/src/contractSupport/index.js'; const sellAssetForPrice = harden({ give: { Asset: null }, want: { Price: null } -}) +}); const sell = seat => { - assertProposalShape(seat, sellAssetForPrice) - buySeats = swapIfCanTradeAndUpdateBook(buySeats, sellSeats, seat) - return 'Trade Successful' -} + assertProposalShape(seat, sellAssetForPrice); + buySeats = swapIfCanTradeAndUpdateBook(buySeats, sellSeats, seat); + return 'Trade Successful'; +}; ``` ## assertNatAssetKind(zcf, brand) @@ -267,9 +267,9 @@ This means the corresponding **[Mint](/reference/ertp-api/mint)** creates fungib If **false** throws with message **brand must be AssetKind.NAT**. ```js -import { assertNatAssetKind } from '@agoric/zoe/src/contractSupport/index.js' +import { assertNatAssetKind } from '@agoric/zoe/src/contractSupport/index.js'; -assertNatAssetKind(zcf, quatloosBrand) +assertNatAssetKind(zcf, quatloosBrand); ``` ## depositToSeat(zcf, recipientSeat, amounts, payments) @@ -290,14 +290,14 @@ On success, returns the exported and settable **depositToSeatSuccessMsg** which defaults to **Deposit and reallocation successful.** ```js -import { depositToSeat } from '@agoric/zoe/src/contractSupport/index.js' +import { depositToSeat } from '@agoric/zoe/src/contractSupport/index.js'; await depositToSeat( zcf, zcfSeat, { Dep: quatloos(2n) }, { Dep: quatloosPayment } -) +); ``` ## withdrawFromSeat(zcf, seat, amounts) @@ -316,11 +316,11 @@ If the seat has exited, aborts with the message **The seat cannot have exited.** Unlike **depositToSeat()**, a **PaymentPKeywordRecord** is returned, not a success message. ```js -import { withdrawFromSeat } from '@agoric/zoe/src/contractSupport/index.js' +import { withdrawFromSeat } from '@agoric/zoe/src/contractSupport/index.js'; const paymentKeywordRecord = await withdrawFromSeat(zcf, zcfSeat, { With: quatloos(2n) -}) +}); ``` ## saveAllIssuers(zcf, issuerKeywordRecord) @@ -336,9 +336,9 @@ This does **not** error if any of the **[Keywords](./zoe-data-types#keyword)** a already present, it is ignored. ```js -import { saveAllIssuers } from '@agoric/zoe/src/contractSupport/index.js' +import { saveAllIssuers } from '@agoric/zoe/src/contractSupport/index.js'; -await saveAllIssuers(zcf, { G: gIssuer, D: dIssuer, P: pIssuer }) +await saveAllIssuers(zcf, { G: gIssuer, D: dIssuer, P: pIssuer }); ``` ## offerTo(zcf, invitation, keywordMapping, proposal, fromSeat, toSeat, offerArgs) @@ -377,7 +377,7 @@ from the contracts indicated by using "A" or "B" in the **Keyword** name. const keywordMapping = harden({ TokenA1: 'TokenB1', TokenA2: 'TokenB2' -}) +}); ``` _offerArgs_ is an object that can be used to pass @@ -407,7 +407,7 @@ const { userSeatPromise: AMMUserSeat, deposited } = zcf.offerTo( proposal, fromSeat, lenderSeat -) +); ``` ## prepareRecorderKitMakers(baggage, marshaller) diff --git a/main/reference/zoe-api/zoe.md b/main/reference/zoe-api/zoe.md index 8686fb0cc..fd2c8b255 100644 --- a/main/reference/zoe-api/zoe.md +++ b/main/reference/zoe-api/zoe.md @@ -36,12 +36,12 @@ const brandKeywordRecord = { FirstCurrency: quatloosBrand, SecondCurrency: moolaBrand // etc. -} +}; ``` ```js // Call example -const brandKeywordRecord = await E(Zoe).getBrands(instance) +const brandKeywordRecord = await E(Zoe).getBrands(instance); ``` ## E(Zoe).getIssuers(instance) @@ -59,12 +59,12 @@ and the values are **Issuers**. const issuerKeywordRecord = { FirstCurrency: quatloosIssuer, SecondCurrency: moolaIssuer -} +}; ``` ```js // Call example -const issuerKeywordRecord = await E(Zoe).getIssuers(instance) +const issuerKeywordRecord = await E(Zoe).getIssuers(instance); ``` ## E(Zoe).getTerms(instance) @@ -87,7 +87,7 @@ custom terms. The returned values look like: ``` ```js -const terms = await E(Zoe).getTerms(instance) +const terms = await E(Zoe).getTerms(instance); ``` ## E(Zoe).getPublicFacet(instance) @@ -103,7 +103,7 @@ Since a facet is defined just as any other object, the contract adds methods to any object. ```js -const ticketSalesPublicFacet = await E(Zoe).getPublicFacet(sellItemsInstance) +const ticketSalesPublicFacet = await E(Zoe).getPublicFacet(sellItemsInstance); ``` ## E(Zoe).getInvitationIssuer() @@ -113,13 +113,13 @@ const ticketSalesPublicFacet = await E(Zoe).getPublicFacet(sellItemsInstance) Returns a **Promise** for the **InvitationIssuer** for the Zoe instance. ```js -const invitationIssuer = await E(Zoe).getInvitationIssuer() +const invitationIssuer = await E(Zoe).getInvitationIssuer(); // Here a user, Bob, has received an untrusted invitation from Alice. // Bob uses the trusted **InvitationIssuer** from Zoe to // transform the untrusted invitation to a trusted one -const trustedInvitation = await invitationIssuer.claim(untrustedInvitation) +const trustedInvitation = await invitationIssuer.claim(untrustedInvitation); const { value: invitationValue } = - await E(invitationIssuer).getAmountOf(trustedInvitation) + await E(invitationIssuer).getAmountOf(trustedInvitation); ``` ## E(Zoe).getInvitationDetails(invitation) @@ -137,8 +137,8 @@ details about the **Invitation**: to match the invitation to the role it plays in the contract. ```js -const invitation = await invitationIssuer.claim(untrustedInvitation) -const invitationValue = await E(Zoe).getInvitationDetails(invitation) +const invitation = await invitationIssuer.claim(untrustedInvitation); +const invitationValue = await E(Zoe).getInvitationDetails(invitation); ``` ## E(Zoe).install(bundle) @@ -152,9 +152,9 @@ Returns a **Promise** for an **Installation** object. ```js // bundleSource takes source code files and // bundles them together in the format install expects. -import bundleSource from '@endto/bundle-source' -const bundle = await bundleSource(pathResolve(`./src/contract.js`)) -const installationP = await E(Zoe).install(bundle) +import bundleSource from '@endto/bundle-source'; +const bundle = await bundleSource(pathResolve(`./src/contract.js`)); +const installationP = await E(Zoe).install(bundle); ``` ## E(Zoe).getConfiguration() @@ -194,7 +194,7 @@ these methods: - **getPublicFacet()** ```js -const instance = await E(Zoe).getInstance(invitation) +const instance = await E(Zoe).getInstance(invitation); ``` ## E(Zoe).getProposalShapeForInvitation(invitation) @@ -213,7 +213,7 @@ See also [Proposal Shapes](./zoe-contract-facet#proposal-shapes). Returns a **Promise** for the contract **installation** the **Invitation**'s contract instance uses. ```js -const installation = await E(Zoe).getInstallation(invitation) +const installation = await E(Zoe).getInstallation(invitation); ``` ## E(Zoe).getInstallationForInstance(instance) @@ -228,7 +228,7 @@ the underlying code. This method can be used as part of a process to inspect the underlying code for a running contract **instance**. ```js -const installation = await E(Zoe).getInstallationForInstance(instance) +const installation = await E(Zoe).getInstallationForInstance(instance); ``` ## E(Zoe).startInstance(installation, issuerKeywordRecord?, terms?, privateArgs?) @@ -258,7 +258,7 @@ not be in the public terms. For example, to share minting authority among multiple contracts, pass in the following as **privateArgs**: ```js -const privateArgs = { externalMint: myExternalMint } +const privateArgs = { externalMint: myExternalMint }; ``` It returns a **Promise** for a **StartInstanceResult** object. The object consists of: @@ -297,11 +297,11 @@ represented as a **Payment**. const issuerKeywordRecord = { Asset: moolaIssuer, Price: quatlooIssuer -} -const terms = { numBids: 3 } +}; +const terms = { numBids: 3 }; const { creatorFacet, publicFacet, creatorInvitation } = await E( Zoe -).startInstance(installation, issuerKeywordRecord, terms) +).startInstance(installation, issuerKeywordRecord, terms); ``` @@ -333,7 +333,7 @@ const myProposal = harden({ give: { Asset: AmountMath.make(quatloosBrand, 4n) }, want: { Price: AmountMath.make(moolaBrand, 15n) }, exit: { onDemand: null } -}) +}); ``` **give** and **want** use **[Keywords](./zoe-data-types#keyword)** defined by the contract. @@ -360,7 +360,7 @@ containing the actual **payments** to be escrowed by Zoe. Every **Keyword** in **give** must have a corresponding **payment**. ```js -const paymentKeywordRecord = harden({ Asset: quatloosPayment }) +const paymentKeywordRecord = harden({ Asset: quatloosPayment }); ```