diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index e867d78a3bd..ffe7f2bfdea 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -9,7 +9,7 @@ body: attributes: value: | Thanks for taking the time to fill out this bug report. - Please check the existing issues, [Plutus Docs](https://plutus.readthedocs.io/en/latest/) and [Cardano Stack Exchange](https://cardano.stackexchange.com/) before raising. + Please check the existing issues, [Plutus Docs](https://intersectmbo.github.io/plutus/docs) and [Cardano Stack Exchange](https://cardano.stackexchange.com/) before raising. - type: textarea id: summary attributes: diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index e2def837ca2..34fce863a59 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -8,7 +8,7 @@ body: attributes: value: | Thanks for taking the time to fill out this feature request. - Please check the existing issues and [Plutus Docs](https://plutus.readthedocs.io/en/latest/) before raising. + Please check the existing issues and [Plutus Docs](https://intersectmbo.github.io/plutus/docs) before raising. - type: textarea id: description attributes: diff --git a/.github/workflows/combined-haddock.yml b/.github/workflows/combined-haddock.yml deleted file mode 100644 index 76aa23443c1..00000000000 --- a/.github/workflows/combined-haddock.yml +++ /dev/null @@ -1,33 +0,0 @@ -# This workflow builds a combined haddock and publishes it to: -# https://intersectmbo.github.io/plutus/haddock/master -# https://intersectmbo.github.io/plutus/haddock/release/X.X.X.X -name: "Combined Haddock" -on: - workflow_dispatch: - push: - branches: - - master - - release/** -jobs: - build-and-deploy-combined-haddock: - runs-on: [self-hosted, plutus-shared] - permissions: - contents: write - environment: - name: github-pages - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Build Haddock - run: | - nix develop --accept-flake-config --command bash ./scripts/combined-haddock.sh haddock all - - - name: Deploy Haddock - uses: JamesIves/github-pages-deploy-action@v4 - with: - # This folder is generated in the step above - folder: haddock - target-folder: haddock/${{ github.ref_name }} - # haddock is ~400MB and keeping the entire history is unnecessary. - single-commit: true diff --git a/.github/workflows/docusaurus-site.yml b/.github/workflows/docusaurus-site.yml new file mode 100644 index 00000000000..c4b254d38a1 --- /dev/null +++ b/.github/workflows/docusaurus-site.yml @@ -0,0 +1,31 @@ +# This workflow builds and publishes the Docusaurus site to: +# https://intersectmbo.github.io/plutus/docs + +name: "🦕 Docusaurus Site" + +on: + workflow_dispatch: + +jobs: + publish: + name: Publish + runs-on: [self-hosted, plutus-shared] + permissions: + contents: write + environment: + name: github-pages + steps: + - name: Checkout + uses: actions/checkout@main + + - name: Build Site + working-directory: doc/docusaurus + run: nix develop --command bash -c 'yarn && yarn build' + + - name: Deploy Site + uses: JamesIves/github-pages-deploy-action@v4.6.1 + with: + folder: doc/docusaurus/build + target-folder: docs + single-commit: true + diff --git a/.github/workflows/haddock-site.yml b/.github/workflows/haddock-site.yml new file mode 100644 index 00000000000..115e8c54dc5 --- /dev/null +++ b/.github/workflows/haddock-site.yml @@ -0,0 +1,59 @@ +# This workflow builds and publishes the Haddock site to: +# https://intersectmbo.github.io/plutus/haddock/$version +# And optionally to: +# https://intersectmbo.github.io/plutus/haddock/latest + +name: "📜 Haddock Site" + +on: + workflow_dispatch: + inputs: + version: + description: | + The release version tag. For example if $version == "1.29.0.0" then the + current contents of the branch tagged "1.29.0.0" will be deployed to: + https://intersectmbo.github.io/plutus/haddock/$version + required: true + type: string + + latest: + description: | + If true, then the $version branch will also be deployed to: + https://intersectmbo.github.io/plutus/haddock/latest. + You want to leave this to true unless you are deploying old versions. + type: boolean + required: true + default: true + +jobs: + publish: + name: Publish + runs-on: [self-hosted, plutus-shared] + permissions: + contents: write + environment: + name: github-pages + steps: + - name: Checkout + uses: actions/checkout@main + with: + ref: ${{ inputs.version }} + + - name: Build Site + run: | + nix develop --command ./scripts/combined-haddock.sh _haddock all + + - name: Deploy Site + uses: JamesIves/github-pages-deploy-action@v4.6.1 + with: + folder: _haddock + target-folder: haddock/${{ inputs.version }} + single-commit: true + + - name: Deploy Site (latest) + if: ${{ inputs.latest == true }} + uses: JamesIves/github-pages-deploy-action@v4.6.1 + with: + folder: _haddock + target-folder: haddock/latest + single-commit: true \ No newline at end of file diff --git a/.github/workflows/publish-docs.yml b/.github/workflows/publish-docs.yml deleted file mode 100644 index 69317178e50..00000000000 --- a/.github/workflows/publish-docs.yml +++ /dev/null @@ -1,42 +0,0 @@ -name: "Build and Deploy to Github Pages" -on: - workflow_dispatch: - push: - branches: - - master -jobs: - build-haddock-site: - runs-on: ubuntu-latest - permissions: - contents: write - environment: - name: github-pages - steps: - - uses: actions/checkout@v4 - - uses: nixbuild/nix-quick-install-action@v28 - with: - nix_conf: | - experimental-features = nix-command flakes - accept-flake-config = true - - name: Build Haddock Site - run: | - nix build .#combined-haddock - mkdir dist - cp -RL ./result/share/doc/* ./dist/ - - name: Build Docusaurus Site - working-directory: docusaurus - run: | - yarn - yarn build - - name: Copy Docusaurus Site to Dist - run: | - mkdir dist/docs - cp -RL docusaurus/build/* ./dist/docs/ - - uses: JamesIves/github-pages-deploy-action@v4 - with: - folder: dist - target-folder: ${{ github.ref_name }} - # Publish Docusaurus and Haddock static builds to the same branch - # We publish our haddock, which is non-trivially big. - # So keeping the whole history is expensive, and anyway we don't need it. - single-commit: true diff --git a/.readthedocs.yml b/.readthedocs.yml deleted file mode 100644 index 76203eac134..00000000000 --- a/.readthedocs.yml +++ /dev/null @@ -1,14 +0,0 @@ -version: 2 - -sphinx: - configuration: doc/read-the-docs-site/conf.py - -build: - os: "ubuntu-22.04" - tools: - # This means "latest version 3", which seems fine - python: "3" - -python: - install: - - requirements: doc/read-the-docs-site/requirements.txt diff --git a/CONTRIBUTING.adoc b/CONTRIBUTING.adoc index 8811bb966f6..1d4e69a666e 100644 --- a/CONTRIBUTING.adoc +++ b/CONTRIBUTING.adoc @@ -415,7 +415,7 @@ The amount of time it's worth spending doing this is probably much more than you PRs should target `master` unless there is a very good reason not to. The only PRs to release branches should be backport PRs which should consist only of cherry-picks of commits from master (and any fixups that are needed). -For more details, see link:./doc/read-the-docs-site/RELEASE{outfilesuffix}[Plutus Release Process]. +For more details, see link:./RELEASE{outfilesuffix}[Plutus Release Process]. ==== What changes to include, and pull request sizes @@ -605,12 +605,10 @@ If your PR contains a dozen drive-by refactorings, it's unlikely to be merged as === Continuous integration -We have a few sources of CI checks at the moment: +We have two sources of CI checks at the moment: - Hydra -- ReadTheDocs - Github Actions -- Buildkite The CI will report statuses on your PRs with links to the logs in case of failure. Pull requests cannot be merged without at least the Hydra CI check being green. @@ -632,16 +630,11 @@ These will be automatically retried, but if you're in a hurry Michael has permis Nondeterministic failures are very annoying. Michael also has permissions to restart failed builds. -==== ReadTheDocs +==== Docusaurus -The documentation site is built on ReadTheDocs. -It will build a preview for each PR which is linked from the PR status. -It's useful to take a look if you're changing any of the documentation. +The documentation site is built with Docusaurus. -Enter the development shell using `nix develop`. -If you get a segfault, run `GC_DONT_GC=1 nix develop` instead. - -Then you can run `serve-docs` to host a local instance at http://0.0.0.0:8002 (Haddock is at http://0.0.0.0:8002/haddock). +Refer to the [README.md](doc/docusaurus/README.md) for more information. ==== Github Actions diff --git a/README.adoc b/README.adoc index d693fa9523e..cd7f1bbcec3 100644 --- a/README.adoc +++ b/README.adoc @@ -42,9 +42,11 @@ After setting it up you should just be able to depend on the `plutus` packages a === User documentation -The main documentation is located https://intersectmbo.github.io/plutus/master/docs/[here]. +The main documentation is located https://intersectmbo.github.io/plutus/docs/[here]. -The latest documentation for the metatheory can be found https://ci.iog.io/job/input-output-hk-plutus/master/x86_64-linux.packages.plutus-metatheory-site/latest/download/1[here]. +The haddock documentation is located https://intersectmbo.github.io/plutus/haddock/[here]. + +The documentation for the metatheory can be found https://intersectmbo.github.io/plutus/metatheory/[here]. === Talks diff --git a/cabal.project b/cabal.project index fbdc55dea12..c18b2e88175 100644 --- a/cabal.project +++ b/cabal.project @@ -18,8 +18,7 @@ index-state: -- Bump this if you need newer packages from CHaP , cardano-haskell-packages 2024-01-16T11:00:00Z -packages: doc/read-the-docs-site - plutus-benchmark +packages: plutus-benchmark plutus-conformance plutus-core plutus-ledger-api diff --git a/docusaurus/.gitignore b/doc/docusaurus/.gitignore similarity index 100% rename from docusaurus/.gitignore rename to doc/docusaurus/.gitignore diff --git a/docusaurus/README.md b/doc/docusaurus/README.md similarity index 65% rename from docusaurus/README.md rename to doc/docusaurus/README.md index ba50651e8e0..a0bfb9ebdd6 100644 --- a/docusaurus/README.md +++ b/doc/docusaurus/README.md @@ -26,16 +26,6 @@ This command generates static content into the `build` directory and can be serv ### Deployment -Using SSH: +Go to the [docusaurus-site.yml](https://github.com/IntersectMBO/plutus/actions/workflows/docusaurus-site.yml) workflow and click `Run workflow` on the right. -``` -$ USE_SSH=true yarn deploy -``` - -Not using SSH: - -``` -$ GIT_USER= yarn deploy -``` - -If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch. +This will build and publish the website to the `gh-pages` branch at https://intersectmbo.github.io/plutus/docs. \ No newline at end of file diff --git a/docusaurus/babel.config.js b/doc/docusaurus/babel.config.js similarity index 100% rename from docusaurus/babel.config.js rename to doc/docusaurus/babel.config.js diff --git a/docusaurus/docs/adr/_category_.json b/doc/docusaurus/docs/adr/_category_.json similarity index 100% rename from docusaurus/docs/adr/_category_.json rename to doc/docusaurus/docs/adr/_category_.json diff --git a/docusaurus/docs/adr/adr-index.md b/doc/docusaurus/docs/adr/adr-index.md similarity index 100% rename from docusaurus/docs/adr/adr-index.md rename to doc/docusaurus/docs/adr/adr-index.md diff --git a/docusaurus/docs/adr/adr1.md b/doc/docusaurus/docs/adr/adr1.md similarity index 100% rename from docusaurus/docs/adr/adr1.md rename to doc/docusaurus/docs/adr/adr1.md diff --git a/docusaurus/docs/adr/adr2.md b/doc/docusaurus/docs/adr/adr2.md similarity index 100% rename from docusaurus/docs/adr/adr2.md rename to doc/docusaurus/docs/adr/adr2.md diff --git a/docusaurus/docs/adr/adr3.md b/doc/docusaurus/docs/adr/adr3.md similarity index 100% rename from docusaurus/docs/adr/adr3.md rename to doc/docusaurus/docs/adr/adr3.md diff --git a/docusaurus/docs/adr/adr4.md b/doc/docusaurus/docs/adr/adr4.md similarity index 100% rename from docusaurus/docs/adr/adr4.md rename to doc/docusaurus/docs/adr/adr4.md diff --git a/docusaurus/docs/essential-concepts/_category_.json b/doc/docusaurus/docs/essential-concepts/_category_.json similarity index 100% rename from docusaurus/docs/essential-concepts/_category_.json rename to doc/docusaurus/docs/essential-concepts/_category_.json diff --git a/docusaurus/docs/essential-concepts/language-versions.md b/doc/docusaurus/docs/essential-concepts/language-versions.md similarity index 100% rename from docusaurus/docs/essential-concepts/language-versions.md rename to doc/docusaurus/docs/essential-concepts/language-versions.md diff --git a/docusaurus/docs/essential-concepts/ledger.md b/doc/docusaurus/docs/essential-concepts/ledger.md similarity index 100% rename from docusaurus/docs/essential-concepts/ledger.md rename to doc/docusaurus/docs/essential-concepts/ledger.md diff --git a/docusaurus/docs/essential-concepts/plutus-foundation.md b/doc/docusaurus/docs/essential-concepts/plutus-foundation.md similarity index 100% rename from docusaurus/docs/essential-concepts/plutus-foundation.md rename to doc/docusaurus/docs/essential-concepts/plutus-foundation.md diff --git a/docusaurus/docs/essential-concepts/plutus-platform.mdx b/doc/docusaurus/docs/essential-concepts/plutus-platform.mdx similarity index 100% rename from docusaurus/docs/essential-concepts/plutus-platform.mdx rename to doc/docusaurus/docs/essential-concepts/plutus-platform.mdx diff --git a/docusaurus/docs/getting-started-plutus-tx.md b/doc/docusaurus/docs/getting-started-plutus-tx.md similarity index 91% rename from docusaurus/docs/getting-started-plutus-tx.md rename to doc/docusaurus/docs/getting-started-plutus-tx.md index 29ae63d3201..cc3ae56e72b 100644 --- a/docusaurus/docs/getting-started-plutus-tx.md +++ b/doc/docusaurus/docs/getting-started-plutus-tx.md @@ -28,4 +28,4 @@ Use `cardano-cli` to deploy your script. Use an off-chain framework, such as [cardano-transaction-lib](https://github.com/Plutonomicon/cardano-transaction-lib) and [lucid](https://github.com/spacebudz/lucid), to interact with your script. -All these are based on the [Cardano API](https://github.com/IntersectMBO/cardano-node/tree/master/cardano-api), a low-level API that provides the capability to do the off-chain work with a local running node. +All these are based on the [Cardano API](https://github.com/IntersectMBO/cardano-api), a low-level API that provides the capability to do the off-chain work with a local running node. diff --git a/docusaurus/docs/index.md b/doc/docusaurus/docs/index.md similarity index 100% rename from docusaurus/docs/index.md rename to doc/docusaurus/docs/index.md diff --git a/docusaurus/docs/reference/_category_.json b/doc/docusaurus/docs/reference/_category_.json similarity index 100% rename from docusaurus/docs/reference/_category_.json rename to doc/docusaurus/docs/reference/_category_.json diff --git a/docusaurus/docs/reference/common-weaknesses.md b/doc/docusaurus/docs/reference/common-weaknesses.md similarity index 100% rename from docusaurus/docs/reference/common-weaknesses.md rename to doc/docusaurus/docs/reference/common-weaknesses.md diff --git a/docusaurus/docs/reference/cost-model-parameters.md b/doc/docusaurus/docs/reference/cost-model-parameters.md similarity index 100% rename from docusaurus/docs/reference/cost-model-parameters.md rename to doc/docusaurus/docs/reference/cost-model-parameters.md diff --git a/docusaurus/docs/reference/examples.md b/doc/docusaurus/docs/reference/examples.md similarity index 100% rename from docusaurus/docs/reference/examples.md rename to doc/docusaurus/docs/reference/examples.md diff --git a/docusaurus/docs/reference/further-resources.md b/doc/docusaurus/docs/reference/further-resources.md similarity index 100% rename from docusaurus/docs/reference/further-resources.md rename to doc/docusaurus/docs/reference/further-resources.md diff --git a/docusaurus/docs/reference/glossary.md b/doc/docusaurus/docs/reference/glossary.md similarity index 100% rename from docusaurus/docs/reference/glossary.md rename to doc/docusaurus/docs/reference/glossary.md diff --git a/docusaurus/docs/reference/haddock-documentation.md b/doc/docusaurus/docs/reference/haddock-documentation.md similarity index 100% rename from docusaurus/docs/reference/haddock-documentation.md rename to doc/docusaurus/docs/reference/haddock-documentation.md diff --git a/docusaurus/docs/reference/plutus-language-changes.md b/doc/docusaurus/docs/reference/plutus-language-changes.md similarity index 100% rename from docusaurus/docs/reference/plutus-language-changes.md rename to doc/docusaurus/docs/reference/plutus-language-changes.md diff --git a/docusaurus/docs/reference/plutus-tx-compiler-options.md b/doc/docusaurus/docs/reference/plutus-tx-compiler-options.md similarity index 100% rename from docusaurus/docs/reference/plutus-tx-compiler-options.md rename to doc/docusaurus/docs/reference/plutus-tx-compiler-options.md diff --git a/docusaurus/docs/reference/script-optimization-techniques.md b/doc/docusaurus/docs/reference/script-optimization-techniques.md similarity index 100% rename from docusaurus/docs/reference/script-optimization-techniques.md rename to doc/docusaurus/docs/reference/script-optimization-techniques.md diff --git a/docusaurus/docs/reference/upgrade-vasil-plutus-script-addresses.md b/doc/docusaurus/docs/reference/upgrade-vasil-plutus-script-addresses.md similarity index 100% rename from docusaurus/docs/reference/upgrade-vasil-plutus-script-addresses.md rename to doc/docusaurus/docs/reference/upgrade-vasil-plutus-script-addresses.md diff --git a/docusaurus/docs/simple-example/_category_.json b/doc/docusaurus/docs/simple-example/_category_.json similarity index 100% rename from docusaurus/docs/simple-example/_category_.json rename to doc/docusaurus/docs/simple-example/_category_.json diff --git a/docusaurus/docs/simple-example/alternatives-to-plutus-tx.md b/doc/docusaurus/docs/simple-example/alternatives-to-plutus-tx.md similarity index 100% rename from docusaurus/docs/simple-example/alternatives-to-plutus-tx.md rename to doc/docusaurus/docs/simple-example/alternatives-to-plutus-tx.md diff --git a/docusaurus/docs/simple-example/auction-properties.md b/doc/docusaurus/docs/simple-example/auction-properties.md similarity index 100% rename from docusaurus/docs/simple-example/auction-properties.md rename to doc/docusaurus/docs/simple-example/auction-properties.md diff --git a/docusaurus/docs/simple-example/eutxo-model.md b/doc/docusaurus/docs/simple-example/eutxo-model.md similarity index 100% rename from docusaurus/docs/simple-example/eutxo-model.md rename to doc/docusaurus/docs/simple-example/eutxo-model.md diff --git a/docusaurus/docs/simple-example/further-reading.md b/doc/docusaurus/docs/simple-example/further-reading.md similarity index 100% rename from docusaurus/docs/simple-example/further-reading.md rename to doc/docusaurus/docs/simple-example/further-reading.md diff --git a/docusaurus/docs/simple-example/libraries.md b/doc/docusaurus/docs/simple-example/libraries.md similarity index 100% rename from docusaurus/docs/simple-example/libraries.md rename to doc/docusaurus/docs/simple-example/libraries.md diff --git a/docusaurus/docs/simple-example/life-cycle.md b/doc/docusaurus/docs/simple-example/life-cycle.md similarity index 100% rename from docusaurus/docs/simple-example/life-cycle.md rename to doc/docusaurus/docs/simple-example/life-cycle.md diff --git a/docusaurus/docs/simple-example/off-chain-code.md b/doc/docusaurus/docs/simple-example/off-chain-code.md similarity index 84% rename from docusaurus/docs/simple-example/off-chain-code.md rename to doc/docusaurus/docs/simple-example/off-chain-code.md index 779d66a0b89..e083f422e63 100644 --- a/docusaurus/docs/simple-example/off-chain-code.md +++ b/doc/docusaurus/docs/simple-example/off-chain-code.md @@ -8,10 +8,10 @@ Since the main purpose of this example is to introduce Plutus Tx and Plutus Core In addition to the on-chain code, one typically needs the accompanying off-chain code and services to perform tasks like building transactions, submitting transactions, deploying smart contracts, querying for available UTXOs on the chain, etc. - + A full suite of solutions is [in development](https://plutus-apps.readthedocs.io/en/latest/plutus/explanations/plutus-tools-component-descriptions.html). See the [plutus-apps](https://github.com/IntersectMBO/plutus-apps) repo and its accompanying [Plutus tools SDK user guide](https://plutus-apps.readthedocs.io/en/latest/) for more details. Some other alternatives include [cardano-transaction-lib](https://github.com/Plutonomicon/cardano-transaction-lib) and [lucid](https://github.com/spacebudz/lucid). -All these are based on the [Cardano API](https://github.com/IntersectMBO/cardano-node/tree/master/cardano-api), a low-level API that provides the capability to do the off-chain work with a local running node. +All these are based on the [Cardano API](https://github.com/IntersectMBO/cardano-api), a low-level API that provides the capability to do the off-chain work with a local running node. diff --git a/docusaurus/docs/simple-example/plutus-tx-code.md b/doc/docusaurus/docs/simple-example/plutus-tx-code.md similarity index 99% rename from docusaurus/docs/simple-example/plutus-tx-code.md rename to doc/docusaurus/docs/simple-example/plutus-tx-code.md index 1a975b09499..30a970ee07b 100644 --- a/docusaurus/docs/simple-example/plutus-tx-code.md +++ b/doc/docusaurus/docs/simple-example/plutus-tx-code.md @@ -7,7 +7,7 @@ sidebar_position: 20 Recall that Plutus Tx is a subset of Haskell. It is the source language one uses to write Plutus validators. A Plutus Tx program is compiled into Plutus Core, which is interpreted on-chain. -The full Plutus Tx code for the auction smart contract can be found at [AuctionValidator.hs](https://github.com/IntersectMBO/plutus/blob/master/doc/read-the-docs-site/tutorials/AuctionValidator.hs). +The full Plutus Tx code for the auction smart contract can be found at [AuctionValidator.hs](https://github.com/IntersectMBO/plutus-tx-template/blob/main/app/AuctionValidator.hs). diff --git a/docusaurus/docs/simple-example/simple-example.md b/doc/docusaurus/docs/simple-example/simple-example.md similarity index 100% rename from docusaurus/docs/simple-example/simple-example.md rename to doc/docusaurus/docs/simple-example/simple-example.md diff --git a/docusaurus/docs/troubleshooting.md b/doc/docusaurus/docs/troubleshooting.md similarity index 100% rename from docusaurus/docs/troubleshooting.md rename to doc/docusaurus/docs/troubleshooting.md diff --git a/docusaurus/docs/using-plutus-tx/_category_.json b/doc/docusaurus/docs/using-plutus-tx/_category_.json similarity index 100% rename from docusaurus/docs/using-plutus-tx/_category_.json rename to doc/docusaurus/docs/using-plutus-tx/_category_.json diff --git a/docusaurus/docs/using-plutus-tx/advanced-plutus-tx-concepts/_category_.json b/doc/docusaurus/docs/using-plutus-tx/advanced-plutus-tx-concepts/_category_.json similarity index 100% rename from docusaurus/docs/using-plutus-tx/advanced-plutus-tx-concepts/_category_.json rename to doc/docusaurus/docs/using-plutus-tx/advanced-plutus-tx-concepts/_category_.json diff --git a/docusaurus/docs/using-plutus-tx/advanced-plutus-tx-concepts/optimizing-scripts-with-asData.md b/doc/docusaurus/docs/using-plutus-tx/advanced-plutus-tx-concepts/optimizing-scripts-with-asData.md similarity index 100% rename from docusaurus/docs/using-plutus-tx/advanced-plutus-tx-concepts/optimizing-scripts-with-asData.md rename to doc/docusaurus/docs/using-plutus-tx/advanced-plutus-tx-concepts/optimizing-scripts-with-asData.md diff --git a/docusaurus/docs/using-plutus-tx/advanced-plutus-tx-concepts/triggering-a-validation-failure.md b/doc/docusaurus/docs/using-plutus-tx/advanced-plutus-tx-concepts/triggering-a-validation-failure.md similarity index 100% rename from docusaurus/docs/using-plutus-tx/advanced-plutus-tx-concepts/triggering-a-validation-failure.md rename to doc/docusaurus/docs/using-plutus-tx/advanced-plutus-tx-concepts/triggering-a-validation-failure.md diff --git a/docusaurus/docs/using-plutus-tx/compiling-plutus-tx.md b/doc/docusaurus/docs/using-plutus-tx/compiling-plutus-tx.md similarity index 100% rename from docusaurus/docs/using-plutus-tx/compiling-plutus-tx.md rename to doc/docusaurus/docs/using-plutus-tx/compiling-plutus-tx.md diff --git a/docusaurus/docs/using-plutus-tx/overview-plutus-tx.md b/doc/docusaurus/docs/using-plutus-tx/overview-plutus-tx.md similarity index 100% rename from docusaurus/docs/using-plutus-tx/overview-plutus-tx.md rename to doc/docusaurus/docs/using-plutus-tx/overview-plutus-tx.md diff --git a/docusaurus/docs/using-plutus-tx/producing-a-blueprint.md b/doc/docusaurus/docs/using-plutus-tx/producing-a-blueprint.md similarity index 100% rename from docusaurus/docs/using-plutus-tx/producing-a-blueprint.md rename to doc/docusaurus/docs/using-plutus-tx/producing-a-blueprint.md diff --git a/docusaurus/docs/using-plutus-tx/writing-plutus-tx-programs.md b/doc/docusaurus/docs/using-plutus-tx/writing-plutus-tx-programs.md similarity index 100% rename from docusaurus/docs/using-plutus-tx/writing-plutus-tx-programs.md rename to doc/docusaurus/docs/using-plutus-tx/writing-plutus-tx-programs.md diff --git a/docusaurus/docs/working-with-scripts/_category_.json b/doc/docusaurus/docs/working-with-scripts/_category_.json similarity index 100% rename from docusaurus/docs/working-with-scripts/_category_.json rename to doc/docusaurus/docs/working-with-scripts/_category_.json diff --git a/docusaurus/docs/working-with-scripts/exporting-scripts-datums-redeemers.md b/doc/docusaurus/docs/working-with-scripts/exporting-scripts-datums-redeemers.md similarity index 100% rename from docusaurus/docs/working-with-scripts/exporting-scripts-datums-redeemers.md rename to doc/docusaurus/docs/working-with-scripts/exporting-scripts-datums-redeemers.md diff --git a/docusaurus/docs/working-with-scripts/profiling-budget-usage.md b/doc/docusaurus/docs/working-with-scripts/profiling-budget-usage.md similarity index 100% rename from docusaurus/docs/working-with-scripts/profiling-budget-usage.md rename to doc/docusaurus/docs/working-with-scripts/profiling-budget-usage.md diff --git a/docusaurus/docs/working-with-scripts/writing-basic-minting-policies.md b/doc/docusaurus/docs/working-with-scripts/writing-basic-minting-policies.md similarity index 100% rename from docusaurus/docs/working-with-scripts/writing-basic-minting-policies.md rename to doc/docusaurus/docs/working-with-scripts/writing-basic-minting-policies.md diff --git a/docusaurus/docs/working-with-scripts/writing-basic-validator-scripts.md b/doc/docusaurus/docs/working-with-scripts/writing-basic-validator-scripts.md similarity index 100% rename from docusaurus/docs/working-with-scripts/writing-basic-validator-scripts.md rename to doc/docusaurus/docs/working-with-scripts/writing-basic-validator-scripts.md diff --git a/docusaurus/docusaurus.config.ts b/doc/docusaurus/docusaurus.config.ts similarity index 97% rename from docusaurus/docusaurus.config.ts rename to doc/docusaurus/docusaurus.config.ts index 3bdfc27ebff..92812868b3c 100644 --- a/docusaurus/docusaurus.config.ts +++ b/doc/docusaurus/docusaurus.config.ts @@ -8,10 +8,10 @@ const config: Config = { favicon: "img/favicon.ico", // Set the production url of your site here - url: "https://plutus.readthedocs.io", + url: "https://intersectmbo.github.io", // Set the // pathname under which your site is served // For GitHub pages deployment, it is often '//' - baseUrl: "/plutus/master/docs/", + baseUrl: "/plutus/docs/", // GitHub pages deployment config. // If you aren't using GitHub pages, you don't need these. diff --git a/docusaurus/package.json b/doc/docusaurus/package.json similarity index 100% rename from docusaurus/package.json rename to doc/docusaurus/package.json diff --git a/docusaurus/sidebars.ts b/doc/docusaurus/sidebars.ts similarity index 100% rename from docusaurus/sidebars.ts rename to doc/docusaurus/sidebars.ts diff --git a/docusaurus/src/components/CsvTable.tsx b/doc/docusaurus/src/components/CsvTable.tsx similarity index 100% rename from docusaurus/src/components/CsvTable.tsx rename to doc/docusaurus/src/components/CsvTable.tsx diff --git a/docusaurus/src/components/LiteralInclude.tsx b/doc/docusaurus/src/components/LiteralInclude.tsx similarity index 100% rename from docusaurus/src/components/LiteralInclude.tsx rename to doc/docusaurus/src/components/LiteralInclude.tsx diff --git a/docusaurus/src/css/custom.css b/doc/docusaurus/src/css/custom.css similarity index 100% rename from docusaurus/src/css/custom.css rename to doc/docusaurus/src/css/custom.css diff --git a/docusaurus/src/theme/Footer/index.js b/doc/docusaurus/src/theme/Footer/index.js similarity index 100% rename from docusaurus/src/theme/Footer/index.js rename to doc/docusaurus/src/theme/Footer/index.js diff --git a/docusaurus/src/theme/MDXComponents.ts b/doc/docusaurus/src/theme/MDXComponents.ts similarity index 100% rename from docusaurus/src/theme/MDXComponents.ts rename to doc/docusaurus/src/theme/MDXComponents.ts diff --git a/docusaurus/static/.nojekyll b/doc/docusaurus/static/.nojekyll similarity index 100% rename from docusaurus/static/.nojekyll rename to doc/docusaurus/static/.nojekyll diff --git a/docusaurus/static/code/AuctionValidator.hs b/doc/docusaurus/static/code/AuctionValidator.hs similarity index 100% rename from docusaurus/static/code/AuctionValidator.hs rename to doc/docusaurus/static/code/AuctionValidator.hs diff --git a/doc/read-the-docs-site/tutorials/BasicPlutusTx.hs b/doc/docusaurus/static/code/BasicPlutusTx.hs similarity index 100% rename from doc/read-the-docs-site/tutorials/BasicPlutusTx.hs rename to doc/docusaurus/static/code/BasicPlutusTx.hs diff --git a/docusaurus/static/code/BasicPolicies.hs b/doc/docusaurus/static/code/BasicPolicies.hs similarity index 100% rename from docusaurus/static/code/BasicPolicies.hs rename to doc/docusaurus/static/code/BasicPolicies.hs diff --git a/docusaurus/static/code/BasicValidators.hs b/doc/docusaurus/static/code/BasicValidators.hs similarity index 100% rename from docusaurus/static/code/BasicValidators.hs rename to doc/docusaurus/static/code/BasicValidators.hs diff --git a/docusaurus/static/code/Cip57Blueprint.hs b/doc/docusaurus/static/code/Cip57Blueprint.hs similarity index 100% rename from docusaurus/static/code/Cip57Blueprint.hs rename to doc/docusaurus/static/code/Cip57Blueprint.hs diff --git a/doc/read-the-docs-site/tutorials/QuickStart.hs b/doc/docusaurus/static/code/QuickStart.hs similarity index 100% rename from doc/read-the-docs-site/tutorials/QuickStart.hs rename to doc/docusaurus/static/code/QuickStart.hs diff --git a/doc/read-the-docs-site/howtos/plutus.json b/doc/docusaurus/static/code/plutus.json similarity index 100% rename from doc/read-the-docs-site/howtos/plutus.json rename to doc/docusaurus/static/code/plutus.json diff --git a/doc/read-the-docs-site/reference/cardano/builtin-parameters.csv b/doc/docusaurus/static/csv/builtin-parameters.csv similarity index 100% rename from doc/read-the-docs-site/reference/cardano/builtin-parameters.csv rename to doc/docusaurus/static/csv/builtin-parameters.csv diff --git a/doc/read-the-docs-site/reference/cardano/machine-parameters.csv b/doc/docusaurus/static/csv/machine-parameters.csv similarity index 100% rename from doc/read-the-docs-site/reference/cardano/machine-parameters.csv rename to doc/docusaurus/static/csv/machine-parameters.csv diff --git a/doc/read-the-docs-site/closing-tx-simple-auction-v3.png b/doc/docusaurus/static/img/closing-tx-simple-auction-v3.png similarity index 100% rename from doc/read-the-docs-site/closing-tx-simple-auction-v3.png rename to doc/docusaurus/static/img/closing-tx-simple-auction-v3.png diff --git a/docusaurus/static/img/docusaurus-social-card.png b/doc/docusaurus/static/img/docusaurus-social-card.png similarity index 100% rename from docusaurus/static/img/docusaurus-social-card.png rename to doc/docusaurus/static/img/docusaurus-social-card.png diff --git a/doc/read-the-docs-site/reference/writing-scripts/common-weaknesses/double-satisfaction.png b/doc/docusaurus/static/img/double-satisfaction.png similarity index 100% rename from doc/read-the-docs-site/reference/writing-scripts/common-weaknesses/double-satisfaction.png rename to doc/docusaurus/static/img/double-satisfaction.png diff --git a/docusaurus/static/img/favicon.ico b/doc/docusaurus/static/img/favicon.ico similarity index 100% rename from docusaurus/static/img/favicon.ico rename to doc/docusaurus/static/img/favicon.ico diff --git a/doc/read-the-docs-site/first-bid-simple-auction-v3.png b/doc/docusaurus/static/img/first-bid-simple-auction-v3.png similarity index 100% rename from doc/read-the-docs-site/first-bid-simple-auction-v3.png rename to doc/docusaurus/static/img/first-bid-simple-auction-v3.png diff --git a/docusaurus/static/img/github.svg b/doc/docusaurus/static/img/github.svg similarity index 100% rename from docusaurus/static/img/github.svg rename to doc/docusaurus/static/img/github.svg diff --git a/docusaurus/static/img/logo-footer.svg b/doc/docusaurus/static/img/logo-footer.svg similarity index 100% rename from docusaurus/static/img/logo-footer.svg rename to doc/docusaurus/static/img/logo-footer.svg diff --git a/docusaurus/static/img/logo.svg b/doc/docusaurus/static/img/logo.svg similarity index 100% rename from docusaurus/static/img/logo.svg rename to doc/docusaurus/static/img/logo.svg diff --git a/doc/read-the-docs-site/explanations/platform-architecture.png b/doc/docusaurus/static/img/platform-architecture.png similarity index 100% rename from doc/read-the-docs-site/explanations/platform-architecture.png rename to doc/docusaurus/static/img/platform-architecture.png diff --git a/doc/read-the-docs-site/second-bid-simple-auction-v3.png b/doc/docusaurus/static/img/second-bid-simple-auction-v3.png similarity index 100% rename from doc/read-the-docs-site/second-bid-simple-auction-v3.png rename to doc/docusaurus/static/img/second-bid-simple-auction-v3.png diff --git a/docusaurus/tsconfig.json b/doc/docusaurus/tsconfig.json similarity index 100% rename from docusaurus/tsconfig.json rename to doc/docusaurus/tsconfig.json diff --git a/docusaurus/yarn.lock b/doc/docusaurus/yarn.lock similarity index 100% rename from docusaurus/yarn.lock rename to doc/docusaurus/yarn.lock diff --git a/doc/read-the-docs-site/.gitignore b/doc/read-the-docs-site/.gitignore deleted file mode 100644 index e35d8850c96..00000000000 --- a/doc/read-the-docs-site/.gitignore +++ /dev/null @@ -1 +0,0 @@ -_build diff --git a/doc/read-the-docs-site/LICENSE b/doc/read-the-docs-site/LICENSE deleted file mode 100644 index 0c8a80022ea..00000000000 --- a/doc/read-the-docs-site/LICENSE +++ /dev/null @@ -1,53 +0,0 @@ -Apache License - -Version 2.0, January 2004 - -http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - -"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. - -"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. - -"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. - -"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. - -"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. - -"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. - -"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). - -"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. - -"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." - -"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: - -You must give any other recipients of the Work or Derivative Works a copy of this License; and -You must cause any modified files to carry prominent notices stating that You changed the files; and -You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and -If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. - -You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. -5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS diff --git a/doc/read-the-docs-site/NOTICE b/doc/read-the-docs-site/NOTICE deleted file mode 100644 index 7bfbc260968..00000000000 --- a/doc/read-the-docs-site/NOTICE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2023 Input Output Global, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/doc/read-the-docs-site/README.md b/doc/read-the-docs-site/README.md index 874d8749230..7d537985e9b 100644 --- a/doc/read-the-docs-site/README.md +++ b/doc/read-the-docs-site/README.md @@ -1,18 +1,16 @@ -# Plutus documentation site +# Read The Docs Site -This is a sphinx site. +As of 20-06-2024, the plutus `readthedocs` site, previously hosted at: +``` +https://plutus.readthedocs.io +``` +Is now permanently redirecting to: +``` +https://intersectmbo.github.io/plutus/docs +``` +Using the [Exact Redirect](https://readthedocs.org/dashboard/plutus/redirects/): +``` +/* -> https://intersectmbo.github.io/plutus/docs +``` +And the [GitHub Webhook](https://readthedocs.org/dashboard/plutus/webhooks/) has been deleted. -Run `nix develop` to enter a development shell with `sphinx-build` and `sphinx-autobuild`. - -The following commands are also available: - -- `develop-rtd-site` - Start a development server with live reload on `http://localhost:8000` -- `build-rtd-site` - Build the docs locally in `_build/index.html` -- `serve-rtd-site` - Build the full site with nix (including Haddock) and serve it on `http://localhost:8002` - -The doc site from main is built automatically and hosted [here](https://plutus.readthedocs.io/en/latest). - -Additionally, the site is built for all PRs, and a link to a preview can be found in the PR statuses. diff --git a/doc/read-the-docs-site/_static/.gitkeep b/doc/read-the-docs-site/_static/.gitkeep deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/doc/read-the-docs-site/_static/theme_overrides.css b/doc/read-the-docs-site/_static/theme_overrides.css deleted file mode 100644 index 44a0fd7699b..00000000000 --- a/doc/read-the-docs-site/_static/theme_overrides.css +++ /dev/null @@ -1,6 +0,0 @@ -/* Fix table wrapping https://github.com/readthedocs/sphinx_rtd_theme/issues/117 */ -@media screen and (min-width: 768px) { - .wy-table-responsive table td, .wy-table-responsive table th { - white-space: normal !important; - } -} diff --git a/doc/read-the-docs-site/_templates/.gitkeep b/doc/read-the-docs-site/_templates/.gitkeep deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/doc/read-the-docs-site/adr/0001-record-architecture-decisions.rst b/doc/read-the-docs-site/adr/0001-record-architecture-decisions.rst deleted file mode 100644 index 69290383797..00000000000 --- a/doc/read-the-docs-site/adr/0001-record-architecture-decisions.rst +++ /dev/null @@ -1,167 +0,0 @@ -ADR 1: Record architectural decisions -======================================= - -Date: 2022-06-08 - -Authors ---------- - -koslambrou - -Status ------- - -Accepted - -Context -------- - -We are in search for a means to document our architectural and design decisions -for all of our components. -In order to do that, there is practice called architectural decision records ("ADR"), -that we can integrate into our workflow. - -This does not replace actual architecture documentation, but provides people who are contributing: - -* the means to understand architectural and design decisions that were made -* a framework for proposing changes to the current architecture - -For each decision, it is important to consider the following factors: - -* what we have decided to do -* why we have made this decision -* what we expect the impact of this decision to be -* what we have learned in the process - -As we're already using `rST `_, -`Sphinxdoc `_ and -`readthedocs `_, it would be practical to -integrate these ADRs as part of our current documentation infrastructure. - -Decision --------- - -* We will use ADRs to document, propose and discuss - any important or significant architectural and design decisions. - -* The ADR format will follow the format described in `Implications`_ section. - -* We will follow the convention of storing those ADRs as rST or Markdown formatted - documents stored under the `docs/adr` directory, as exemplified in Nat Pryce's - `adr-tools `_. This does not imply that we will - be using `adr-tools` itself, as we might diverge from the proposed structure. - -* We will keep rejected ADRs - -* We will strive, if possible, to create an ADR as early as possible in relation to the actual - implementation. - -Implications ------------- - -ADRs should be written using the template described in the `ADR template`_ which comes from -Chapter 6.5.2 (*A Template for Documenting Architectural Decisions*) of -*Documenting Software Architectures: Views and Beyond (2nd Edition)*. - -However, the mandatory sections are *Title*, *Status*, *Issue/Context*, *Decision*, *Implications/Consequences*. -The rest are optional. - -Another good reference is the article -`Architecture Decision Records `_ -by Michael Nygard (Nov. 15, 2011). - -ADR template -^^^^^^^^^^^^ - -What follows is the ADR format (adapted from the book). - -+----------------------+---------------------------------------------------------------------------+ -| Section | Description | -+======================+===========================================================================+ -| Title | These documents have names that are short noun phrases. | -| | | -| | For example, "ADR 1: Deployment on Ruby on Rails 3.0.10" | -| | or "ADR 9: LDAP for Multitenant Integration" | -+----------------------+---------------------------------------------------------------------------+ -| Authors | List each author's name and email. | -+----------------------+---------------------------------------------------------------------------+ -| Status | State the status of the decision, such as "draft" if the decision is | -| | still being written, as "proposed" if the project stakeholders haven't | -| | agreed with it yet, "accepted" once it is agreed. If a later ADR changes | -| | or reverses a decision, it may be marked as "deprecated" or "superseded" | -| | with a reference to its replacement. (This is not the status of | -| | implementing the decision.) | -+----------------------+---------------------------------------------------------------------------+ -| Issue (or context) | This section describes the architectural design issue being addressed. | -| | This description should leave no questions as to why this issue needs to | -| | be addressed now. The language in this section is value-neutral. It is | -| | simply describing facts. | -+----------------------+---------------------------------------------------------------------------+ -| Decision | Clearly state the solution chosen. It is the selection of one of the | -| | positions that the architect could have taken. It is stated in full | -| | sentences, with active voice. "We will …" | -+----------------------+---------------------------------------------------------------------------+ -| Tags | Add one or more tags to the decision. Useful for organizing the set of | -| | decision. | -+----------------------+---------------------------------------------------------------------------+ -| Assumptions | Clearly describe the underlying assumptions in the environment in which a | -| | decision is being made. These could be cost, schedule, technology, and so | -| | on. Note that constraints in the environment (such as a list of accepted | -| | technology standards, an enterprise architecture, or commonly employed | -| | patterns) may limit the set of alternatives considered. | -+----------------------+---------------------------------------------------------------------------+ -| Argument | Outline why a position was selected. This is probably as important as the | -| | decision itself. The argument for a decision can include items such as | -| | implementation cost, total cost of ownership, time to market, and | -| | availability of required development resources. | -+----------------------+---------------------------------------------------------------------------+ -| Alternatives | List alternatives (that is, options or positions) considered. | -| | | -| | Explain alternatives with sufficient detail to judge their suitability; | -| | refer to external documentation to do so if necessary. Only viable | -| | positions should be described here. While you don’t need an exhaustive | -| | list, you also don’t want to hear the question “Did you think about... ?” | -| | during a final review, which might lead to a loss of credibility and a | -| | questioning of other architectural decisions. Listing alternatives | -| | espoused by others also helps them know that their opinions were heard. | -| | Finally, listing alternatives helps the architect make the right | -| | decision, because listing alternatives cannot be done unless those | -| | alternatives were given due consideration. | -+----------------------+---------------------------------------------------------------------------+ -| Implications | Describe the decision’s implications. For example, it may | -| (or consequences) | | -| | * Introduce a need to make other decisions | -| | * Create new requirements | -| | * Modify existing requirements | -| | * Pose additional constraints to the environment | -| | * Require renegotiation of scope | -| | * Require renegotiation of the schedule with the customers | -| | * Require additional training for the staff | -| | | -| | Clearly understanding and stating the implications of the decisions has | -| | been a very effective tool in gaining buy-in. All consequences should be | -| | listed here, not just the "positive" ones. A particular decision may have | -| | positive, negative, and neutral consequences, but all of them affect the | -| | team and project in the future. | -+----------------------+---------------------------------------------------------------------------+ -| Related Decisions | List decisions related to this one. Useful relations among decisions | -| | include causality (which decisions caused other ones), structure (showing | -| | decisions’ parents or children, corresponding to architecture elements at | -| | higher or lower levels), or temporality (which decisions came before or | -| | after others). | -+----------------------+---------------------------------------------------------------------------+ -| Related Requirements | Map decisions to objectives or requirements, to show accountability. Each | -| | architecture decision is assessed as to its contribution to each major | -| | objective. We can then assess how well the objective is met across all | -| | decisions, as part of an overall architecture evaluation. | -+----------------------+---------------------------------------------------------------------------+ -| Affected Artifacts | List the architecture elements and/or relations affected by this | -| | decision. You might also list the effects on other design or scope | -| | decisions, pointing to the documents where those decisions are described. | -| | You might also include external artifacts upstream and downstream of the | -| | architecture, as well as management artifacts such as budgets and | -| | schedules. | -+----------------------+---------------------------------------------------------------------------+ -| Notes | Capture notes and issues that are discussed during the decision process. | -| | They can be links to a external document, a PR, a Github issue, etc. | -+----------------------+---------------------------------------------------------------------------+ diff --git a/doc/read-the-docs-site/adr/0002-steppable-cek-machine.md b/doc/read-the-docs-site/adr/0002-steppable-cek-machine.md deleted file mode 100644 index 1305fe5042e..00000000000 --- a/doc/read-the-docs-site/adr/0002-steppable-cek-machine.md +++ /dev/null @@ -1,189 +0,0 @@ -# ADR 2: Steppable CEK machine - -Date: 2022-10 - -## Authors - -Marty Stumpf -Ziyang Liu - -## Status - -Proposed - -## Context - -In order to have a minimal viable product of a debugger for Plutus, we need a CEK machine that will give us more information for debugging than our current one. - -In order to provide debugging information for each evaluation step, we need a steppable CEK machine. Implementing the steppable CEK machine is a non-trivial task and involves some design decisions. One decision to make is about whether we can share the code between the production and the debugging machine. That is not the scope of this ADR. See the next ADR for that. - -This ADR proposes a design for an implementation of a steppable CEK machine. Of course, this doesn't mean that this is the final decision. This means that the next step for us is to prototype the machine in this way - which we have reasons to believe will go well. We may adjust our proposed approach depending on how the prototyping goes. - -## Decision - -This section describes the proposed implementation of the debugging machine. - -We first **abstract out the computation to "steps"** on our current machine. We then **implement a coroutine system** to add the debugging functionalities. - -### Abstracting out the computation to "steps" - -This abstraction has been implemented in [PR#4909](https://github.com/IntersectMBO/plutus/pull/4909/). - -The current machine inlined the steps. We separate each steps into separate functions. They all return a `CekState`: - -```haskell -data CekState uni fun = - -- the next state is computing - Computing WordArray (Context uni fun) (Closure uni fun) - -- the next state is returning - | Returning WordArray (Context uni fun) (CekValue uni fun) - -- evaluation finished - | Terminating (Term NamedDeBruijn uni fun ()) - -data Closure uni fun = - Closure (Term NamedDeBruijn uni fun ()) (CekValEnv uni fun) -``` - -The computing step is `computeCekStep` with the following signature: - -```haskell -computeCekStep - :: forall uni fun s - . (Ix fun, PrettyUni uni fun, GivenCekReqs uni fun s) - => WordArray - -> Context uni fun - -> Closure uni fun - -> CekM uni fun s (CekState uni fun) -``` - -Similarly for the returning step (`returnCekStep`). Then we link up all the steps with `continue`, and the machine behaves very similar to our current one: - -```haskell -continue :: forall uni fun s - . (Ix fun, PrettyUni uni fun, GivenCekReqs uni fun s) - => CekState uni fun - -> CekM uni fun s (Term NamedDeBruijn uni fun ()) -continue (Computing !unbudgetedSteps ctx (Closure term env)) = do - state <- computeCekStep unbudgetedSteps ctx env term - continue state -continue (Returning !unbudgetedSteps ctx val) = do - state <- returnCekStep unbudgetedSteps ctx val - continue state -continue (Terminating term) = pure term -``` - -### Coroutines in Haskell - -The next step is to add debugging capabilities between each step. To do so, we implement it as a *coroutine system*. A detailed introduction to coroutines in Haskell can be found in [Coroutine Pipelines](https://themonadreader.files.wordpress.com/2011/10/issue19.pdf). -This section gives a brief summary. - -A coroutine system is composed of multiple computations cooperatively passing data and control to one another. -In this instance, one computation is the user issuing commands like "step forward", and the other is the CEK machine processing the commands and performing actions like interpreting the script being debugged. -We'll refer to them as the "user computation" and the "machine computation" respectively. - -Coroutines in Haskell can be implemented using the free monad transformer, [FreeT](https://hackage.haskell.org/package/free/docs/Control-Monad-Trans-Free.html#t:FreeT). -The `Coroutine` type used in the above article is isomorphic to `FreeT`. - -To use `FreeT f m`, we need two things: a suspension functor `f`, and a base monad `m`. - -The suspension functor is a pattern functor that describes the ways the user computation can suspend and pass control to the machine computation. -Each constructor of the suspension functor should thus represent a user request, such as "step forward". -Constructors generally follow a `RequestType request (response -> a)` pattern. - -As an example, consider the following suspension functor (the `uni` and `fun` parameters are omitted for readability): - -```haskell -data RequestF a - = StepF CekState (CekState -> a) - | LogF Text a - | InputF (Command -> a) - deriving Functor -``` - -`StepF` passes a `CekState` to the machine computation and suspends, requesting the machine computation to progress one step, and send a `CekState` back. -`LogF` sends a `Text` to the machine computation (its response type is `()` and is omitted). -`InputF` requests a `Command` from the user. - -Note that this pattern is not limited to a single suspension functor and two computations. -Multiple suspension functors and computations can be composed using [coproducts](https://www.cambridge.org/core/services/aop-cambridge-core/content/view/14416CB20C4637164EA9F77097909409/S0956796808006758a.pdf/data-types-a-la-carte.pdf). - -The base monad `m` is the monad the machine computation runs in. -The machine computation interprets each request into an `m` action. -It is essentially a natural transformation from the suspension functor to `m`. This `m` will replace our current monad `CekM`. Although we can actually just use `CekM` in the steppable CEK machine when we add `IO` capabilities for debugging. This is because we can convert it to/from `IO` via `unsafeSTToIO` and `unsafeIOToST`. - -Suppose we define a type `SteppableCekM a` as our base monad `m`. -Then the machine computation can be implemented as the following request handler function: - -```haskell -handle :: RequestF a -> SteppableCekM a -handle = \case - StepF state k -> step state >>= pure . k - LogF text k -> log text >> pure k - InputF k -> input >>= pure . k -``` - -where `step state`, `log text` and `input` return `SteppableCekM` actions. `step` will likely correspond to `computeCekStep` and `returnCekStep` depending on the states. - -We can then use `handle` to construct a monad morphism, interpreting the user computation (a `FreeT` structure) into a `SteppableCekM` action: - -```haskell -runSteppableCek :: FreeT RequestF SteppableCekM a -> SteppableCekM a -runSteppableCek userAction = do - runFreeT userAction >>= \case - Pure res -> pure res - Free req -> handle req >>= runSteppableCek -``` - -To construct the user computation, `FreeT RequestF SteppableCekM`, we first provide helper functions for constructing `RequestF`s and lifting them into the `FreeT`: - -```haskell -stepF :: Monad m => CekState -> FreeT RequestF m CekState -stepF state = liftF (StepF state id) - -logF :: Monad m => Text -> FreeT RequestF m () -logF text = liftF (LogF text ()) - -inputF :: Monad m => FreeT RequestF m Command -inputF = liftF (InputF id) -``` - -then we can implement the user computation like this: - -```haskell -userComputation :: CekState -> FreeT RequestF SteppableCekM () - userComputation currentState = do - cmd <- inputF - case cmd of - Step -> do - logF "Received Step command" - mState <- stepF currentState - userComputation mState - ... -``` - -We enter the debugging mode with the input UPLC program or term to debug with `enterDebug`: - -```haskell -enterDebug :: UPLCTerm -> FreeT RequestF SteppableCekM () -enterDebug termToDebug = do - state <- stepF (Computing (toWordArray 0) NoFrame (Closure term Env.empty)) - userComputation state - ... -``` - -### Argument: coroutine system - -Why a coroutine system? In short, structuring the code this way will ease our future work. Some of the advantages are mentioned above already. Here is a summary: - -- The debugger is naturally a coroutine, where one routine is the user and the other is the CEK machine, and they take turns to suspend and pass data and control to each other in a debugging session. The literature has contributed a good way to design/implement a coroutine. It makes sense to implement a well studied design. -- We can probably reuse the same monad (`CekM`) in the steppable CEK machine, because we can convert it to/from `IO` via `unsafeSTToIO` and `unsafeIOToST`. -- It should be easier when we add more functionalities because multiple suspension functors and computations can be composed using [coproducts](https://www.cambridge.org/core/services/aop-cambridge-core/content/view/14416CB20C4637164EA9F77097909409/S0956796808006758a.pdf/data-types-a-la-carte.pdf). -- This should also play nicely when we implement Debug Adapter Protocol for the debugger later on. - -## Implications - -In summary, we proposed to implement the debugging machine as a coroutine system with "steps". This implies that: - -- We have to maintain the CEK machine. E.g., we need to check its conformance. -- We will add a debugger for our users. We can give users more information at each evaluation step. -- We will need to write some tests to ensure that the debugging machine continuously output reasonable information. diff --git a/doc/read-the-docs-site/adr/0003-sharing-prod-debugging-cek.md b/doc/read-the-docs-site/adr/0003-sharing-prod-debugging-cek.md deleted file mode 100644 index eb7a9cde27f..00000000000 --- a/doc/read-the-docs-site/adr/0003-sharing-prod-debugging-cek.md +++ /dev/null @@ -1,122 +0,0 @@ -# ADR 3: Sharing code between the production and debugging CEK machine - -Date: 2022-10 - -## Authors - -Marty Stumpf - -## Status - -Draft - -## Context - -In order to have a minimal viable product of a debugger for Plutus, we need a CEK machine that will give us more information for debugging than our current one. - -One of the first decision we need to make is: should the debugging machine be a separate one? The debugging machine need to satisfy these requirements: - -- we must not compromise the performance of the production machine, and -- the debugging machine must behave the same as the production machine. - -There are tradeoffs between these two requirements. If we have a separate machine, the performance of the production machine will be untouched. But there is more scope for us to make mistakes with the new machine. - -However, if we share code between the two machines, the performance of the production machine may be compromised. - -This ADR proposes an approach for the two machines to share code while not compromising performance. - -## Decision: Polymorphic compute/return steps - -As long as the debugging machine has the same type, we can alter `computeCek`/`returnCek` to be polymorphic over a type-level `Bool` specifying if we’re in debug mode or not. Then we demote it to the term level in the definition of `computeCek`/`returnCek` and branch on the `Bool` thus implementing different logic depending on whether we're in debug mode or not. This promotion to the type level allows us to statically instantiate the `Bool` in an instance and thus make GHC compile the whole worker of the CEK machine twice: once in debug mode and once in production mode. Theoretically, GHC will take care to remove all the dead debug code when in production mode. - -### Detailed description with code snippets - -Whether we are debugging or not, we will be returning a `CekState`: - -```haskell -data CekState uni fun = - -- the next state is computing - Computing WordArray (Context uni fun) (Closure uni fun) - -- the next state is returning - | Returning WordArray (Context uni fun) (CekValue uni fun) - -- evaluation finished - | Terminating (Term NamedDeBruijn uni fun ()) - -data Closure uni fun = - Closure (Term NamedDeBruijn uni fun ()) (CekValEnv uni fun) -``` - -We enter either modes via `enterComputeCek`, which takes an extra `Bool` than our current implementation, to indicate whether we are in debugging mode or not: - -```haskell -enterComputeCek - :: forall uni fun s - . (Ix fun, PrettyUni uni fun, GivenCekReqs uni fun s) - => Bool - -> Context uni fun - -> Closure uni fun - -> CekM uni fun s (CekState uni fun) -enterComputeCek debug ctx (Closure term env) = - -- The initial step is always computing with zero budget, empty context and environment. - -- `computeCekStep` matches on the `term` and calls `computeCek` or `returnCek` depending on the clause. - computeCekStep (toWordArray 0) NoFrame (Closure term Env.empty) where - - computeCek - :: WordArray -- for costing - -> Context uni fun - -> Closure uni fun - -> CekM uni fun s (CekState uni fun) - computeCek = if debug then computeCekDebug else computeCekStep - {-# NOINLINE computeCek #-} -- Making sure the `if` is only evaluated once. - - -- in debugging mode, immediately returns the current `CekState` and halts execution. Debugging mode details to be worked out. - computeCekDebug - :: WordArray - -> Context uni fun - -> Closure uni fun - -> CekM uni fun s (CekState uni fun) - computeCekDebug budget ctx (Closure term env) = - pure $ Computing budget ctx (Closure term env) - - -- In production mode, `computeCekStep` matches on the term and calls `computeCek` or `returnCek` on a subterm. - -- In production mode, `computeCek` calls the original `computeCekStep`, i.e. in production mode `computeCekStep` calls itself through the thin `computeCek` wrapper thus achieving recursion and replicating the old behavior of the CEK machine. - computeCekStep - :: WordArray - -> Context uni fun - -> Closure uni fun - -> CekM uni fun s (CekState uni fun) -- the return type is `CekState` instead of a term. - computeCekStep unbudgetedSteps ctx (Closure (Force _ body) env) = do -- exactly like in current prod - !unbudgetedSteps' <- stepAndMaybeSpend BForce unbudgetedSteps -- update costs - computeCek unbudgetedSteps' (FrameForce ctx) (Closure body env) -- compute again with updated costs and ctx - -- there's a lot of code in here! Some clauses call `returnCek`, some `computeCek`, achieving recursive calling similar to our current implementation. - - -- details of `forceEvaluate`, `applyEvaluate` etc to be worked out. - - -- similarly for the returning step - - returnCek = if debug then returnCekDebug else returnCekStep - {-# NOINLINE returnCek #-} - - returnCekDebug = ... - - - returnCekStep - :: forall uni fun s - . (PrettyUni uni fun, GivenCekReqs uni fun s) - => WordArray - -> Context uni fun - -> CekValue uni fun - -> CekM uni fun s (CekState uni fun) -- return a state instead of a term - returnCekStep !unbudgetedSteps NoFrame val = do - spendAccumulatedBudget unbudgetedSteps - pure $ Terminating $ dischargeCekValue val --wrap the term in the `Terminating` constructor when returning the term. - -``` - -This trick lets us inline the "step" functions and call them recursively like before. Because when we are not debugging, we are still using basically the same code as our current implementation, the performance should not be affected by much. (Given that the machine is tail-recursive, the additional wrapping of the returned term in the `Terminating` constructor will affect performance in a negligible way.) - -## Implications - -This is a draft of an idea. There are further details to be worked out in a prototype. The implementor should use their own judgement. - -Whether we proceed with this approach or not depends on how the prototyping goes, and its benchmarking results. If we find that the slow down is negligible enough, then we may proceed with this. Otherwise, we proceed with a separate implementation for the debugging machine. diff --git a/doc/read-the-docs-site/adr/0004-deferred-unlifting.md b/doc/read-the-docs-site/adr/0004-deferred-unlifting.md deleted file mode 100644 index ec57ee45d2c..00000000000 --- a/doc/read-the-docs-site/adr/0004-deferred-unlifting.md +++ /dev/null @@ -1,84 +0,0 @@ -# ADR 4: Deferred unlifting in Plutus Core - -Date: 2022-11 - -## Authors - -Michael Peyton Jones - -## Status - -Accepted - -## Context - -A key part of the evaluation of builtin applications in Plutus Core is "unlifting". -Unlifting is the process of taking a Plutus Core term and turning it into a Haskell value of a known type. -For example, we can unlift an integer constant term into the actual Haskell integer it contains. -This is necessary in order to apply the denotation of the builtin being applied, since that is a Haskell function that operates on Haskell types (e.g. integer addition). - -However, unlifting can fail: we cannot unlift a _string_ constant into a Haskell integer! -This failure is visible in program execution, since it terminates the program with an error. - -The original design of the builtin application machinery performed unlifting of an argument as soon as it was received. -This meant that unlifting failures would surface at that point, whereas most of the errors that relate to builtin evaluation can only occur once the builtin has all its arguments, since that's when we run the actual function. - -For example: -``` -[(builtin addInteger) (con string "hello")] -``` -would fail (due to the unlifting failure), even though the builtin _never_ receives all its arguments and is never fully evaluated. - -The fact that unlifting errors occur early on makes the specification of the behaviour of builtins significantly more complex. -It would be simpler if unlifting errors occurred when the builtin has all its arguments. -We refer to these two alternatives as "immediate" unlifting (the status quo) and "deferred" unlifting. - -Deferred unlifting only makes evaluation slightly more lenient: some terms (such as the above example) do not give an error where they would do with immediate unlifting. - -## Decision - -We decided: -- To switch to deferred unlifting by default in protocol version 7 (Vasil). -- Having observed (after the hard fork) that no script evaluation in the history of the chain relied on immediate unlifting, to remove all support for immediate unlifting from the evaluator. - -## Argument - -The difference between immediate and deferred unlifting is only visible in quite specific circumstances. -Since builtins are _usually_ fully applied (otherwise they don't do anything!), an unlifting error will usually be forced right away, regardless of whether we use immediate or deferred unlifting. -The only case where this is not true is where the builtin _never_ receives all its arguments, such as the example given above. -More generally, the only case where behaviour differs is _partially applied_ builtins which are applied to _ill-typed arguments_. -This is quite unusual, since users typically write programs that a) do something and b) are well-typed. - -Consequently we felt that it was safe to change the default unlifting behaviour. - -However, in order to gain the full benefit of simplification, we would like to remove the existence of immediate unlifting entirely. -If historical script evaluations on the chain still rely on immediate unlifting, then we must support it (and specify it!) forever. -However, once the default has changed, if the history of the chain still validates with _deferred_ unlifting, then we know that no historical script evaluations relied on that behaviour. -At that point we can _unconditionally_ enable deferred unlifting without worrying about not being able to validate the chain. - -In theory, there could be outputs locked with script hashes whose behaviour would (if they are ever spent) rely on inmmediate unlifting. -We cannot rule this out, but given that it has never been relevant in the entire history of the chain, we considered this to be extremely unlikely. - -## Alternatives - -### 1. Status quo - -Undesirable, we face the complexity forever. - -### 2. Support both versions forever - -Arguably even worse than 1, in that we have to maintain and specify both versions forever, so our complexity burden is even greater. - -## Implications - -This has already been implemented, and the specification has been updated. -It has no further implications for other decisions that we know of. - -## Notes - -Relevant PRs: -- [Support for both versions of unlifting](https://github.com/IntersectMBO/plutus/pull/4516) -- [Choose the unlifting mode based on protocol version](https://github.com/IntersectMBO/plutus/pull/4522) -- [Remove immediate unlifting](https://github.com/IntersectMBO/plutus/pull/4879) -- [Mainnet script dump test](https://github.com/IntersectMBO/plutus/pull/4726) -- [Update PLC specification for deferred unlifting](https://github.com/IntersectMBO/plutus/pull/4960) diff --git a/doc/read-the-docs-site/adr/index.rst b/doc/read-the-docs-site/adr/index.rst deleted file mode 100644 index 4a6c8a94376..00000000000 --- a/doc/read-the-docs-site/adr/index.rst +++ /dev/null @@ -1,36 +0,0 @@ -Architectural decision records -==================================== - -We document our architectural and design decisions for all of our components. -In order to do that, there is practice called architectural decision records ("ADR"), -that we can integrate into our workflow. -An ADR is a document that captures an important architectural decision made along with its context and consequences. - -The goals are: - -* making decisions transparent to internal/external stakeholders and contributors. - -* getting feedback on decisions that we're about to make or have made - -* providing external contributors a framework to propose architectural changes - -* providing a big picture of all major decisions that were made - -The general process for creating an ADR is: - -1. cloning the repository - -2. creating a new file with the format `-.rst` in the directory `doc/adr` - -3. adding the ADR in the table of content tree of the Readthedocs - -4. committing and pushing to the repository - -.. toctree:: - :maxdepth: 1 - :titlesonly: - - 0001-record-architecture-decisions - 0002-steppable-cek-machine - 0003-sharing-prod-debugging-cek - 0004-deferred-unlifting diff --git a/doc/read-the-docs-site/bibliography.bib b/doc/read-the-docs-site/bibliography.bib deleted file mode 100644 index 202dd9b30ad..00000000000 --- a/doc/read-the-docs-site/bibliography.bib +++ /dev/null @@ -1,109 +0,0 @@ -@inproceedings{eutxo, - title = {The {Extended UTXO} Model}, - author = {Manuel M. T. Chakravarty and James Chapman and Kenneth - MacKenzie and Orestis Melkonian and Michael {Peyton - Jones} and Philip Wadler}, - booktitle = {Proceedings of Trusted Smart Contracts (WTSC)}, - year = 2020, - volume = "12063", - publisher = "Springer", - series = "LNCS", - note={Also available at https://github.com/IntersectMBO/plutus} -} - -@inproceedings{utxoma, - title={{UTXO$_{\mathrm{ma}}$}: {UTXO} with Multi-Asset Support}, - author={Manuel M. T. Chakravarty and James Chapman and Kenneth MacKenzie and Orestis Melkonian and Jann M{\"u}ller and Michael {Peyton Jones} and Polina Vinogradova and Philip Wadler and Joachim Zahnentferner}, - year=2020, - booktitle={International Symposium on Leveraging Applications of Formal Methods}, - organization={Springer}, - note={Also available at https://github.com/IntersectMBO/plutus} -} - -@inproceedings{eutxoma, - title={Native custom tokens in the extended {UTXO} model}, - author={Chakravarty, Manuel MT and Chapman, James and MacKenzie, Kenneth and Melkonian, Orestis and M{\"u}ller, Jann and Jones, Michael Peyton and Vinogradova, Polina and Wadler, Philip}, - booktitle={International Symposium on Leveraging Applications of Formal Methods}, - pages={89--111}, - year={2020}, - organization={Springer}, - note={Also available at https://github.com/IntersectMBO/plutus} -} - -@techreport{chakravarty2020hydra, - title={Hydra: Fast Isomorphic State Channels}, - author={Chakravarty, Manuel M. T. and Coretti, Sandro and Fitzi, Matthias and Gazi, Peter and Kant, Philipp and Kiayias, Aggelos and Russell, Alexander}, - year={2020}, - url= {https://eprint.iacr.org/2020/299}, - institution={Cryptology ePrint Archive, Report 2020/299} -} - -@Misc{functional-smart-contracts-summit, - author= {Chakravarty, Manuel MT and Thompson, Simon and Wadler, Philip}, - title = {Functional smart contracts on Cardano}, - howpublished = {\url{https://www.youtube.com/watch?v=MpWeg6Fg0t8}} -} - -@Misc{plutus-platform-summit, - author= {Peyton Jones, Michael and M{\"u}ller, Jann}, - title = {The Plutus Platform}, - howpublished = {\url{https://www.youtube.com/watch?v=usMPt8KpBeI}} -} - -@inproceedings{marlowe, - author = {Pablo Lamela Seijas and - Simon J. Thompson}, - title = {Marlowe: Financial Contracts on Blockchain}, - booktitle = {Leveraging Applications of Formal Methods, Verification and Validation. - Industrial Practice - 8th International Symposium, ISoLA 2018, Limassol, - Cyprus, November 5-9, 2018, Proceedings, Part {IV}}, - pages = {356--375}, - year = {2018}, - crossref = {DBLP:conf/isola/2018-4}, - url = {https://doi.org/10.1007/978-3-030-03427-6\_27}, - doi = {10.1007/978-3-030-03427-6\_27}, - timestamp = {Tue, 14 May 2019 10:00:41 +0200}, - biburl = {https://dblp.org/rec/bib/conf/isola/SeijasT18}, - bibsource = {dblp computer science bibliography, https://dblp.org} -} - -@techreport{Cardano-wallet-spec, -author = {Duncan Coutts and Edsko de Vries}, -title = {Formal specification for a {Cardano} wallet}, -note={Available at \url{https://cardanodocs.com/files/formal-specification-of-the-cardano-wallet.pdf}}, -institution={IOHK}, -year={2018} -} - -@techreport{Cardano-ledger-spec, -title = {A Formal Specification of the {Cardano} Ledger}, -author={Jared Corduan and Polina Vinogradova and Matthias G{\"u}demann}, -note={Available at \url{https://github.com/IntersectMBO/cardano-ledger-specs}}, -institution={IOHK}, -year={2019} -} - -@techreport{plutus-core-spec, -title = {Formal Specification of the {Plutus Core} Language}, -note={Available at \url{https://github.com/IntersectMBO/plutus}}, -author={IOHK}, -institution={IOHK}, -year={2019} -} - -@techreport{plutus-report -title = {Plutus Platform Technical Report}, -note={Available at \url{https://github.com/IntersectMBO/plutus}}, -author={IOHK}, -institution={IOHK}, -year={2019} -} - -@misc{cbor, - title = {{RFC 7049 - Concise Binary Object Representation (CBOR)}}, - howpublished = {\url{https://tools.ietf.org/html/rfc7049}}, - month = oct, - year = {2013}, - note = {Accessed: 2020-01-01}, - author={IETF} -} diff --git a/doc/read-the-docs-site/cardano-logo.png b/doc/read-the-docs-site/cardano-logo.png deleted file mode 100644 index f888d1bd35b..00000000000 Binary files a/doc/read-the-docs-site/cardano-logo.png and /dev/null differ diff --git a/doc/read-the-docs-site/conf.py b/doc/read-the-docs-site/conf.py deleted file mode 100644 index fba9bce21d0..00000000000 --- a/doc/read-the-docs-site/conf.py +++ /dev/null @@ -1,128 +0,0 @@ - - -import sys -import os -import sphinx_rtd_theme -import recommonmark - -from recommonmark.transform import AutoStructify -from os.path import abspath, join, dirname - -sys.path.insert(0, abspath(join(dirname(__file__)))) -sys.path.append(os.path.abspath('exts')) - -# -- RTD configuration ------------------------------------------------ - -on_rtd = os.environ.get("READTHEDOCS", None) == "True" - -# This is used for linking and such so we link to the thing we're building -rtd_version = os.environ.get("READTHEDOCS_VERSION", "latest") -if rtd_version not in ["stable", "latest"]: - rtd_version = "stable" - -# -- Project information ----------------------------------------------------- - -project = 'Plutus Core and Plutus Tx User Guide' -copyright = '2023, IOHK' -author = 'IOHK' - -# The full version, including alpha/beta/rc tags -release = '1.0.0' - -# -- General configuration --------------------------------------------------- -master_doc = 'index' -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. - -extensions = [ - "sphinx_rtd_theme", - 'recommonmark', - 'sphinx_markdown_tables', - 'sphinxemoji.sphinxemoji', - "sphinx.ext.intersphinx", - 'sphinxcontrib.plantuml', - 'sphinxcontrib.bibtex', - 'hs_domain', -] - -bibtex_bibfiles = ['bibliography.bib'] -bibtex_default_style = 'plain' - -# Amazingly, RTD actually provide plantuml -if on_rtd: - plantuml = 'java -Djava.awt.headless=true -jar /usr/share/plantuml/plantuml.jar' - -primary_domain = 'hs' - -haddock_mapping = {} -haddock_dir = os.getenv('SPHINX_HADDOCK_DIR', None) -if haddock_dir: - for entry in os.scandir(haddock_dir): - if entry.is_dir(): - html_dir = os.path.join(entry.path, 'html') - inv_file = os.path.join(html_dir, 'objects.inv') - if os.path.exists(inv_file): - haddock_mapping[entry.name] = (html_dir, inv_file) - -intersphinx_mapping = haddock_mapping - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] -html_static_path = ['_static'] - -source_suffix = { - '.rst': 'restructuredtext', - '.md': 'markdown', -} - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -# This pattern also affects html_static_path and html_extra_path. -exclude_patterns = [ - 'haddock', # Otherwise it tries to pick up the README.md's in the Haddock doc! - 'README.md' -] - -# -- Options for HTML output ------------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -# -html_theme = "sphinx_rtd_theme" - -html_theme_options = { - 'logo_only': False, - 'display_version': False, - 'prev_next_buttons_location': 'bottom', - 'style_external_links': False, - 'style_nav_header_background': '#fcfcfc', - # Toc options - 'collapse_navigation': False, - 'sticky_navigation': True, - 'navigation_depth': 4, - 'includehidden': True, - 'titles_only': False -} - -html_logo = "cardano-logo.png" - -html_context = { - "display_github": True, # Add 'Edit on Github' link instead of 'View page source' - "github_user": "input-output-hk", - "github_repo": "plutus", - "github_version": "master", - "conf_py_path": "/doc/read-the-docs-site/", - "source_suffix": source_suffix, -} - -# -- Custom Document processing ---------------------------------------------- - -def setup(app): - app.add_config_value('recommonmark_config', { - 'enable_auto_doc_ref': False, - 'enable_auto_toc_tree': False, - }, True) - app.add_transform(AutoStructify) - app.add_css_file("theme_overrides.css") diff --git a/doc/read-the-docs-site/explanations/index.rst b/doc/read-the-docs-site/explanations/index.rst deleted file mode 100644 index edaf5ac897f..00000000000 --- a/doc/read-the-docs-site/explanations/index.rst +++ /dev/null @@ -1,11 +0,0 @@ -Explanations -============ - -.. toctree:: - :maxdepth: 3 - :titlesonly: - - platform - ledger - plutus-foundation - language-versions diff --git a/doc/read-the-docs-site/explanations/language-versions.rst b/doc/read-the-docs-site/explanations/language-versions.rst deleted file mode 100644 index eed8d7814a0..00000000000 --- a/doc/read-the-docs-site/explanations/language-versions.rst +++ /dev/null @@ -1,63 +0,0 @@ -.. _what_are_plutus_language_versions: - -What are Plutus language versions? -================================== - -The Cardano ledger tags scripts with a *language*. This determines what the ledger -will do with the script. - -For example, the "simple" script language introduced in the Allegra era allows for -a few basic kinds of checks to be made, such as time locks. In order to interpret -simple scripts, the ledger must (among other things) extract the validation interval -information from the transaction in order to check the conditions imposed by the script. - -Plutus scripts, introduced in the Alonzo era, have a more complex interface than -simple scripts. Plutus scripts are programs written in the Plutus Core programming -language that receive three arguments: - - 1. the datum, - 2. the redeemer, and - 3. the context. - -The *context* contains all the information about the transaction which is currently -being validated. (See :ref:`Scripts and the Extended UTXO model <scripts_and_the_eutxo_model>` -for more details). - -Languages must continue to behave the same forever; otherwise, we could change the -behaviour of existing scripts, potentially making outputs un-spendable and breaking -users' assumptions. That means that many kinds of changes to the behaviour of the -language instead require a "new" language. This includes changes to the interface -of the language. - -For example, if we want to put more information in the *context* (e.g., in order to -convey information about new fields that have been added to transactions), then -we need a new language, because old scripts would not be able to understand the new information. - -.. note:: - For more details about what kinds of changes require a new language, see the - Cardano Improvement Proposal, `CIP 35--Plutus Core Evolution <https://cips.cardano.org/cips/cip35/>`_. - -Hence, in order to change Plutus, we need to create a new language in the ledger. -Since in most cases this language will be very similar to the ones that came before, -we refer to these as "Plutus language versions." However, from the ledger's perspective, -they are entirely unrelated and there is generally no requirement that they be similar -or compatible in any way. - -There are two different uses of "language" here that are important to keep distinct: - - * Plutus Core is a *programming* language in which Plutus scripts are written; - * Plutus (the Plutus Core programming language and a particular interface) is a - "language" in the terminology of the ledger. - -In particular, a specific version of the Plutus Core programming language may be -used in multiple versions of the Plutus ledger language, if, for example, the only -difference is to the interface. To date, all versions of Plutus use the same version -of the Plutus Core! That means that, in practice, the process for creating scripts -of different Plutus language versions tends to be similar. The main difference is that -you will likely need a different ``ScriptContext`` type, and different built-in -functions may be available. - -*See also:* - -* :ref:`Plutus language changes <plutus_language_changes>` for a description of what has changed between versions. -* :doc:`Upgrading to Vasil and Plutus script addresses </reference/cardano/upgr-vasil-plutus-script-addresses>`. diff --git a/doc/read-the-docs-site/explanations/ledger.rst b/doc/read-the-docs-site/explanations/ledger.rst deleted file mode 100644 index e9c57dad86f..00000000000 --- a/doc/read-the-docs-site/explanations/ledger.rst +++ /dev/null @@ -1,139 +0,0 @@ -.. _what_is_a_ledger: - -What is a ledger? -================= - -The :ref:`Plutus Platform<what_is_the_plutus_platform>` is designed to work with -distributed ledgers (henceforth simply “ledgers”). Ledgers are typically *implemented* -with a blockchain, such as Cardano. However, much of the time when we are talking -about ledgers we don't care about the underlying implementation, and so we will just -talk about the ledger itself. - -.. note:: - This is not always true: applications do need to care about details of how the - underlying blockchain works, because that affects behaviour such as settlement - time and rollback policies. As much as possible the Plutus Application Framework - tries to shield developers from this complexity, but it is not always possible. - -In its simplest form, a ledger is a system that tracks who owns what. - -For example: - -+------------+----------+ -| Owner | Balance | -+============+==========+ -| Alice | 43 USD | -+------------+----------+ -| Bob | 12 USD | -+------------+----------+ - -Ledgers are typically transformed by performing a *transaction* that transfers some -assets from one party to another. In order to be *valid* a transaction will have to -pass some checks, such as demonstrating that the transfer is authorized by the owner -of the funds. After applying a transaction (say, Alice sends Bob 5 USD), we have a -new state of the ledger. - -+------------+----------+ -| Owner | Balance | -+============+==========+ -| Alice | 38 USD | -+------------+----------+ -| Bob | 17 USD | -+------------+----------+ - -Account-based and UTXO-based ledgers ------------------------------------- - -There are two dominant paradigms for how to *represent* such a system. The first, -account-based ledgers, model the system exactly as in our example above. They keep -a list of accounts, and for each account, a balance. A transaction simply decreases -the balance of the sender, and increases the balance of the recipient. - -Account-based ledgers (such as Ethereum) are very simple to implement, but they -have difficulties due to the fact that the state of an account is *global*: all -transactions that do anything with an account must touch this one number. This can -lead to issues with throughput, as well as ordering issues (if Alice sends 5 USD to -Bob, and Bob sends 5 USD to Carol, this may succeed or fail depending on the order -in which the transactions are processed). - -The other paradigm is UTXO-based ledgers. UTXO-based ledgers (such as Bitcoin) -represent the state of the ledger as a set of "unspent transaction outputs" (UTXOs). -A UTXO is like an envelope with some money in it: it is "addressed" to a particular -party, and it contains some funds. A transaction *spends* some number of UTXOs, -and creates some more. - -So a transaction that sends 5 USD from Alice to Bob would do so by spending some -number of already-existing UTXOs belonging to Alice, and creating a new UTXO with -5 USD belonging to Bob. - -UTXO-based ledgers are more complicated, but avoid some of the issues of account-based -ledgers, since any transaction deals only with the inputs that it spends. Cardano -is a UTXO-based ledger, and we heavily rely on this. For example, :term:`Hydra`, -Cardano's scalability solution, uses the fact that independent parts of the transaction -graph can be processed in parallel to improve throughput. - -.. _scripts_and_the_eutxo_model: - -Scripts and the Extended UTXO Model ------------------------------------ - -UTXO-based ledgers typically start out with a very simple model of "ownership" of -UTXOs. An output will have a public key (strictly, the hash of a public key) attached -to it, and in order to spend this output the spending transaction must be signed by -the corresponding private key. We call this a "pay-to-pubkey" output. - -Cardano uses an extended model called the :term:`Extended UTXO Model` (EUTXO). -In the EUTXO model, an output can be locked by (the hash of) a *script*. We call -this a "pay-to-script" output. A script is a *program* that decides whether or not -the transaction which spends the output is authorized to do so. Such a script is -called a validator script, because it validates whether the spending is allowed. - -A simple validator script would be one that checked whether the spending transaction -was signed by a particular key---this would exactly replicate the behaviour of simple -pay-to-pubkey outputs. However, with a bit of careful extension, we can use scripts -to let us express a large amount of useful logic on the chain. - -With the EUTXO model, validator scripts are passed three arguments: - -- The *datum*: this is a piece of data attached to the *output* that the script is - locking (strictly, again, just the hash is present). This is typically used to - carry state. -- The *redeemer*: this is a piece of data attached to the *input* that is doing - the spending. This is typically used to provide an input to the script from the - spender. -- The *context*: this is a piece of data which represents information about the - transaction doing the spending. This is used to make assertions about the way - the output is being sent (such as "Bob signed it"). - -As an example, let's see how we could implement an atomic swap. - -- The datum contains the keys of the two parties in the swap, and a description - of what they are swapping. -- The redeemer is unused. -- The context contains a representation of the transaction. - -The logic of the validator script is then: does the transaction make a payment from -the second party to the first party, containing the value that they are supposed -to send? If so, then they may spend this output and send it where they want (or we -could insist that they send it to their key, but we might as well let them do what -they like with it). - -Different kinds of scripts --------------------------- - -The Cardano ledger currently has a few different kinds of validator scripts: - -- The "simple" script language (introduced in the Allegra hard fork), which allows - basic checks such as time locks -- Various Plutus language versions (see :ref:`What are Plutus language versions? <what_are_plutus_language_versions>`) - -Further reading ------------------ - -See `The EUTXO Handbook, A deep dive into Cardano's accounting model <https://www.essentialcardano.io/article/the-eutxo-handbook>`_. - -The Extended UTXO Model is described in :cite:t:`functional-smart-contracts-summit`. -More formal detail can be found in in :cite:t:`eutxo,utxoma,eutxoma`. - -For more help on how to actually implement interesting logic using the EUTXO model -and scripts, read some of our :ref:`tutorials<plutus_tutorials>`. diff --git a/doc/read-the-docs-site/explanations/platform.rst b/doc/read-the-docs-site/explanations/platform.rst deleted file mode 100644 index 46bb59f2f7e..00000000000 --- a/doc/read-the-docs-site/explanations/platform.rst +++ /dev/null @@ -1,73 +0,0 @@ -.. _what_is_the_plutus_platform: - -What is the Plutus Platform? -============================ - -The Plutus Platform is a platform for writing *applications* that interact with a *distributed ledger* featuring *scripting* capabilities, in particular the :term:`Cardano` blockchain. - -Applications ------------- - -What sort of "applications" are we talking about here? -Let's think about a pair of users, Alice and Bob, who want to engage in an atomic swap of some assets stored on Cardano. - -.. uml:: - :caption: Alice and Bob doing an atomic swap - - actor Alice - actor Bob - participant Application - database Cardano - - Alice -> Application: I want to do an escrowed swap with Bob,\n 50 Ada for my Special Token - Application -> Ledger: I want to lock up Alice's Special Token so that\n it can only be unlocked if Bob completes the swap - Ledger -> Application: Ok, that change has settled - Application -> Bob: Hey, Alice wants to do a swap with you - Bob -> Application: I want to take up Alice's swap - Application -> Cardano: I want to spend that locked output with Alice's\n Special Token while sending 50 of Bob's Ada to Alice - Ledger -> Ledger: Does this transaction satisfy the \nconditions that were asked for? Yes it does! - Ledger -> Application: Ok, that change has settled - Application -> Alice: The swap is completed! - Application -> Bob: The swap is completed! - -Alice and Bob don't interact directly, nor do they directly interact with the ledger. -Very few "smart" blockchain systems encourage their users to interact directly with the chain themselves, since this is usually complex and error-prone. -Rather, the users interact with some *application* that presents the world in a form that they can understand and interact with. - -Of course, such an application must want to do something with the ledger, otherwise you wouldn't need anything new! -Simple applications might do nothing more than submit basic transactions that transfer assets - imagine a simple "regular payments" application. -However, our main focus is applications that *do* use smart features in order to have a kernel of trusted code that is validated as part of the ledger. - -This enables applications that are not possible otherwise. -Alice and Bob need trusted logic in order to perform their swap: a "dumb" application could submit the transactions transferring the assets, but would have no recourse against Bob defecting. -Using the smart features of the ledger ensures that Bob can't take Alice's token unless he *really does* send her the money, and it does this without involving a trusted third party. - -Creating and using the trusted kernel of code is the most technically difficult and security-sensitive part of the whole operation. -Nonetheless, writing the rest of the application contains plenty of complexity. -Amongst other things, an application needs to deal with the software around the ledger (wallets, nodes, etc.); distributed systems issues such as settlement delays, inconsistent state between parties, and rollbacks; and simple user-experience issues like upgrades, state management and synchronization. -Furthermore, while none of these are quite as security-critical as the trusted kernel, users certainly *can* be attacked through such applications, and even non-malicious bugs are likely to be quite upsetting when a user's money is at stake. - -Even simple applications must deal with this complexity, and for more advanced applications that deal with state across time, the difficulty is magnified. - -The Plutus Platform -------------------- - -This is why the Plutus Platform is a *platform*. -Rather than just providing a few tools to make the bare minimum possible, we aim to support application development in its entirety, right the way through from authoring to testing, runtime support, and (eventually) verification. -Ultimately, we wrote it because we needed it ourselves to do anything useful! - -Conceptually, the Platform breaks down based on which part of the system we're interested in: - -- :ref:`Plutus Foundation<what_is_plutus_foundation>`: support for writing the trusted kernel of code, and executing it on the chain -- `The Plutus Application Framework <https://github.com/IntersectMBO/plutus-apps>`_: support for writing applications ("Plutus Applications") in a particular style - -.. figure:: ./platform-architecture.png - - A high-level architecture of the Plutus Platform, with an emphasis on applications. - -Further reading ---------------- - -The platform is introduced in :cite:t:`plutus-platform-summit`. - -The design of the platform is discussed in :cite:t:`plutus-report`. diff --git a/doc/read-the-docs-site/explanations/plutus-foundation.rst b/doc/read-the-docs-site/explanations/plutus-foundation.rst deleted file mode 100644 index e19712972a8..00000000000 --- a/doc/read-the-docs-site/explanations/plutus-foundation.rst +++ /dev/null @@ -1,38 +0,0 @@ -.. _what_is_plutus_foundation: - -What is Plutus Foundation? -========================== - -In order for an application to run its :ref:`trusted kernel<what_is_the_plutus_platform>` of logic as a script on a :ref:`ledger<what_is_a_ledger>`, the ledger needs a way of specifying and executing scripts. -Scripts are simply programs, so this means we need a *programming language*. - -Plutus Core ------------ - -In the Plutus Platform, this language is *Plutus Core*. -Plutus Core is a variant of the lambda calculus, a well-studied formalism for computing. - -.. note:: - Plutus Core is our "assembly language". - Trust me, you don't want to see any! - Dealing with that is the compiler's job. - -Plutus Core is designed for simplicity, determinism, and to allow careful cost control of program execution. -Using the lambda calculus makes it an easy compilation target for functional programming languages, and allows us to have a simple, formally verified evaluator. - -Plutus Tx ---------- - -Writing Plutus Core by hand is not a job for a human! -It is designed to be written by a compiler, and the Platform provides a compiler from a subset of Haskell to Plutus Core. -This allows you to seamlessly write applications in Haskell, while compiling part of the code to on-chain Plutus Core, and part into an off-chain application. - -Supporting "mixed" code in this way enables libraries written with the Plutus Haskell SDK to share logic and datatypes across both parts of the application, reducing the risk of errors significantly. - -Further reading ---------------- - -The formal details of Plutus Core are in its specification :cite:p:`plutus-core-spec`. -The design is discussed in :cite:t:`plutus-report`. - -For more about Plutus Tx, see the :ref:`tutorial<plutus_tx_tutorial>`. diff --git a/doc/read-the-docs-site/extensions-flags-pragmas.rst b/doc/read-the-docs-site/extensions-flags-pragmas.rst deleted file mode 100644 index 2a16a28074e..00000000000 --- a/doc/read-the-docs-site/extensions-flags-pragmas.rst +++ /dev/null @@ -1,85 +0,0 @@ -.. _extensions_flags_pragmas: - -GHC Extensions, Flags and Pragmas -================================= - -Plutus Tx is a subset of Haskell and is compiled to Untyped Plutus Core by the Plutus Tx compiler, a GHC (Glasgow Haskell Compiler) plugin. - -In order to ensure the success and correct compilation of Plutus Tx programs, all Plutus Tx modules (that is, Haskell modules that contain code to be compiled by the Plutus Tx compiler) should use the following GHC extensions, flags and pragmas. - - -Extensions -------------------------------------------------- - -Plutus Tx modules should use the ``Strict`` extension: :: - - {-# LANGUAGE Strict #-} - -Unlike in Haskell, function applications in Plutus Tx are strict. -In other words, when evaluating ``(\x -> 42) (3 + 4)`` the expression ``3 + 4`` is evaluated first, before evaluating the function body (``42``), even though ``x`` is not used in the function body. -The ``Strict`` extension ensures that let bindings and patterns are also (by default) strict, for instance, evaluating -``let x = 3 + 4 in 42`` evaluates ``3 + 4`` first, even though ``x`` is not used. - -Bang patterns and lazy patterns can be used to explicitly specify whether a let binding is strict or non-strict, as in ``let !x = 3 + 4 in 42`` (strict) and ``let ~x = 3 + 4 in 42`` (non-strict). -At this time, it is not possible to make function applications non-strict: ``(\(~x) -> 42) (3 + 4)`` still evaluates ``3 + 4`` strictly. - -Making let bindings strict by default has the following advantages: - -* It makes let bindings and function applications semantically equivalent, e.g., ``let x = 3 + 4 in 42`` has the same semantics as ``(\x -> 42) (3 + 4)``. - This is what one would come to expect, as it is the case in most other programming languages, regardless of whether the language is strict or non-strict. -* Untyped Plutus Core programs, which are compiled from Plutus Tx, are not evaluated lazily (unlike Haskell), that is, there is no memoization of the results of evaluated expressions. - Thus using non-strict bindings can cause an expression to be inadvertently evaluated for an unbounded number of times. - Consider ``let x = <expensive> in \y -> x + y``. - If ``x`` is non-strict, ``<expensive>`` will be evalutated every time ``\y -> x + y`` is applied to an argument, which means it can be evaluated 0 time, 1 time, 2 times, or any number of times (this is not the case if lazy evaluation was employed). - On the other hand, if ``x`` is strict, it is always evaluated once, which is at most one more time than what is necessary. - -Flags -------------------------------------------------- - -GHC has a variety of optimization flags, many of which are on by default. -Although Plutus Tx is, syntactically, a subset of Haskell, it has different semantics and a different evaluation strategy (Haskell: non-strict semantics, call by need; Plutus Tx: strict semantics, call by value). -As a result, some GHC optimizations are not helpful for Plutus Tx programs, and can even be harmful, in the sense that it can make Plutus Tx programs less efficient, or fail to be compiled. -An example is the full laziness optimization, controlled by GHC flag ``-ffull-laziness``, which floats let bindings out of lambdas whenever possible. -Since Untyped Plutus Core does not employ lazy evaluation, the full laziness optimization is usually not beneficial, and can sometimes make a Plutus Tx program more expensive. -Conversely, some GHC features must be turned on in order to ensure Plutus Tx programs are compiled successfully. - -All Plutus Tx modules should use the following GHC flags: :: - - -fno-ignore-interface-pragmas - -fno-omit-interface-pragmas - -fno-full-laziness - -fno-spec-constr - -fno-specialise - -fno-strictness - -fno-unbox-strict-fields - -fno-unbox-small-strict-fields - -``-fno-ignore-interface-pragmas`` and ``-fno-omit-interface-pragmas`` ensure unfoldings of Plutus Tx functions are available. -The rest are GHC optimizations that are generally bad for Plutus Tx, and should thus be turned off. - -These flags can be specified either in a Haskell module, e.g.: :: - - {-# OPTIONS_GHC -fno-ignore-interface-pragmas #-} - -or in a build file. E.g., if your project is built using Cabal, you can add the flags to the ``.cabal`` files, like so: - - ghc-options: - -fno-ignore-interface-pragmas - -Note that this section only covers GHC flags, not Plutus Tx compiler flags. -Information about the latter can be found in :ref:`plutus_tx_options`. - -Pragmas -------------------------------------------------- - -All functions and methods should have the ``INLINEABLE`` pragma, so that their unfoldings are made available to the Plutus Tx compiler. - -The ``-fexpose-all-unfoldings`` flag also makes GHC expose all unfoldings, but unfoldings exposed this way can be more optimized than unfoldings exposed via ``INLINEABLE``. -In general we do not want GHC to perform optimizations, since GHC optimizes a program based on the assumption that it has non-strict semantics and is evaluated lazily (call by need), which is not true for Plutus Tx programs. -Therefore, ``INLINEABLE`` is preferred over ``-fexpose-all-unfoldings`` even though the latter is simpler. - -``-fexpose-all-unfoldings`` can be useful for functions that are generated by GHC and do not have the ``INLINEABLE`` pragma. -``-fspecialise`` and ``-fspec-constr`` are two examples of optimizations that can generate such functions. -The most reliable solution, however, is to simply turn these optimizations off. -Another option is to bump ``-funfolding-creation-threshold`` to make it more likely for GHC to retain unfoldings for functions without the ``INLINEABLE`` pragma. -``-fexpose-all-unfoldings`` should be used as a last resort. diff --git a/doc/read-the-docs-site/exts/hs_domain.py b/doc/read-the-docs-site/exts/hs_domain.py deleted file mode 100644 index dc7a8d40277..00000000000 --- a/doc/read-the-docs-site/exts/hs_domain.py +++ /dev/null @@ -1,28 +0,0 @@ -# This is a copy of the one from the module, it's here so that -# it's easier for people not using Nix to build the site. - -from sphinxcontrib.domaintools import * - -def hs_domain(): - return custom_domain('HaskellDomain', - name = 'hs', - label = "Haskell", - - elements = dict( - hsobj = dict( - objname = "Haskell entity", - ), - hstype = dict( - objname = "Haskell type", - ), - hsval = dict( - objname = "Haskell value", - ), - hsmod = dict( - objname = "Haskell module", - ), - ) - ) - -def setup(app): - app.add_domain(hs_domain()) diff --git a/doc/read-the-docs-site/howtos/Cip57Blueprint.hs b/doc/read-the-docs-site/howtos/Cip57Blueprint.hs deleted file mode 100644 index ebf255e5b2a..00000000000 --- a/doc/read-the-docs-site/howtos/Cip57Blueprint.hs +++ /dev/null @@ -1,164 +0,0 @@ --- BEGIN pragmas -{-# LANGUAGE DataKinds #-} -{-# LANGUAGE DeriveAnyClass #-} -{-# LANGUAGE DerivingStrategies #-} -{-# LANGUAGE FlexibleInstances #-} -{-# LANGUAGE GADTs #-} -{-# LANGUAGE KindSignatures #-} -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE RecordWildCards #-} -{-# LANGUAGE ScopedTypeVariables #-} -{-# LANGUAGE StandaloneDeriving #-} -{-# LANGUAGE Strict #-} -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE TypeApplications #-} -{-# LANGUAGE UndecidableInstances #-} -{-# LANGUAGE ViewPatterns #-} -{-# OPTIONS_GHC -Wno-missing-signatures #-} - --- END pragmas - -module Cip57Blueprint where - --- BEGIN imports -import PlutusTx.Blueprint - -import Data.ByteString (ByteString) -import Data.Kind (Type) -import Data.List.NonEmpty (NonEmpty) -import Data.Set (Set) -import Data.Set qualified as Set -import Data.Text (Text) -import GHC.Generics (Generic) -import PlutusLedgerApi.V3 (BuiltinData, ScriptContext, UnsafeFromData (..)) -import PlutusTx.Blueprint.TH (makeIsDataSchemaIndexed) -import PlutusTx.Lift (makeLift) -import PlutusTx.Prelude (BuiltinUnit, check) - --- END imports --- BEGIN MyParams annotations - -{-# ANN MkMyParams (SchemaTitle "Title for the MyParams definition") #-} -{-# ANN MkMyParams (SchemaDescription "Description for the MyParams definition") #-} - --- END MyParams annotations --- BEGIN MyRedeemer annotations - -{-# ANN R1 (SchemaComment "Left redeemer") #-} -{-# ANN R2 (SchemaComment "Right redeemer") #-} - --- END MyRedeemer annotations --- BEGIN interface types - -type MyDatum = Integer - -data MyRedeemer = R1 | R2 - -data MyParams = MkMyParams - { myBool :: Bool - , myInteger :: Integer - } - -$(makeLift ''MyParams) - --- END interface types --- BEGIN makeIsDataSchemaIndexed MyParams - -$(makeIsDataSchemaIndexed ''MyParams [('MkMyParams, 0)]) -$(makeIsDataSchemaIndexed ''MyRedeemer [('R1, 0), ('R2, 1)]) - --- END makeIsDataSchemaIndexed MyParams --- BEGIN generic instances - -deriving stock instance (Generic MyParams) -deriving stock instance (Generic MyRedeemer) - --- END generic instances --- BEGIN AsDefinitionId instances - -deriving anyclass instance (AsDefinitionId MyParams) -deriving anyclass instance (AsDefinitionId MyRedeemer) - --- END AsDefinitionId instances --- BEGIN validator - -typedValidator :: MyParams -> MyDatum -> MyRedeemer -> ScriptContext -> Bool -typedValidator MkMyParams{..} datum redeemer _scriptContext = - case redeemer of - R1 -> myBool - R2 -> myInteger == datum - -untypedValidator :: MyParams -> BuiltinData -> BuiltinData -> BuiltinData -> BuiltinUnit -untypedValidator params datum redeemer scriptContext = - check $ typedValidator params datum' redeemer' scriptContext' - where - datum' = unsafeFromBuiltinData datum - redeemer' = unsafeFromBuiltinData redeemer - scriptContext' = unsafeFromBuiltinData scriptContext - --- END validator --- BEGIN contract blueprint declaration - -myContractBlueprint :: ContractBlueprint -myContractBlueprint = - MkContractBlueprint - { contractId = Just "my-contract" - , contractPreamble = myPreamble -- defined below - , contractValidators = Set.singleton myValidator -- defined below - , contractDefinitions = deriveDefinitions @[MyParams, MyDatum, MyRedeemer] - } - --- END contract blueprint declaration --- BEGIN preamble declaration - -myPreamble :: Preamble -myPreamble = - MkPreamble - { preambleTitle = "My Contract" - , preambleDescription = Just "A simple contract" - , preambleVersion = "1.0.0" - , preamblePlutusVersion = PlutusV2 - , preambleLicense = Just "MIT" - } - --- END preamble declaration --- BEGIN validator blueprint declaration - -myValidator = - MkValidatorBlueprint - { validatorTitle = "My Validator" - , validatorDescription = Just "An example validator" - , validatorParameters = - [ MkParameterBlueprint - { parameterTitle = Just "My Validator Parameters" - , parameterDescription = Just "Compile-time validator parameters" - , parameterPurpose = Set.singleton Spend - , parameterSchema = definitionRef @MyParams - } - ] - , validatorRedeemer = - MkArgumentBlueprint - { argumentTitle = Just "My Redeemer" - , argumentDescription = Just "A redeemer that does something awesome" - , argumentPurpose = Set.fromList [Spend, Mint] - , argumentSchema = definitionRef @MyRedeemer - } - , validatorDatum = - Just - MkArgumentBlueprint - { argumentTitle = Just "My Datum" - , argumentDescription = Just "A datum that contains something awesome" - , argumentPurpose = Set.singleton Spend - , argumentSchema = definitionRef @MyDatum - } - , validatorCompiledCode = Nothing -- you can optionally provide the compiled code here - } - --- END validator blueprint declaration --- BEGIN write blueprint to file - --- >>> writeBlueprintToFile "plutus.json" -writeBlueprintToFile :: FilePath -> IO () -writeBlueprintToFile path = writeBlueprint path myContractBlueprint - --- END write blueprint to file diff --git a/doc/read-the-docs-site/howtos/asdata.rst b/doc/read-the-docs-site/howtos/asdata.rst deleted file mode 100644 index 4372aaf6869..00000000000 --- a/doc/read-the-docs-site/howtos/asdata.rst +++ /dev/null @@ -1,128 +0,0 @@ -.. highlight:: haskell -.. _asdata: - -How to use ``AsData`` to optimize scripts -========================================= - -The Plutus libraries contain a ``PlutusTx.asData`` module that contains Template Haskell (TH) code for encoding algebraic data types (ADTs) as ``Data`` objects in Plutus Core, as opposed to sums-of-products terms. -In general, ``asData`` pushes the burden of a computation nearer to where a value is used, in a crude sense making the evaluation less strict and more lazy. -This is intended for expert Plutus developers. - -Purpose -------- - -Values stored in datums or redeemers need to be encoded into ``Data`` objects. -When writing and optimizing a Plutus script, one of the challenges is finding the right approach to handling ``Data`` objects and how expensive that method will be. -To make an informed decision, you may need to benchmark and profile your smart contract code to measure its actual resource consumption. -The primary purpose of ``asData`` is to give you more options for how you want to handle ``Data``. - -Choice of two approoaches -------------------------- - -When handling ``Data`` objects, you have a choice of two pathways. -It is up to you to determine which pathway to use depending on your particular use case. -There are trade offs in performance and where errors occur. - -Approach one: proactively do all of the parsing -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The first approach is to parse the object immediately (using ``fromBuiltinData``) into a native Plutus Core datatype, which will also identify any problems with the structuring of the object. -However, this performs all the work up front. - -This is the normal style that has been promoted in the past. - -Approach two: only do the parsing if and when necessary -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -In the second approach, the script doesn't do any parsing work immediately, and instead does it later, when it needs to. -It might be that this saves you a lot of work, because you may never need to parse the entire object. -Instead, the script will just carry the item around as a ``Data`` object. - -Using this method, every time the script uses the object, it will look at it to find out if it has the right shape. -If it does have the right shape, it will deconstruct the ``Data`` object and do its processing; if not, it will throw an error. -This work may be repeated depending on how your script is written. -In some cases, you might do less work, in some cases you might do more work, depending on your specific use case. - -The Plutus Tx library provides some helper functions to make this second style easier to do, in the form of the ``asData`` function. - -Using ``asData`` ------------------- - -The ``asData`` function takes the definition of a data type and replaces it with an equivalent definition whose representation uses ``Data`` directly. - -For example, if we wanted to use it on the types from the :ref:`auction example<simple_example>`, we would put the datatype declarations inside a Template Haskell quote and call ``asData`` on it. - -.. literalinclude:: ../tutorials/AuctionValidator.hs - :start-after: BLOCK9 - :end-before: BLOCK10 - -This is normal Template Haskell that just generates new Haskell source, so you can see the code that it generates with `{-# OPTIONS_GHC -ddump-splices #-}`, but it will look something like this: - -.. code-block:: - - PlutusTx.asData - [d| data Bid' - = Bid' {bBidder' :: PubKeyHash, bAmount' :: Lovelace} - deriving newtype (Eq, Ord, ToBuitinData, FromBuiltinData, UnsafeFromBuiltinData) - data AuctionRedeemer' = NewBid' Bid | Payout' - deriving newtype (Eq, Ord, ToBuitinData, FromBuiltinData, UnsafeFromBuiltinData) |] - - ======> - - newtype Bid' = Bid'2 BuiltinData - deriving newtype (Eq, Ord, PlutusTx.ToData, FromData, UnsafeFromData) - - {-# COMPLETE Bid' #-} - pattern Bid' :: PubKeyHash -> Lovelace -> Bid' - pattern Bid' ... - - newtype AuctionRedeemer' = AuctionRedeemer'2 BuiltinData - deriving newtype (Eq, Ord, PlutusTx.ToData, FromData, UnsafeFromData) - - {-# COMPLETE NewBid', Payout' #-} - pattern NewBid' :: Bid -> AuctionRedeemer' - pattern NewBid' ... - pattern Payout' :: AuctionRedeemer' - pattern Payout' ... - -That is: - -- It creates a newtype wrapper around ``BuiltinData`` -- It creates pattern synonyms corresponding to each of the constructors you wrote - -This lets you write code "as if" you were using the original declaration that you wrote, while in fact the pattern synonyms are handling conversion to/from ``Data`` for you. -But any values of this type actually are represented with ``Data``. -That means that when we newtype-derive the instances for converting to and from ``Data`` we get the instances for ``BuiltinData`` - which are free! - -Nested fields -~~~~~~~~~~~~~ - -The most important caveat to using ``asData`` is that ``Data`` objects encoding datatypes must also encode the *fields* of the datatype as ``Data``. -However, ``asData`` tries to make the generated code a drop-in replacement for the original code, which means that when using the pattern synonyms they try to give you the fields as they were originally defined, which means *not* encoded as ``Data``. - -For example, in the ``Bid`` case above the ``bAmount`` field is originally defined to have type ``Lovelace`` which is a newtype around a Plutus Core builtin integer. -However, since we are using ``asData``, we need to encode the field into ``Data`` in order to store it. -That means that when you construct a ``Bid`` object you must take the ``Integer`` that you start with and convert it to ``Data``, and when you pattern match on a ``Bid`` object you do the reverse conversion. - -These conversions are potentially expensive! -If the ``bAmount`` field was a complex data structure, then every time we constructed or deconstructed a ``Bid`` object we would need to convert that datastructure to or from ``Data``. -Whether or not this is a problem depends on the precise situation, but in general: - -- If the field is a builtin integer or bytestring or a wrapper around those, it is probably cheap -- If the field is a datatype which is itself defined with ``asData`` then it is free (since it's already ``Data``!) -- If the field is a complex or large datatype then it is potentially expensive - -Therefore ``asData`` tends to work best when you use it for a type and also for all the types of its fields. - -Choosing an approach --------------------- - -There are a number of tradeoffs to consider: - -1. Plutus Tx's datatypes are faster to work with and easier to optimize than ``Data``, so if the resulting object is going to be processed in its entirety (or have parts of it repeatedly processed) then it can be better to parse it up-front. -2. If it is important to check that the entire structure is well-formed, then it is better to parse it up-front, since the conversion will check the entire structure for well-formedness immediately, rather than checking only the parts that are used when they are used. -3. If you do not want to use ``asData`` for the types of the fields, then it may be better to not use it at all in order to avoid conversion penalties at the use sites. - -Which approach is better is an empirical question and may vary in different cases. -A single script may wish to use different approaches in different places. -For example, your datum might contain a large state object which is usually only inspected in part (a good candidate for ``asData``), whereas your redeemer might be a small object which is inspected frequently to determine what to do (a good candidate for a native Plutus Tx datatype). diff --git a/doc/read-the-docs-site/howtos/exporting-a-blueprint.rst b/doc/read-the-docs-site/howtos/exporting-a-blueprint.rst deleted file mode 100644 index a48da0cb28a..00000000000 --- a/doc/read-the-docs-site/howtos/exporting-a-blueprint.rst +++ /dev/null @@ -1,310 +0,0 @@ -.. highlight:: haskell -.. _exporting_a_blueprint: - -How to produce a Plutus Contract Blueprint -========================================== - -Plutus Contract Blueprints (`CIP-0057`_) are used to document the binary interface of a -Plutus contract in a machine-readable format (JSON schema). - -A contract Blueprint can be produced by using the -`writeBlueprint` function exported by the `PlutusTx.Blueprint` module:: - - writeBlueprint - :: FilePath - -- ^ The file path where the blueprint will be written to, - -- e.g. '/tmp/plutus.json' - -> ContractBlueprint - -- ^ Contains all the necessary information to generate - -- a blueprint for a Plutus contract. - -> IO () - -In order to demonstrate the usage of the `writeBlueprint` function, -Let's consider the following example validator function and its interface: - -.. literalinclude:: Cip57Blueprint.hs - :start-after: BEGIN interface types - :end-before: END interface types - -.. literalinclude:: Cip57Blueprint.hs - :start-after: BEGIN validator - :end-before: END validator - -First of all we need to import required functionality: - -.. literalinclude:: Cip57Blueprint.hs - :start-after: BEGIN imports - :end-before: END imports - -Next we define a contract blueprint value of the following type: - -.. code-block:: haskell - - data ContractBlueprint where - MkContractBlueprint - :: forall referencedTypes - . { contractId :: Maybe Text - -- ^ An optional identifier for the contract. - , contractPreamble :: Preamble - -- ^ An object with meta-information about the contract. - , contractValidators :: Set (ValidatorBlueprint referencedTypes) - -- ^ A set of validator blueprints that are part of the contract. - , contractDefinitions :: Definitions referencedTypes - -- ^ A registry of schema definitions used across the blueprint. - } - -> ContractBlueprint - -.. note:: - - The 'referencedTypes' type parameter is used to track the types used in the contract - making sure their schemas are included in the blueprint and that they are referenced - in a type-safe way. - - The blueprint will contain JSON schema definitions for all the types used in the contract, - including the types **nested** within the top-level types (`MyParams`, `MyDatum`, `MyRedeemer`): - - * ``Integer`` - nested within `MyDatum` and `MyParams`. - * ``Bool`` - nested within `MyParams`. - - This way, the `referencedTypes` type variable is inferred to be the following list: - - .. code-block:: haskell - - '[ MyParams -- top-level type - , MyDatum -- top-level type - , MyRedeemer -- top-level type - , Integer -- nested type - , Bool -- nested type - ] - -We can construct a value of this type like in this: - -.. literalinclude:: Cip57Blueprint.hs - :start-after: BEGIN contract blueprint declaration - :end-before: END contract blueprint declaration - -The `contractId` field is optional and can be used to give a unique identifier to the contract. - -The `contractPreamble` field is a value of type `PlutusTx.Blueprint.Preamble` -contains a meta-information about the contract: - -.. code-block:: haskell - - data Preamble = MkPreamble - { preambleTitle :: Text - -- ^ A short and descriptive title of the contract application - , preambleDescription :: Maybe Text - -- ^ A more elaborate description - , preambleVersion :: Text - -- ^ A version number for the project. - , preamblePlutusVersion :: PlutusVersion - -- ^ The Plutus version assumed for all validators - , preambleLicense :: Maybe Text - -- ^ A license under which the specification - -- and contract code is distributed - } - -Here is an example construction: - -.. literalinclude:: Cip57Blueprint.hs - :start-after: BEGIN preamble declaration - :end-before: END preamble declaration - -The ``contractDefinitions`` field is a registry of schema definitions used across the blueprint. -It can be constructed using the ``deriveDefinitions`` function which automatically -constructs schema definitions for all the types its applied to inluding the types -nested within them. - -Since every type in the ``referencedTypes`` list is going to have its derived JSON-schema in the -``contractDefinitions`` registry under a certain unique ``DefinitionId`` key, we need to make sure -that it has: - -* an instance of the ``GHC.Generics.Generic`` type class: - - .. literalinclude:: Cip57Blueprint.hs - :start-after: BEGIN generic instances - :end-before: END generic instances - -* an instance of the ``AsDefinitionId`` type class. Most of the times it could be derived - generically with the ``anyclass`` strategy, for example: - - .. literalinclude:: Cip57Blueprint.hs - :start-after: BEGIN AsDefinitionId instances - :end-before: END AsDefinitionId instances - -* an instance of the ``HasSchema`` type class. If your validator exposes standard supported types - like ``Integer`` or ``Bool`` you don't need to define this instance. If your validator uses - custom types then you should be deriving it using the ``makeIsDataSchemaIndexed`` Template Haskell function, - which derives it alongside with the corresponding `ToBuiltinData`/`FromBuiltinData` instances, - for example: - - .. literalinclude:: Cip57Blueprint.hs - :start-after: BEGIN makeIsDataSchemaIndexed MyParams - :end-before: END makeIsDataSchemaIndexed MyParams - -Finally, we need to define a validator blueprint for each validator used in the contract. - -Our contract can contain one or more validators and for each one we need to provide -a description as a value of the following type: - - .. code-block:: haskell - - data ValidatorBlueprint (referencedTypes :: [Type]) = MkValidatorBlueprint - { validatorTitle :: Text - -- ^ A short and descriptive name for the validator. - , validatorDescription :: Maybe Text - -- ^ An informative description of the validator. - , validatorRedeemer :: ArgumentBlueprint referencedTypes - -- ^ A description of the redeemer format expected by this validator. - , validatorDatum :: Maybe (ArgumentBlueprint referencedTypes) - -- ^ A description of the datum format expected by this validator. - , validatorParameters :: Maybe (NonEmpty (ParameterBlueprint referencedTypes)) - -- ^ A list of parameters required by the script. - , validatorCompiledCode :: Maybe ByteString - -- ^ A full compiled and CBOR-encoded serialized flat script. - } - -In our example this would be: - -.. literalinclude:: Cip57Blueprint.hs - :start-after: BEGIN validator blueprint declaration - :end-before: END validator blueprint declaration - -The ``definitionRef`` function is used to reference a schema definition of a given type. It is -smart enough to discover the schema definition from the ``referencedType`` list and -fails to compile if the referenced type is not included. - -With all the pieces in place, we can now write the blueprint to a file: - -.. literalinclude:: Cip57Blueprint.hs - :start-after: BEGIN write blueprint to file - :end-before: END write blueprint to file - -Annotations ------------ - -Any `CIP-0057`_ blueprint type definition may include `optional keywords`_ to provide -additional information: - -* title -* description -* $comment - -Its possible to add these keywords to a Blueprint type definition by annotating the -Haskell type from which its derived with a corresponding annotation: - -* ``SchemaTitle`` -* ``SchemaDescription`` -* ``SchemaComment`` - -For example, to add a title and description to the ``MyParams`` type, -we can use the ``SchemaTitle`` and ``SchemaDescription`` annotations: - -.. literalinclude:: Cip57Blueprint.hs - :start-after: BEGIN MyParams annotations - :end-before: END MyParams annotations - -results in the following JSON schema definition: - -.. code-block:: json - - { - "title": "Title for the MyParams definition", - "description": "Description for the MyParams definition", - "dataType": "constructor", - "fields": [ - { "$ref": "#/definitions/Bool" }, - { "$ref": "#/definitions/Integer" } - ], - "index": 0 - } - -For sum-types its possible to annotate constructors: - -.. literalinclude:: Cip57Blueprint.hs - :start-after: BEGIN MyRedeemer annotations - :end-before: END MyRedeemer annotations - -to produce the JSON schema definition: - -.. code-block:: json - - { - "oneOf": [ - { - "$comment": "Left redeemer", - "dataType": "constructor", - "fields": [], - "index": 0 - }, - { - "$comment": "Right redeemer", - "dataType": "constructor", - "fields": [], - "index": 1 - } - ] - } - -It is also possible to annotate validator's parameter or argument **type** -(as opposed to annotating *constructors*): - -.. code-block:: haskell - - {-# ANN type MyParams (SchemaTitle "Example parameter title") #-} - {-# ANN type MyRedeemer (SchemaTitle "Example redeemer title") #-} - -and then instead of providing them literally - -.. code-block:: haskell - - myValidator = - MkValidatorBlueprint - { ... elided - , validatorParameters = - [ MkParameterBlueprint - { parameterTitle = Just "My Validator Parameters" - , parameterDescription = Just "Compile-time validator parameters" - , parameterPurpose = Set.singleton Spend - , parameterSchema = definitionRef @MyParams - } - ] - , validatorRedeemer = - MkArgumentBlueprint - { argumentTitle = Just "My Redeemer" - , argumentDescription = Just "A redeemer that does something awesome" - , argumentPurpose = Set.fromList [Spend, Mint] - , argumentSchema = definitionRef @MyRedeemer - } - , ... elided - } - -use TH to have a more concise version : - -.. code-block:: haskell - - myValidator = - MkValidatorBlueprint - { ... elided - , validatorParameters = - [ $(deriveParameterBlueprint ''MyParams (Set.singleton Purpose.Spend)) ] - , validatorRedeemer = - $(deriveArgumentBlueprint ''MyRedeemer (Set.fromList [Purpose.Spend, Purpose.Mint])) - , ... elided - } - - -Result ------- - -Here is the full `CIP-0057`_ blueprint produced by this "howto" example: - -.. literalinclude:: plutus.json - -.. note:: - You can find a more elaborate example of a contract blueprint in the ``Blueprint.Tests`` - module of the plutus repository. - -.. _CIP-0057: https://cips.cardano.org/cip/CIP-0057 -.. _optional keywords: https://cips.cardano.org/cip/CIP-0057#for-any-data-type - diff --git a/doc/read-the-docs-site/howtos/exporting-a-script.rst b/doc/read-the-docs-site/howtos/exporting-a-script.rst deleted file mode 100644 index b888aec959c..00000000000 --- a/doc/read-the-docs-site/howtos/exporting-a-script.rst +++ /dev/null @@ -1,46 +0,0 @@ -.. highlight:: haskell -.. _exporting_a_script: - -How to export scripts, datums and redeemers -=========================================== - -.. note:: - This guide uses the scripts from the :ref:`basic validators tutorial <basic_validators_tutorial>`. - -Since scripts must match their on-chain hashes exactly, it is important that the -scripts which an application uses do not accidentally change. For example, changing -the source code or updating dependencies or tooling may lead to small changes in -the script. As a result, the hash will change. In cases where the hashes must match -exactly, even changes which do not alter the functionality of the script can be problematic. - -For this reason, once you expect that you will not modify the on-chain part of your application more, it is sensible to *freeze* it by saving the final Plutus Core to a file. - -Additionally, while most Plutus Applications use scripts by directly submitting them as part of transactions from the application itself, it can be useful to be able to export a serialized script. -For example, you might want to submit it as part of a manually created transaction with the Cardano node CLI, or send it to another party for them to use. - -Fortunately, it is quite simple to do this. -Most of the types have typeclass instances for ``Serialise`` which allows translating directly into CBOR. -This applies to ``Validator``, ``Redeemer``, and ``Datum`` types. -If you want to create values that you can pass to the Cardano CLI, you will need to convert them to the appropriate types from ``cardano-api`` and use ``serialiseToTextEnvelope``. - -.. literalinclude:: ../tutorials/BasicValidators.hs - :start-after: BLOCK5 - :end-before: BLOCK6 - -``CompiledCode`` has a different serialization method, ``Flat``, but the principle is the same. - -The serialized form of ``CompiledCode`` can also be dumped using a plugin option: - -.. code-block:: haskell - - {-# OPTIONS_GHC -fplugin-opt PlutusTx.Plugin:dump-uplc #-} - -This will dump the output to a temporary file with a name based on the module name. -The filename will be printed to the console when compiling the source file. -You can then move it to a more permanent location. - -It can be read in conveniently with ``loadFromFile`` as an alternative to ``compile``. - -.. literalinclude:: ../tutorials/BasicValidators.hs - :start-after: BLOCK6 - :end-before: BLOCK7 diff --git a/doc/read-the-docs-site/howtos/index.rst b/doc/read-the-docs-site/howtos/index.rst deleted file mode 100644 index 270e01c3280..00000000000 --- a/doc/read-the-docs-site/howtos/index.rst +++ /dev/null @@ -1,13 +0,0 @@ -.. _plutus_howtos: - -How-to guides -============= - -.. toctree:: - :maxdepth: 3 - :titlesonly: - - asdata - exporting-a-script - exporting-a-blueprint - profiling-scripts diff --git a/doc/read-the-docs-site/howtos/myscript.uplc b/doc/read-the-docs-site/howtos/myscript.uplc deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/doc/read-the-docs-site/howtos/profiling-scripts.rst b/doc/read-the-docs-site/howtos/profiling-scripts.rst deleted file mode 100644 index 37ccf4bc125..00000000000 --- a/doc/read-the-docs-site/howtos/profiling-scripts.rst +++ /dev/null @@ -1,64 +0,0 @@ -.. highlight:: haskell -.. _profiling_scripts: - -How to profile the budget usage of Plutus scripts -================================================= - -Figuring out why your script takes more CPU or memory units than you expect can be tricky. -You can find out more detail about how these resources are being used in your script by *profiling* it, and viewing the results in a flamegraph. - -Compiling a script for profiling --------------------------------- - -Profiling requires compiling your script differently so that it will emit information that we can use to analyse its performance. - -.. note:: As with profiling in other languages, this additional instrumentation can affect how your program is optimized, so its behaviour may not be identical to the non-profiled version. - -To do this, you need to give a couple of options to the Plutus Tx plugin in the source file where your script is compiled. - -.. code-block:: haskell - - {-# OPTIONS_GHC -fplugin-opt PlutusTx.Plugin:profile-all #-} - {-# OPTIONS_GHC -fplugin-opt PlutusTx.Plugin:conservative-optimisation #-} - -This instructs the plugin to insert profiling instrumentation for all functions. -In the future there may be the option to profile a more targeted set of functions. -It also makes sure that any inserted profiling instrumentation code would not be optimized away during PlutusTx compilation. - -Acquiring an executable script ------------------------------- - -Profiling works by seeing how the budget is used as the script runs. -It therefore requires an executable script, which means that you need not only the validator script but all the arguments it receives. -You can get this fully-applied script from the emulator or from the Cardano node. - -Running the script ------------------- - -You can run the script with the ``uplc`` executable. - -.. note:: All the executables referred to here can be built from the ``plutus`` repository using ``cabal build``. - -.. code-block:: bash - - uplc evaluate -i myscript.flat --if flat --trace-mode LogsWithBudgets -o logs - -This runs the script using the trace mode that emits budget information, and puts the resulting logs in a file. -This will be a CSV file with three columns: a message indicating which function we are entering or exiting; the cumulative CPU used at that time; and the cumulative memory used at that time. - -Analysing the results ---------------------- - -We can then convert the logs into a flamegraph using the standard ``flamegraph.pl`` tool. -The ``traceToStacks`` executable turns the logs into a format that ``flamegraph.pl`` understands - -.. code-block:: bash - - cat logs | traceToStacks | flamegraph.pl > cpu.svg - cat logs | traceToStacks --column 2 | flamegraph.pl > mem.svg - -Since ``flamegraph.pl`` can only handle one metric at a time, ``traceToStacks`` has a ``--column`` argument to select the other column if you want to get a memory flamegraph. - -You can then view the resulting SVGs in a viewer of your choice, e.g. a web browser. - -Alternatively, there are other, more powerful, tools that understand the format produced by ``traceToStacks``, such as `speedscope <https://www.speedscope.app/>`_. diff --git a/doc/read-the-docs-site/index.rst b/doc/read-the-docs-site/index.rst deleted file mode 100644 index 3b7013904ce..00000000000 --- a/doc/read-the-docs-site/index.rst +++ /dev/null @@ -1,58 +0,0 @@ -Plutus Core and Plutus Tx user guide -================================================== - -Plutus Core ---------------------- - -The Plutus project consists of Plutus Core, the programming language used for -scripts on Cardano; tooling and compilers for compiling various intermediate -languages into Plutus Core; and Plutus Tx, the compiler that compiles the Haskell -source code into Plutus Core to form the on-chain part of a contract application. -All of this is used in combination to write Plutus Core scripts that run on the -Cardano blockchain. - -This documentation introduces the Plutus Core programming language and programming -with Plutus Tx. It includes explanations, tutorials, how-to instructions, -troubleshooting, and reference information. - -The intended audience of this documentation includes people who want to implement -smart contracts on the Cardano blockchain. This involves using Plutus Tx to write -scripts, requiring some knowledge of the Haskell programming language. - -This guide is also meant for certification companies, certification auditors, -and people who need an accurate specification. See, for example: - -* the `Cardano Ledger Specification <https://github.com/IntersectMBO/cardano-ledger#cardano-ledger>`_ and -* the `Plutus Core Specification <https://github.com/IntersectMBO/plutus#specifications-and-design>`_. - -The Plutus repository ----------------------------------- - -The `Plutus repository <https://github.com/IntersectMBO/plutus>`_ contains -the implementation, specification, and mechanized metatheory of Plutus Core. -It also contains the Plutus Tx compiler and the libraries, such as ``PlutusTx.List``, -for writing Haskell code that can be compiled to Plutus Core. - -.. toctree:: - :caption: Explore Plutus - :maxdepth: 2 - - explanations/index - simple-example - quick-start - extensions-flags-pragmas - tutorials/index - howtos/index - troubleshooting - -.. toctree:: - :caption: Architectural decision records - :maxdepth: 1 - - adr/index - -.. toctree:: - :caption: Reference - :maxdepth: 2 - - reference/index diff --git a/doc/read-the-docs-site/plutus-doc.cabal b/doc/read-the-docs-site/plutus-doc.cabal deleted file mode 100644 index c57a7650bbf..00000000000 --- a/doc/read-the-docs-site/plutus-doc.cabal +++ /dev/null @@ -1,105 +0,0 @@ -cabal-version: 2.2 -name: plutus-doc -version: 0.1.0.0 -license: Apache-2.0 -license-files: - LICENSE - NOTICE - -maintainer: jann.mueller@iohk.io -author: Michael Peyton Jones, Jann Mueller -synopsis: Plutus documentation -description: Plutus documentation -category: Language -build-type: Simple - -source-repository head - type: git - location: https://github.com/IntersectMBO/plutus - -common lang - default-language: Haskell2010 - default-extensions: - DeriveFoldable - DeriveFunctor - DeriveGeneric - DeriveLift - DeriveTraversable - ExplicitForAll - GeneralizedNewtypeDeriving - ImportQualifiedPost - MultiParamTypeClasses - ScopedTypeVariables - StandaloneDeriving - - -- See Plutus Tx readme for why we need the following flags: - -- -fobject-code -fno-ignore-interface-pragmas and -fno-omit-interface-pragmas - ghc-options: - -Wall -Wnoncanonical-monad-instances -Wincomplete-uni-patterns - -Wincomplete-record-updates -Wredundant-constraints -Widentities - -fobject-code -fno-ignore-interface-pragmas - -fno-omit-interface-pragmas - -common ghc-version-support - -- See the section on GHC versions in CONTRIBUTING - if (impl(ghc <9.6) || impl(ghc >=9.7)) - buildable: False - -executable doc-doctests - import: lang, ghc-version-support - - if (impl(ghcjs) || os(windows)) - buildable: False - - hs-source-dirs: tutorials howtos - main-is: Main.hs - ghc-options: -Wno-unused-imports - build-tool-depends: doctest:doctest - other-modules: - AuctionValidator - BasicPlutusTx - BasicPolicies - BasicValidators - Cip57Blueprint - - build-depends: - , aeson - , base >=4.9 && <5 - , bytestring - , containers - , flat ^>=0.6 - , lens - , plutus-core ^>=1.30 - , plutus-ledger-api ^>=1.30 - , plutus-tx ^>=1.30 - , prettyprinter - , random - , serialise - , template-haskell >=2.13.0.0 - , text - - if !(impl(ghcjs) || os(ghcjs)) - build-depends: plutus-tx-plugin - -executable quick-start - import: lang, ghc-version-support - - if (impl(ghcjs) || os(windows)) - buildable: False - - hs-source-dirs: tutorials - main-is: QuickStart.hs - build-tool-depends: doctest:doctest - other-modules: AuctionValidator - build-depends: - , aeson - , base >=4.9 && <5 - , base16-bytestring - , bytestring - , plutus-core ^>=1.30 - , plutus-ledger-api ^>=1.30 - , plutus-tx ^>=1.30 - , plutus-tx-plugin ^>=1.30 - - if !(impl(ghcjs) || os(ghcjs)) - build-depends: plutus-tx-plugin diff --git a/doc/read-the-docs-site/quick-start.rst b/doc/read-the-docs-site/quick-start.rst deleted file mode 100644 index b1a03838f3a..00000000000 --- a/doc/read-the-docs-site/quick-start.rst +++ /dev/null @@ -1,10 +0,0 @@ -.. _quick_start: - -Quick Start -================================= - -The easiest way to create a Cardano smart contract is to use the `plutus-tx-template <https://github.com/IntersectMBO/plutus-tx-template>`_ repository template. - -Follow the instructions inside the `README.md` to setup your environment and run the example project. - -There are several other options for writing on-chain validators, such as `Aiken <https://aiken-lang.org/>`_ and `OpShin <https://github.com/OpShin/opshin>`_, and you can refer to their respective documentation for how to use them. diff --git a/doc/read-the-docs-site/reference/bibliography.rst b/doc/read-the-docs-site/reference/bibliography.rst deleted file mode 100644 index a5ef6e68180..00000000000 --- a/doc/read-the-docs-site/reference/bibliography.rst +++ /dev/null @@ -1,6 +0,0 @@ -.. _bibliography: - -Bibliography -============ - -.. bibliography:: ../bibliography.bib diff --git a/doc/read-the-docs-site/reference/cardano/cost-model-parameters.rst b/doc/read-the-docs-site/reference/cardano/cost-model-parameters.rst deleted file mode 100644 index 7fb37c213ee..00000000000 --- a/doc/read-the-docs-site/reference/cardano/cost-model-parameters.rst +++ /dev/null @@ -1,18 +0,0 @@ -.. _cost_model_parameters: - -Cost model parameters -===================== - -The cost model for Plutus Core scripts has a number of parameters. -These are listed and briefly described below. -All of these parameters are listed in the Cardano protocol parameters and can be individually adjusted. - -.. csv-table:: Machine parameters - :file: ./machine-parameters.csv - :widths: 20, 30, 40 - :header-rows: 1 - -.. csv-table:: Builtin parameters - :file: ./builtin-parameters.csv - :widths: 20, 30, 40 - :header-rows: 1 diff --git a/doc/read-the-docs-site/reference/cardano/index.rst b/doc/read-the-docs-site/reference/cardano/index.rst deleted file mode 100644 index 8922c53ef9c..00000000000 --- a/doc/read-the-docs-site/reference/cardano/index.rst +++ /dev/null @@ -1,10 +0,0 @@ -Plutus on Cardano -================= - -.. toctree:: - :maxdepth: 3 - :titlesonly: - - language-changes - upgr-vasil-plutus-script-addresses - cost-model-parameters diff --git a/doc/read-the-docs-site/reference/cardano/language-changes.rst b/doc/read-the-docs-site/reference/cardano/language-changes.rst deleted file mode 100644 index 047cf77917c..00000000000 --- a/doc/read-the-docs-site/reference/cardano/language-changes.rst +++ /dev/null @@ -1,100 +0,0 @@ -.. _plutus_language_changes: - -Plutus language changes -======================= - -Language versions ------------------ - -See the documentation on :ref:`language versions <what_are_plutus_language_versions>` for an explanation of what they are. - -PlutusV1 -~~~~~~~~~~ - -``PlutusV1`` was the initial version of Plutus, introduced in the Alonzo hard fork. - -PlutusV2 -~~~~~~~~~~ - -``PlutusV2`` was introduced in the Vasil hard fork. - -The main changes in ``PlutusV2`` were to the interface to scripts. -The ``ScriptContext`` was extended to include the following information: - -- The full "redeemers" structure, which contains all the redeemers used in the transaction -- Reference inputs in the transaction (proposed in `CIP-31 <https://cips.cardano.org/cips/cip31/>`_) -- Inline datums in the transaction (proposed in `CIP-32 <https://cips.cardano.org/cips/cip32/>`_) -- Reference scripts in the transaction (proposed in `CIP-33 <https://cips.cardano.org/cips/cip33/>`_) - -Examples ------------- - -- `PlutusV2 functionalities <https://github.com/input-output-hk/cardano-node-wiki/blob/main/docs/reference/plutus/babbage-script-example.md>`_ -- `How to use reference inputs <https://github.com/perturbing/vasil-tests/blob/main/reference-inputs-cip-31.md>`_ -- `How to use inline datums <https://github.com/perturbing/vasil-tests/blob/main/inline-datums-cip-32.md>`_ -- `How to reference scripts <https://github.com/perturbing/vasil-tests/blob/main/referencing-scripts-cip-33.md>`_ -- `How to use collateral outputs <https://github.com/perturbing/vasil-tests/blob/main/collateral-output-cip-40.md>`_ - -Built-in functions and types ----------------------------- - -Built-in functions and types can be introduced with just a hard fork. -In some cases they are also available only in particular language versions. -This section indicates in which hard fork particular built-ins were introduced, and any language version constraints. - -Alonzo -~~~~~~ - -This is when the majority of the built-in types and functions were added to ``PlutusV1``. -You can find an enumeration of them in :cite:t:`plutus-core-spec`. - -Vasil -~~~~~ - -All of the built-in types and functions from ``PlutusV1`` were added to ``PlutusV2``. - -The following built-in function was added to ``PlutusV2`` only (ie, it is not available in ``PlutusV1``). - -- ``serializeData`` (proposed in `CIP-42 <https://cips.cardano.org/cips/cip42/>`_) - -PlutusV3 -~~~~~~~~~ - -Plutus and cryptography teams at IOG, in collaboration with `MLabs <https://mlabs.city/>`_, continue to develop Plutus capabilities. Starting with the release of `Cardano node v.8.8.0-pre <https://github.com/IntersectMBO/cardano-node/releases/tag/8.8.0-pre>`_, ``PlutusV3`` is available on `SanchoNet <https://sancho.network/>`_, introducing the Cardano community to governance features from `CIP-1694 <https://cips.cardano.org/cip/CIP-1694#goal>`_ in a controlled testnet environment. - -``PlutusV3`` is the new ledger language that enhances Plutus Core's cryptographic capabilities, offering the following benefits for the smart contract developer community: - -- Providing an updated script context that will let users see `CIP-1694 <https://cips.cardano.org/cip/CIP-1694#goal>`_ governance-related entities and voting features -- Interoperability between blockchains -- Advanced Plutus primitives -- Well-known and optimal cryptographic algorithms -- Support for porting of smart contracts from Ethereum -- Creating sidechain bridges -- Improving performance by adding a sums of products (SOPs) feature to support the direct encoding of differrent data types. - -Sums of products -~~~~~~~~~~~~~~~~ - -``PlutusV3`` introduces sums of products - a way of encoding data types that leads to smaller and cheaper scripts compared with `Scott encoding <https://en.wikipedia.org/wiki/Mogensen%E2%80%93Scott_encoding>`_, a common way of encoding data types in Plutus Core. - -The sums of products approach aims to boost script efficiency and improve code generation for Plutus Core compilers. The changes involve new term constructors for packing fields into constructor values and efficient tag inspection for case branches, potentially running programs 30% faster. For an in-depth discussion, see `CIP-85 <https://cips.cardano.org/cip/CIP-0085>`_. - -New cryptographic primitives -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -``PlutusV3`` provides new built-in primitives that expand the language's capabilities. - -- **BLS12-381**: A curve pairing that includes 17 primitives that support cryptographic curves. This is a benefit to sidechain specification implementation and `Mithril <https://iohk.io/en/blog/posts/2023/07/20/mithril-nears-mainnet-release/>`_ integration. -- **Blake2b-224**: A cryptographic hash function for on-chain computation of public-key hashes for the validation of transaction signatures. Supports community projects and contributes to Cardano's versatility. -- **Keccak-256**: A cryptographic hash function that produces a 256-bit (32-byte) hash value, commonly used for secure data verification. Supports Ethereum signature verification within scripts and cross-chain solutions. - -Bitwise primitives -~~~~~~~~~~~~~~~~~~~ - -PlutusV3 initially brings several new bitwise primitives (with more to come at later stages). The introduction of `CIP-58 <https://cips.cardano.org/cip/CIP-0058>`_ bitwise primitives will enable the following features: - -- Very low-level bit manipulations within Plutus, supporting the ability to execute high-performance data manipulation operations. -- Supporting the implementation of secure and robust cryptographic algorithms within Plutus. -- Facilitating standard, high-performance implementations for conversions between integers and bytestrings. - -``PlutusV3`` adds two bitwise primitives: ``integerToByteString`` and ``byteStringToInteger``. The remaining primitives will be added to ``PlutusV3`` gradually and will not require a new ledger language. diff --git a/doc/read-the-docs-site/reference/cardano/upgr-vasil-plutus-script-addresses.rst b/doc/read-the-docs-site/reference/cardano/upgr-vasil-plutus-script-addresses.rst deleted file mode 100644 index 56f21b3608b..00000000000 --- a/doc/read-the-docs-site/reference/cardano/upgr-vasil-plutus-script-addresses.rst +++ /dev/null @@ -1,42 +0,0 @@ -.. _upgrading_to_vasil_and_plutus_script_addresses: - -Upgrading to Vasil and Plutus script addresses -==================================================== - -A Plutus V2 script will not have the same hash value as a Plutus V1 script ----------------------------------------------------------------------------------- - -DApp developers might expect that when doing a migration from ``PlutusV1`` scripts -to ``PlutusV2`` scripts, the same source code, when recompiled, will generate the -same hash value of that script address. However, it is impossible for a compiled -``PlutusV2`` script to have the same script hash and address as a compiled ``PlutusV1`` script. - -Using the exact same script with different language versions will result in different -hashes. The exact same script (as in ``UPLC.Program``) can be used as a ``PlutusV1`` script -or a ``PlutusV2`` script, and since the language version is part of the hash, the two -hashes will be different. - -A Plutus V1 script will not necessarily have the same hash value when recompiled with a later version of the Plutus Compiler ----------------------------------------------------------------------------------------------------------------------------------- - -Suppose you write your Haskell source code (Plutus Tx), compile it into Plutus Core -code (PLC), generate its hash value, then use it in a transaction. If you don’t save -your compiled code, and then decide to use the same script in the future, you would -have to recompile it. This could result in a different hash value of the script address -even without upgrading from ``PlutusV1`` to ``PlutusV2`` scripts. This is because the hash -is computed based on the output of the compiled code. - -Given Plutus compiler version changes, changes in the dependencies, and multiple -other improvements, it is expected that the hash value of the script address will -change after the source code is recompiled. - -When to export and save the output of a compiled script ---------------------------------------------------------------------- - -Once you expect that you will not modify the on-chain part of your application and -you don’t want the hash value of your script address to change, the best way to -keep it the same is to save the output of your final compiled Plutus Core code (PLC) -to a file. - -For details on how to export scripts, please see :doc:`How to export scripts, datums and -redeemers </howtos/exporting-a-script>`. diff --git a/doc/read-the-docs-site/reference/glossary.rst b/doc/read-the-docs-site/reference/glossary.rst deleted file mode 100644 index 46f82eda749..00000000000 --- a/doc/read-the-docs-site/reference/glossary.rst +++ /dev/null @@ -1,113 +0,0 @@ -.. _glossary: - -Glossary -======== - -.. glossary:: - address - The address of an UTXO says where the output is "going". - The address stipulates the conditions for unlocking the output. - This can be a public key hash, or (in the Extended UTXO model) a script hash. - - Cardano - The blockchain system upon which the Plutus Platform is built. - - currency - A class of token whose minting is controlled by a particular monetary policy script. - On the Cardano ledger there is a special currency called Ada which can never be minted and which is controlled separately. - - datum - The data field on script outputs in the Extended UTXO model. - - Extended UTXO Model - The ledger model which the Plutus Platform relies on. - - This is implemented in the Alonzo hard fork of the Cardano blockchain. - - See :ref:`what_is_a_ledger`. - - minting - A transaction which mints tokens creates new tokens, providing that the corresponding minting policy script is satisfied. - The amount minted can be negative, in which case the tokens will be destroyed instead of created. - - minting policy script - A script which must be satisfied in order for a transaction to mint tokens of the corresponding currency. - - Hydra - A Layer 2 scalability solution for Cardano. See :cite:t:`chakravarty2020hydra`. - - distributed ledger - ledger - See :ref:`what_is_a_ledger`. - - Marlowe - A domain-specific language for writing financial contract applications. - - multi-asset - A generic term for a ledger which supports multiple different asset types natively. - - off-chain code - The part of a contract application’s code which runs off the chain, usually as a contract application. - - on-chain code - The part of a contract application’s code which runs on the chain (i.e. as scripts). - - Plutus Core - The programming language in which scripts on the Cardano blockchain are written. - Plutus Core is a small functional programming language — a formal specification is available with further details. - Plutus Core is not read or written by humans, it is a compilation target for other languages. - - See :ref:`what_is_plutus_foundation`. - - Plutus IR - An intermediate language that compiles to Plutus Core. - Plutus IR is not used by users, but rather as a compilation target on the way to Plutus Core. - However, it is significantly more human-readable than Plutus Core, so should be preferred in cases where humans may want to inspect the program. - - Plutus Platform - The combined software support for writing contract applications, - including: - - 1. Plutus Foundation, and - - 2. The Plutus Application Framework - - See :ref:`what_is_the_plutus_platform`. - - Plutus Tx - The libraries and compiler for compiling Haskell into Plutus Core to form the on-chain part of a contract application. - - redeemer - The argument to the validator script which is provided by the transaction which spends a script output. - - rollback - The result of the local node switching to the consensus chain. - - script - A generic term for an executable program used in the ledger. - In the Cardano blockchain, these are written in Plutus Core. - - script context - A data structure containing a summary of the transaction being validated, as well as a way of identifying the current script being run. - - script output - A UTXO locked by a script. - - token - A generic term for a native tradeable asset in the ledger. - - transaction output - Outputs produced by transactions. - They are consumed when they are spent by another transaction. - Typically, some kind of evidence is required to be able to spend a UTXO, such as a signature from a public key, or (in the Extended UTXO Model) satisfying a script. - - UTXO - An unspent :term:`transaction output` - - utxo congestion - The effect of multiple transactions attempting to spend the same :term:`transaction output`. - - validator script - The script attached to a script output in the Extended UTXO model. - Must be run and return positively in order for the output to be spent. - Determines the address of the output. diff --git a/doc/read-the-docs-site/reference/index.rst b/doc/read-the-docs-site/reference/index.rst deleted file mode 100644 index 9943e2e6756..00000000000 --- a/doc/read-the-docs-site/reference/index.rst +++ /dev/null @@ -1,11 +0,0 @@ -Reference -========= - -.. toctree:: - :maxdepth: 3 - :titlesonly: - - writing-scripts/index - cardano/index - glossary - bibliography diff --git a/doc/read-the-docs-site/reference/writing-scripts/common-weaknesses/double-satisfaction.rst b/doc/read-the-docs-site/reference/writing-scripts/common-weaknesses/double-satisfaction.rst deleted file mode 100644 index 827f440cb51..00000000000 --- a/doc/read-the-docs-site/reference/writing-scripts/common-weaknesses/double-satisfaction.rst +++ /dev/null @@ -1,73 +0,0 @@ -Double satisfaction -=================== - -Suppose we have a validator V that implements a typical “atomic swap” or “escrowed swap” between A and B where A goes first, i.e. V says: - - This output can only be spent if, in the same transaction, there is an output sending the agreed-upon payment (encoded in the output’s datum) to A. - -Now suppose that A and B have two swaps in progress, one for a token T1 at the price of 10 Ada, and one for a token T2 at the same price. -That means that there will exist two outputs, both locked by V. - -Now B constructs a transaction which spends both outputs, and creates one output addressed to A with 10 Ada (taking T1 and T2 for himself). - -.. figure:: double-satisfaction.png - - A diagram showing the transaction setup for the double satisfaction of two swaps. - -A naive implementation of V will just check that the transaction has *an* output to A with 10 Ada in it, and then be satisfied. -But this allows B to "double satisfy" the two validators, because they will both see the same output and be satisfied. -The end result is that B can get away with paying only 10 Ada to A, even though B's true liability to A is 20 Ada! - -What is going wrong here? -~~~~~~~~~~~~~~~~~~~~~~~~~ - -It is difficult to say exactly what is going wrong here. -Neither validator’s expectations are explicitly being violated. - -One way of looking at it is that this is a consequence of the fact that validators only *validate*, rather than *doing* things. -In a model like Ethereum's, where smart contracts *make transfers*, then two smart contracts would simply make two transfers, and there would be no problem. -But in the EUTXO model all a validator can do is try to ascertain whether its wishes have been carried out, which in this case is ambiguous. - -Following this metaphor, we can see how the same problem could arise in the real world. -Suppose that two tax auditors from two different departments come to visit you in turn to see if you’ve paid your taxes. -You come up with a clever scheme to confuse them. -Your tax liability to both departments is $10, so you make a single payment to the tax office's bank account for $10. -When the auditors arrive, you show them your books, containing the payment to the tax office. -They both leave satisfied. - -How do we solve this problem in the real world? -Well, the two tax offices might have different bank accounts, but more likely they would simply require you to use two different payment references! -That way, the payment that each auditor expect to see is unique, so they know it's for them. -We can do something similar in the EUTXO model, see the section on `Unique outputs`_ below. - -Risks -~~~~~ - -This is a serious problem for many kinds of application. -Any application that makes payments to specific parties needs to ensure that those payments are correctly identified and don't overlap with other payments. - -Solutions -~~~~~~~~~ - -It's possible that a solution will be developed that makes this weakness easier to avoid. -In the mean time, there are workarounds that developers can use. - -Unique outputs --------------- - -The simplest workaround is to ensure that the outputs which your scripts care about are unique. -This prevents them being confused with other outputs. - -In the swap example, if A had used a different key hashes as their payment addresses in each, then one output could not have satisfied both validators, since each one would want an output addressed to a different key hash. - -It is not too difficult to use unique outputs. -For payments to users, wallets typically already generate unique key hashes for every payment received. -For payments to script addresses it is a bit more complicated, and applications may wish to include the equivalent of a "payment reference" in the datum to keep things unique. - -Ban other scripts ------------------ - -A more draconian workaround is to for your script to insist that it runs in a transaction which is running no other scripts, so there is no risk of confusion. -Note that it is not enough to consider just validator scripts, minting and reward scripts must also be banned. - -However, this prevents even benign usage of multiple scripts in one transaction, which stops people from designing interesting interactions, and may force users to break up transactions unnecessarily. diff --git a/doc/read-the-docs-site/reference/writing-scripts/common-weaknesses/hard-limits.rst b/doc/read-the-docs-site/reference/writing-scripts/common-weaknesses/hard-limits.rst deleted file mode 100644 index 3488bdc757a..00000000000 --- a/doc/read-the-docs-site/reference/writing-scripts/common-weaknesses/hard-limits.rst +++ /dev/null @@ -1,72 +0,0 @@ -Hard limits -=========== - -Many resources on Cardano are limited in some fashion. At a high level, limits can be enforced in two ways: - -- *Hard limits*: these are limits which cannot be breached. Typically, these are implemented with specific thresholds, where exceeding the threshold causes a hard failure. -- *Soft limits*: these are limits which *can* be breached, but where there is a significant disincentive to do so. One way of implementing a soft limit is to have sharply increasing costs to using the resource beyond the soft limit. - -Hard limits are clear, easy to specify, and provide hard guarantees for the protocol, but they have the disadvantage that there is no way to evade the limit. -This means that there is a discontinuity at the limit: beforehand you can always do more by paying more, but after the limit there is nothing you can do. - -Currently, these resources on Cardano have hard limits: - -- Transaction size -- Block size -- UTXO size -- Script execution units - -If an application *requires* a transaction that exceeds one of these limits, then the application will be stuck unless the limit is increased or removed. -This is most common when scripts are involved, since a script can require a very particular shape of transaction, regardless of whether this exceeds limits. - -Examples: - -- A script requires providing a datum which is extremely large and exceeds the transaction size limit. -- A script which locks an output needs more execution units than the limit. -- A script requires creating a single output containing a very large amount of tokens, which exceeds the output size limit. - -Risks -~~~~~ - -This is typically an issue for applications that work with user-supplied data, or data that can grow in an unbounded way over time. -This can result in data which itself becomes large, or which requires a large amount of resources to process. - -For example: - -- Managing an arbitrary collection of assets (unbounded over time). -- Allowing user-specified payloads in datums (user-supplied unbounded data). - -Script size should not itself be a risk (since scripts and their sizes should generally be known ahead of time), but large scripts can reduce the amount of space available for other uses, heightening the risk of hitting a limit. - -Solutions -~~~~~~~~~ - -In the long run, hard limits may be increased, removed, or turned into soft limits. - -In the mean time, there are some approaches that developers can use to reduce the risk. - -Careful testing ---------------- - -It is important to test as many of the execution paths of your application as possible. -This is important for correctness, but also to ensure that there are not unexpected cases where script resource usage spikes. - -Bounding data usage -------------------- - -Carefully consider whether your application may rely on unbounded data, and try to avoid that. -For example, if your application needs to manage a large quantity of assets, try to split them across multiple UTXOs instead of relying on a single UTXO to hold them all. - -Providing datums when creating outputs --------------------------------------- - -Datum size issues are most likely to be discovered when an output is spent, because the datum is provided only as a hash on the output. -Insisting that the datum is provided in the transaction that creates the output can reveal that it is too big earlier in the process, allowing another path to be taken. -Depending on the application, this may still prevent it from progressing, if there is only one way to move forwards. - -If `CIP-32 <https://cips.cardano.org/cips/cip32/>`_ is implemented, this can be done conveniently by using inline datums, although that also risks hitting the output size limit. - -Reducing script size costs through reference inputs ---------------------------------------------------- - -If `CIP-33 <https://cips.cardano.org/cips/cip33/>`_ is implemented, then the contribution of scripts to transaction size can be massively reduced by using a reference script instead of including the entire script. diff --git a/doc/read-the-docs-site/reference/writing-scripts/common-weaknesses/index.rst b/doc/read-the-docs-site/reference/writing-scripts/common-weaknesses/index.rst deleted file mode 100644 index c90254ee7a0..00000000000 --- a/doc/read-the-docs-site/reference/writing-scripts/common-weaknesses/index.rst +++ /dev/null @@ -1,12 +0,0 @@ -Common weaknesses -================= - -This section provides a listing of common *weaknesses* in Plutus applications. -"Weakness" is used in the sense of the `Common Weakness Enumeration <https://cwe.mitre.org/>`_), as a potential source of vulnerabilities in applications. - -.. toctree:: - :maxdepth: 3 - :titlesonly: - - double-satisfaction - hard-limits diff --git a/doc/read-the-docs-site/reference/writing-scripts/compiler-options-table.rst b/doc/read-the-docs-site/reference/writing-scripts/compiler-options-table.rst deleted file mode 100644 index 1636aac858e..00000000000 --- a/doc/read-the-docs-site/reference/writing-scripts/compiler-options-table.rst +++ /dev/null @@ -1,183 +0,0 @@ - -.. - This file is generated by running plutus-tx-plugin:gen-plugin-opts-doc. - Do not modify by hand. - -.. list-table:: - :header-rows: 1 - :widths: 35 15 15 50 - - * - Option - - Value Type - - Default - - Description - - - * - ``conservative-optimisation`` - - Bool - - False - - When conservative optimisation is used, only the optimisations that never make the program worse (in terms of cost or size) are employed. Implies ``no-relaxed-float-in``, ``no-inline-constants``, and ``preserve-logging``. - - - * - ``context-level`` - - Int - - 1 - - Set context level for error messages. - - - * - ``coverage-all`` - - Bool - - False - - Add all available coverage annotations in the trace output - - - * - ``coverage-boolean`` - - Bool - - False - - Add boolean coverage annotations in the trace output - - - * - ``coverage-location`` - - Bool - - False - - Add location coverage annotations in the trace output - - - * - ``defer-errors`` - - Bool - - False - - If a compilation error happens and this option is turned on, the compilation error is suppressed and the original Haskell expression is replaced with a runtime-error expression. - - - * - ``dump-compilation-trace`` - - Bool - - False - - Dump compilation trace for debugging - - - * - ``dump-pir`` - - Bool - - False - - Dump Plutus IR - - - * - ``dump-plc`` - - Bool - - False - - Dump Typed Plutus Core - - - * - ``dump-uplc`` - - Bool - - False - - Dump Untyped Plutus Core - - - * - ``inline-constants`` - - Bool - - True - - Always inline constants. Inlining constants always reduces script costs slightly, but may increase script sizes if a large constant is used more than once. Implied by ``no-conservative-optimisation``. - - - * - ``max-cse-iterations`` - - Int - - 4 - - Set the max iterations for CSE - - - * - ``max-simplifier-iterations-pir`` - - Int - - 12 - - Set the max iterations for the PIR simplifier - - - * - ``max-simplifier-iterations-uplc`` - - Int - - 12 - - Set the max iterations for the UPLC simplifier - - - * - ``optimize`` - - Bool - - True - - Run optimization passes such as simplification and floating let-bindings. - - - * - ``pedantic`` - - Bool - - False - - Run type checker after each compilation pass - - - * - ``preserve-logging`` - - Bool - - False - - Turn off optimisations that may alter (i.e., add, remove or change the order of) trace messages. Implied by ``conservative-optimisation``. - - - * - ``profile-all`` - - ProfileOpts - - None - - Set profiling options to All, which adds tracing when entering and exiting a term. - - - * - ``relaxed-float-in`` - - Bool - - True - - Use a more aggressive float-in pass, which often leads to reduced costs but may occasionally lead to slightly increased costs. Implied by ``no-conservative-optimisation``. - - - * - ``remove-trace`` - - Bool - - False - - Eliminate calls to ``trace`` from Plutus Core - - - * - ``simplifier-beta`` - - Bool - - True - - Run a simplification pass that performs beta transformations - - - * - ``simplifier-inline`` - - Bool - - True - - Run a simplification pass that performs inlining - - - * - ``simplifier-remove-dead-bindings`` - - Bool - - True - - Run a simplification pass that removes dead bindings - - - * - ``simplifier-unwrap-cancel`` - - Bool - - True - - Run a simplification pass that cancels unwrap/wrap pairs - - - * - ``strictify-bindings`` - - Bool - - True - - Run a simplification pass that makes bindings stricter - - - * - ``target-version`` - - Version - - 1.1.0 - - The target Plutus Core language version - - - * - ``typecheck`` - - Bool - - True - - Perform type checking during compilation. - - - * - ``verbosity`` - - Verbosity - - Quiet - - Set logging verbosity level (0=Quiet, 1=Verbose, 2=Debug) - - diff --git a/doc/read-the-docs-site/reference/writing-scripts/compiler-options.rst b/doc/read-the-docs-site/reference/writing-scripts/compiler-options.rst deleted file mode 100644 index 94d7946b8ad..00000000000 --- a/doc/read-the-docs-site/reference/writing-scripts/compiler-options.rst +++ /dev/null @@ -1,16 +0,0 @@ -.. _plutus_tx_options: - -Plutus Tx Compiler Options -========================== - -These options can be passed to the compiler via the ``OPTIONS_GHC`` pragma, for instance - -.. code-block:: haskell - - {-# OPTIONS_GHC -fplugin-opt PlutusTx.Plugin:dump-uplc #-} - {-# OPTIONS_GHC -fplugin-opt PlutusTx.Plugin:max-simplifier-iterations=3 #-} - -For each boolean option, you can add a ``no-`` prefix to switch it off, such as -``no-typecheck``, ``no-simplifier-beta``. - -.. include:: ./compiler-options-table.rst diff --git a/doc/read-the-docs-site/reference/writing-scripts/examples.rst b/doc/read-the-docs-site/reference/writing-scripts/examples.rst deleted file mode 100644 index ff6aa465db3..00000000000 --- a/doc/read-the-docs-site/reference/writing-scripts/examples.rst +++ /dev/null @@ -1,17 +0,0 @@ -.. _plutus_examples: - -Examples -======== - -Full examples of Plutus Applications can be found in the ``plutus-apps`` `repository <https://github.com/IntersectMBO/plutus-apps/tree/master/plutus-use-cases>`_. -The source code can be found in the ``src`` and the tests in the ``test`` folder. - -The examples are a mixture of simple examples and more complex ones, including: - -- A crowdfunding application -- A futures application -- A stablecoin -- A uniswap clone - -.. important:: - Make sure to look at the same version of the `plutus-apps` repository as you are using, to ensure that the examples work. diff --git a/doc/read-the-docs-site/reference/writing-scripts/index.rst b/doc/read-the-docs-site/reference/writing-scripts/index.rst deleted file mode 100644 index f0aa7cd73b5..00000000000 --- a/doc/read-the-docs-site/reference/writing-scripts/index.rst +++ /dev/null @@ -1,11 +0,0 @@ -Writing scripts -=============== - -.. toctree:: - :maxdepth: 3 - :titlesonly: - - compiler-options - optimization - examples - common-weaknesses/index diff --git a/doc/read-the-docs-site/reference/writing-scripts/optimization.rst b/doc/read-the-docs-site/reference/writing-scripts/optimization.rst deleted file mode 100644 index 02a4d46237f..00000000000 --- a/doc/read-the-docs-site/reference/writing-scripts/optimization.rst +++ /dev/null @@ -1,96 +0,0 @@ -Optimization techniques for Plutus scripts -========================================== - -Identifying problem areas -~~~~~~~~~~~~~~~~~~~~~~~~~ - -In order to identify which parts of the script are responsible for significant resource consumption, you can use the :ref:`profiling support <profiling_scripts>`. - -Using strict let-bindings to avoid recomputation -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Let-bindings in Haskell are translated to strict let-bindings in Plutus IR, unless they look like they might do computation, in which case they are translated to non-strict let-bindings. -This is to avoid triggering effects (e.g. errors) at unexpected times. - -However, non-strict let-bindings are less efficient. -They do not evaluate their right-hand side immediately, instead they do so where the variable is used. -But they are not *lazy* (evaluating the right-hand side at most once), instead it may be evaluated once each time it is used. -You may wish to explicitly mark let-bindings as strict in Haskell to avoid this. - -.. code-block:: haskell - - -- This may be compiled non-strictly, which could result - -- in it being evaluated multiple times. However, it will - -- not be evaluated if we take the branch where it is not used. - let x = y + z - in if b then x + x else 1 - - -- This will be compiled strictly, but this will mean it - -- is evaluated even if we take the branch where it is not used. - let !x = y + z - in if b then x + x else 1 - -Specializing higher-order functions -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The use of higher-order functions is a common technique to facilitate code reuse. -Higher-order functions are widely used in the Plutus libraries but can be less efficient than specialized versions. - -For instance, the Plutus function ``findOwnInput`` makes use of the higher-order function ``find`` to search for the current script input. - -.. code-block:: haskell - - findOwnInput :: ScriptContext -> Maybe TxInInfo - findOwnInput ScriptContext{scriptContextTxInfo=TxInfo{txInfoInputs}, - scriptContextPurpose=Spending txOutRef} = - find (\TxInInfo{txInInfoOutRef} -> txInInfoOutRef == txOutRef) txInfoInputs - findOwnInput _ = Nothing - -This can be rewritten with a recursive function specialized to the specific check in question. - -.. code-block:: haskell - - findOwnInput :: ScriptContext -> Maybe TxInInfo - findOwnInput ScriptContext{scriptContextTxInfo=TxInfo{txInfoInputs}, - scriptContextPurpose=Spending txOutRef} = go txInfoInputs - where - go [] = Nothing - go (i@TxInInfo{txInInfoOutRef} : rest) = if txInInfoOutRef == txOutRef - then Just i - else go rest - findOwnInput _ = Nothing - -Common sub-expression elimination -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -When several instances of identical expressions exist within a function’s body, it’s worth replacing them with a single (strict) let-bound variable to hold the computed value. - -In this example, the cost of storing and retrieving ``n * c`` in a single variable is significantly less than recomputing it several times. - -.. code-block:: haskell - - let a' = a `divide` n * c - -- occurrence 1 - b' = b * (n * c) - -- occurrence 2 - C' = c + (n * c) - in - foo a' b' c' n - - -- Only one occurrence - let !t_mul = n * c - a' = a `divide` t_mul - b' = b * t_mul - c' = c + t_mul - in - foo a' b' c' n - -Using ``error`` for faster failure -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Plutus scripts have access to one impure effect, ``error``, which immediately terminates the script evaluation and will fail validation. -This failure is very fast, but it is also unrecoverable, so only use it in cases where you want to fail the entire validation if there is a failure. - -The Plutus libraries have some functions that fail with ``error``. -Usually these are given an ``unsafe`` prefix to their name. -For example, :hsobj:`PlutusTx.IsData.Class.FromData` parses a value of type ``Data``, returning the result in a ``Maybe`` value to indicate whether it succeeded or failed; whereas :hsobj:`PlutusTx.IsData.Class.UnsafeFromData` does the same but fails with ``error``. diff --git a/doc/read-the-docs-site/requirements.txt b/doc/read-the-docs-site/requirements.txt deleted file mode 100644 index 9a31c1dc8d1..00000000000 --- a/doc/read-the-docs-site/requirements.txt +++ /dev/null @@ -1,63 +0,0 @@ -alabaster==0.7.12 -argcomplete==2.0.0 -Babel==2.9.1 -Brotli==1.0.9 -brotlicffi==1.0.9.2 -certifi>=2023.07.22 -cffi==1.15.0 -chardet==4.0.0 -charset-normalizer==2.0.10 -commonmark==0.9.1 -dicttoxml==1.7.4 -docutils==0.17.1 -future==0.18.3 -idna==3.3 -imagesize==1.3.0 -importlib-metadata==4.10.1 -Jinja2==3.0.3 -latexcodec==2.0.1 -Markdown==3.3.6 -MarkupSafe==2.0.1 -more-itertools==8.12.0 -oset==0.1.3 -packaging==21.3 -pbr==5.8.0 -pexpect==4.8.0 -pip==21.1.3 -prettytable==3.0.0 -ptyprocess==0.7.0 -pybtex==0.24.0 -pybtex-docutils==1.0.1 -pycparser==2.21 -Pygments==2.15.0 -pyparsing==3.0.6 -PySocks==1.7.1 -PyStemmer==2.0.1 -pytz==2021.3 -PyYAML==6.0.1 -recommonmark==0.7.1 -requests==2.31.0 -requests-toolbelt==0.9.1 -six==1.16.0 -snowballstemmer==2.2.0 -Sphinx==4.4.0 -sphinx-markdown-tables==0.0.14 -sphinx-rtd-theme==1.0.0 -sphinxcontrib-apidoc==0.3.0 -sphinxcontrib-applehelp==1.0.2 -sphinxcontrib-bibtex==2.5.0 -sphinxcontrib-devhelp==1.0.2 -sphinxcontrib-domaintools==0.3 -sphinxcontrib-htmlhelp==2.0.0 -sphinxcontrib-jsmath==1.0.1 -sphinxcontrib-plantuml==0.22 -sphinxcontrib-qthelp==1.0.3 -sphinxcontrib-serializinghtml==1.1.5 -sphinxcontrib-websupport==1.2.4 -sphinxemoji==0.1.6 -toml==0.10.2 -urllib3>=1.26.18 -wcwidth==0.2.5 -xmltodict==0.12.0 -yq==2.13.0 -zipp==3.7.0 diff --git a/doc/read-the-docs-site/simple-example.rst b/doc/read-the-docs-site/simple-example.rst deleted file mode 100644 index 10408d1dae9..00000000000 --- a/doc/read-the-docs-site/simple-example.rst +++ /dev/null @@ -1,330 +0,0 @@ -.. _simple_example: - -Simple example -=================== - -Plutus script for an auction smart contract -------------------------------------------------- - -.. caution:: - This conceptual guide to an auction smart contract in Plutus introduces fundamentals for educational use. However, it is not optimized for security or efficiency and should not be deployed in production environments. This example simplifies some security aspects, leading to potential vulnerabilities. For detailed insights on developing secure smart contracts, please refer to the `Cardano Plutus Script Vulnerability Guide <https://library.mlabs.city/common-plutus-security-vulnerabilities>`_ by MLabs. - -Overview -~~~~~~~~~~~~ - -This example presents Plutus Tx code for a smart contract that controls the auction of an asset, which can be executed on the Cardano blockchain. In a sense, the smart contract is acting as the auctioneer in that it enforces certain rules and requirements in order for the auction to occur successfully. - -Plutus Tx is a high-level language for writing the validation logic of the contract, the logic that determines whether a transaction is allowed to spend a UTXO. -Plutus Tx is not a new language, but rather a subset of Haskell, and it is compiled into Plutus Core, a low-level language based on higher-order polymorphic lambda calculus. -Plutus Core is the code that runs on-chain, i.e., by every node validating the transaction, using an interpreter known as the CEK machine. -A Plutus Core program included in a Cardano transaction is often referred to as Plutus script or Plutus validator. - -To develop and deploy a smart contract, you would also need off-chain code for building transactions, submitting transactions, deploying smart contracts, querying for available UTXOs on the chain and so on. -You may also want a front-end interface for your smart contract for better user experiences. -In this example, we are not covering these aspects. - -Before we get to the Plutus Tx code, let's briefly go over some basic concepts, including UTXO, EUTXO, datum, redeemer and script context. - -The EUTXO model, datum, redeemer and script context ------------------------------------------------------ - -On the Cardano blockchain, a transaction contains an arbitrary number of inputs and an arbitrary number of outputs. -The effect of a transaction is to consume inputs and produce new outputs. - -UTXO (unspent transaction output) is the ledger model used by some blockchains, including bitcoin. -A UTXO is produced by a transaction, is immutable, and can only be spent once by another transaction. -In the original UTXO model, a UTXO contains a wallet address and a value (e.g., some amount of one or more currencies/tokens). -Inside a transaction, a UTXO is uniquely identified by the wallet address. -It can be spent by a transaction if the transaction is signed by the private key of the wallet address. - -The Extended UTXO model (EUTXO) extends the original model with a new kind of UTXO: script UTXO. -A script UTXO contains a value, a script (usually a Plutus script), a piece of data called *datum*, and is identified by the hash of the script. -For a transaction to spend it, the transaction must provide a piece of input data to the script, referred to as the *redeemer*. -The script is then run, and it must succeed in order for the transaction to be allowed to spend the UTXO. -In addition to the redeemer, the script also has access to the datum contained in the UTXO, as well as the details of the transaction trying to spend it. This is referred to as *script context*. - -Note that the only thing a Plutus script does is to determine whether a transaction can spend the script UTXO that contains the script. It is *not* responsible for such things as deciding whether it can spend a different UTXO, checking that the input value in a transaction equals the output value, or updating the state of the smart contract. -Consider it a pure function that returns ``Bool``. -Checking transaction validity is done by the ledger rules, and updating the state of a smart contract is done by constructing the transaction to produce a new script UTXO with an updated datum. - -The immutability of UTXOs leads to the extremely useful property of completely predictable transaction fees. -The Plutus script in a transaction can be run off-chain to determine the fee before submitting the transaction onto the blockchain. -When the transaction is submitted, if some UTXOs it tries to spend have already been spent, the transaction is immediately rejected without penalty. -If all input UTXOs still exist, and the Plutus script is invoked, the on-chain behavior would be exactly identical to the off-chain behavior. -This could not be achieved if transaction inputs were mutable, such as is the case in Ethereum's account-based model. - -See also: - - * `Plutus scripts <https://docs.cardano.org/smart-contracts/plutus/plutus-scripts/>`_ for further reading about scripts, and - * `Understanding the Extended UTXO model <https://docs.cardano.org/learn/eutxo-explainer>`_ - -Auction properties ----------------------- - -In this example, Alice wants to auction some asset she owns, represented as a non-fungible token (NFT) on Cardano. -She would like to create and deploy an auction smart contract with the following properties: - -* there is a minimum bid amount -* each bid must be higher than the previous highest bid (if any) -* once a new bid is made, the previous highest bid (if it exists) is immediately refunded -* there is a deadline for placing bids; once the deadline has passed, new bids are no longer accepted, the asset can be transferred to the highest bidder (or to the seller if there are no bids), and the highest bid (if one exists) can be transferred to the seller. - -Next, let's go through and discuss the Plutus Tx code we're using, shown below, for this specific example of an auction smart contract. - -Plutus Tx code ---------------------- - -Recall that Plutus Tx is a subset of Haskell. It is the source language one uses to write Plutus validators. -A Plutus Tx program is compiled into Plutus Core, which is interpreted on-chain. -The full Plutus Tx code for the auction smart contract can be found at `AuctionValidator.hs <https://github.com/IntersectMBO/plutus/blob/master/doc/read-the-docs-site/tutorials/AuctionValidator.hs>`_. - -Data types -~~~~~~~~~~~~~~~~~~~~~~~ - -First, let's define the following data types and instances for the validator: - -.. literalinclude:: tutorials/AuctionValidator.hs - :start-after: BLOCK1 - :end-before: BLOCK2 - -The purpose of ``makeLift`` and ``unstableMakeIsData`` will be explained later. - -Typically, writing a Plutus Tx validator script for a smart contract involves four data types: - -Contract parameters - These are fixed properties of the contract. - In our example, it is the ``AuctionParams`` type, containing properties like seller and minimum bid. - -Datum - This is part of a script UTXO. It should be thought of as the state of the contract. - Our example requires only one piece of state: the current highest bid. We use the ``AuctionDatum`` type to represent this. - -Redeemer - This is an input to the Plutus script provided by the transaction that is trying to spend a script UTXO. - If a smart contract is regarded as a state machine, the redeemer would be the input that ticks the state machine. - In our example, it is the ``AuctionRedeemer`` type: one may either submit a new bid, or request to close the auction and pay out the winner and the seller, both of which lead to a new state of the auction. - -Script context - This type contains the information of the transaction that the validator can inspect. - In our example, our validator verifies several conditions of the transaction; e.g., if it is a new bid, then it must be submitted before the auction's end time; the previous highest bid must be refunded to the previous bidder, etc. - - The script context type is fixed for each Plutus language version. For Plutus V2, for example, it is ``PlutusLedgerApi.V2.Contexts.ScriptContext``. - -.. note:: - When writing a Plutus validator using Plutus Tx, it is advisable to turn off Haskell's ``Prelude``. - Usage of most functions and methods in ``Prelude`` should be replaced by their counterparts in the ``plutus-tx`` library, e.g., ``PlutusTx.Eq.==``. - -Main validator function -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Now we are ready to introduce our main validator function. -The beginning of the function looks like the following: - -.. literalinclude:: tutorials/AuctionValidator.hs - :start-after: BLOCK2 - :end-before: BLOCK3 - -Depending on whether this transaction is attempting to submit a new bid or to request payout, the validator validates the corresponding set of conditions. - -The ``sufficientBid`` condition verifies that the bid amount is sufficient: - -.. literalinclude:: tutorials/AuctionValidator.hs - :start-after: BLOCK3 - :end-before: BLOCK4 - -The ``validBidTime`` condition verifies that the bid is submitted before the auction's deadline: - -.. literalinclude:: tutorials/AuctionValidator.hs - :start-after: BLOCK4 - :end-before: BLOCK5 - -Here, ``to x`` is the time interval ending at ``x``, i.e., ``(-∞, x]``. -``txInfoValidRange`` is a transaction property. -It is the time interval in which the transaction is allowed to go through phase-1 validation. -``contains`` takes two time intervals, and checks that the first interval completely includes the second. -Since the transaction may be validated at any point in the ``txInfoValidRange`` interval, we need to check that the entire interval lies within ``(-∞, apEndTime params]``. - -The reason we need the ``txInfoValidRange`` interval instead of using the exact time the transaction is validated is due to `determinism <https://iohk.io/en/blog/posts/2021/09/06/no-surprises-transaction-validation-on-cardano/>`_. -Using the exact time would be like calling a ``getCurrentTime`` function and branching based on the current time. -On the other hand, by using the ``txInfoValidRange`` interval, the same interval is always used by the same transaction. - -The ``refundsPreviousHighestBid`` condition checks that the transaction pays the previous highest bid to the previous bidder: - -.. literalinclude:: tutorials/AuctionValidator.hs - :start-after: BLOCK5 - :end-before: BLOCK6 - -It uses ``PlutusTx.find`` to find the transaction output (a UTXO) that pays to the previous bidder the amount equivalent to the previous highest bid, and verifies that there is at least one such output. - -``lovelaceValue amt`` constructs a ``Value`` with ``amt`` Lovelaces (the subunit of the Ada currency). -``Value`` is a multi-asset type that represents a collection of assets, including Ada. -An asset is identified by a (symbol, token) pair, where the symbol represents the policy that controls the minting and burning of tokens, and the token represents a particular kind of token manipulated by the policy. -``(adaSymbol, adaToken)`` is the special identifier for Ada/Lovelace. - -The ``correctNewDatum`` condition verifies that the transaction produces a *continuing output* containing the correct datum (the new highest bid): - -.. literalinclude:: tutorials/AuctionValidator.hs - :start-after: BLOCK6 - :end-before: BLOCK7 - -A "continuing output" is a transaction output that pays to the same script address from which we are currently spending. -Exactly one continuing output must be present in this example so that the next bidder can place a new bid. The new bid, in turn, will need to spend the continuing output and get validated by the same validator script. - -If the transaction is requesting a payout, the validator will then verify the other three conditions: `validPayoutTime`, `sellerGetsHighestBid` and `highestBidderGetsAsset`. -These conditions are similar to the ones already explained, so their details are omitted. - -Finally, we need to compile the validator written in Plutus Tx into Plutus Core, using the Plutus Tx compiler: - -.. literalinclude:: tutorials/AuctionValidator.hs - :start-after: BLOCK8 - :end-before: BLOCK9 - -The type of the compiled validator is ``CompiledCode (BuiltinData -> BuiltinData -> BuiltinData -> ())``, where type ``BuiltinData -> BuiltinData -> BuiltinData -> ()`` is also known as the *untyped validator*. -An untyped validator takes three ``BuiltinData`` arguments, representing the serialized datum, redeemer, and script context. -The call to ``PlutusTx.unsafeFromBuiltinData`` is the reason we need the ``PlutusTx.unstableMakeIsData`` shown before, which derives ``UnsafeFromData`` instances. -And instead of returning a ``Bool``, it simply returns ``()``, and the validation succeeds if the script evaluates without error. - -Note that ``AuctionParams`` is an argument of neither the untyped validator nor the final UPLC program. ``AuctionParams`` contains contract properties that don't change, so it is simply built into the validator. - -Since the Plutus Tx compiler compiles ``a`` into ``CompiledCode a``, we first use ``auctionUntypedValidator`` to obtain an untyped validator. -It takes ``AuctionParams``, and returns an untyped validator. -We then define the ``auctionValidatorScript`` function, which takes ``AuctionParams`` and returns the compiled Plutus Core program. - -To create the Plutus validator script for a particular auction, we call ``auctionValidatorScript`` with the appropriate ``AuctionParams``. -We will then be able to launch the auction on-chain by submitting a transaction that outputs a script UTXO with ``Nothing`` as the datum. - -.. note:: - It is worth noting that we must call ``PlutusTx.compile`` on the entire ``auctionUntypedValidator``, rather than applying it to ``params`` before compiling, as in ``$$(PlutusTx.compile [||auctionUntypedValidator params||])``. - The latter won't work, because everything being compiled (inside ``[||...||]``) must be known at compile time, but ``params`` is not: it can differ at runtime depending on what kind of auction we want to run. - Instead, we compile the entire ``auctionUntypedValidator`` into Plutus Core, then use ``liftCode`` to lift ``params`` into a Plutus Core term, and apply the compiled ``auctionUntypedValidator`` to it at the Plutus Core level. - To do so, we need the ``Lift`` instance for ``AuctionParams``, derived via ``PlutusTx.makeLift``. - -Life cycle of the auction smart contract -------------------------------------------- - -With the Plutus script written, Alice is now ready to start the auction smart contract. -At the outset, Alice creates a script UTXO whose address is the hash of the Plutus script, whose value is the token to be auctioned, and whose datum is ``Nothing``. -Recall that the datum represents the highest bid, and there's no bid yet. -This script UTXO also contains the script itself, so that nodes validating transactions that -try to spend this script UTXO have access to the script. - -Initial UTXO -~~~~~~~~~~~~~~~~~ - -Alice needs to create the initial UTXO transaction with the desired UTXO as an output. -The token being auctioned can either be minted by this transaction, or if it already exists in another UTXO on the ledger, the transaction should consume that UTXO as an input. -We will not go into the details here of how minting tokens works. - -The first bid -~~~~~~~~~~~~~~~~~~ - -Suppose Bob, the first bidder, wants to bid 100 Ada for Alice's NFT. -In order to do this, Bob creates a transaction that has at least two inputs and at least one output. - -The required inputs are (1) the script UTXO Alice created; (2) Bob's bid of 100 Ada. -The 100 Ada can come in one or multiple UTXOs. -Note that the input UTXOs must have a total value of more than 100 Ada, because in addition to the bid amount, they also need to cover the transaction fee. - -The required output is a script UTXO with the same address as the initial UTXO (since the Plutus script itself remains the same), which is known as a *continuing output*. -This continuing output UTXO should contain: - -* a datum that contains Bob's wallet address and Bob's bid amount (100 Ada). - - * Bob's wallet address is used to claim the token (if Bob ends up winning the auction) or receive the refund (if a higher bid is placed later). - -* a value: the token being auctioned plus the 100 Ada from Bob's bid. - -If the input UTXOs contain more Ada than 100 plus the transaction fee, then there should be additional output UTXOs that return the extra Ada. -Again, verifying that the input value of a transaction minus the transaction fee equals the output value (unless the transaction is burning tokens) is the responsibility of the ledger, not the Plutus script. - -In order for Bob's transaction to be able to spend the initial script UTXO Alice created, Bob's transaction must also contain a redeemer. -As shown in the code above, there are two kinds of redeemers in our example: ``NewBid Bid`` and ``Payout``. -The redeemer in Bob's transaction is a ``NewBid Bid`` where the ``Bid`` contains Bob's wallet address and bid amount. - -.. image:: first-bid-simple-auction-v3.png - :width: 700 - :alt: First bid diagram - -Once Bob's transaction is submitted, the node validating this transaction will run the Plutus script, which checks a number of conditions like whether the bid happens before the deadline, and whether the bid is high enough. -If the checks pass and everything else about the transaction is valid, the transaction will go through and be included in a block. -At this point, the initial UTXO created by Alice no longer exists on the ledger, since it has been spent by Bob's transaction. - -The second bid -~~~~~~~~~~~~~~~~~~~~ - -Next, suppose a second bidder, Charlie, wants to outbid Bob. Charlie wants to bid 200 Ada. - -Charlie will create another transaction. -This transaction should have an additional output compared to Bob's transaction: a UTXO that returns Bob's bid of 100 Ada. -Recall that this is one of the conditions checked by the Plutus script; the transaction is rejected if the refund output is missing. - -.. image:: second-bid-simple-auction-v3.png - :width: 700 - :alt: Second bid diagram - -Charlie's transaction needs to spend the script UTXO produced by Bob's transaction, so it also needs a redeemer. The redeemer is a ``NewBid Bid`` where ``Bid`` contains Charlie's wallet address and bid amount. -Charlie's transaction cannot spend the initial UTXO produced by Alice, since it has already been spent by Bob's transaction. - -Closing the auction -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Let’s assume that there won’t be another bid. -Once the deadline has passed, the auction can be closed. - -In order to do that, somebody has to create another transaction. -That could be Alice, who wants to collect the bid, or it could be Charlie, who wants to collect the NFT. -It can be anybody, but Alice and Charlie have an incentive to create it. - -This transaction has one required input: the script UTXO produced by Charlie's transaction, and two required outputs: (1) the payment of the auctioned token to Charlie; (2) the payment of 200 Ada to Alice. - -.. image:: closing-tx-simple-auction-v3.png - :width: 700 - :alt: Closing transaction diagram - -Libraries for writing Plutus Tx scripts -------------------------------------------- - -This auction example shows a relatively low-level way of writing scripts using Plutus Tx. -In practice, you may consider using a higher-level library that abstracts away some of the details. -For example, `plutus-apps <https://github.com/IntersectMBO/plutus-apps>`_ provides a constraint library for writing Plutus Tx. -Using these libraries, writing a validator in Plutus Tx becomes a matter of defining state transactions and the corresponding constraints, e.g., the condition ``refundsPreviousHighestBid`` can simply be written as ``Constraints.mustPayToPubKey bidder (lovelaceValue amt)``. - -Alternatives to Plutus Tx ------------------------------ - -There are languages other than Plutus Tx that can be compiled into Plutus Core. -We list some of them here for reference. However, we are not endorsing them; we are not representing their qualities nor their state of development regarding their production-readiness. - -* `Aiken <https://github.com/txpipe/aiken/>`_ -* `Hebi <https://github.com/OpShin/hebi>`_ -* `Helios <https://github.com/hyperion-bt/helios>`_ -* `OpShin <https://github.com/OpShin/opshin>`_ -* `plu-ts <https://github.com/HarmonicLabs/plu-ts>`_ -* `Plutarch <https://github.com/Plutonomicon/plutarch-core>`_ -* `Pluto <https://github.com/Plutonomicon/pluto>`_ - -Off-chain code ------------------------ - -Since the main purpose of this example is to introduce Plutus Tx and Plutus Core, we walked through only the on-chain code, which is responsible for validating transactions (in the sense of determining whether a transaction is allowed to spend a UTXO). - -In addition to the on-chain code, one typically needs the accompanying off-chain code and services to perform tasks like building transactions, submitting transactions, deploying smart contracts, querying for available UTXOs on the chain, etc. - -A full suite of solutions is `in development <https://plutus-apps.readthedocs.io/en/latest/plutus/explanations/plutus-tools-component-descriptions.html>`_. -See the `plutus-apps <https://github.com/IntersectMBO/plutus-apps>`_ repo and its accompanying `Plutus tools SDK user guide <https://plutus-apps.readthedocs.io/en/latest/>`_ for more details. - -Some other alternatives include `cardano-transaction-lib <https://github.com/Plutonomicon/cardano-transaction-lib>`_ and `lucid <https://github.com/spacebudz/lucid>`_. -All these are based on the `Cardano API <https://github.com/IntersectMBO/cardano-node/tree/master/cardano-api>`_, a low-level API that provides the capability to do the off-chain work with a local running node. - -See also: `Plutus application development <https://docs.cardano.org/smart-contracts/plutus/dapp-development/>`_, a high-level overview of resources for building DApps using Plutus. -A DApp is basically a smart contract plus a front end. - -Further reading ------------------------ - -The EUTXO model -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -* `The Extended UTXO Model <https://iohk.io/en/research/library/papers/the-extended-utxo-model/>`_ (Paper) -* `The EUTXO Handbook <https://www.essentialcardano.io/article/the-eutxo-handbook>`_ -* Blog Post: Cardano's Extended UTXO accounting model---built to support multi-assets and smart contracts (`part 1 <https://iohk.io/en/blog/posts/2021/03/11/cardanos-extended-utxo-accounting-model/>`_, `part 2 <https://iohk.io/en/blog/posts/2021/03/12/cardanos-extended-utxo-accounting-model-part-2/>`_) diff --git a/doc/read-the-docs-site/troubleshooting.rst b/doc/read-the-docs-site/troubleshooting.rst deleted file mode 100644 index bfad2b869db..00000000000 --- a/doc/read-the-docs-site/troubleshooting.rst +++ /dev/null @@ -1,134 +0,0 @@ -Troubleshooting -=============== - -Plugin errors -------------- - -Errors that start with ``GHC Core to PLC plugin`` are errors from ``plutus-tx-plugin``. - -.. note:: - Often these errors arise due to GHC doing something to the code before the plugin gets to see it. - So the solution is often to prevent GHC from doing this, which is why we often recommend trying various GHC compiler flags. - -Haddock -~~~~~~~ - -The plugin will typically fail when producing Haddock documentation. -However, in this instance you can simply tell it to defer any errors to runtime (which will never happen since you're building documentation). - -A easy way to do this is to add the following lines for your ``package-name`` to ``cabal.project``:: - - package package-name - haddock-options: "--optghc=-fplugin-opt PlutusTx.Plugin:defer-errors" - -Non-``INLINABLE`` functions -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -A common error is: - -``Error: Reference to a name which is not a local, a builtin, or an external INLINABLE function`` - -This means the plugin doesn't have access to implementation of the function, which it needs to be able to compile the function to Plutus Core. -Some things you can do to fix it: - -- Make sure to add ``{-# INLINABLE functionname #-}`` to your function. -- If there's an extra ``$c`` in front of the function name in the error, GHC has generated a specialised version of your function, - which prevents the plugin from accessing it. - You can turn off specialisation with ``{-# OPTIONS_GHC -fno-specialise #-}`` -- Other compiler options that can help: - - - ``{-# OPTIONS_GHC -fno-strictness #-}`` - - ``{-# OPTIONS_GHC -fno-ignore-interface-pragmas #-}`` - - ``{-# OPTIONS_GHC -fno-omit-interface-pragmas #-}`` - - ``{-# OPTIONS_GHC -fobject-code #-}`` - - Some more details are in `the plutus-tx readme <https://github.com/IntersectMBO/plutus/tree/master/plutus-tx#building-projects-with-plutus-tx>`_. - -Haskell Language Server issues ------------------------------- - -For more advice on using Haskell Language Server (HLS), consult the `CONTRIBUTING guide <https://github.com/IntersectMBO/plutus/blob/master/CONTRIBUTING.adoc>`_ in the ``plutus`` repository. - -Wrong version -~~~~~~~~~~~~~ - -``ghcide compiled against GHC 8.10.3 but currently using 8.10.2.20201118`` - -Your editor is not picking up the right version of the Haskell Language Server (HLS). -Plutus needs a custom version of HLS which is provided by Nix. -So get this working in your editor, make sure to do these two things: - -- Start your editor from ``nix develop`` (or use ``direnv``) -- Most editors are configured to use ``haskell-language-server-wrapper``, which is a wrapper which picks the right HLS version. - Change this to just ``haskell-language-server``. - -If this doesn't work, run ``which haskell-language-server`` in `nix develop`, and use this absolute path in the configuration of your editor. - -Error codes ------------ - -To reduce code size, on-chain errors only output codes. Here's what they mean: - -.. - This list can be generated with: - grep -rEoh "\btrace\w*\s+\"[^\"]{1,5}\"\s+(--.*|\{-\".*\"-\})" * - -- Ledger errors - - - ``L0: Input constraint`` - - ``L1: Output constraint`` - - ``L2: Missing datum`` - - ``L3: Wrong validation interval`` - - ``L4: Missing signature`` - - ``L5: Spent value not OK`` - - ``L6: Produced value not OK`` - - ``L7: Public key output not spent`` - - ``L8: Script output not spent`` - - ``L9: Value minted not OK`` - - ``La: MustPayToPubKey`` - - ``Lb: MustPayToOtherScript`` - - ``Lc: MustHashDatum`` - - ``Ld: checkScriptContext failed`` - - ``Le: Can't find any continuing outputs`` - - ``Lf: Can't get any continuing outputs`` - - ``Lg: Can't get validator and datum hashes`` - - ``Lh: Can't get currency symbol of the current validator script`` - - ``Li: DecodingError`` - -- Prelude errors - - ``PT1: TH Generation of Indexed Data Error`` - - ``PT2: PlutusTx.IsData.Class.unsafeFromBuiltinData: Void is not supported`` - - ``PT3: PlutusTx.Ratio: zero denominator`` - - ``PT5: PlutusTx.Prelude.check: input is 'False'`` - - ``PT6: PlutusTx.List.!!: negative index`` - - ``PT7: PlutusTx.List.!!: index too large`` - - ``PT8: PlutusTx.List.head: empty list`` - - ``PT9: PlutusTx.List.tail: empty list`` - - ``PT10: PlutusTx.Enum.().succ: bad argument`` - - ``PT11: PlutusTx.Enum.().pred: bad argument`` - - ``PT12: PlutusTx.Enum.().toEnum: bad argument`` - - ``PT13: PlutusTx.Enum.Bool.succ: bad argument`` - - ``PT14: PlutusTx.Enum.Bool.pred: bad argument`` - - ``PT15: PlutusTx.Enum.Bool.toEnum: bad argument`` - - ``PT16: PlutusTx.Enum.Ordering.succ: bad argument`` - - ``PT17: PlutusTx.Enum.Ordering.pred: bad argument`` - - ``PT18: PlutusTx.Enum.Ordering.toEnum: bad argument`` - - ``PT19: PlutusTx.List.last: empty list`` - - ``PT20: PlutusTx.Ratio.recip: reciprocal of zero`` - -- State machine errors - - - ``S0: Can't find validation input`` - - ``S1: State transition invalid - checks failed`` - - ``S2: Thread token not found`` - - ``S3: Non-zero value allocated in final state`` - - ``S4: State transition invalid - constraints not satisfied by ScriptContext`` - - ``S5: State transition invalid - constraints not satisfied by ScriptContext`` - - ``S6: State transition invalid - input is not a valid transition at the current state`` - - ``S7: Value minted different from expected`` - - ``S8: Pending transaction does not spend the designated transaction output`` - -- Currency errors - - - ``C0: Value minted different from expected`` - - ``C1: Pending transaction does not spend the designated transaction output`` diff --git a/doc/read-the-docs-site/tutorials/AuctionValidator.hs b/doc/read-the-docs-site/tutorials/AuctionValidator.hs deleted file mode 100644 index 64b002a3f6d..00000000000 --- a/doc/read-the-docs-site/tutorials/AuctionValidator.hs +++ /dev/null @@ -1,237 +0,0 @@ -{-# LANGUAGE DataKinds #-} -{-# LANGUAGE DerivingStrategies #-} -{-# LANGUAGE ImportQualifiedPost #-} -{-# LANGUAGE MultiParamTypeClasses #-} -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE PatternSynonyms #-} -{-# LANGUAGE ScopedTypeVariables #-} -{-# LANGUAGE Strict #-} -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE ViewPatterns #-} - -{-# OPTIONS_GHC -fno-ignore-interface-pragmas #-} -{-# OPTIONS_GHC -fno-omit-interface-pragmas #-} -{-# OPTIONS_GHC -fno-full-laziness #-} -{-# OPTIONS_GHC -fno-spec-constr #-} -{-# OPTIONS_GHC -fno-specialise #-} -{-# OPTIONS_GHC -fno-strictness #-} -{-# OPTIONS_GHC -fno-unbox-strict-fields #-} -{-# OPTIONS_GHC -fno-unbox-small-strict-fields #-} -{-# OPTIONS_GHC -fplugin-opt PlutusTx.Plugin:target-version=1.0.0 #-} - -module AuctionValidator where - -import PlutusCore.Version (plcVersion100) -import PlutusLedgerApi.V1 (Lovelace, POSIXTime, PubKeyHash, Value) -import PlutusLedgerApi.V1.Address (pubKeyHashAddress) -import PlutusLedgerApi.V1.Interval (contains) -import PlutusLedgerApi.V1.Value (lovelaceValue) -import PlutusLedgerApi.V2 (Datum (..), OutputDatum (..), ScriptContext (..), TxInfo (..), - TxOut (..), from, to) -import PlutusLedgerApi.V2.Contexts (getContinuingOutputs) -import PlutusTx -import PlutusTx.AsData qualified as PlutusTx -import PlutusTx.Prelude qualified as PlutusTx -import PlutusTx.Show qualified as PlutusTx - --- BLOCK1 -data AuctionParams = AuctionParams - { apSeller :: PubKeyHash, - -- ^ Seller's wallet address. The highest bid (if exists) will be sent to the seller. - -- If there is no bid, the asset auctioned will be sent to the seller. - apAsset :: Value, - -- ^ The asset being auctioned. It can be a single token, multiple tokens of the same - -- kind, or tokens of different kinds, and the token(s) can be fungible or non-fungible. - -- These can all be encoded as a `Value`. - apMinBid :: Lovelace, - -- ^ The minimum bid in Lovelace. - apEndTime :: POSIXTime - -- ^ The deadline for placing a bid. This is the earliest time the auction can be closed. - } - -PlutusTx.makeLift ''AuctionParams - -data Bid = Bid - { bBidder :: PubKeyHash, - -- ^ Bidder's wallet address. - bAmount :: Lovelace - -- ^ Bid amount in Lovelace. - } - -PlutusTx.deriveShow ''Bid -PlutusTx.unstableMakeIsData ''Bid - -instance PlutusTx.Eq Bid where - {-# INLINEABLE (==) #-} - bid == bid' = - bBidder bid PlutusTx.== bBidder bid' - PlutusTx.&& bAmount bid PlutusTx.== bAmount bid' - --- | Datum represents the state of a smart contract. In this case --- it contains the highest bid so far (if exists). -newtype AuctionDatum = AuctionDatum { adHighestBid :: Maybe Bid } - -PlutusTx.unstableMakeIsData ''AuctionDatum - --- | Redeemer is the input that changes the state of a smart contract. --- In this case it is either a new bid, or a request to close the auction --- and pay out the seller and the highest bidder. -data AuctionRedeemer = NewBid Bid | Payout - -PlutusTx.unstableMakeIsData ''AuctionRedeemer --- BLOCK2 - - -{-# INLINEABLE auctionTypedValidator #-} --- | Given the auction parameters, determines whether the transaction is allowed to --- spend the UTXO. -auctionTypedValidator :: - AuctionParams -> - AuctionDatum -> - AuctionRedeemer -> - ScriptContext -> - Bool -auctionTypedValidator params (AuctionDatum highestBid) redeemer ctx@(ScriptContext txInfo _) = - PlutusTx.and conditions - where - conditions :: [Bool] - conditions = case redeemer of - NewBid bid -> - [ -- The new bid must be higher than the highest bid. - -- If this is the first bid, it must be at least as high as the minimum bid. - sufficientBid bid, - -- The bid is not too late. - validBidTime, - -- The previous highest bid should be refunded. - refundsPreviousHighestBid, - -- A correct new datum is produced, containing the new highest bid. - correctNewDatum bid - ] - Payout -> - [ -- The payout is not too early. - validPayoutTime, - -- The seller gets the highest bid. - sellerGetsHighestBid, - -- The highest bidder gets the asset. - highestBidderGetsAsset - ] --- BLOCK3 - sufficientBid :: Bid -> Bool - sufficientBid (Bid _ amt) = case highestBid of - Just (Bid _ amt') -> amt PlutusTx.> amt' - Nothing -> amt PlutusTx.>= apMinBid params --- BLOCK4 - validBidTime :: Bool - validBidTime = to (apEndTime params) `contains` txInfoValidRange txInfo --- BLOCK5 - refundsPreviousHighestBid :: Bool - refundsPreviousHighestBid = case highestBid of - Nothing -> True - Just (Bid bidder amt) -> - case PlutusTx.find - (\o -> txOutAddress o PlutusTx.== pubKeyHashAddress bidder - PlutusTx.&& txOutValue o PlutusTx.== lovelaceValue amt) - (txInfoOutputs txInfo) of - Just _ -> True - Nothing -> PlutusTx.traceError ("Not found: refund output") --- BLOCK6 - correctNewDatum :: Bid -> Bool - correctNewDatum bid = case getContinuingOutputs ctx of - [o] -> case txOutDatum o of - OutputDatum (Datum newDatum) -> case PlutusTx.fromBuiltinData newDatum of - Just bid' -> - PlutusTx.traceIfFalse - ( "Invalid output datum: expected " - PlutusTx.<> PlutusTx.show bid - PlutusTx.<> ", but got " - PlutusTx.<> PlutusTx.show bid' - ) - (bid PlutusTx.== bid') - Nothing -> - PlutusTx.traceError - ( "Failed to decode output datum: " - PlutusTx.<> PlutusTx.show newDatum - ) - OutputDatumHash _ -> - PlutusTx.traceError "Expected OutputDatum, got OutputDatumHash" - NoOutputDatum -> - PlutusTx.traceError "Expected OutputDatum, got NoOutputDatum" - os -> - PlutusTx.traceError - ( "Expected exactly one continuing output, got " - PlutusTx.<> PlutusTx.show (PlutusTx.length os) - ) --- BLOCK7 - validPayoutTime :: Bool - validPayoutTime = from (apEndTime params) `contains` txInfoValidRange txInfo - - sellerGetsHighestBid :: Bool - sellerGetsHighestBid = case highestBid of - Nothing -> True - Just (Bid _ amt) -> - case PlutusTx.find - ( \o -> - txOutAddress o PlutusTx.== pubKeyHashAddress (apSeller params) - PlutusTx.&& txOutValue o PlutusTx.== lovelaceValue amt - ) - (txInfoOutputs txInfo) of - Just _ -> True - Nothing -> PlutusTx.traceError ("Not found: Output paid to seller") - - highestBidderGetsAsset :: Bool - highestBidderGetsAsset = case highestBid of - Nothing -> True - Just (Bid bidder _) -> - case PlutusTx.find - ( \o -> - txOutAddress o PlutusTx.== pubKeyHashAddress bidder - PlutusTx.&& txOutValue o PlutusTx.== apAsset params - ) - (txInfoOutputs txInfo) of - Just _ -> True - Nothing -> PlutusTx.traceError ("Not found: Output paid to highest bidder") --- BLOCK8 -{-# INLINEABLE auctionUntypedValidator #-} -auctionUntypedValidator :: - AuctionParams -> - BuiltinData -> - BuiltinData -> - BuiltinData -> - PlutusTx.BuiltinUnit -auctionUntypedValidator params datum redeemer ctx = - PlutusTx.check - ( auctionTypedValidator - params - (PlutusTx.unsafeFromBuiltinData datum) - (PlutusTx.unsafeFromBuiltinData redeemer) - (PlutusTx.unsafeFromBuiltinData ctx) - ) - -auctionValidatorScript :: - AuctionParams -> - CompiledCode (BuiltinData -> BuiltinData -> BuiltinData -> PlutusTx.BuiltinUnit) -auctionValidatorScript params = - $$(PlutusTx.compile [||auctionUntypedValidator||]) - `PlutusTx.unsafeApplyCode` PlutusTx.liftCode plcVersion100 params --- BLOCK9 -PlutusTx.asData [d| - data Bid' = Bid' - { bBidder' :: PubKeyHash, - -- ^ Bidder's wallet address. - bAmount' :: Lovelace - -- ^ Bid amount in Lovelace. - } - -- We can derive instances with the newtype strategy, and they - -- will be based on the instances for 'Data' - deriving newtype (Eq, Ord, PlutusTx.ToData, FromData, UnsafeFromData) - - -- don't do this for the datum, since it's just a newtype so - -- simply delegates to the underlying type - - -- | Redeemer is the input that changes the state of a smart contract. - -- In this case it is either a new bid, or a request to close the auction - -- and pay out the seller and the highest bidder. - data AuctionRedeemer' = NewBid' Bid | Payout' - deriving newtype (Eq, Ord, PlutusTx.ToData, FromData, UnsafeFromData) - |] --- BLOCK10 diff --git a/doc/read-the-docs-site/tutorials/BasicPolicies.hs b/doc/read-the-docs-site/tutorials/BasicPolicies.hs deleted file mode 100644 index abac078a5c0..00000000000 --- a/doc/read-the-docs-site/tutorials/BasicPolicies.hs +++ /dev/null @@ -1,57 +0,0 @@ -{-# LANGUAGE DataKinds #-} -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE ScopedTypeVariables #-} -{-# LANGUAGE TemplateHaskell #-} -module BasicPolicies where - -import PlutusCore.Default qualified as PLC -import PlutusTx -import PlutusTx.Lift -import PlutusTx.Prelude - -import PlutusLedgerApi.V1.Contexts -import PlutusLedgerApi.V1.Crypto -import PlutusLedgerApi.V1.Scripts -import PlutusLedgerApi.V1.Value -import PlutusTx.AssocMap qualified as Map - -tname :: TokenName -tname = error () - -key :: PubKeyHash -key = error () - --- BLOCK1 -oneAtATimePolicy :: () -> ScriptContext -> Bool -oneAtATimePolicy _ ctx = - -- 'ownCurrencySymbol' lets us get our own hash (= currency symbol) - -- from the context - let ownSymbol = ownCurrencySymbol ctx - txinfo = scriptContextTxInfo ctx - minted = txInfoMint txinfo - -- Here we're looking at some specific token name, which we - -- will assume we've got from elsewhere for now. - in currencyValueOf minted ownSymbol == singleton ownSymbol tname 1 - -{-# INLINABLE currencyValueOf #-} --- | Get the quantities of just the given 'CurrencySymbol' in the 'Value'. -currencyValueOf :: Value -> CurrencySymbol -> Value -currencyValueOf (Value m) c = case Map.lookup c m of - Nothing -> mempty - Just t -> Value (Map.singleton c t) --- BLOCK2 --- The 'plutus-ledger' package from 'plutus-apps' provides helper functions to automate --- some of this boilerplate. -oneAtATimePolicyUntyped :: BuiltinData -> BuiltinData -> BuiltinUnit --- 'check' fails with 'error' if the argument is not 'True'. -oneAtATimePolicyUntyped r c = - check $ oneAtATimePolicy (unsafeFromBuiltinData r) (unsafeFromBuiltinData c) - --- We can use 'compile' to turn a minting policy into a compiled Plutus Core program, --- just as for validator scripts. -oneAtATimeCompiled :: CompiledCode (BuiltinData -> BuiltinData -> BuiltinUnit) -oneAtATimeCompiled = $$(compile [|| oneAtATimePolicyUntyped ||]) --- BLOCK3 -singleSignerPolicy :: () -> ScriptContext -> Bool -singleSignerPolicy _ ctx = txSignedBy (scriptContextTxInfo ctx) key --- BLOCK4 diff --git a/doc/read-the-docs-site/tutorials/BasicValidators.hs b/doc/read-the-docs-site/tutorials/BasicValidators.hs deleted file mode 100644 index 24add791f32..00000000000 --- a/doc/read-the-docs-site/tutorials/BasicValidators.hs +++ /dev/null @@ -1,98 +0,0 @@ -{-# LANGUAGE DataKinds #-} -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE NumericUnderscores #-} -{-# LANGUAGE ScopedTypeVariables #-} -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE TypeApplications #-} -{-# LANGUAGE TypeFamilies #-} -{-# LANGUAGE ViewPatterns #-} -module BasicValidators where - -import PlutusCore.Default qualified as PLC -import PlutusTx -import PlutusTx.Lift -import PlutusTx.Prelude - -import PlutusLedgerApi.Common -import PlutusLedgerApi.V1.Contexts -import PlutusLedgerApi.V1.Crypto -import PlutusLedgerApi.V1.Scripts -import PlutusLedgerApi.V1.Value - -import Data.ByteString qualified as BS -import Data.ByteString.Lazy qualified as BSL - -import Codec.Serialise -import Flat qualified - -import Prelude (IO, print, show) -import Prelude qualified as Haskell - -myKeyHash :: PubKeyHash -myKeyHash = Haskell.undefined - --- BLOCK1 --- | A specific date. -newtype Date = Date Integer --- | Either a specific end date, or "never". -data EndDate = Fixed Integer | Never - --- 'unstableMakeIsData' is a TemplateHaskell function that takes a type name and --- generates an 'IsData' instance definition for it. It should work for most --- types, including newtypes and sum types. For production usage use 'makeIsDataIndexed' --- which ensures that the output is stable across time. -unstableMakeIsData ''Date -unstableMakeIsData ''EndDate --- BLOCK2 -alwaysSucceeds :: BuiltinData -> BuiltinData -> BuiltinData -> () -alwaysSucceeds _ _ _ = () - -alwaysFails :: BuiltinData -> BuiltinData -> BuiltinData -> () -alwaysFails _ _ _ = error () - --- We can use 'compile' to turn a validator function into a compiled Plutus Core program. --- Here's a reminder of how to do it. -alwaysSucceedsCompiled :: CompiledCode (BuiltinData -> BuiltinData -> BuiltinData -> ()) -alwaysSucceedsCompiled = $$(compile [|| alwaysSucceeds ||]) --- BLOCK3 --- | Checks if a date is before the given end date. -beforeEnd :: Date -> EndDate -> Bool -beforeEnd (Date d) (Fixed e) = d <= e -beforeEnd (Date _) Never = True - --- | Check that the date in the redeemer is before the limit in the datum. -validateDate :: BuiltinData -> BuiltinData -> BuiltinData -> BuiltinUnit --- The 'check' function takes a 'Bool' and fails if it is false. --- This is handy since it's more natural to talk about booleans. -validateDate datum redeemer _ = - check $ beforeEnd (unsafeFromBuiltinData datum) (unsafeFromBuiltinData redeemer) - -dateValidator :: CompiledCode (BuiltinData -> BuiltinData -> BuiltinData -> BuiltinUnit) -dateValidator = $$(compile [|| validateDate ||]) --- BLOCK4 -validatePayment :: BuiltinData -> BuiltinData -> BuiltinData -> BuiltinUnit -validatePayment _ _ ctx = - let valCtx = unsafeFromBuiltinData ctx - -- The 'TxInfo' in the validation context is the representation of the - -- transaction being validated - txinfo = scriptContextTxInfo valCtx - -- 'pubKeyOutputsAt' collects the 'Value' at all outputs which pay to - -- the given public key hash - values = pubKeyOutputsAt myKeyHash txinfo - -- 'fold' sums up all the values, we assert that there must be more - -- than 1 Ada (more stuff is fine!) - in check $ lovelaceValueOf (fold values) >= 1_000_000 ---- BLOCK5 --- We can serialize a 'Validator' directly to CBOR -serialisedDateValidator :: SerialisedScript -serialisedDateValidator = serialiseCompiledCode dateValidator - --- The serialized forms can be written or read using normal Haskell IO functionality. -showSerialised :: IO () -showSerialised = print serialisedDateValidator --- BLOCK6 --- The 'loadFromFile' function is a drop-in replacement for 'compile', but --- takes the file path instead of the code to compile. -validatorCodeFromFile :: CompiledCode (() -> () -> ScriptContext -> Bool) -validatorCodeFromFile = $$(loadFromFile "howtos/myscript.uplc") --- BLOCK7 diff --git a/doc/read-the-docs-site/tutorials/Main.hs b/doc/read-the-docs-site/tutorials/Main.hs deleted file mode 100644 index cfc05d9557e..00000000000 --- a/doc/read-the-docs-site/tutorials/Main.hs +++ /dev/null @@ -1,6 +0,0 @@ -module Main where - -import PlutusTx () - -main :: IO () -main = pure () diff --git a/doc/read-the-docs-site/tutorials/basic-minting-policies.rst b/doc/read-the-docs-site/tutorials/basic-minting-policies.rst deleted file mode 100644 index e2ddadc8f4b..00000000000 --- a/doc/read-the-docs-site/tutorials/basic-minting-policies.rst +++ /dev/null @@ -1,64 +0,0 @@ -.. highlight:: haskell -.. _basic_minting_policies_tutorial: - -Writing basic minting policies -============================== - -:term:`Minting policy scripts<minting policy script>` are the programs that can be used to control the minting of new assets on the chain. -Minting policy scripts are much like :term:`validator scripts<validator script>`, and they are written similarly, so check out the :ref:`basic validators tutorial<basic_validators_tutorial>` before reading this one. - -Minting policy arguments ------------------------- - -Minting policies, like validators, receive some information from the validating node: - -- The :term:`redeemer`, which is some script-specific data specified by the party performing the minting. -- The :term:`script context`, which contains a representation of the spending transaction, as well as the hash of the minting policy which is currently being run. - -The minting policy is a function which receives these two inputs as *arguments*. -The validating node is responsible for passing them in and running the minting policy. -As with validator scripts, the arguments are passed encoded as :hsobj:`PlutusCore.Data.Data`. - -Plutus script context versions ------------------------------------- - -Minting policies have access to the :term:`script context` as their second argument. -Each version of Plutus minting policy scripts are differentiated only by their ``ScriptContext`` argument. - - See this example from the file ``MustSpendScriptOutput.hs`` (lines 340 to 422) showing code addressing `Versioned Policies for both Plutus V1 and Plutus V2 <https://github.com/IntersectMBO/plutus-apps/blob/05e394fb6188abbbe827ff8a51a24541a6386422/plutus-contract/test/Spec/TxConstraints/MustSpendScriptOutput.hs#L340-L422>`_. - -Minting policies tend to be particularly interested in the ``mint`` field, since the point of a minting policy is to control which tokens are minted. - -It is also important for a minting policy to look at the tokens in the ``mint`` field that use its own currency symbol i.e. policy hash. -Note that checking only a specific token name is usually not correct. -The minting policy must check for correct minting (or lack there of) of all token names under its currency symbol. -This requires the policy to refer to its own hash --- fortunately this is provided for us in the script context of a minting policy. - -Writing minting policies ------------------------- - -Here is an example that puts this together to make a simple policy that allows anyone to mint the token so long as they do it one token at a time. -To begin with, we'll write a version that works with structured types. - -.. literalinclude:: BasicPolicies.hs - :start-after: BLOCK1 - :end-before: BLOCK2 - -However, scripts are actually given their arguments as type ``Data``, and must signal failure with ``error``, so we need to wrap up our typed version to use it on-chain. - -.. literalinclude:: BasicPolicies.hs - :start-after: BLOCK2 - :end-before: BLOCK3 - -Other policy examples ---------------------- - -Probably the simplest useful policy is one that requires a specific key to have signed the transaction in order to do any minting. -This gives the key holder total control over the supply, but this is often sufficient for asset types where there is a centralized authority. - -.. literalinclude:: BasicPolicies.hs - :start-after: BLOCK3 - :end-before: BLOCK4 - -.. note:: - We don't need to check that this transaction actually mints any of our asset type: the ledger rules ensure that the minting policy will only be run if some of that asset is being minted. diff --git a/doc/read-the-docs-site/tutorials/basic-validators.rst b/doc/read-the-docs-site/tutorials/basic-validators.rst deleted file mode 100644 index 466d5513d5b..00000000000 --- a/doc/read-the-docs-site/tutorials/basic-validators.rst +++ /dev/null @@ -1,102 +0,0 @@ -.. highlight:: haskell -.. _basic_validators_tutorial: - -Writing basic validator scripts -=============================== - -:term:`Validator scripts<validator script>` are the programs that can be used to lock transaction outputs on the chain. -Validator scripts are :term:`Plutus Core` programs, but we can use :term:`Plutus Tx` to write them easily in Haskell. -Check out the :ref:`Plutus Tx tutorial<plutus_tx_tutorial>` before reading this one. - -Validator arguments -------------------- - -Validators receive some information from the validating node: - -- The :term:`redeemer`, which is some script-specific data specified by the party spending the output. -- The :term:`datum`, which is some script-specific data specified by the party who created the output. -- The :term:`script context`, which contains a representation of the spending transaction, as well as the index of the input whose validator is currently being run. - -The validator is a function which receives these three inputs as *arguments*. -The validating node is responsible for passing them in and running the validator. - -The ``Data`` type ------------------ - -But how are the validator's arguments passed? -Different scripts are going to expect different sorts of values in their datums and redeemers. - -The answer is that we pass the arguments as a *generic* structured data type :hsobj:`PlutusCore.Data.Data`. -``Data`` is designed to make it easy to encode structured data into it, and is essentially a subset of CBOR. - -Validator scripts take three arguments of type ``Data``. -Since ``Data`` is represented as a builtin type in Plutus Core, we use a special Haskell type ``BuiltinData`` rather than the underlying ``Data`` type - -However, you will typically not want to use ``BuiltinData`` directly in your program, rather you will want to use your own datatypes. -We can easily convert to and from ``BuiltinData`` with the :hsobj:`PlutusTx.IsData.Class.ToData`, :hsobj:`PlutusTx.IsData.Class.FromData`, and :hsobj:`PlutusTx.IsData.Class.UnsafeFromData` typeclasses. -You usually don't need to write your own instances of these classes. -Instead, you can use the ``unstableMakeIsData`` or ``makeIsDataIndexed`` Template Haskell functions to generate one. - -.. note:: - The :hsobj:`PlutusTx.IsData.Class.UnsafeFromData` class provides ``unsafeFromBuiltinData``, which is the same as ``fromBuiltinData``, but is faster and fails with ``error`` rather than returning a ``Maybe``. - We'll use ``unsafeFromBuiltinData`` in this tutorial, but sometimes the other version is useful. - -.. literalinclude:: BasicValidators.hs - :start-after: BLOCK1 - :end-before: BLOCK2 - -Signaling failure ------------------ - -The most important thing that a validator can do is *fail*. -This indicates that the attempt to spend the output is invalid and that transaction validation should fail. -A validator succeeds if it does not explicitly fail. -The actual value returned by the validator is irrelevant. - -How does a validator fail? -It does so by using the :hsobj:`PlutusTx.Builtins.error` builtin. -Some other builtins may also trigger failure if they are used incorrectly (e.g. ``1/0``). - -Validator functions -------------------- - -We write validator scripts as Haskell functions, which we compile with Plutus Tx into Plutus Core. -The type of a validator function is ``BuiltinData -> BuiltinData -> BuiltinData -> ()``, that is, a function which takes three arguments of type ``BuiltinData``, and returns a value of type ``()`` ("unit" or "the empty tuple" -- since the return type doesn't matter we just pick something trivial). - -Here are two examples of simple validators that always succeed and always fail, respectively: - -.. literalinclude:: BasicValidators.hs - :start-after: BLOCK2 - :end-before: BLOCK3 - -If we want to write a validator that uses types other than ``BuiltinData``, we'll need to use the functions from :hsobj:`PlutusTx.IsData.Class.FromData` to decode them. -Importantly, ``unsafeFromBuiltinData`` can fail: in our example if the ``BuiltinData`` in the second argument is *not* a correctly encoded ``Date`` then it will fail the whole validation with ``error``, which is usually what we want if we have bad arguments. - -.. TODO: write a HOWTO about error reporting - -.. important:: - Unfortunately there's no way to provide failure diagnostics when a validator fails on chain -- it just fails. - However, since transaction validation is entirely deterministic, you'll always be informed of this before you submit the transaction to the chain, so you can debug it locally using ``traceError``. - -Here's an example that uses our date types to check whether the date which was provided is less than the stored limit in the datum. - -.. literalinclude:: BasicValidators.hs - :start-after: BLOCK3 - :end-before: BLOCK4 - -Plutus script context versions ------------------------------------- - -Validators have access to the :term:`script context` as their third argument. -Each version of Plutus validators are differentiated only by their ``ScriptContext`` argument. - - See this example from the file ``MustSpendScriptOutput.hs`` (lines 340 to 422) showing code addressing `Versioned Policies for both Plutus V1 and Plutus V2 <https://github.com/IntersectMBO/plutus-apps/blob/05e394fb6188abbbe827ff8a51a24541a6386422/plutus-contract/test/Spec/TxConstraints/MustSpendScriptOutput.hs#L340-L422>`_. - -The script context gives validators a great deal of power, because it allows them to inspect other inputs and outputs of the current transaction. -For example, here is a validator that will only accept the transaction if a particular payment is made as part of it. - -.. literalinclude:: BasicValidators.hs - :start-after: BLOCK4 - :end-before: BLOCK5 - -This makes use of some useful functions for working with script contexts. diff --git a/doc/read-the-docs-site/tutorials/index.rst b/doc/read-the-docs-site/tutorials/index.rst deleted file mode 100644 index e77c3c51b12..00000000000 --- a/doc/read-the-docs-site/tutorials/index.rst +++ /dev/null @@ -1,12 +0,0 @@ -.. _plutus_tutorials: - -Tutorials -========= - -.. toctree:: - :maxdepth: 3 - :titlesonly: - - plutus-tx - basic-validators - basic-minting-policies diff --git a/doc/read-the-docs-site/tutorials/plutus-tx.rst b/doc/read-the-docs-site/tutorials/plutus-tx.rst deleted file mode 100644 index bc328dfb03a..00000000000 --- a/doc/read-the-docs-site/tutorials/plutus-tx.rst +++ /dev/null @@ -1,219 +0,0 @@ -.. highlight:: haskell -.. _plutus_tx_tutorial: - -Using Plutus Tx -=============== - -Plutus applications are written as a single Haskell program, which describes both the code that runs off the chain (on a user’s computer, or in their wallet, for example), and on the chain as part of transaction validation. - -The parts of the program that describe the on-chain code are still just Haskell, but they are compiled into :term:`Plutus Core`, rather than into the normal compilation target language. -We refer to them as :term:`Plutus Tx` programs (where 'Tx' indicates that these components usually go into transactions). - -.. warning:: - - Strictly speaking, while the majority of simple Haskell will work, only a subset of Haskell is supported by the Plutus Tx compiler. - The Plutus Tx compiler will tell you if you are attempting to use an unsupported component. - -The key technique that we use to implement Plutus Tx is called *staged metaprogramming*, which means that the main Haskell program generates *another* program (in this case, the Plutus Core program that will run on the blockchain). -Plutus Tx is the mechanism we use to write those programs, but since Plutus Tx is just part of the main Haskell program, we can share types and definitions between the two. - -.. _template_haskell_preliminaries: - -Template Haskell preliminaries ------------------------------- - -Plutus Tx uses Haskell's metaprogramming support, Template Haskell, for two main reasons: - -- Template Haskell enables us to work at compile time, which is when we do Plutus Tx compilation. -- It allows us to wire up the machinery that invokes the Plutus Tx compiler. - -Template Haskell is very versatile, but we only use a few features. - -Template Haskell begins with *quotes*. -A Template Haskell quote is a Haskell expression ``e`` inside special brackets ``[|| e ||]``. -It has type ``Q (TExp a)`` where ``e`` has type ``a``. ``TExp a`` is a *representation* an expression of type ``a``, i.e. the syntax of the actual Haskell expression that was quoted. -The quote lives in the type ``Q`` of quotes, which isn’t very interesting for us. - -.. note:: - - There is also an abbreviation ``TExpQ a`` for ``Q (TExp a)``, which avoids some parentheses. - -You can *splice* a quote into your program using the ``$$`` operator. -This inserts the syntax represented by the quote into the program at the point where the splice is written. - -Simply put, a quote allows us to talk about Haskell programs as *values*. - -The Plutus Tx compiler compiles Haskell *expressions* (not values!), so naturally it takes a quote (representing an expression) as an argument. -The result is a new quote, this time for a Haskell program that represents the *compiled* program. -In Haskell, the type of :hsobj:`PlutusTx.TH.compile` is ``TExpQ a → TExpQ (CompiledCode a)``. -This is just what we already said: - -- ``TExpQ a`` is a quoted representing a program of type ``a``. - -- ``TExpQ (CompiledCode a)`` is quote representing a - compiled Plutus Core program. - -.. note:: - - :hsobj:`PlutusTx.CompiledCode` also has a type parameter ``a``, which corresponds to the type of the original expression. - This lets us "remember" the type of the original Haskell program we compiled. - -Since :hsobj:`PlutusTx.TH.compile` produces a quote, to use the result we need to splice it back into our program. -The Plutus Tx compiler runs when compiling the main program, and the compiled program will be inserted into the main program. - -This is all you need to know about the Template Haskell! -We often use the same simple pattern: make a quote, immediately call :hsobj:`PlutusTx.TH.compile`, and then splice the result back in. - -.. _writing_basic_plutustx_programs: - -Writing basic Plutus Tx programs --------------------------------- - -.. literalinclude:: BasicPlutusTx.hs - :start-after: BLOCK1 - :end-before: BLOCK2 - -This simple program just evaluates to the integer ``1``. - -.. note:: - The examples that show the Plutus Core generated from compilation include doctests. - The syntax of Plutus Core might look unfamiliar, since this syntax is used for the 'assembly language', which means you don't need to inspect the compiler's output. - But for the purpose of this tutorial, it is useful to understand what is happening. - -.. literalinclude:: BasicPlutusTx.hs - :start-after: BLOCK2 - :end-before: BLOCK3 - -We can see how the metaprogramming works: the Haskell program ``1`` was turned into a ``CompiledCode Integer`` at compile time, which we spliced into our Haskell program. -We can inspect the generated program at runtime to see the generated Plutus Core (or to put it on the blockchain). - -We also see the standard usage pattern: a TH quote, wrapped in a call to :hsobj:`PlutusTx.TH.compile`, wrapped in a ``$$`` splice. -This is how all our Plutus Tx programs are written. - -This is a slightly more complex program. It includes the identity function on integers. - -.. literalinclude:: BasicPlutusTx.hs - :start-after: BLOCK3 - :end-before: BLOCK4 - -.. _functions_and_datatypes: - -Functions and datatypes ------------------------ - -You can use functions inside your expression. -In practice, you will usually want to define the entirety of your Plutus Tx program as a definition outside the quote, and then simply call it inside the quote. - -.. literalinclude:: BasicPlutusTx.hs - :start-after: BLOCK4 - :end-before: BLOCK5 - -We can use normal Haskell datatypes and pattern matching freely: - -.. literalinclude:: BasicPlutusTx.hs - :start-after: BLOCK5 - :end-before: BLOCK6 - -Unlike functions, datatypes do not need any kind of special annotation to be used inside a quote, hence we can use types like ``Maybe`` from the Haskell ``Prelude``. -This works for your own datatypes too! - -Here’s a small example with a datatype representing a potentially open-ended end date. - -.. literalinclude:: BasicPlutusTx.hs - :start-after: BLOCK6 - :end-before: BLOCK7 - -We could also have defined the ``pastEnd`` function as a separate ``INLINABLE`` binding and just referred to it in the quote, but in this case, it’s small enough to just write in place. - -.. _typeclasses: - -Typeclasses ------------ - -So far we have used functions like ``lessThanEqInteger`` for comparing ``Integer`` s, which is much less convenient than ``<`` from the standard Haskell ``Ord`` typeclass. - -Plutus Tx does support typeclasses, but we cannot use many of the standard typeclasses, since we require their class methods to be ``INLINABLE``, and the implementations for types such as ``Integer`` use the Plutus Tx built-ins. - -Redefined versions of many standard typeclasses are available in the Plutus Tx Prelude. -As such, you should be able to use most typeclass functions in your Plutus Tx programs. - -For example, here is a version of the ``pastEnd`` function using ``<``. -This will be compiled to exactly the same code as the previous definition. - -.. literalinclude:: BasicPlutusTx.hs - :start-after: BLOCK7 - :end-before: BLOCK8 - -.. _the_plutus_tx_prelude: - -The Plutus Tx Prelude ---------------------- - -The :hsmod:`PlutusTx.Prelude` module is a drop-in replacement for the normal Haskell Prelude, with some redefined functions and typeclasses that makes it easier for the Plutus Tx compiler to handle (i.e.``INLINABLE``). - -Use the Plutus Tx Prelude for code that you expect to compile with the Plutus Tx compiler. -All the definitions in the Plutus Tx Prelude include working Haskell definitions, which means that you can use them in normal Haskell code too, although the Haskell Prelude versions will probably perform better. - -To use the Plutus Tx Prelude, use the ``NoImplicitPrelude`` language pragma and import :hsmod:`PlutusTx.Prelude`. - -Plutus Tx includes some built-in types and functions for working with primitive data (integers and bytestrings), as well as a few special functions. -These types are also exported from the Plutus Tx Prelude. - -The :hsobj:`PlutusTx.Builtins.error` built-in deserves a special mention. -:hsobj:`PlutusTx.Builtins.error` causes the transaction to abort when it is evaluated, which is one way to trigger a validation failure. - -.. _lifting_values: - -Lifting values --------------- - -So far we’ve seen how to define pieces of code *statically* (when you *compile* your main Haskell program), but you might want to generate code *dynamically* (that is, when you *run* your main Haskell program). -For example, you might be writing the body of a transaction to initiate a crowdfunding smart contract, which would need to be parameterized by data determining the size of the goal, the campaign start and end times, etc. - -We can do this in the same way that we parameterize code in functional programming: write the static code as a *function* and provide the argument later to configure it. - -In our case, there is a slight complication: we want to make the argument and apply the function to it at *runtime*. -Plutus Tx addresses this through *lifting*. -Lifting enables the use of the same types, both inside your Plutus Tx program *and* in the external code that uses it. - -.. note:: - - In this context, *runtime* means the runtime of the main Haskell program, **not** when the Plutus Core runs on the chain. - We want to configure our code when the main Haskell program runs, as that is when we will be getting user input. - -In this example, we add an add-one function. - -.. literalinclude:: BasicPlutusTx.hs - :start-after: BLOCK8 - :end-before: BLOCK9 - -Now, suppose we want to apply this to ``4`` at runtime, giving us a program that computes to ``5``. -We need to *lift* the argument (``4``) from Haskell to Plutus Core, and then we need to apply the function to it. - -.. literalinclude:: BasicPlutusTx.hs - :start-after: BLOCK9 - :end-before: BLOCK10 - -We lifted the argument using the :hsobj:`PlutusTx.liftCode` function. -To use this, a type must have an instance of the :hsobj:`PlutusTx.Lift` class. -For your own datatypes you should generate these with the :hsobj:`PlutusTx.makeLift` TH function from :hsmod:`PlutusTx.Lift`. - -.. note:: - - :hsobj:`PlutusTx.liftCode` is relatively unsafe because it ignores any errors that might occur from lifting something that might not be supported. - There is a :hsobj:`PlutusTx.safeLiftCode` if you want to explicitly handle these occurrences. - -The combined program applies the original compiled lambda to the lifted value (notice that the lambda is a bit complicated now, since we have compiled the addition into a built-in). - -Here’s an example with our custom datatype. -The output is the encoded version of ``False``. - -.. literalinclude:: BasicPlutusTx.hs - :start-after: BLOCK10 - :end-before: BLOCK11 - -Plutus Tx Compiler Options --------------------------- - -A number of options can be passed to the Plutus Tx compiler. See :ref:`plutus_tx_options` -for details. diff --git a/docusaurus/static/code/BasicPlutusTx.hs b/docusaurus/static/code/BasicPlutusTx.hs deleted file mode 100644 index f7ce8375007..00000000000 --- a/docusaurus/static/code/BasicPlutusTx.hs +++ /dev/null @@ -1,188 +0,0 @@ --- BLOCK1 --- Necessary language extensions for the Plutus Tx compiler to work. -{-# LANGUAGE DataKinds #-} -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE ScopedTypeVariables #-} -{-# LANGUAGE TemplateHaskell #-} - -{-# OPTIONS_GHC -fplugin-opt PlutusTx.Plugin:target-version=1.0.0 #-} - -module BasicPlutusTx where - -import PlutusCore.Default qualified as PLC -import PlutusCore.Version (plcVersion100) --- Main Plutus Tx module. -import PlutusTx --- Additional support for lifting. -import PlutusTx.Lift --- Builtin functions. -import PlutusTx.Builtins --- The Plutus Tx Prelude, discussed further below. -import PlutusTx.Prelude - --- Setup for doctest examples. - --- $setup --- >>> import Tutorial.PlutusTx --- >>> import PlutusTx --- >>> import PlutusCore --- >>> import PlutusCore.Evaluation.Machine.Ck --- >>> import Data.Text.Prettyprint.Doc - --- BLOCK2 -integerOne :: CompiledCode Integer -{- 'compile' turns the 'TExpQ Integer' into a - 'TExpQ (CompiledCode Integer)' and the splice - inserts it into the program. -} -integerOne = $$(compile - {- The quote has type 'TExpQ Integer'. - We always use unbounded integers in Plutus Core, so we have to pin - down this numeric literal to an ``Integer`` rather than an ``Int``. -} - [|| (1 :: Integer) ||]) - -{- | ->>> pretty $ getPlc integerOne -(program 1.0.0 - (con 1) -) --} --- BLOCK3 -integerIdentity :: CompiledCode (Integer -> Integer) -integerIdentity = $$(compile [|| \(x:: Integer) -> x ||]) - -{- | ->>> pretty $ getPlc integerIdentity -(program 1.0.0 - (lam ds (con integer) ds) -) --} --- BLOCK4 -{- Functions which will be used in Plutus Tx programs should be marked - with GHC’s 'INLINABLE' pragma. This is usually necessary for - non-local functions to be usable in Plutus Tx blocks, as it instructs - GHC to keep the information that the Plutus Tx compiler needs. While - you may be able to get away with omitting it, it is good practice to - always include it. -} -{-# INLINABLE plusOne #-} -plusOne :: Integer -> Integer -{- 'addInteger' comes from 'PlutusTx.Builtins', and is - mapped to the builtin integer addition function in Plutus Core. -} -plusOne x = x `addInteger` 1 - -{-# INLINABLE myProgram #-} -myProgram :: Integer -myProgram = - let - -- Local functions do not need to be marked as 'INLINABLE'. - plusOneLocal :: Integer -> Integer - plusOneLocal x = x `addInteger` 1 - - localTwo = plusOneLocal 1 - externalTwo = plusOne 1 - in localTwo `addInteger` externalTwo - -functions :: CompiledCode Integer -functions = $$(compile [|| myProgram ||]) - -{- We’ve used the CK evaluator for Plutus Core to evaluate the program - and check that the result was what we expected. -} -{- | ->>> pretty $ unsafeEvaluateCk $ toTerm $ getPlc functions -(con 4) --} --- BLOCK5 -matchMaybe :: CompiledCode (Maybe Integer -> Integer) -matchMaybe = $$(compile [|| \(x:: Maybe Integer) -> case x of - Just n -> n - Nothing -> 0 - ||]) --- BLOCK6 --- | Either a specific end date, or "never". -data EndDate = Fixed Integer | Never - --- | Check whether a given time is past the end date. -pastEnd :: CompiledCode (EndDate -> Integer -> Bool) -pastEnd = $$(compile [|| \(end::EndDate) (current::Integer) -> case end of - Fixed n -> n `lessThanEqualsInteger` current - Never -> False - ||]) --- BLOCK7 --- | Check whether a given time is past the end date. -pastEnd' :: CompiledCode (EndDate -> Integer -> Bool) -pastEnd' = $$(compile [|| \(end::EndDate) (current::Integer) -> case end of - Fixed n -> n < current - Never -> False - ||]) --- BLOCK8 -addOne :: CompiledCode (Integer -> Integer) -addOne = $$(compile [|| \(x:: Integer) -> x `addInteger` 1 ||]) --- BLOCK9 -addOneToN :: Integer -> CompiledCode Integer -addOneToN n = - addOne - -- 'unsafeApplyCode' applies one 'CompiledCode' to another. - `unsafeApplyCode` - -- 'liftCode' lifts the argument 'n' into a - -- 'CompiledCode Integer'. It needs a version to tell it what - -- Plutus Core language version to target, if you don't care you - -- can use 'liftCodeDef' - liftCode plcVersion100 n - -{- | ->>> pretty $ getPlc addOne -(program 1.0.0 - [ - (lam - addInteger - (fun (con integer) (fun (con integer) (con integer))) - (lam ds (con integer) [ [ addInteger ds ] (con 1) ]) - ) - (lam - arg - (con integer) - (lam arg (con integer) [ [ (builtin addInteger) arg ] arg ]) - ) - ] -) ->>> let program = getPlc $ addOneToN 4 ->>> pretty program -(program 1.0.0 - [ - [ - (lam - addInteger - (fun (con integer) (fun (con integer) (con integer))) - (lam ds (con integer) [ [ addInteger ds ] (con 1) ]) - ) - (lam - arg - (con integer) - (lam arg (con integer) [ [ (builtin addInteger) arg ] arg ]) - ) - ] - (con 4) - ] -) ->>> pretty $ unsafeEvaluateCk $ toTerm program -(con 5) --} --- BLOCK10 --- 'makeLift' generates instances of 'Lift' automatically. -makeLift ''EndDate - -pastEndAt :: EndDate -> Integer -> CompiledCode Bool -pastEndAt end current = - pastEnd - `unsafeApplyCode` - liftCode plcVersion100 end - `unsafeApplyCode` - liftCode plcVersion100 current - -{- | ->>> let program = getPlc $ pastEndAt Never 5 ->>> pretty $ unsafeEvaluateCk $ toTerm program -(abs - out_Bool (type) (lam case_True out_Bool (lam case_False out_Bool case_False)) -) --} --- BLOCK11 diff --git a/docusaurus/static/code/QuickStart.hs b/docusaurus/static/code/QuickStart.hs deleted file mode 100644 index a874fb3ba83..00000000000 --- a/docusaurus/static/code/QuickStart.hs +++ /dev/null @@ -1,26 +0,0 @@ --- BLOCK1 -{-# LANGUAGE ImportQualifiedPost #-} - -module Main where - -import AuctionValidator -import Data.ByteString qualified as B -import Data.ByteString.Base16 qualified as Base16 -import Data.ByteString.Short qualified as B -import PlutusLedgerApi.V2 qualified as V2 - -main :: IO () -main = B.writeFile "validator.uplc" . Base16.encode $ B.fromShort serialisedScript - where - script = auctionValidatorScript params - serialisedScript = V2.serialiseCompiledCode script - params = - AuctionParams - { apSeller = error "Replace with seller's wallet address" - , -- The asset to be auctioned is 10000 lovelaces - apAsset = V2.singleton V2.adaSymbol V2.adaToken 10000 - , -- The minimum bid is 100 lovelaces - apMinBid = 100 - , apEndTime = error "Replace with your desired end time" - } --- BLOCK2 diff --git a/docusaurus/static/code/plutus.json b/docusaurus/static/code/plutus.json deleted file mode 100644 index 542a1ed4301..00000000000 --- a/docusaurus/static/code/plutus.json +++ /dev/null @@ -1,92 +0,0 @@ -{ - "$id": "my-contract", - "$schema": "https://cips.cardano.org/cips/cip57/schemas/plutus-blueprint.json", - "$vocabulary": { - "https://cips.cardano.org/cips/cip57": true, - "https://json-schema.org/draft/2020-12/vocab/applicator": true, - "https://json-schema.org/draft/2020-12/vocab/core": true, - "https://json-schema.org/draft/2020-12/vocab/validation": true - }, - "preamble": { - "title": "My Contract", - "description": "A simple contract", - "version": "1.0.0", - "plutusVersion": "v2", - "license": "MIT" - }, - "validators": [ - { - "title": "My Validator", - "description": "An example validator", - "redeemer": { - "title": "My Redeemer", - "description": "A redeemer that does something awesome", - "purpose": { - "oneOf": [ - "spend", - "mint" - ] - }, - "schema": { - "$ref": "#/definitions/MyRedeemer" - } - }, - "datum": { - "title": "My Datum", - "description": "A datum that contains something awesome", - "purpose": "spend", - "schema": { - "$ref": "#/definitions/Integer" - } - }, - "parameters": [ - { - "title": "My Validator Parameters", - "description": "Compile-time validator parameters", - "purpose": "spend", - "schema": { - "$ref": "#/definitions/MyParams" - } - } - ] - } - ], - "definitions": { - "Bool": { - "dataType": "#boolean" - }, - "Integer": { - "dataType": "integer" - }, - "MyParams": { - "title": "Title for the MyParams definition", - "description": "Description for the MyParams definition", - "dataType": "constructor", - "fields": [ - { - "$ref": "#/definitions/Bool" - }, - { - "$ref": "#/definitions/Integer" - } - ], - "index": 0 - }, - "MyRedeemer": { - "oneOf": [ - { - "$comment": "Left redeemer", - "dataType": "constructor", - "fields": [], - "index": 0 - }, - { - "$comment": "Right redeemer", - "dataType": "constructor", - "fields": [], - "index": 1 - } - ] - } - } -} diff --git a/docusaurus/static/csv/builtin-parameters.csv b/docusaurus/static/csv/builtin-parameters.csv deleted file mode 100644 index 649c735fe1d..00000000000 --- a/docusaurus/static/csv/builtin-parameters.csv +++ /dev/null @@ -1,160 +0,0 @@ -Builtin function,Parameter name,Note -addInteger,addInteger-cpu-arguments-intercept,Linear model intercept for the CPU calculation -addInteger,addInteger-cpu-arguments-slope,Linear model coefficient for the CPU calculation -addInteger,addInteger-memory-arguments-intercept,Linear model intercept for the memory calculation -addInteger,addInteger-memory-arguments-slope,Linear model coefficient for the memory calculation -appendByteString,appendByteString-cpu-arguments-intercept,Linear model intercept for the CPU calculation -appendByteString,appendByteString-cpu-arguments-slope,Linear model coefficient for the CPU calculation -appendByteString,appendByteString-memory-arguments-intercept,Linear model intercept for the memory calculation -appendByteString,appendByteString-memory-arguments-slope,Linear model coefficient for the memory calculation -appendString,appendString-cpu-arguments-intercept,Linear model intercept for the CPU calculation -appendString,appendString-cpu-arguments-slope,Linear model coefficient for the CPU calculation -appendString,appendString-memory-arguments-intercept,Linear model intercept for the memory calculation -appendString,appendString-memory-arguments-slope,Linear model coefficient for the memory calculation -bData,bData-cpu-arguments,Constant CPU cost -bData,bData-memory-arguments,Constant CPU cost -blake2b_256,blake2b_256-cpu-arguments-intercept,Linear model intercept for the CPU calculation -blake2b_256,blake2b_256-cpu-arguments-slope,Linear model coefficient for the CPU calculation -blake2b_256,blake2b_256-memory-arguments,Constant memory cost -chooseData,chooseData-cpu-arguments,Constant CPU cost -chooseData,chooseData-memory-arguments,Constant memory cost -chooseList,chooseList-cpu-arguments,Constant CPU cost -chooseList,chooseList-memory-arguments,Constant memory cost -chooseUnit,chooseUnit-cpu-arguments,Constant CPU cost -chooseUnit,chooseUnit-memory-arguments,Constant memory cost -consByteString,consByteString-cpu-arguments-intercept,Linear model intercept for the CPU calculation -consByteString,consByteString-cpu-arguments-slope,Linear model coefficient for the CPU calculation -consByteString,consByteString-memory-arguments-intercept,Linear model intercept for the memory calculation -consByteString,consByteString-memory-arguments-slope,Linear model coefficient for the memory calculation -constrData,constrData-cpu-arguments,Constant CPU cost -constrData,constrData-memory-arguments,Constant memory cost -decodeUtf8,decodeUtf8-cpu-arguments-intercept,Linear model intercept for the CPU calculation -decodeUtf8,decodeUtf8-cpu-arguments-slope,Linear model coefficient for the CPU calculation -decodeUtf8,decodeUtf8-memory-arguments-intercept,Linear model intercept for the memory calculation -decodeUtf8,decodeUtf8-memory-arguments-slope,Linear model coefficient for the memory calculation -divideInteger,divideInteger-cpu-arguments-constant,Constant CPU cost (argument sizes above diagonal) -divideInteger,divideInteger-cpu-arguments-model-arguments-intercept,Linear model intercept for the CPU calculation (argument sizes on or below diagonal) -divideInteger,divideInteger-cpu-arguments-model-arguments-slope,Linear model coefficient for the CPU calculation (argument sizes on or below diagonal) -divideInteger,divideInteger-memory-arguments-intercept,Linear model intercept for the memory calculation (argument sizes on or below diagonal) -divideInteger,divideInteger-memory-arguments-minimum,Constant memory cost (argument sizes above diagonal) -divideInteger,divideInteger-memory-arguments-slope,Linear model coefficient for the memory calculation (argument sizes on or below diagonal) -encodeUtf8,encodeUtf8-cpu-arguments-intercept,Linear model intercept for the CPU calculation below diagonal -encodeUtf8,encodeUtf8-cpu-arguments-slope,Linear model coefficient for the CPU calculation -encodeUtf8,encodeUtf8-memory-arguments-intercept,Linear model intercept for the memory calculation -encodeUtf8,encodeUtf8-memory-arguments-slope,Linear model coefficient for the memory calculation -equalsByteString,equalsByteString-cpu-arguments-constant,Constant CPU cost (arguments different sizes) -equalsByteString,equalsByteString-cpu-arguments-intercept,Linear model intercept for the CPU calculation (arguments same size) -equalsByteString,equalsByteString-cpu-arguments-slope,Linear model coefficient for the CPU calculation (arguments same size) -equalsByteString,equalsByteString-memory-arguments,Constant memory -equalsData,equalsData-cpu-arguments-intercept,Linear model intercept for the CPU calculation -equalsData,equalsData-cpu-arguments-slope,Linear model coefficient for the CPU calculation -equalsData,equalsData-memory-arguments,Constant memory cost -equalsInteger,equalsInteger-cpu-arguments-intercept,Linear model intercept for the CPU calculation -equalsInteger,equalsInteger-cpu-arguments-slope,Linear model coefficient for the memory calculation -equalsInteger,equalsInteger-memory-arguments,Constant memory cost -equalsString,equalsString-cpu-arguments-constant,Constant CPU cost (arguments different sizes) -equalsString,equalsString-cpu-arguments-intercept,Linear model intercept for the CPU calculation (arguments same size) -equalsString,equalsString-cpu-arguments-slope,Linear model coefficient for the CPU calculation (arguments same size) -equalsString,equalsString-memory-arguments,Constant memory cost -fstPair,fstPair-cpu-arguments,Constant CPU cost -fstPair,fstPair-memory-arguments,Constant memory cost -headList,headList-cpu-arguments,Constant CPU cost -headList,headList-memory-arguments,Constant memory cost -iData,iData-cpu-arguments,Constant CPU cost -iData,iData-memory-arguments,Constant memory cost -ifThenElse,ifThenElse-cpu-arguments,Constant CPU cost -ifThenElse,ifThenElse-memory-arguments,Constant memory cost -indexByteString,indexByteString-cpu-arguments,Constant CPU cost -indexByteString,indexByteString-memory-arguments,Constant memory cost -lengthOfByteString,lengthOfByteString-cpu-arguments,Constant CPU cost -lengthOfByteString,lengthOfByteString-memory-arguments,Constant memory cost -lessThanByteString,lessThanByteString-cpu-arguments-intercept,Linear model intercept for the CPU calculation -lessThanByteString,lessThanByteString-cpu-arguments-slope,Linear model coefficient for the CPU calculation -lessThanByteString,lessThanByteString-memory-arguments,Constant memory cost -lessThanEqualsByteString,lessThanEqualsByteString-cpu-arguments-intercept,Linear model intercept for the CPU calculation -lessThanEqualsByteString,lessThanEqualsByteString-cpu-arguments-slope,Linear model coefficient for the CPU calculation -lessThanEqualsByteString,lessThanEqualsByteString-memory-arguments,Constant memory cost -lessThanEqualsInteger,lessThanEqualsInteger-cpu-arguments-intercept,Linear model intercept for the CPU calculation -lessThanEqualsInteger,lessThanEqualsInteger-cpu-arguments-slope,Linear model coefficient for the CPU calculation -lessThanEqualsInteger,lessThanEqualsInteger-memory-arguments,Constant memory cost -lessThanInteger,lessThanInteger-cpu-arguments-intercept,Linear model intercept for the CPU calculation -lessThanInteger,lessThanInteger-cpu-arguments-slope,Linear model coefficient for the CPU calculation -lessThanInteger,lessThanInteger-memory-arguments,Constant memory cost -listData,listData-cpu-arguments,Constant CPU cost -listData,listData-memory-arguments,Constant memory cost -mapData,mapData-cpu-arguments,Constant CPU cost -mapData,mapData-memory-arguments,Constant memory cost -mkCons,mkCons-cpu-arguments,Constant CPU cost -mkCons,mkCons-memory-arguments,Constant memory cost -mkNilData,mkNilData-cpu-arguments,Constant CPU cost -mkNilData,mkNilData-memory-arguments,Constant memory cost -mkNilPairData,mkNilPairData-cpu-arguments,Constant CPU cost -mkNilPairData,mkNilPairData-memory-arguments,Constant memory cost -mkPairData,mkPairData-cpu-arguments,Constant CPU cost -mkPairData,mkPairData-memory-arguments,Constant memory cost -modInteger,modInteger-cpu-arguments-constant,Constant CPU cost (argument sizes above diagonal) -modInteger,modInteger-cpu-arguments-model-arguments-intercept,Linear model intercept for the CPU calculation (argument sizes on or below diagonal) -modInteger,modInteger-cpu-arguments-model-arguments-slope,Linear model coefficient for the CPU calculation (argument sizes above diagonal) -modInteger,modInteger-memory-arguments-intercept,Linear model intercept for the memory calculation -modInteger,modInteger-memory-arguments-minimum,Constant memory cost (argument sizes above diagonal) -modInteger,modInteger-memory-arguments-slope,Linear model coefficient for the memory calculation (argument sizes on or below diagonal) -multiplyInteger,multiplyInteger-cpu-arguments-intercept,Linear model intercept for the CPU calculation -multiplyInteger,multiplyInteger-cpu-arguments-slope,Linear model coefficient for the CPU calculation -multiplyInteger,multiplyInteger-memory-arguments-intercept,Linear model intercept for the memory calculation -multiplyInteger,multiplyInteger-memory-arguments-slope,Linear model coefficient for the memory calculation -nullList,nullList-cpu-arguments,Constant CPU cost -nullList,nullList-memory-arguments,Constant memory cost -quotientInteger,quotientInteger-cpu-arguments-constant,Constant CPU cost (argument sizes above diagonal) -quotientInteger,quotientInteger-cpu-arguments-model-arguments-intercept,Linear model intercept for the CPU calculation (argument sizes on or below diagonal) -quotientInteger,quotientInteger-cpu-arguments-model-arguments-slope,Linear model coefficient for the CPU calculation (argument sizes on or below diagonal) -quotientInteger,quotientInteger-memory-arguments-intercept,Linear model intercept for the CPU calculation (argument sizes on or below diagonal) -quotientInteger,quotientInteger-memory-arguments-minimum,Constant memory cost (argument sizes above diagonal) -quotientInteger,quotientInteger-memory-arguments-slope,Linear model coefficient for the memory calculation (argument sizes on or below diagonal) -remainderInteger,remainderInteger-cpu-arguments-constant,Constant CPU cost (argument sizes above diagonal) -remainderInteger,remainderInteger-cpu-arguments-model-arguments-intercept,Linear model intercept for the CPU calculation (argument sizes on or below diagonal) -remainderInteger,remainderInteger-cpu-arguments-model-arguments-slope,Linear model coefficient for the CPU calculation (argument sizes on or below diagonal) -remainderInteger,remainderInteger-memory-arguments-intercept,Linear model intercept for the memory calculation (argument sizes on or below diagonal) -remainderInteger,remainderInteger-memory-arguments-minimum,Constant memory cost (argument sizes above diagonal) -remainderInteger,remainderInteger-memory-arguments-slope,Linear model coefficient for the memory calculation (argument sizes on or below diagonal) -serialiseData,serialiseData-cpu-arguments-intercept,Linear model intercept for the CPU calculation -serialiseData,serialiseData-cpu-arguments-slope,Linear model coefficient for the CPU calculation -serialiseData,serialiseData-memory-arguments-intercept,Linear model intercept for the memory calculation -serialiseData,serialiseData-memory-arguments-slope,Linear model coefficient for the memory calculation -sha2_256,sha2_256-cpu-arguments-intercept,Linear model intercept for the CPU calculation -sha2_256,sha2_256-cpu-arguments-slope,Linear model coefficient for the CPU calculation -sha2_256,sha2_256-memory-arguments,Constant memory cost -sha3_256,sha3_256-cpu-arguments-intercept,Linear model intercept for the CPU calculation -sha3_256,sha3_256-cpu-arguments-slope,Linear model coefficient for the CPU calculation -sha3_256,sha3_256-memory-arguments,Constant memory cost -sliceByteString,sliceByteString-cpu-arguments-intercept,Linear model intercept for the CPU calculation -sliceByteString,sliceByteString-cpu-arguments-slope,Linear model coefficient for the CPU calculation -sliceByteString,sliceByteString-memory-arguments-intercept,Linear model intercept for the memory calculation -sliceByteString,sliceByteString-memory-arguments-slope,Linear model coefficient for the memory calculation -sndPair,sndPair-cpu-arguments,Constant CPU cost -sndPair,sndPair-memory-arguments,Constant memory cost -subtractInteger,subtractInteger-cpu-arguments-intercept,Linear model intercept for the CPU calculation -subtractInteger,subtractInteger-cpu-arguments-slope,Linear model coefficient for the CPU calculation -subtractInteger,subtractInteger-memory-arguments-intercept,Linear model intercept for the memory calculation -subtractInteger,subtractInteger-memory-arguments-slope,Linear model coefficient for the memory calculation -tailList,tailList-cpu-arguments,Constant CPU cost -tailList,tailList-memory-arguments,Constant memory cost -trace,trace-cpu-arguments,Constant CPU cost -trace,trace-memory-arguments,Constant memory cost -unBData,unBData-cpu-arguments,Constant CPU cost -unBData,unBData-memory-arguments,Constant memory cost -unConstrData,unConstrData-cpu-arguments,Constant CPU cost -unConstrData,unConstrData-memory-arguments,Constant memory cost -unIData,unIData-cpu-arguments,Constant CPU cost -unIData,unIData-memory-arguments,Constant memory cost -unListData,unListData-cpu-arguments,Constant CPU cost -unListData,unListData-memory-arguments,Constant memory cost -unMapData,unMapData-cpu-arguments,Constant CPU cost -unMapData,unMapData-memory-arguments,Constant memory cost -verifyEcdsaSecp256k1Signature,verifyEcdsaSecp256k1Signature-cpu-arguments,Constant CPU cost -verifyEcdsaSecp256k1Signature,verifyEcdsaSecp256k1Signature-memory-arguments,Constant memory cost -verifyEd25519Signature,verifyEd25519Signature-cpu-arguments-intercept,Linear model intercept for the CPU calculation -verifyEd25519Signature,verifyEd25519Signature-cpu-arguments-slope,Linear model coefficient for the CPU calculation -verifyEd25519Signature,verifyEd25519Signature-memory-arguments,Constant memory cost -verifySchnorrSecp256k1Signature,verifySchnorrSecp256k1Signature-cpu-arguments-intercept,Linear model intercept for the CPU calculation -verifySchnorrSecp256k1Signature,verifySchnorrSecp256k1Signature-cpu-arguments-slope,Linear model coefficient for the CPU calculation -verifySchnorrSecp256k1Signature,verifySchnorrSecp256k1Signature-memory-arguments,Constant memory cost diff --git a/docusaurus/static/csv/machine-parameters.csv b/docusaurus/static/csv/machine-parameters.csv deleted file mode 100644 index ad191aa17e8..00000000000 --- a/docusaurus/static/csv/machine-parameters.csv +++ /dev/null @@ -1,17 +0,0 @@ -Operation,Parameter name,Note -apply,cekApplyCost-exBudgetCPU,Constant CPU cost -apply,cekApplyCost-exBudgetMemory,Constant memory cost -builtin,cekBuiltinCost-exBudgetCPU,Constant CPU cost -builtin,cekBuiltinCost-exBudgetMemory,Constant memory cost -con,cekConstCost-exBudgetCPU,Constant CPU cost -con,cekConstCost-exBudgetMemory,Constant memory cost -delay,cekDelayCost-exBudgetCPU,Constant CPU cost -delay,cekDelayCost-exBudgetMemory,Constant memory cost -force,cekForceCost-exBudgetCPU,Constant CPU cost -force,cekForceCost-exBudgetMemory,Constant memory cost -lam,cekLamCost-exBudgetCPU,Constant CPU cost -lam,cekLamCost-exBudgetMemory,Constant memory cost -startup,cekStartupCost-exBudgetCPU,Constant CPU cost -startup,cekStartupCost-exBudgetMemory,Constant memory cost -var,cekVarCost-exBudgetCPU,Constant CPU cost -var,cekVarCost-exBudgetMemory,Constant memory cost diff --git a/docusaurus/static/img/closing-tx-simple-auction-v3.png b/docusaurus/static/img/closing-tx-simple-auction-v3.png deleted file mode 100644 index 54d4a0befbb..00000000000 Binary files a/docusaurus/static/img/closing-tx-simple-auction-v3.png and /dev/null differ diff --git a/docusaurus/static/img/double-satisfaction.png b/docusaurus/static/img/double-satisfaction.png deleted file mode 100644 index a75a0ba20fa..00000000000 Binary files a/docusaurus/static/img/double-satisfaction.png and /dev/null differ diff --git a/docusaurus/static/img/first-bid-simple-auction-v3.png b/docusaurus/static/img/first-bid-simple-auction-v3.png deleted file mode 100644 index 090947d2917..00000000000 Binary files a/docusaurus/static/img/first-bid-simple-auction-v3.png and /dev/null differ diff --git a/docusaurus/static/img/platform-architecture.png b/docusaurus/static/img/platform-architecture.png deleted file mode 100644 index 4da5fbf4457..00000000000 Binary files a/docusaurus/static/img/platform-architecture.png and /dev/null differ diff --git a/docusaurus/static/img/second-bid-simple-auction-v3.png b/docusaurus/static/img/second-bid-simple-auction-v3.png deleted file mode 100644 index 8d5969dd57c..00000000000 Binary files a/docusaurus/static/img/second-bid-simple-auction-v3.png and /dev/null differ diff --git a/nix/outputs.nix b/nix/outputs.nix index 563c6ce3976..1083c410f8d 100644 --- a/nix/outputs.nix +++ b/nix/outputs.nix @@ -34,8 +34,6 @@ in { packages.plutus-metatheory-site = repoRoot.nix.plutus-metatheory-site; packages.pre-commit-check = ghc96.pre-commit-check; - packages.read-the-docs-site = ghc96.read-the-docs-site; - packages.combined-haddock = ghc96.combined-haddock; } (lib.optionalAttrs (system == "x86_64-linux" || system == "x86_64-darwin") @@ -50,9 +48,7 @@ in (lib.optionalAttrs (system == "x86_64-linux") { hydraJobs.latex-documents = repoRoot.nix.latex-documents; - hydraJobs.read-the-docs-site = ghc96.read-the-docs-site; hydraJobs.pre-commit-check = ghc96.pre-commit-check; - hydraJobs.combined-haddock = ghc96.combined-haddock; hydraJobs.mingwW64.ghc96 = ghc96-mingwW64.hydraJobs; diff --git a/nix/project.nix b/nix/project.nix index c97349103a4..4d986debedf 100644 --- a/nix/project.nix +++ b/nix/project.nix @@ -175,23 +175,6 @@ let project = lib.iogx.mkHaskellProject { inherit cabalProject; shellArgs = repoRoot.nix.shell; - readTheDocs = { - enable = true; - siteFolder = "doc/read-the-docs-site"; - }; - combinedHaddock = { - enable = true; - prologue = '' - = Combined documentation for all the public Plutus libraries - - == Handy module entrypoints - - * "PlutusTx": Compiling Haskell to PLC (Plutus Core; on-chain code). - * "PlutusTx.Prelude": Haskell prelude replacement compatible with PLC. - * "PlutusCore": Programming language in which scripts on the Cardano blockchain are written. - * "UntypedPlutusCore": On-chain Plutus code. - ''; - }; }; in diff --git a/nix/shell.nix b/nix/shell.nix index 44bab32897f..e7dba26712b 100644 --- a/nix/shell.nix +++ b/nix/shell.nix @@ -58,6 +58,7 @@ in # Node JS pkgs.nodejs_20 + pkgs.yarn ];