diff --git a/.github/workflows/cd-gitbook-sdk-docs.yaml b/.github/workflows/cd-gitbook-sdk-docs.yaml deleted file mode 100644 index 574253955c..0000000000 --- a/.github/workflows/cd-gitbook-sdk-docs.yaml +++ /dev/null @@ -1,29 +0,0 @@ -name: Publish SDK Docs to GitBook - -on: - push: - tags: - - "js/sdk@*" - -permissions: - contents: read - -jobs: - publish-docs: - name: Sync docs to GitBook - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v6 - - uses: actions/setup-node@v6 - with: - node-version-file: .nvmrc - - name: Publish docs - env: - GITBOOK_API_TOKEN: ${{ secrets.GITBOOK_API_TOKEN }} - GITBOOK_ORG_ID: ${{ secrets.GITBOOK_ORG_ID }} - PARENT_SPACE_ID: ${{ secrets.GITBOOK_PARENT_SPACE_ID }} - GITBOOK_SITE_ID: ${{ secrets.GITBOOK_SITE_ID }} - GIT_REF: ${{ github.ref }} - SPACE_VISIBILITY: ${{ vars.GITBOOK_SPACE_VISIBILITY }} - MAKE_DEFAULT: ${{ vars.GITBOOK_MAKE_DEFAULT }} - run: node scripts/gitbook-sync-sdk.mjs diff --git a/.gitignore b/.gitignore index 6c925760ab..afefc0200f 100644 --- a/.gitignore +++ b/.gitignore @@ -55,3 +55,7 @@ cache # Ignore developer-only local files .local + + +docs/ts +docs/python \ No newline at end of file diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000000..875ad8cd70 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,42 @@ +# SDK Docs workflow + +## Prerequisites +- `pip install -r docs/requirements.txt` +- `yarn install` +- `yarn build:libs` + +## Local preview +- TypeScript docs: `mkdocs serve -f docs/mkdocs-ts.yaml` +- Python docs: `mkdocs serve -f docs/mkdocs-python.yaml` + +## Deploying a new version (mike) +- TypeScript: + `yarn workspace @human-protocol/sdk build:doc` + `mike deploy -F ./docs/mkdocs-ts.yaml --deploy-prefix docs/ts [VERSION]` + `mike set-default -F ./docs/mkdocs-ts.yaml --deploy-prefix docs/ts [VERSION]` +- Python: + `mike deploy -F ./docs/mkdocs-python.yaml --deploy-prefix docs/python [VERSION]` + `mike set-default -F ./docs/mkdocs-python.yaml --deploy-prefix docs/python [VERSION]` + +## Deleting a deployed version +- TypeScript: `mike delete -F ./docs/mkdocs-ts.yaml --deploy-prefix docs/ts [VERSION]` +- Python: `mike delete -F ./docs/mkdocs-python.yaml --deploy-prefix docs/python [VERSION]` + +## Landing page (docs/index.html) +- If you edit `docs/index.html`, apply the change both on your working branch and on `gh-pages`. + +NEVER MERGE THE BRANCHES: `gh-pages` only contains docs builds, not the monorepo code. + +## Serving static files +- Serve only `index.html` (SDK docs won’t load): from `docs/`, run + `python -m http.server 8080 --bind 127.0.0.1` +- Serve the full published docs: create a mike deployment, switch to the `gh-pages` branch, go to `docs/`, then run + `python -m http.server 8080 --bind 127.0.0.1` + +## Repository structure (docs) +- `docs/index.html`: Static landing page that links to SDK docs (TS/Python). +- `docs/mkdocs-ts.yaml`: MkDocs config for the TypeScript site (deploys under `docs/ts` via mike). +- `docs/mkdocs-python.yaml`: MkDocs config for the Python site (deploys under `docs/python` via mike). +- `docs/ts/`: TypeScript site output; versioned builds live under `docs/ts/` with per-version assets in `docs/ts//assets/`. +- `docs/python/`: Python site output (if published); versioned builds live under `docs/python/`. +- `docs/overrides/`: Shared MkDocs theme overrides and assets (logo/header partials and images). diff --git a/docs/index.html b/docs/index.html new file mode 100644 index 0000000000..72ae5385ea --- /dev/null +++ b/docs/index.html @@ -0,0 +1,218 @@ + + + + + HUMAN Protocol SDKs + + + + +
+ +

+ HUMAN Protocol SDKs +

+

+ Choose your preferred language SDK to integrate with HUMAN Protocol. + Both SDKs expose the same core concepts, so you can build automation, + dApps, and services in the stack you know best. +

+ +
+ +
+
+ TypeScript Logo +
+
+ TypeScript + Node.js +
+

TypeScript SDK

+

+ Type-safe SDK for web, dApps and backend services. +

+ +
+ + +
+
+ Python Logo +
+
+ Python +
+

Python SDK

+

+ Python SDK for automation, bots, data/ML pipelines, and backend services. +

+ +
+
+
+ + + + diff --git a/docs/mkdocs-python.yaml b/docs/mkdocs-python.yaml new file mode 100644 index 0000000000..5661c3eb87 --- /dev/null +++ b/docs/mkdocs-python.yaml @@ -0,0 +1,98 @@ +site_name: HUMAN Protocol Python SDK Docs +site_url: https://sdk.humanprotocol.org/python/ +repo_name: humanprotocol/human-protocol +repo_url: https://github.com/humanprotocol/human-protocol +docs_dir: ../packages/sdk/python/human-protocol-sdk/docs +site_dir: python +theme: + name: material + custom_dir: overrides + logo: assets/img/logo.svg + favicon: assets/img/logo.svg + palette: + - scheme: default + primary: deep purple + accent: purple + toggle: + icon: material/brightness-7 + name: Switch to dark mode + - scheme: slate + primary: deep purple + accent: purple + toggle: + icon: material/brightness-3 + name: Switch to light mode + font: + text: Noto Sans + code: Roboto Mono + features: + - navigation.instant + - navigation.instant.prefetch + - navigation.top + - navigation.tracking + - navigation.path + - navigation.indexes + - navigation.prune + - content.tabs + - content.code.copy + - toc.follow + - announce.dismiss +extra: + language: python + version: + provider: mike + logo_href: https://sdk.humanprotocol.org +markdown_extensions: + - toc: + baselevel: 1 + permalink: true + - admonition + - pymdownx.details + - pymdownx.superfences + - pymdownx.tabbed: + alternate_style: true + - pymdownx.highlight: + anchor_linenums: true + - pymdownx.magiclink + - attr_list + - md_in_html +plugins: + - search + - mkdocstrings: + handlers: + python: + paths: [../packages/sdk/python/human-protocol-sdk] + options: + docstring_style: google + show_source: false + separate_signature: true + merge_init_into_class: true + heading_level: 2 + - mike + - section-index +nav: + - Overview: index.md + - Encryption: + - Encryption: encryption.md + - Encryption Utils: encryption_utils.md + - LegacyEncryption: legacy_encryption.md + - Escrow: + - EscrowClient: escrow_client.md + - EscrowUtils: escrow_utils.md + - KVStore: + - KVStoreClient: kvstore_client.md + - KVStoreUtils: kvstore_utils.md + - Operator: + - OperatorUtils: operator_utils.md + - Staking: + - StakingClient: staking_client.md + - StakingUtils: staking_utils.md + - Statistics: + - StatisticsUtils: statistics_utils.md + - Transaction: + - TransactionUtils: transaction_utils.md + - Worker: + - WorkerUtils: worker_utils.md + - Core utilities: core.md +extra_css: + - assets/css/custom.css diff --git a/docs/mkdocs-ts.yaml b/docs/mkdocs-ts.yaml new file mode 100644 index 0000000000..f55a4650d5 --- /dev/null +++ b/docs/mkdocs-ts.yaml @@ -0,0 +1,89 @@ +site_name: HUMAN Protocol TypeScript SDK Docs +site_url: https://sdk.humanprotocol.org/ts/ +repo_name: humanprotocol/human-protocol +repo_url: https://github.com/humanprotocol/human-protocol +docs_dir: ../packages/sdk/typescript/human-protocol-sdk/docs +site_dir: ts +theme: + name: material + custom_dir: overrides + logo: assets/img/logo.svg + favicon: assets/img/logo.svg + palette: + - scheme: default + primary: deep purple + accent: purple + toggle: + icon: material/brightness-7 + name: Switch to dark mode + - scheme: slate + primary: deep purple + accent: purple + toggle: + icon: material/brightness-3 + name: Switch to light mode + font: + text: Noto Sans + code: Roboto Mono + features: + - navigation.instant + - navigation.instant.prefetch + - navigation.top + - navigation.tracking + - navigation.path + - navigation.indexes + - navigation.prune + - content.tabs + - content.code.copy + - toc.follow + - announce.dismiss +extra: + language: typescript + version: + provider: mike + logo_href: https://sdk.humanprotocol.org +markdown_extensions: + - toc: + baselevel: 1 + permalink: true + - admonition + - pymdownx.details + - pymdownx.superfences + - pymdownx.tabbed: + alternate_style: true + - pymdownx.highlight: + anchor_linenums: true + - pymdownx.magiclink + - attr_list + - md_in_html + - pymdownx.escapeall: + hardbreak: false + nbsp: false +plugins: + - search + - mike + - section-index +nav: + - Overview: index.md + - Encryption: + - Encryption: classes/Encryption.md + - Encryption Utils: classes/EncryptionUtils.md + - Escrow: + - EscrowClient: classes/EscrowClient.md + - EscrowUtils: classes/EscrowUtils.md + - KVStore: + - KVStoreClient: classes/KVStoreClient.md + - KVStoreUtils: classes/KVStoreUtils.md + - Operator: + - OperatorUtils: classes/OperatorUtils.md + - Staking: + - StakingClient: classes/StakingClient.md + - StakingUtils: classes/StakingUtils.md + - Statistics: + - StatisticsUtils: classes/StatisticsUtils.md + - Transaction: + - TransactionUtils: classes/TransactionUtils.md + - Worker: + - WorkerUtils: classes/WorkerUtils.md +extra_css: + - assets/css/custom.css diff --git a/docs/overrides/assets/css/custom.css b/docs/overrides/assets/css/custom.css new file mode 100644 index 0000000000..acb3e3d0c7 --- /dev/null +++ b/docs/overrides/assets/css/custom.css @@ -0,0 +1,279 @@ +/* Define brand */ +:root, [data-md-color-scheme="default"] { + --md-default-bg-color: rgb(250, 250, 250); + --md-primary-fg-color: rgb(33, 25, 67); + --md-primary-fg-color--light: rgb(99, 9, 255); + --md-primary-fg-color--dark: rgb(99, 9, 255); + --md-primary-bg-color: rgb(212, 207, 255); + --md-primary-bg-color--light: rgb(212, 207, 255); + --md-accent-fg-color: rgb(212, 207, 255); + --pg-light-border: rgb(99, 9, 255); + --hb-hero-color: rgb(45, 45, 45); + --md-footer-bg-color--dark: var(--md-primary-fg-color); + --md-typeset-a-color: rgb(99, 9, 255); +} +:root, [data-md-color-scheme="slate"] { + --md-default-bg-color: rgb(33, 25, 67); + --md-primary-fg-color: rgb(16, 7, 53); + --md-primary-fg-color--light: rgb(99, 9, 255); + --md-primary-fg-color--dark: rgb(99, 9, 255); + --md-primary-bg-color: rgb(212, 207, 255); + --md-primary-bg-color--light: rgb(212, 207, 255); + --md-accent-fg-color: rgb(99, 9, 255); + --pg-light-border: rgb(47, 47, 47); + --hb-hero-color: rgb(212, 207, 255); + --md-code-bg-color: rgb(22 23 24); + --md-footer-bg-color--dark: var(--md-primary-fg-color); +} + + +.md-typeset .admonition.question, .md-typeset details.question { + border-color: transparent; +} + +.md-typeset .question>.admonition-title:before, .md-typeset .question>summary:before { + background-color: rgb(99, 9, 255); +} + +[data-md-color-scheme="slate"] .md-typeset .question>.admonition-title:before, [data-md-color-scheme="slate"] .md-typeset .question>summary:after { + background-color: rgba(212, 207, 255); +} + +[data-md-color-scheme="default"] .md-typeset .question>.admonition-title:before, [data-md-color-scheme="default"] .md-typeset .question>summary:after { + background-color: rgb(99, 9, 255); +} + +[data-md-color-scheme="slate"] .md-typeset .question>.admonition-title, [data-md-color-scheme="slate"] .md-typeset .question>summary { + background-color: rgb(16, 7, 53); +} + +[data-md-color-scheme="default"] .md-typeset .question>.admonition-title, [data-md-color-scheme="default"] .md-typeset .question>summary { + background-color: rgba(212, 207, 255, 0.25); +} + +[data-md-color-scheme="slate"] .md-typeset .admonition.question:focus-within, [data-md-color-scheme="slate"] .md-typeset details.question:focus-within { + box-shadow: 0 0 0 .2rem rgb(99, 9, 255); +} + +[data-md-color-scheme="default"] .md-typeset .admonition.question:focus-within, [data-md-color-scheme="default"] .md-typeset details.question:focus-within { + box-shadow: 0 0 0 .2rem rgb(212, 207, 255); +} + +/* Hide the logo that appears at the TOP of the left sidebar (drawer) */ +.md-sidebar--primary .md-logo { + display: none !important; +} + +/* Tidy up the title row spacing after removing the logo */ +.md-sidebar--primary .md-nav__title { + padding-top: 0.4rem; + padding-bottom: 0.4rem; +} + +/* Safety: if an inline SVG sneaks in, hide it too */ +.md-sidebar--primary .md-nav__title svg { + display: none !important; +} + +h1, h2, h3, h4, h5, h6 { + font-weight: 700 !important; +} + +/* Language switch: match version switch styling */ +.md-header__langswitch { + position: relative; + display: inline-flex; + align-items: center; + gap: 0.4rem; + padding: 6px 12px; + border-radius: 999px; + font-weight: 600; + font-size: 0.85rem; + border: 1px solid rgba(255, 255, 255, 0.3); + background: rgba(255, 255, 255, 0.08); + color: #fff; + cursor: pointer; +} + +.md-header__button:hover{ + opacity: 1; +} + +.md-header__langswitch:hover, +.md-header__langswitch:focus-within { + background: #ffffff; /* solid for dark scheme default */ + border-color: #ffffff; /* solid border */ + color: var(--md-primary-fg-color); +} + +/* Light scheme override: use brand color solid instead of rgba */ +[data-md-color-scheme="default"] .md-header__langswitch { + background: rgba(99, 9, 255, 0.08); + color: rgb(212, 207, 255); + border-color: rgba(99, 9, 255); +} + +.md-header__langlabel { + white-space: nowrap; +} + + +.md-header__langmenu { + position: absolute; + top: calc(100% + 14px); + right: 0; + min-width: 170px; + padding: 8px; + border-radius: 10px; + background: var(--md-default-bg-color); + border: 1px solid var(--md-primary-bg-color); + box-shadow: 0 12px 28px rgba(0, 0, 0, 0.18); + display: none; + flex-direction: column; + gap: 2px; + z-index: 40; + +} + +.md-header__langswitch:hover .md-header__langmenu, +.md-header__langswitch:focus-within .md-header__langmenu { + display: flex; +} + +.md-header__langitem { + padding: 0.4rem 0.7rem; + text-decoration: none; + color: var(--md-primary-fg-color); + border-radius: 8px; + display: flex; + justify-content: space-between; + font-weight: 100; +} + +.md-header__langitem:hover, +.md-header__langitem:focus-visible { + background: rgba(99, 9, 255, 0.08); + color: var(--md-primary-fg-color); +} + +.md-header__langitem--active { + background: rgba(99, 9, 255, 0.12); + color: var(--md-primary-fg-color); +} + +/* Mobile: optionally hide or shrink */ +@media (max-width: 900px) { + .md-header__langswitch { + display: none; /* or keep and it will still work */ + } +} + +/* Version switch (mike) */ +.md-version { + position: relative; +} + +.md-header .md-version__current { + display: inline-flex; + align-items: center; + gap: 0.4rem; + padding: 6px 12px; + border-radius: 999px; + font-weight: 600; + font-size: 0.85rem; + text-transform: none; + letter-spacing: 0; + border: 1px solid rgba(255, 255, 255, 0.3); + background: rgba(255, 255, 255, 0.08); + color: #fff; +} + +[data-md-color-scheme="default"] .md-header .md-version__current { + background: rgba(99, 9, 255, 0.08); + color: rgb(212, 207, 255); + border-color: rgba(99, 9, 255); +} + +[data-md-color-scheme="slate"] .md-header .md-version__current { + background: rgba(255, 255, 255, 0.08); + color: #f9f6ff; + border-color: rgba(255, 255, 255, 0.3); +} + +.md-version__label { + margin-right: 0.15rem; +} + +.md-version__icon { + opacity: 0.7; +} + +.md-version__list { + position: absolute; + top: calc(100% + 6px); + right: 0; + min-width: 190px; + padding: 8px; + border-radius: 10px; + background: var(--md-default-bg-color); + border: 1px solid var(--md-primary-bg-color); + box-shadow: 0 12px 28px rgba(0, 0, 0, 0.18); + display: none; + flex-direction: column; + gap: 2px; + z-index: 40; +} + +.md-version[open] .md-version__list, +.md-version:focus-within .md-version__list { + display: flex; +} + +.md-version__item { + list-style: none; + color: var(--md-primary-fg-color); +} + +.md-version__link { + display: flex; + justify-content: space-between; + align-items: center; + padding: 8px 10px; + border-radius: 8px; + text-decoration: none; + color: inherit; + font-weight: 500; + transition: background 0.15s ease, color 0.15s ease; +} + +.md-version__link:hover, +.md-version__link:focus-visible { + background: rgba(99, 9, 255, 0.08); + color: var(--md-primary-fg-color); +} + +.md-version__link--active { + background: rgba(99, 9, 255, 0.12); + color: var(--md-primary-fg-color); + font-weight: 700; +} + +/* Disclaimer bar */ +.md-disclaimer { + background: rgb(212, 207, 255); + color: var(--md-primary-fg-color); + border-bottom: 1px solid rgba(99, 9, 255, 0.25); + padding: 0.1rem 0; +} + +.md-disclaimer p { + margin: 0; + font-size: 0.6rem; + text-align: center; +} + +.md-disclaimer__link { + font-weight: 550; + color: rgb(99, 9, 255); + text-decoration: underline; +} \ No newline at end of file diff --git a/docs/overrides/assets/img/logo.svg b/docs/overrides/assets/img/logo.svg new file mode 100644 index 0000000000..b827f1dbc7 --- /dev/null +++ b/docs/overrides/assets/img/logo.svg @@ -0,0 +1,3 @@ + + + diff --git a/docs/overrides/assets/img/python-logo.webp b/docs/overrides/assets/img/python-logo.webp new file mode 100644 index 0000000000..0a2ac72630 Binary files /dev/null and b/docs/overrides/assets/img/python-logo.webp differ diff --git a/docs/overrides/assets/img/ts-logo.png b/docs/overrides/assets/img/ts-logo.png new file mode 100644 index 0000000000..77fbb6aec2 Binary files /dev/null and b/docs/overrides/assets/img/ts-logo.png differ diff --git a/docs/overrides/partials/header.html b/docs/overrides/partials/header.html new file mode 100644 index 0000000000..0cc6f97067 --- /dev/null +++ b/docs/overrides/partials/header.html @@ -0,0 +1,171 @@ +{#- + This file was automatically generated - do not edit +-#} +{% set class = "md-header" %} +{% if "navigation.tabs.sticky" in features %} + {% set class = class ~ " md-header--shadow md-header--lifted" %} +{% elif "navigation.tabs" not in features %} + {% set class = class ~ " md-header--shadow" %} +{% endif %} + +
+ + + {% if "navigation.tabs.sticky" in features %} + {% if "navigation.tabs" in features %} + {% include "partials/tabs.html" %} + {% endif %} + {% endif %} +
+ +
+
+

+ The new styling applies starting with version 5.2.0. For earlier versions, visit + legacy-sdk.humanprotocol.org. +

+
+
+ + diff --git a/docs/overrides/partials/logo.html b/docs/overrides/partials/logo.html new file mode 100644 index 0000000000..1e7def1860 --- /dev/null +++ b/docs/overrides/partials/logo.html @@ -0,0 +1,10 @@ + \ No newline at end of file diff --git a/docs/requirements.txt b/docs/requirements.txt new file mode 100644 index 0000000000..206680fe29 --- /dev/null +++ b/docs/requirements.txt @@ -0,0 +1,6 @@ +mkdocs-material +pymdown-extensions +pyyaml +mike +mkdocs-section-index +mkdocstrings[python] \ No newline at end of file diff --git a/docs/sdk/README.md b/docs/sdk/README.md deleted file mode 100644 index 225cab21fa..0000000000 --- a/docs/sdk/README.md +++ /dev/null @@ -1,38 +0,0 @@ -# HUMAN Protocol SDK - -Welcome to the official documentation for HUMAN Protocol SDK. - -## Overview - -- Covers both TypeScript and Python SDKs used to build on HUMAN Protocol. -- Use the sidebar to browse guides and API references; search to quickly find classes and functions. - -## Install - -### Typescript - -```bash -npm install @human-protocol/sdk -# or -yarn add @human-protocol/sdk -``` - -### Python - -```bash -pip install human-protocol-sdk -``` - -## Links - -- [NPM package](https://www.npmjs.com/package/@human-protocol/sdk) -- [PyPI package](https://pypi.org/project/human-protocol-sdk/) -- [GitHub repository](https://github.com/humanprotocol/human-protocol) - -## Versioning - -- Content is imported from the repository at release time. - -## Changelog - -- [CHANGELOG](changelog.md) — release notes and changes. diff --git a/docs/sdk/SUMMARY.md b/docs/sdk/SUMMARY.md deleted file mode 100644 index 5241c9eb3d..0000000000 --- a/docs/sdk/SUMMARY.md +++ /dev/null @@ -1,61 +0,0 @@ -# Table of contents - -- [HUMAN Protocol SDK](README.md) - -## Typescript SDK - -- [Encryption](typescript/encryption/README.md) - - [Encryption](typescript/encryption/classes/Encryption.md) - - [EncryptionUtils](typescript/encryption/classes/EncryptionUtils.md) -- [Escrow](typescript/escrow/README.md) - - [EscrowClient](typescript/escrow/classes/EscrowClient.md) - - [EscrowUtils](typescript/escrow/classes/EscrowUtils.md) -- [KVStore](typescript/kvstore/README.md) - - [KVStoreClient](typescript/kvstore/classes/KVStoreClient.md) - - [KVStoreUtils](typescript/kvstore/classes/KVStoreUtils.md) -- [Staking](typescript/staking/README.md) - - [StakingClient](typescript/staking/classes/StakingClient.md) -- [Operator](typescript/operator/README.md) - - [OperatorUtils](typescript/operator/classes/OperatorUtils.md) -- [Storage](typescript/storage/README.md) - - [StorageClient](typescript/storage/classes/StorageClient.md) -- [Statistics](typescript/statistics/README.md) - - [StatisticsClient](typescript/statistics/classes/StatisticsClient.md) -- [Transaction](typescript/transaction/README.md) - - [TransactionUtils](typescript/transaction/classes/TransactionUtils.md) - -## Python SDK - -- [agreement](python/human_protocol_sdk.agreement.md) - - [bootstrap](python/human_protocol_sdk.agreement.bootstrap.md) - - [measures](python/human_protocol_sdk.agreement.measures.md) - - [utils](python/human_protocol_sdk.agreement.utils.md) -- [encryption](python/human_protocol_sdk.encryption.md) - - [encryption](python/human_protocol_sdk.encryption.encryption.md) - - [legacy_encryption](python/human_protocol_sdk.legacy_encryption.md) - - [encryption_utils](python/human_protocol_sdk.encryption.encryption_utils.md) -- [escrow](python/human_protocol_sdk.escrow.md) - - [escrow_client](python/human_protocol_sdk.escrow.escrow_client.md) - - [escrow_utils](python/human_protocol_sdk.escrow.escrow_utils.md) -- [kvstore](python/human_protocol_sdk.kvstore.md) - - [kvstore_client](python/human_protocol_sdk.kvstore.kvstore_client.md) - - [kvstore_utils](python/human_protocol_sdk.kvstore.kvstore_utils.md) -- [staking](python/human_protocol_sdk.staking.md) - - [staking_client](python/human_protocol_sdk.staking.staking_client.md) - - [staking_utils](python/human_protocol_sdk.staking.staking_utils.md) -- [operator](python/human_protocol_sdk.operator.md) - - [operator_utils](python/human_protocol_sdk.operator.operator_utils.md) -- [statistics](python/human_protocol_sdk.statistics.md) - - [statistics_client](python/human_protocol_sdk.statistics.statistics_client.md) -- [storage](python/human_protocol_sdk.storage.md) - - [storage_client](python/human_protocol_sdk.storage.storage_client.md) - - [storage_utils](python/human_protocol_sdk.storage.storage_utils.md) -- [transaction](python/human_protocol_sdk.transaction.md) - - [transaction_utils](python/human_protocol_sdk.transaction.transaction_utils.md) -- [constants](python/human_protocol_sdk.constants.md) -- [filter](python/human_protocol_sdk.filter.md) -- [utils](python/human_protocol_sdk.utils.md) - ---- - -- [CHANGELOG](changelog.md) diff --git a/docs/sdk/changelog.md b/docs/sdk/changelog.md deleted file mode 100644 index 1050ceae31..0000000000 --- a/docs/sdk/changelog.md +++ /dev/null @@ -1,36 +0,0 @@ -# Changelog - -### Added -- new optional config for querying subgraph with retries when failuers are due to bad indexers errors - -### Changed - -### Deprecated - -### Removed - -### Fixed - -### Security - -# How to upgrade - -## Typescript - -### yarn - -``` -yarn upgrade @human-protocol/sdk -``` - -### npm - -``` -npm update @human-protocol/sdk -``` - -## Python - -``` -pip install --upgrade human-protocol-sdk -``` diff --git a/docs/sdk/python/human_protocol_sdk.agreement.bootstrap.md b/docs/sdk/python/human_protocol_sdk.agreement.bootstrap.md deleted file mode 100644 index d1659f6ba2..0000000000 --- a/docs/sdk/python/human_protocol_sdk.agreement.bootstrap.md +++ /dev/null @@ -1,41 +0,0 @@ -# human_protocol_sdk.agreement.bootstrap module - -Module containing methods to calculate confidence intervals using bootstrapping. - -### human_protocol_sdk.agreement.bootstrap.confidence_intervals(data, statistic_fn, n_iterations=1000, n_sample=None, confidence_level=0.95, algorithm='bca', seed=None) - -Returns a tuple, containing the confidence interval for the boostrap estimates of the given statistic and statistics of the bootstrap samples. - -* **Parameters:** - * **data** (`Sequence`) – Data to estimate the statistic. - * **statistic_fn** (`Callable`) – Function to calculate the statistic. statistic_fn(data) must return a number. - * **n_iterations** (`int`) – Number of bootstrap samples to use for the estimate. - * **n_sample** (`Optional`[`int`]) – If provided, determines the size of each bootstrap sample - drawn from the data. If omitted, is equal to the length of the data. - * **confidence_level** – Size of the confidence interval. - * **algorithm** – Which algorithm to use for the confidence interval - estimation. “bca” uses the “Bias Corrected Bootstrap with - Acceleration”, “percentile” simply takes the appropriate - percentiles from the bootstrap distribution. - * **seed** – Random seed to use. -* **Return type:** - `Tuple`[`Tuple`[`float`, `float`], `ndarray`] -* **Returns:** - Confidence interval and bootstrap distribution. -* **Example:** - ```python - from human_protocol_sdk.agreement.bootstrap import confidence_interval - import numpy as np - - np.random.seed(42) - data = np.random.randn(10_000) - fn = np.mean - sample_mean = fn(data) - print(f"Sample mean is {sample_mean:.3f}") - # Sample mean is -0.002 - - cl = 0.99 - ci, _ = confidence_interval(data, fn, confidence_level=cl) - print(f"Population mean is between {ci[0]:.2f} and {ci[1]:.2f} with a probablity of {cl}") - # Population mean is between -0.02 and 0.02 with a probablity of 0.99 - ``` diff --git a/docs/sdk/python/human_protocol_sdk.agreement.md b/docs/sdk/python/human_protocol_sdk.agreement.md deleted file mode 100644 index aaa48cd386..0000000000 --- a/docs/sdk/python/human_protocol_sdk.agreement.md +++ /dev/null @@ -1,105 +0,0 @@ -# human_protocol_sdk.agreement package - -**A subpackage for calculating Inter Rater Agreement measures for annotated data.** - -This module contains methods that estimate the agreement -between annotatorsin a data labelling project. -Its role is to provide easy access to means of estimating data quality -for developers of Reputation and Recording Oracles. - -## Getting Started - -This module is an optional extra of the HUMAN Protocol SDK. -In order to use it, run the following command: - -```bash -pip install human_protocol_sdk[agreement] -``` - -### A simple example - -The main functionality of the module is provided by a single function called [agreement](human_protocol_sdk.agreement.measures.md#human_protocol_sdk.agreement.measures.agreement). -Suppose we have a very small annotation, where 3 annotators label 4 different images. -The goal is to find find if an image contain a cat or not, -so they label them either cat or not. - -After processing, the data might look look like that: - -```python -from numpy import nan -annotations = [ - ['cat', 'not', 'cat'], - ['cat', 'cat', 'cat'], - ['not', 'not', 'not'], - ['cat', nan, 'not'], -] -``` - -Each row contains the annotations for a single item and -each column contains the annotations of an individual annotator. -We call this format ‘annotation’ format, -which is the default format expected by the agreement function -and all measures implemented in this package. - -Our data contains a missing value, indicated by the nan entry. -Annotator 2 did not provide an annotation for item 4. -All missing values must be marked in this way. - -So, we can simply plug our annotations into the function. - -```python -agreement_report = agreement(annotations, measure="fleiss_kappa") -print(agreement_report) -# { -# 'results': { -# 'measure': 'fleiss_kappa', -# 'score': 0.3950000000000001, -# 'ci': None, -# 'confidence_level': None -# }, -# 'config': { -# 'measure': 'fleiss_kappa', -# 'labels': array(['cat', 'not'], dtype='* - -Elliptic curve definition. - -#### KEY_LEN *= 32* - -ECIES using AES256 and HMAC-SHA-256-32 - -#### MODE - -Cipher mode definition. - -alias of `CTR` - -#### PUBLIC_KEY_LEN *: `int`* *= 64* - -Length of public keys: 512 bit keys in uncompressed form, without -format byte - -#### decrypt(data, private_key, shared_mac_data=b'') - -Decrypt data with ECIES method using the given private key -1) generate shared-secret = kdf( ecdhAgree(myPrivKey, msg[1:65]) ) -2) verify tag -3) decrypt -ecdhAgree(r, recipientPublic) == ecdhAgree(recipientPrivate, R) -[where R = r\*G, and recipientPublic = recipientPrivate\*G] - -* **Parameters:** - * **data** (`bytes`) – Data to be decrypted - * **private_key** (`PrivateKey`) – Private key to be used in agreement. - * **shared_mac_data** (`bytes`) – shared mac additional data as suffix. -* **Return type:** - `bytes` -* **Returns:** - Decrypted byte string -* **Example:** - ```python - from human_protocol_sdk.legacy_encryption import Encryption - from eth_keys import datatypes - - private_key_str = "9822f95dd945e373300f8c8459a831846eda97f314689e01f7cf5b8f1c2298b3" - encrypted_message_str = "0402f48d28d29ae3d681e4cbbe499be0803c2a9d94534d0a4501ab79fd531183fbd837a021c1c117f47737e71c430b9d33915615f68c8dcb5e2f4e4dda4c9415d20a8b5fad9770b14067f2dd31a141a8a8da1f56eb2577715409dbf3c39b9bfa7b90c1acd838fe147c95f0e1ca9359a4cfd52367a73a6d6c548b492faa" - - private_key = datatypes.PrivateKey(bytes.fromhex(private_key_str)) - - encryption = Encryption() - encrypted_message = encryption.decrypt(bytes.fromhex(encrypted_message_str), private_key) - ``` - -#### encrypt(data, public_key, shared_mac_data=b'') - -Encrypt data with ECIES method to the given public key -1) generate r = random value -2) generate shared-secret = kdf( ecdhAgree(r, P) ) -3) generate R = rG [same op as generating a public key] -4) 0x04 || R || AsymmetricEncrypt(shared-secret, plaintext) || tag - -* **Parameters:** - * **data** (`bytes`) – Data to be encrypted - * **public_key** (`PublicKey`) – Public to be used to encrypt provided data. - * **shared_mac_data** (`bytes`) – shared mac additional data as suffix. -* **Return type:** - `bytes` -* **Returns:** - Encrypted byte string -* **Example:** - ```python - from human_protocol_sdk.legacy_encryption import Encryption - from eth_keys import datatypes - - public_key_str = "0a1d228684bc8c8c7611df3264f04ebd823651acc46b28b3574d2e69900d5e34f04a26cf13237fa42ab23245b58060c239b356b0a276f57e8de1234c7100fcf9" - - public_key = datatypes.PublicKey(bytes.fromhex(private_key_str)) - - encryption = Encryption() - encrypted_message = encryption.encrypt(b'your message', public_key) - ``` - -#### generate_private_key() - -Generates a new SECP256K1 private key and return it - -* **Return type:** - `PrivateKey` -* **Returns:** - New SECP256K1 private key. -* **Example:** - ```python - from human_protocol_sdk.legacy_encryption import Encryption - - encryption = Encryption() - private_key = encryption.generate_private_key() - ``` - -#### *static* generate_public_key(private_key) - -Generates a public key with combination to private key provided. - -* **Parameters:** - **private_key** (`bytes`) – Private to be used to create public key. -* **Return type:** - `PublicKey` -* **Returns:** - Public key object. -* **Example:** - ```python - from human_protocol_sdk.legacy_encryption import Encryption - - private_key_str = "9822f95dd945e373300f8c8459a831846eda97f314689e01f7cf5b8f1c2298b3" - - public_key = Encryption.generate_public_key(bytes.fromhex(private_key_str)) - ``` - -#### *static* is_encrypted(data) - -Checks whether data is already encrypted by verifying ecies header. - -* **Parameters:** - **data** (`bytes`) – Data to be checked. -* **Return type:** - `bool` -* **Returns:** - True if data is encrypted, False otherwise. -* **Example:** - ```python - from human_protocol_sdk.legacy_encryption import Encryption - - encrypted_message_str = "0402f48d28d29ae3d681e4cbbe499be0803c2a9d94534d0a4501ab79fd531183fbd837a021c1c117f47737e71c430b9d33915615f68c8dcb5e2f4e4dda4c9415d20a8b5fad9770b14067f2dd31a141a8a8da1f56eb2577715409dbf3c39b9bfa7b90c1acd838fe147c95f0e1ca9359a4cfd52367a73a6d6c548b492faa" - - is_encrypted = Encryption.is_encrypted(bytes.fromhex(encrypted_message_str)) - ``` - -### *exception* human_protocol_sdk.legacy_encryption.InvalidPublicKey - -Bases: `Exception` - -A custom exception raised when trying to convert bytes -into an elliptic curve public key. diff --git a/docs/sdk/python/human_protocol_sdk.md b/docs/sdk/python/human_protocol_sdk.md deleted file mode 100644 index 09d67a12cb..0000000000 --- a/docs/sdk/python/human_protocol_sdk.md +++ /dev/null @@ -1,224 +0,0 @@ -# human_protocol_sdk package - -## Subpackages - -* [human_protocol_sdk.agreement package](human_protocol_sdk.agreement.md) - * [Getting Started](human_protocol_sdk.agreement.md#getting-started) - * [A simple example](human_protocol_sdk.agreement.md#a-simple-example) - * [Submodules](human_protocol_sdk.agreement.md#submodules) - * [human_protocol_sdk.agreement.bootstrap module](human_protocol_sdk.agreement.bootstrap.md) - * [`confidence_intervals()`](human_protocol_sdk.agreement.bootstrap.md#human_protocol_sdk.agreement.bootstrap.confidence_intervals) - * [human_protocol_sdk.agreement.measures module](human_protocol_sdk.agreement.measures.md) - * [`agreement()`](human_protocol_sdk.agreement.measures.md#human_protocol_sdk.agreement.measures.agreement) - * [`cohens_kappa()`](human_protocol_sdk.agreement.measures.md#human_protocol_sdk.agreement.measures.cohens_kappa) - * [`fleiss_kappa()`](human_protocol_sdk.agreement.measures.md#human_protocol_sdk.agreement.measures.fleiss_kappa) - * [`krippendorffs_alpha()`](human_protocol_sdk.agreement.measures.md#human_protocol_sdk.agreement.measures.krippendorffs_alpha) - * [`percentage()`](human_protocol_sdk.agreement.measures.md#human_protocol_sdk.agreement.measures.percentage) - * [`sigma()`](human_protocol_sdk.agreement.measures.md#human_protocol_sdk.agreement.measures.sigma) - * [human_protocol_sdk.agreement.utils module](human_protocol_sdk.agreement.utils.md) - * [`NormalDistribution`](human_protocol_sdk.agreement.utils.md#human_protocol_sdk.agreement.utils.NormalDistribution) - * [`confusion_matrix()`](human_protocol_sdk.agreement.utils.md#human_protocol_sdk.agreement.utils.confusion_matrix) - * [`label_counts()`](human_protocol_sdk.agreement.utils.md#human_protocol_sdk.agreement.utils.label_counts) - * [`observed_and_expected_differences()`](human_protocol_sdk.agreement.utils.md#human_protocol_sdk.agreement.utils.observed_and_expected_differences) - * [`records_from_annotations()`](human_protocol_sdk.agreement.utils.md#human_protocol_sdk.agreement.utils.records_from_annotations) -* [human_protocol_sdk.encryption package](human_protocol_sdk.encryption.md) - * [Submodules](human_protocol_sdk.encryption.md#submodules) - * [human_protocol_sdk.encryption.encryption module](human_protocol_sdk.encryption.encryption.md) - * [Code Example](human_protocol_sdk.encryption.encryption.md#code-example) - * [Module](human_protocol_sdk.encryption.encryption.md#module) - * [`Encryption`](human_protocol_sdk.encryption.encryption.md#human_protocol_sdk.encryption.encryption.Encryption) - * [human_protocol_sdk.encryption.encryption_utils module](human_protocol_sdk.encryption.encryption_utils.md) - * [Code Example](human_protocol_sdk.encryption.encryption_utils.md#code-example) - * [Module](human_protocol_sdk.encryption.encryption_utils.md#module) - * [`EncryptionUtils`](human_protocol_sdk.encryption.encryption_utils.md#human_protocol_sdk.encryption.encryption_utils.EncryptionUtils) -* [human_protocol_sdk.escrow package](human_protocol_sdk.escrow.md) - * [Submodules](human_protocol_sdk.escrow.md#submodules) - * [human_protocol_sdk.escrow.escrow_client module](human_protocol_sdk.escrow.escrow_client.md) - * [Code Example](human_protocol_sdk.escrow.escrow_client.md#code-example) - * [Module](human_protocol_sdk.escrow.escrow_client.md#module) - * [`EscrowCancel`](human_protocol_sdk.escrow.escrow_client.md#human_protocol_sdk.escrow.escrow_client.EscrowCancel) - * [`EscrowClient`](human_protocol_sdk.escrow.escrow_client.md#human_protocol_sdk.escrow.escrow_client.EscrowClient) - * [`EscrowClientError`](human_protocol_sdk.escrow.escrow_client.md#human_protocol_sdk.escrow.escrow_client.EscrowClientError) - * [`EscrowConfig`](human_protocol_sdk.escrow.escrow_client.md#human_protocol_sdk.escrow.escrow_client.EscrowConfig) - * [`EscrowWithdraw`](human_protocol_sdk.escrow.escrow_client.md#human_protocol_sdk.escrow.escrow_client.EscrowWithdraw) - * [human_protocol_sdk.escrow.escrow_utils module](human_protocol_sdk.escrow.escrow_utils.md) - * [Code Example](human_protocol_sdk.escrow.escrow_utils.md#code-example) - * [Module](human_protocol_sdk.escrow.escrow_utils.md#module) - * [`CancellationRefund`](human_protocol_sdk.escrow.escrow_utils.md#human_protocol_sdk.escrow.escrow_utils.CancellationRefund) - * [`EscrowData`](human_protocol_sdk.escrow.escrow_utils.md#human_protocol_sdk.escrow.escrow_utils.EscrowData) - * [`EscrowUtils`](human_protocol_sdk.escrow.escrow_utils.md#human_protocol_sdk.escrow.escrow_utils.EscrowUtils) - * [`Payout`](human_protocol_sdk.escrow.escrow_utils.md#human_protocol_sdk.escrow.escrow_utils.Payout) - * [`StatusEvent`](human_protocol_sdk.escrow.escrow_utils.md#human_protocol_sdk.escrow.escrow_utils.StatusEvent) -* [human_protocol_sdk.kvstore package](human_protocol_sdk.kvstore.md) - * [Submodules](human_protocol_sdk.kvstore.md#submodules) - * [human_protocol_sdk.kvstore.kvstore_client module](human_protocol_sdk.kvstore.kvstore_client.md) - * [Code Example](human_protocol_sdk.kvstore.kvstore_client.md#code-example) - * [Module](human_protocol_sdk.kvstore.kvstore_client.md#module) - * [`KVStoreClient`](human_protocol_sdk.kvstore.kvstore_client.md#human_protocol_sdk.kvstore.kvstore_client.KVStoreClient) - * [`KVStoreClientError`](human_protocol_sdk.kvstore.kvstore_client.md#human_protocol_sdk.kvstore.kvstore_client.KVStoreClientError) - * [human_protocol_sdk.kvstore.kvstore_utils module](human_protocol_sdk.kvstore.kvstore_utils.md) - * [Code Example](human_protocol_sdk.kvstore.kvstore_utils.md#code-example) - * [Module](human_protocol_sdk.kvstore.kvstore_utils.md#module) - * [`KVStoreData`](human_protocol_sdk.kvstore.kvstore_utils.md#human_protocol_sdk.kvstore.kvstore_utils.KVStoreData) - * [`KVStoreUtils`](human_protocol_sdk.kvstore.kvstore_utils.md#human_protocol_sdk.kvstore.kvstore_utils.KVStoreUtils) -* [human_protocol_sdk.operator package](human_protocol_sdk.operator.md) - * [Submodules](human_protocol_sdk.operator.md#submodules) - * [human_protocol_sdk.operator.operator_utils module](human_protocol_sdk.operator.operator_utils.md) - * [Code Example](human_protocol_sdk.operator.operator_utils.md#code-example) - * [Module](human_protocol_sdk.operator.operator_utils.md#module) - * [`OperatorData`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.OperatorData) - * [`OperatorFilter`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.OperatorFilter) - * [`OperatorUtils`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.OperatorUtils) - * [`OperatorUtilsError`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.OperatorUtilsError) - * [`RewardData`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.RewardData) -* [human_protocol_sdk.staking package](human_protocol_sdk.staking.md) - * [Submodules](human_protocol_sdk.staking.md#submodules) - * [human_protocol_sdk.staking.staking_client module](human_protocol_sdk.staking.staking_client.md) - * [Code Example](human_protocol_sdk.staking.staking_client.md#code-example) - * [Module](human_protocol_sdk.staking.staking_client.md#module) - * [`StakingClient`](human_protocol_sdk.staking.staking_client.md#human_protocol_sdk.staking.staking_client.StakingClient) - * [`StakingClientError`](human_protocol_sdk.staking.staking_client.md#human_protocol_sdk.staking.staking_client.StakingClientError) - * [human_protocol_sdk.staking.staking_utils module](human_protocol_sdk.staking.staking_utils.md) - * [Code Example](human_protocol_sdk.staking.staking_utils.md#code-example) - * [Module](human_protocol_sdk.staking.staking_utils.md#module) - * [`StakerData`](human_protocol_sdk.staking.staking_utils.md#human_protocol_sdk.staking.staking_utils.StakerData) - * [`StakingUtils`](human_protocol_sdk.staking.staking_utils.md#human_protocol_sdk.staking.staking_utils.StakingUtils) - * [`StakingUtilsError`](human_protocol_sdk.staking.staking_utils.md#human_protocol_sdk.staking.staking_utils.StakingUtilsError) -* [human_protocol_sdk.statistics package](human_protocol_sdk.statistics.md) - * [Submodules](human_protocol_sdk.statistics.md#submodules) - * [human_protocol_sdk.statistics.statistics_client module](human_protocol_sdk.statistics.statistics_client.md) - * [Code Example](human_protocol_sdk.statistics.statistics_client.md#code-example) - * [Module](human_protocol_sdk.statistics.statistics_client.md#module) - * [`DailyEscrowData`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.DailyEscrowData) - * [`DailyHMTData`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.DailyHMTData) - * [`DailyPaymentData`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.DailyPaymentData) - * [`DailyWorkerData`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.DailyWorkerData) - * [`EscrowStatistics`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.EscrowStatistics) - * [`HMTHolder`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.HMTHolder) - * [`HMTHoldersParam`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.HMTHoldersParam) - * [`HMTStatistics`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.HMTStatistics) - * [`PaymentStatistics`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.PaymentStatistics) - * [`StatisticsClient`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.StatisticsClient) - * [`StatisticsClientError`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.StatisticsClientError) - * [`WorkerStatistics`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.WorkerStatistics) -* [human_protocol_sdk.storage package](human_protocol_sdk.storage.md) - * [Submodules](human_protocol_sdk.storage.md#submodules) - * [human_protocol_sdk.storage.storage_client module](human_protocol_sdk.storage.storage_client.md) - * [Code Example](human_protocol_sdk.storage.storage_client.md#code-example) - * [Module](human_protocol_sdk.storage.storage_client.md#module) - * [`Credentials`](human_protocol_sdk.storage.storage_client.md#human_protocol_sdk.storage.storage_client.Credentials) - * [`StorageClient`](human_protocol_sdk.storage.storage_client.md#human_protocol_sdk.storage.storage_client.StorageClient) - * [`StorageClientError`](human_protocol_sdk.storage.storage_client.md#human_protocol_sdk.storage.storage_client.StorageClientError) - * [`StorageFileNotFoundError`](human_protocol_sdk.storage.storage_client.md#human_protocol_sdk.storage.storage_client.StorageFileNotFoundError) - * [human_protocol_sdk.storage.storage_utils module](human_protocol_sdk.storage.storage_utils.md) - * [`StorageUtils`](human_protocol_sdk.storage.storage_utils.md#human_protocol_sdk.storage.storage_utils.StorageUtils) -* [human_protocol_sdk.transaction package](human_protocol_sdk.transaction.md) - * [Submodules](human_protocol_sdk.transaction.md#submodules) - * [human_protocol_sdk.transaction.transaction_utils module](human_protocol_sdk.transaction.transaction_utils.md) - * [Code Example](human_protocol_sdk.transaction.transaction_utils.md#code-example) - * [Module](human_protocol_sdk.transaction.transaction_utils.md#module) - * [`InternalTransaction`](human_protocol_sdk.transaction.transaction_utils.md#human_protocol_sdk.transaction.transaction_utils.InternalTransaction) - * [`TransactionData`](human_protocol_sdk.transaction.transaction_utils.md#human_protocol_sdk.transaction.transaction_utils.TransactionData) - * [`TransactionUtils`](human_protocol_sdk.transaction.transaction_utils.md#human_protocol_sdk.transaction.transaction_utils.TransactionUtils) - * [`TransactionUtilsError`](human_protocol_sdk.transaction.transaction_utils.md#human_protocol_sdk.transaction.transaction_utils.TransactionUtilsError) -* [human_protocol_sdk.worker package](human_protocol_sdk.worker.md) - * [Submodules](human_protocol_sdk.worker.md#submodules) - * [human_protocol_sdk.worker.worker_utils module](human_protocol_sdk.worker.worker_utils.md) - * [`WorkerData`](human_protocol_sdk.worker.worker_utils.md#human_protocol_sdk.worker.worker_utils.WorkerData) - * [`WorkerUtils`](human_protocol_sdk.worker.worker_utils.md#human_protocol_sdk.worker.worker_utils.WorkerUtils) - * [`WorkerUtilsError`](human_protocol_sdk.worker.worker_utils.md#human_protocol_sdk.worker.worker_utils.WorkerUtilsError) - -## Submodules - -* [human_protocol_sdk.constants module](human_protocol_sdk.constants.md) - * [`ChainId`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId) - * [`ChainId.BSC_MAINNET`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId.BSC_MAINNET) - * [`ChainId.BSC_TESTNET`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId.BSC_TESTNET) - * [`ChainId.LOCALHOST`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId.LOCALHOST) - * [`ChainId.MAINNET`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId.MAINNET) - * [`ChainId.POLYGON`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId.POLYGON) - * [`ChainId.POLYGON_AMOY`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId.POLYGON_AMOY) - * [`ChainId.SEPOLIA`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId.SEPOLIA) - * [`KVStoreKeys`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.KVStoreKeys) - * [`KVStoreKeys.category`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.KVStoreKeys.category) - * [`KVStoreKeys.fee`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.KVStoreKeys.fee) - * [`KVStoreKeys.job_types`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.KVStoreKeys.job_types) - * [`KVStoreKeys.operator_name`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.KVStoreKeys.operator_name) - * [`KVStoreKeys.public_key`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.KVStoreKeys.public_key) - * [`KVStoreKeys.public_key_hash`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.KVStoreKeys.public_key_hash) - * [`KVStoreKeys.registration_instructions`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.KVStoreKeys.registration_instructions) - * [`KVStoreKeys.registration_needed`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.KVStoreKeys.registration_needed) - * [`KVStoreKeys.role`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.KVStoreKeys.role) - * [`KVStoreKeys.url`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.KVStoreKeys.url) - * [`KVStoreKeys.webhook_url`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.KVStoreKeys.webhook_url) - * [`KVStoreKeys.website`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.KVStoreKeys.website) - * [`OperatorCategory`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.OperatorCategory) - * [`OperatorCategory.MACHINE_LEARNING`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.OperatorCategory.MACHINE_LEARNING) - * [`OperatorCategory.MARKET_MAKING`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.OperatorCategory.MARKET_MAKING) - * [`OrderDirection`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.OrderDirection) - * [`OrderDirection.ASC`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.OrderDirection.ASC) - * [`OrderDirection.DESC`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.OrderDirection.DESC) - * [`Role`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.Role) - * [`Role.exchange_oracle`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.Role.exchange_oracle) - * [`Role.job_launcher`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.Role.job_launcher) - * [`Role.recording_oracle`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.Role.recording_oracle) - * [`Role.reputation_oracle`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.Role.reputation_oracle) - * [`Status`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.Status) - * [`Status.Cancelled`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.Status.Cancelled) - * [`Status.Complete`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.Status.Complete) - * [`Status.Launched`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.Status.Launched) - * [`Status.Paid`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.Status.Paid) - * [`Status.Partial`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.Status.Partial) - * [`Status.Pending`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.Status.Pending) - * [`Status.ToCancel`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.Status.ToCancel) -* [human_protocol_sdk.filter module](human_protocol_sdk.filter.md) - * [`CancellationRefundFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.CancellationRefundFilter) - * [`CancellationRefundFilter.__init__()`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.CancellationRefundFilter.__init__) - * [`EscrowFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.EscrowFilter) - * [`EscrowFilter.__init__()`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.EscrowFilter.__init__) - * [`FilterError`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.FilterError) - * [`PayoutFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.PayoutFilter) - * [`PayoutFilter.__init__()`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.PayoutFilter.__init__) - * [`StakersFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.StakersFilter) - * [`StakersFilter.__init__()`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.StakersFilter.__init__) - * [`StatisticsFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.StatisticsFilter) - * [`StatisticsFilter.__init__()`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.StatisticsFilter.__init__) - * [`StatusEventFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.StatusEventFilter) - * [`StatusEventFilter.__init__()`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.StatusEventFilter.__init__) - * [`TransactionFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.TransactionFilter) - * [`TransactionFilter.__init__()`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.TransactionFilter.__init__) - * [`WorkerFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.WorkerFilter) - * [`WorkerFilter.__init__()`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.WorkerFilter.__init__) -* [human_protocol_sdk.legacy_encryption module](human_protocol_sdk.legacy_encryption.md) - * [`DecryptionError`](human_protocol_sdk.legacy_encryption.md#human_protocol_sdk.legacy_encryption.DecryptionError) - * [`Encryption`](human_protocol_sdk.legacy_encryption.md#human_protocol_sdk.legacy_encryption.Encryption) - * [`Encryption.CIPHER`](human_protocol_sdk.legacy_encryption.md#human_protocol_sdk.legacy_encryption.Encryption.CIPHER) - * [`Encryption.ELLIPTIC_CURVE`](human_protocol_sdk.legacy_encryption.md#human_protocol_sdk.legacy_encryption.Encryption.ELLIPTIC_CURVE) - * [`Encryption.KEY_LEN`](human_protocol_sdk.legacy_encryption.md#human_protocol_sdk.legacy_encryption.Encryption.KEY_LEN) - * [`Encryption.MODE`](human_protocol_sdk.legacy_encryption.md#human_protocol_sdk.legacy_encryption.Encryption.MODE) - * [`Encryption.PUBLIC_KEY_LEN`](human_protocol_sdk.legacy_encryption.md#human_protocol_sdk.legacy_encryption.Encryption.PUBLIC_KEY_LEN) - * [`Encryption.decrypt()`](human_protocol_sdk.legacy_encryption.md#human_protocol_sdk.legacy_encryption.Encryption.decrypt) - * [`Encryption.encrypt()`](human_protocol_sdk.legacy_encryption.md#human_protocol_sdk.legacy_encryption.Encryption.encrypt) - * [`Encryption.generate_private_key()`](human_protocol_sdk.legacy_encryption.md#human_protocol_sdk.legacy_encryption.Encryption.generate_private_key) - * [`Encryption.generate_public_key()`](human_protocol_sdk.legacy_encryption.md#human_protocol_sdk.legacy_encryption.Encryption.generate_public_key) - * [`Encryption.is_encrypted()`](human_protocol_sdk.legacy_encryption.md#human_protocol_sdk.legacy_encryption.Encryption.is_encrypted) - * [`InvalidPublicKey`](human_protocol_sdk.legacy_encryption.md#human_protocol_sdk.legacy_encryption.InvalidPublicKey) -* [human_protocol_sdk.utils module](human_protocol_sdk.utils.md) - * [`SubgraphOptions`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.SubgraphOptions) - * [`SubgraphOptions.__init__()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.SubgraphOptions.__init__) - * [`SubgraphOptions.base_delay`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.SubgraphOptions.base_delay) - * [`SubgraphOptions.indexer_id`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.SubgraphOptions.indexer_id) - * [`SubgraphOptions.max_retries`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.SubgraphOptions.max_retries) - * [`custom_gql_fetch()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.custom_gql_fetch) - * [`get_contract_interface()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_contract_interface) - * [`get_erc20_interface()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_erc20_interface) - * [`get_escrow_interface()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_escrow_interface) - * [`get_factory_interface()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_factory_interface) - * [`get_hmt_balance()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_hmt_balance) - * [`get_kvstore_interface()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_kvstore_interface) - * [`get_staking_interface()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_staking_interface) - * [`handle_error()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.handle_error) - * [`is_indexer_error()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.is_indexer_error) - * [`parse_transfer_transaction()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.parse_transfer_transaction) - * [`validate_json()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.validate_json) - * [`validate_url()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.validate_url) diff --git a/docs/sdk/python/human_protocol_sdk.operator.md b/docs/sdk/python/human_protocol_sdk.operator.md deleted file mode 100644 index 7dd40a95c2..0000000000 --- a/docs/sdk/python/human_protocol_sdk.operator.md +++ /dev/null @@ -1,22 +0,0 @@ -# human_protocol_sdk.operator package - -This module enables to perform actions on staking contracts and -obtain staking information from both the contracts and subgraph. - -## Submodules - -* [human_protocol_sdk.operator.operator_utils module](human_protocol_sdk.operator.operator_utils.md) - * [Code Example](human_protocol_sdk.operator.operator_utils.md#code-example) - * [Module](human_protocol_sdk.operator.operator_utils.md#module) - * [`OperatorData`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.OperatorData) - * [`OperatorData.__init__()`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.OperatorData.__init__) - * [`OperatorFilter`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.OperatorFilter) - * [`OperatorFilter.__init__()`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.OperatorFilter.__init__) - * [`OperatorUtils`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.OperatorUtils) - * [`OperatorUtils.get_operator()`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.OperatorUtils.get_operator) - * [`OperatorUtils.get_operators()`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.OperatorUtils.get_operators) - * [`OperatorUtils.get_reputation_network_operators()`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.OperatorUtils.get_reputation_network_operators) - * [`OperatorUtils.get_rewards_info()`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.OperatorUtils.get_rewards_info) - * [`OperatorUtilsError`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.OperatorUtilsError) - * [`RewardData`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.RewardData) - * [`RewardData.__init__()`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.RewardData.__init__) diff --git a/docs/sdk/python/human_protocol_sdk.operator.operator_utils.md b/docs/sdk/python/human_protocol_sdk.operator.operator_utils.md deleted file mode 100644 index 8a1a1cab2c..0000000000 --- a/docs/sdk/python/human_protocol_sdk.operator.operator_utils.md +++ /dev/null @@ -1,188 +0,0 @@ -# human_protocol_sdk.operator.operator_utils module - -Utility class for operator-related operations. - -## Code Example - -```python -from human_protocol_sdk.constants import ChainId -from human_protocol_sdk.operator import OperatorUtils, OperatorFilter - -print( - OperatorUtils.get_operators( - OperatorFilter(chain_id=ChainId.POLYGON_AMOY, roles=["Job Launcher"]) - ) -) -``` - -## Module - -### *class* human_protocol_sdk.operator.operator_utils.OperatorData(chain_id, id, address, amount_jobs_processed, reputation_networks, staked_amount=None, locked_amount=None, locked_until_timestamp=None, withdrawn_amount=None, slashed_amount=None, role=None, fee=None, public_key=None, webhook_url=None, website=None, url=None, job_types=None, registration_needed=None, registration_instructions=None, name=None, category=None) - -Bases: `object` - -#### \_\_init_\_(chain_id, id, address, amount_jobs_processed, reputation_networks, staked_amount=None, locked_amount=None, locked_until_timestamp=None, withdrawn_amount=None, slashed_amount=None, role=None, fee=None, public_key=None, webhook_url=None, website=None, url=None, job_types=None, registration_needed=None, registration_instructions=None, name=None, category=None) - -Initializes a OperatorData instance. - -* **Parameters:** - * **chain_id** ([`ChainId`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId)) – Chain Identifier - * **id** (`str`) – Identifier - * **address** (`str`) – Address - * **staked_amount** (`Optional`[`str`]) – Amount staked - * **locked_amount** (`Optional`[`str`]) – Amount locked - * **locked_until_timestamp** (`Optional`[`str`]) – Locked until timestamp - * **withdrawn_amount** (`Optional`[`str`]) – Amount withdrawn - * **slashed_amount** (`Optional`[`str`]) – Amount slashed - * **amount_jobs_processed** (`str`) – Amount of jobs launched - * **role** (`Optional`[`str`]) – Role - * **fee** (`Optional`[`str`]) – Fee - * **public_key** (`Optional`[`str`]) – Public key - * **webhook_url** (`Optional`[`str`]) – Webhook URL - * **website** (`Optional`[`str`]) – Website URL - * **url** (`Optional`[`str`]) – URL - * **job_types** (`Union`[`List`[`str`], `str`, `None`]) – Job types - * **registration_needed** (`Optional`[`bool`]) – Whether registration is needed - * **registration_instructions** (`Optional`[`str`]) – Registration instructions - * **reputation_networks** (`Union`[`List`[`str`], `str`]) – List of reputation networks - * **name** (`Optional`[`str`]) – Name - * **category** (`Optional`[`str`]) – Category - -### *class* human_protocol_sdk.operator.operator_utils.OperatorFilter(chain_id, roles=[], min_staked_amount=None, order_by=None, order_direction=OrderDirection.DESC, first=10, skip=0) - -Bases: `object` - -A class used to filter operators. - -#### \_\_init_\_(chain_id, roles=[], min_staked_amount=None, order_by=None, order_direction=OrderDirection.DESC, first=10, skip=0) - -Initializes a OperatorFilter instance. - -* **Parameters:** - * **chain_id** ([`ChainId`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId)) – Chain ID to request data - * **roles** (`Optional`[`str`]) – Roles to filter by - * **min_staked_amount** (`Optional`[`int`]) – Minimum amount staked to filter by - * **order_by** (`Optional`[`str`]) – Property to order by, e.g., “role” - * **order_direction** ([`OrderDirection`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.OrderDirection)) – Order direction of results, “asc” or “desc” - * **first** (`int`) – Number of items per page - * **skip** (`int`) – Number of items to skip (for pagination) - -### *class* human_protocol_sdk.operator.operator_utils.OperatorUtils - -Bases: `object` - -A utility class that provides additional operator-related functionalities. - -#### *static* get_operator(chain_id, operator_address, options=None) - -Gets the operator details. - -* **Parameters:** - * **chain_id** ([`ChainId`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId)) – Network in which the operator exists - * **operator_address** (`str`) – Address of the operator - * **options** (`Optional`[[`SubgraphOptions`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.SubgraphOptions)]) – Optional config for subgraph requests -* **Return type:** - `Optional`[[`OperatorData`](#human_protocol_sdk.operator.operator_utils.OperatorData)] -* **Returns:** - Operator data if exists, otherwise None -* **Example:** - ```python - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.operator import OperatorUtils - - chain_id = ChainId.POLYGON_AMOY - operator_address = '0x62dD51230A30401C455c8398d06F85e4EaB6309f' - - operator_data = OperatorUtils.get_operator(chain_id, operator_address) - print(operator_data) - ``` - -#### *static* get_operators(filter, options=None) - -Get operators data of the protocol. - -* **Parameters:** - * **filter** ([`OperatorFilter`](#human_protocol_sdk.operator.operator_utils.OperatorFilter)) – Operator filter - * **options** (`Optional`[[`SubgraphOptions`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.SubgraphOptions)]) – Optional config for subgraph requests -* **Return type:** - `List`[[`OperatorData`](#human_protocol_sdk.operator.operator_utils.OperatorData)] -* **Returns:** - List of operators data -* **Example:** - ```python - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.operator import OperatorUtils, OperatorFilter - - print( - OperatorUtils.get_operators( - OperatorFilter(chain_id=ChainId.POLYGON_AMOY, roles=["Job Launcher"]) - ) - ) - ``` - -#### *static* get_reputation_network_operators(chain_id, address, role=None, options=None) - -Get the reputation network operators of the specified address. - -* **Parameters:** - * **chain_id** ([`ChainId`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId)) – Network in which the reputation network exists - * **address** (`str`) – Address of the reputation oracle - * **role** (`Optional`[`str`]) – (Optional) Role of the operator - * **options** (`Optional`[[`SubgraphOptions`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.SubgraphOptions)]) – Optional config for subgraph requests -* **Return type:** - `List`[[`OperatorData`](#human_protocol_sdk.operator.operator_utils.OperatorData)] -* **Returns:** - Returns an array of operator details -* **Example:** - ```python - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.operator import OperatorUtils - - operators = OperatorUtils.get_reputation_network_operators( - ChainId.POLYGON_AMOY, - '0x62dD51230A30401C455c8398d06F85e4EaB6309f' - ) - print(operators) - ``` - -#### *static* get_rewards_info(chain_id, slasher, options=None) - -Get rewards of the given slasher. - -* **Parameters:** - * **chain_id** ([`ChainId`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId)) – Network in which the slasher exists - * **slasher** (`str`) – Address of the slasher - * **options** (`Optional`[[`SubgraphOptions`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.SubgraphOptions)]) – Optional config for subgraph requests -* **Return type:** - `List`[[`RewardData`](#human_protocol_sdk.operator.operator_utils.RewardData)] -* **Returns:** - List of rewards info -* **Example:** - ```python - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.operator import OperatorUtils - - rewards_info = OperatorUtils.get_rewards_info( - ChainId.POLYGON_AMOY, - '0x62dD51230A30401C455c8398d06F85e4EaB6309f' - ) - print(rewards_info) - ``` - -### *exception* human_protocol_sdk.operator.operator_utils.OperatorUtilsError - -Bases: `Exception` - -Raised when an error occurs while interacting with the operator. - -### *class* human_protocol_sdk.operator.operator_utils.RewardData(escrow_address, amount) - -Bases: `object` - -#### \_\_init_\_(escrow_address, amount) - -Initializes a RewardData instance. - -* **Parameters:** - * **escrow_address** (`str`) – Escrow address - * **amount** (`int`) – Amount diff --git a/docs/sdk/python/human_protocol_sdk.staking.md b/docs/sdk/python/human_protocol_sdk.staking.md deleted file mode 100644 index 04a5aea76f..0000000000 --- a/docs/sdk/python/human_protocol_sdk.staking.md +++ /dev/null @@ -1,28 +0,0 @@ -# human_protocol_sdk.staking package - -This module enables to perform actions on staking contracts and -obtain staking information from both the contracts and subgraph. - -## Submodules - -* [human_protocol_sdk.staking.staking_client module](human_protocol_sdk.staking.staking_client.md) - * [Code Example](human_protocol_sdk.staking.staking_client.md#code-example) - * [Module](human_protocol_sdk.staking.staking_client.md#module) - * [`StakingClient`](human_protocol_sdk.staking.staking_client.md#human_protocol_sdk.staking.staking_client.StakingClient) - * [`StakingClient.__init__()`](human_protocol_sdk.staking.staking_client.md#human_protocol_sdk.staking.staking_client.StakingClient.__init__) - * [`StakingClient.approve_stake()`](human_protocol_sdk.staking.staking_client.md#human_protocol_sdk.staking.staking_client.StakingClient.approve_stake) - * [`StakingClient.get_staker_info()`](human_protocol_sdk.staking.staking_client.md#human_protocol_sdk.staking.staking_client.StakingClient.get_staker_info) - * [`StakingClient.slash()`](human_protocol_sdk.staking.staking_client.md#human_protocol_sdk.staking.staking_client.StakingClient.slash) - * [`StakingClient.stake()`](human_protocol_sdk.staking.staking_client.md#human_protocol_sdk.staking.staking_client.StakingClient.stake) - * [`StakingClient.unstake()`](human_protocol_sdk.staking.staking_client.md#human_protocol_sdk.staking.staking_client.StakingClient.unstake) - * [`StakingClient.withdraw()`](human_protocol_sdk.staking.staking_client.md#human_protocol_sdk.staking.staking_client.StakingClient.withdraw) - * [`StakingClientError`](human_protocol_sdk.staking.staking_client.md#human_protocol_sdk.staking.staking_client.StakingClientError) -* [human_protocol_sdk.staking.staking_utils module](human_protocol_sdk.staking.staking_utils.md) - * [Code Example](human_protocol_sdk.staking.staking_utils.md#code-example) - * [Module](human_protocol_sdk.staking.staking_utils.md#module) - * [`StakerData`](human_protocol_sdk.staking.staking_utils.md#human_protocol_sdk.staking.staking_utils.StakerData) - * [`StakerData.__init__()`](human_protocol_sdk.staking.staking_utils.md#human_protocol_sdk.staking.staking_utils.StakerData.__init__) - * [`StakingUtils`](human_protocol_sdk.staking.staking_utils.md#human_protocol_sdk.staking.staking_utils.StakingUtils) - * [`StakingUtils.get_staker()`](human_protocol_sdk.staking.staking_utils.md#human_protocol_sdk.staking.staking_utils.StakingUtils.get_staker) - * [`StakingUtils.get_stakers()`](human_protocol_sdk.staking.staking_utils.md#human_protocol_sdk.staking.staking_utils.StakingUtils.get_stakers) - * [`StakingUtilsError`](human_protocol_sdk.staking.staking_utils.md#human_protocol_sdk.staking.staking_utils.StakingUtilsError) diff --git a/docs/sdk/python/human_protocol_sdk.staking.staking_client.md b/docs/sdk/python/human_protocol_sdk.staking.staking_client.md deleted file mode 100644 index c0155d7cb5..0000000000 --- a/docs/sdk/python/human_protocol_sdk.staking.staking_client.md +++ /dev/null @@ -1,106 +0,0 @@ -# human_protocol_sdk.staking.staking_client module - -This client enables performing actions on staking contracts and -obtaining staking information from both the contracts and subgraph. - -Internally, the SDK will use one network or another according to the network ID of the web3. -To use this client, you need to create a Web3 instance and configure the default account, -as well as some middlewares. - -## Code Example - -* With Signer - -```python -from eth_typing import URI -from web3 import Web3 -from web3.middleware import SignAndSendRawMiddlewareBuilder -from web3.providers.auto import load_provider_from_uri - -from human_protocol_sdk.staking import StakingClient - -def get_w3_with_priv_key(priv_key: str): - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - gas_payer = w3.eth.account.from_key(priv_key) - w3.eth.default_account = gas_payer.address - w3.middleware_onion.inject( - SignAndSendRawMiddlewareBuilder.build(priv_key), - 'SignAndSendRawMiddlewareBuilder', - layer=0, - ) - return (w3, gas_payer) - -(w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') -staking_client = StakingClient(w3) -``` - -* Without Signer (For read operations only) - -```python -from eth_typing import URI -from web3 import Web3 -from web3.providers.auto import load_provider_from_uri - -from human_protocol_sdk.staking import StakingClient - -w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) -staking_client = StakingClient(w3) -``` - -## Module - -### *class* human_protocol_sdk.staking.staking_client.StakingClient(w3) - -Bases: `object` - -A class used to manage staking on the HUMAN network. - -#### \_\_init_\_(w3) - -Initializes a Staking instance - -* **Parameters:** - **w3** (`Web3`) – Web3 instance - -#### approve_stake(\*args, \*\*kwargs) - -#### get_staker_info(staker_address) - -Retrieves comprehensive staking information for a staker. - -* **Parameters:** - **staker_address** (`str`) – The address of the staker -* **Return type:** - `dict` -* **Returns:** - A dictionary containing staker information -* **Validate:** - - Staker address must be valid -* **Example:** - ```python - from eth_typing import URI - from web3 import Web3 - from web3.providers.auto import load_provider_from_uri - - from human_protocol_sdk.staking import StakingClient - - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - staking_client = StakingClient(w3) - - staking_info = staking_client.get_staker_info('0xYourStakerAddress') - print(staking_info['stakedAmount']) - ``` - -#### slash(\*args, \*\*kwargs) - -#### stake(\*args, \*\*kwargs) - -#### unstake(\*args, \*\*kwargs) - -#### withdraw(\*args, \*\*kwargs) - -### *exception* human_protocol_sdk.staking.staking_client.StakingClientError - -Bases: `Exception` - -Raises when some error happens when interacting with staking. diff --git a/docs/sdk/python/human_protocol_sdk.staking.staking_utils.md b/docs/sdk/python/human_protocol_sdk.staking.staking_utils.md deleted file mode 100644 index 86d2a79482..0000000000 --- a/docs/sdk/python/human_protocol_sdk.staking.staking_utils.md +++ /dev/null @@ -1,49 +0,0 @@ -# human_protocol_sdk.staking.staking_utils module - -Utility class for staking-related operations. - -## Code Example - -```python -from human_protocol_sdk.constants import ChainId -from human_protocol_sdk.staking.staking_utils import StakingUtils, StakersFilter - -stakers = StakingUtils.get_stakers( - StakersFilter( - chain_id=ChainId.POLYGON_AMOY, - min_staked_amount="1000000000000000000", - max_locked_amount="5000000000000000000", - order_by="withdrawnAmount", - order_direction="asc", - first=5, - skip=0, - ) -) -print("Filtered stakers:", stakers) -``` - -## Module - -### *class* human_protocol_sdk.staking.staking_utils.StakerData(id, address, staked_amount, locked_amount, withdrawn_amount, slashed_amount, locked_until_timestamp, last_deposit_timestamp) - -Bases: `object` - -#### \_\_init_\_(id, address, staked_amount, locked_amount, withdrawn_amount, slashed_amount, locked_until_timestamp, last_deposit_timestamp) - -### *class* human_protocol_sdk.staking.staking_utils.StakingUtils - -Bases: `object` - -#### *static* get_staker(chain_id, address, options=None) - -* **Return type:** - `Optional`[[`StakerData`](#human_protocol_sdk.staking.staking_utils.StakerData)] - -#### *static* get_stakers(filter, options=None) - -* **Return type:** - `List`[[`StakerData`](#human_protocol_sdk.staking.staking_utils.StakerData)] - -### *exception* human_protocol_sdk.staking.staking_utils.StakingUtilsError - -Bases: `Exception` diff --git a/docs/sdk/python/human_protocol_sdk.statistics.md b/docs/sdk/python/human_protocol_sdk.statistics.md deleted file mode 100644 index ee37413d17..0000000000 --- a/docs/sdk/python/human_protocol_sdk.statistics.md +++ /dev/null @@ -1,38 +0,0 @@ -# human_protocol_sdk.statistics package - -This module allows to read statistical data from the subgraph. - -## Submodules - -* [human_protocol_sdk.statistics.statistics_client module](human_protocol_sdk.statistics.statistics_client.md) - * [Code Example](human_protocol_sdk.statistics.statistics_client.md#code-example) - * [Module](human_protocol_sdk.statistics.statistics_client.md#module) - * [`DailyEscrowData`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.DailyEscrowData) - * [`DailyEscrowData.__init__()`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.DailyEscrowData.__init__) - * [`DailyHMTData`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.DailyHMTData) - * [`DailyHMTData.__init__()`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.DailyHMTData.__init__) - * [`DailyPaymentData`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.DailyPaymentData) - * [`DailyPaymentData.__init__()`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.DailyPaymentData.__init__) - * [`DailyWorkerData`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.DailyWorkerData) - * [`DailyWorkerData.__init__()`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.DailyWorkerData.__init__) - * [`EscrowStatistics`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.EscrowStatistics) - * [`EscrowStatistics.__init__()`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.EscrowStatistics.__init__) - * [`HMTHolder`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.HMTHolder) - * [`HMTHolder.__init__()`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.HMTHolder.__init__) - * [`HMTHoldersParam`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.HMTHoldersParam) - * [`HMTHoldersParam.__init__()`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.HMTHoldersParam.__init__) - * [`HMTStatistics`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.HMTStatistics) - * [`HMTStatistics.__init__()`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.HMTStatistics.__init__) - * [`PaymentStatistics`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.PaymentStatistics) - * [`PaymentStatistics.__init__()`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.PaymentStatistics.__init__) - * [`StatisticsClient`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.StatisticsClient) - * [`StatisticsClient.__init__()`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.StatisticsClient.__init__) - * [`StatisticsClient.get_escrow_statistics()`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.StatisticsClient.get_escrow_statistics) - * [`StatisticsClient.get_hmt_daily_data()`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.StatisticsClient.get_hmt_daily_data) - * [`StatisticsClient.get_hmt_holders()`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.StatisticsClient.get_hmt_holders) - * [`StatisticsClient.get_hmt_statistics()`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.StatisticsClient.get_hmt_statistics) - * [`StatisticsClient.get_payment_statistics()`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.StatisticsClient.get_payment_statistics) - * [`StatisticsClient.get_worker_statistics()`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.StatisticsClient.get_worker_statistics) - * [`StatisticsClientError`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.StatisticsClientError) - * [`WorkerStatistics`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.WorkerStatistics) - * [`WorkerStatistics.__init__()`](human_protocol_sdk.statistics.statistics_client.md#human_protocol_sdk.statistics.statistics_client.WorkerStatistics.__init__) diff --git a/docs/sdk/python/human_protocol_sdk.statistics.statistics_client.md b/docs/sdk/python/human_protocol_sdk.statistics.statistics_client.md deleted file mode 100644 index 5d7b6396c0..0000000000 --- a/docs/sdk/python/human_protocol_sdk.statistics.statistics_client.md +++ /dev/null @@ -1,349 +0,0 @@ -# human_protocol_sdk.statistics.statistics_client module - -This client enables to obtain statistical information from the subgraph. - -## Code Example - -```python -from human_protocol_sdk.constants import ChainId -from human_protocol_sdk.statistics import StatisticsClient - -statistics_client = StatisticsClient(ChainId.POLYGON_AMOY) -``` - -## Module - -### *class* human_protocol_sdk.statistics.statistics_client.DailyEscrowData(timestamp, escrows_total, escrows_pending, escrows_solved, escrows_paid, escrows_cancelled) - -Bases: `object` - -A class used to specify daily escrow data. - -#### \_\_init_\_(timestamp, escrows_total, escrows_pending, escrows_solved, escrows_paid, escrows_cancelled) - -Initializes a DailyEscrowData instance. - -* **Parameters:** - * **timestamp** (`datetime`) – Timestamp - * **escrows_total** (`int`) – Total escrows - * **escrows_pending** (`int`) – Pending escrows - * **escrows_solved** (`int`) – Solved escrows - * **escrows_paid** (`int`) – Paid escrows - * **escrows_cancelled** (`int`) – Cancelled escrows - -### *class* human_protocol_sdk.statistics.statistics_client.DailyHMTData(timestamp, total_transaction_amount, total_transaction_count, daily_unique_senders, daily_unique_receivers) - -Bases: `object` - -A class used to specify daily HMT data. - -#### \_\_init_\_(timestamp, total_transaction_amount, total_transaction_count, daily_unique_senders, daily_unique_receivers) - -Initializes a DailyHMTData instance. - -* **Parameters:** - * **timestamp** (`datetime`) – Timestamp - * **total_transaction_amount** (`int`) – Total transaction amount - * **total_transaction_count** (`int`) – Total transaction count - * **daily_unique_senders** (`int`) – Total unique senders - * **daily_unique_receivers** (`int`) – Total unique receivers - -### *class* human_protocol_sdk.statistics.statistics_client.DailyPaymentData(timestamp, total_amount_paid, total_count, average_amount_per_worker) - -Bases: `object` - -A class used to specify daily payment data. - -#### \_\_init_\_(timestamp, total_amount_paid, total_count, average_amount_per_worker) - -Initializes a DailyPaymentData instance. - -* **Parameters:** - * **timestamp** (`datetime`) – Timestamp - * **total_amount_paid** (`int`) – Total amount paid - * **total_count** (`int`) – Total count - * **average_amount_per_worker** (`int`) – Average amount per worker - -### *class* human_protocol_sdk.statistics.statistics_client.DailyWorkerData(timestamp, active_workers) - -Bases: `object` - -A class used to specify daily worker data. - -#### \_\_init_\_(timestamp, active_workers) - -Initializes a DailyWorkerData instance. - -* **Parameters:** - * **timestamp** (`datetime`) – Timestamp - * **active_workers** (`int`) – Active workers - -### *class* human_protocol_sdk.statistics.statistics_client.EscrowStatistics(total_escrows, daily_escrows_data) - -Bases: `object` - -A class used to specify escrow statistics. - -#### \_\_init_\_(total_escrows, daily_escrows_data) - -Initializes a EscrowStatistics instance. - -* **Parameters:** - * **total_escrows** (`int`) – Total escrows - * **daily_escrows_data** (`List`[[`DailyEscrowData`](#human_protocol_sdk.statistics.statistics_client.DailyEscrowData)]) – Daily escrows data - -### *class* human_protocol_sdk.statistics.statistics_client.HMTHolder(address, balance) - -Bases: `object` - -A class used to specify HMT holder. - -#### \_\_init_\_(address, balance) - -Initializes a HMTHolder instance. - -* **Parameters:** - * **address** (`str`) – Holder address - * **balance** (`int`) – Holder balance - -### *class* human_protocol_sdk.statistics.statistics_client.HMTHoldersParam(address=None, order_direction='asc') - -Bases: `object` - -A class used to specify parameters for querying HMT holders. - -#### \_\_init_\_(address=None, order_direction='asc') - -Initializes a HMTHoldersParam instance. - -* **Parameters:** - * **address** (`Optional`[`str`]) – Filter by holder’s address - * **order_direction** (`str`) – Optional. Direction of sorting (‘asc’ for ascending, ‘desc’ for descending) - -### *class* human_protocol_sdk.statistics.statistics_client.HMTStatistics(total_transfer_amount, total_transfer_count, total_holders) - -Bases: `object` - -A class used to specify HMT statistics. - -#### \_\_init_\_(total_transfer_amount, total_transfer_count, total_holders) - -Initializes a HMTStatistics instance. - -* **Parameters:** - * **total_transfer_amount** (`int`) – Total transfer amount - * **total_transfer_count** (`int`) – Total transfer count - * **total_holders** (`int`) – Total holders - -### *class* human_protocol_sdk.statistics.statistics_client.PaymentStatistics(daily_payments_data) - -Bases: `object` - -A class used to specify payment statistics. - -#### \_\_init_\_(daily_payments_data) - -Initializes a PaymentStatistics instance. - -* **Parameters:** - **daily_payments_data** (`List`[[`DailyPaymentData`](#human_protocol_sdk.statistics.statistics_client.DailyPaymentData)]) – Daily payments data - -### *class* human_protocol_sdk.statistics.statistics_client.StatisticsClient(chain_id=ChainId.POLYGON_AMOY) - -Bases: `object` - -A client used to get statistical data. - -#### \_\_init_\_(chain_id=ChainId.POLYGON_AMOY) - -Initializes a Statistics instance - -* **Parameters:** - **chain_id** ([`ChainId`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId)) – Chain ID to get statistical data from - -#### get_escrow_statistics(filter=, options=None) - -Get escrow statistics data for the given date range. - -* **Parameters:** - * **filter** ([`StatisticsFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.StatisticsFilter)) – Object containing the date range - * **options** (`Optional`[[`SubgraphOptions`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.SubgraphOptions)]) – Optional config for subgraph requests -* **Return type:** - [`EscrowStatistics`](#human_protocol_sdk.statistics.statistics_client.EscrowStatistics) -* **Returns:** - Escrow statistics data -* **Example:** - ```python - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.statistics import StatisticsClient - from human_protocol_sdk.filter import StatisticsFilter - - statistics_client = StatisticsClient(ChainId.POLYGON_AMOY) - - print(statistics_client.get_escrow_statistics()) - print( - statistics_client.get_escrow_statistics( - StatisticsFilter( - date_from=datetime.datetime(2023, 5, 8), - date_to=datetime.datetime(2023, 6, 8), - ) - ) - ) - ``` - -#### get_hmt_daily_data(filter=, options=None) - -Get HMT daily statistics data for the given date range. - -* **Parameters:** - * **filter** ([`StatisticsFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.StatisticsFilter)) – Object containing the date range - * **options** (`Optional`[[`SubgraphOptions`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.SubgraphOptions)]) – Optional config for subgraph requests -* **Return type:** - `List`[[`DailyHMTData`](#human_protocol_sdk.statistics.statistics_client.DailyHMTData)] -* **Returns:** - HMT statistics data -* **Example:** - ```python - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.statistics import StatisticsClient, StatisticsFilter - - statistics_client = StatisticsClient(ChainId.POLYGON_AMOY) - - print(statistics_client.get_hmt_daily_data()) - print( - statistics_client.get_hmt_daily_data( - StatisticsFilter( - date_from=datetime.datetime(2023, 5, 8), - date_to=datetime.datetime(2023, 6, 8), - ) - ) - ) - ``` - -#### get_hmt_holders(param=, options=None) - -Get HMT holders data with optional filters and ordering. - -* **Parameters:** - * **param** ([`HMTHoldersParam`](#human_protocol_sdk.statistics.statistics_client.HMTHoldersParam)) – Object containing filter and order parameters - * **options** (`Optional`[[`SubgraphOptions`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.SubgraphOptions)]) – Optional config for subgraph requests -* **Return type:** - `List`[[`HMTHolder`](#human_protocol_sdk.statistics.statistics_client.HMTHolder)] -* **Returns:** - List of HMT holders -* **Example:** - ```python - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.statistics import StatisticsClient, HMTHoldersParam - - statistics_client = StatisticsClient(ChainId.POLYGON_AMOY) - - print(statistics_client.get_hmt_holders()) - print( - statistics_client.get_hmt_holders( - HMTHoldersParam( - address="0x123...", - order_direction="asc", - ) - ) - ) - ``` - -#### get_hmt_statistics(options=None) - -Get HMT statistics data. - -* **Parameters:** - **options** (`Optional`[[`SubgraphOptions`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.SubgraphOptions)]) – Optional config for subgraph requests -* **Return type:** - [`HMTStatistics`](#human_protocol_sdk.statistics.statistics_client.HMTStatistics) -* **Returns:** - HMT statistics data -* **Example:** - ```python - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.statistics import StatisticsClient - - statistics_client = StatisticsClient(ChainId.POLYGON_AMOY) - - print(statistics_client.get_hmt_statistics()) - ``` - -#### get_payment_statistics(filter=, options=None) - -Get payment statistics data for the given date range. - -* **Parameters:** - * **filter** ([`StatisticsFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.StatisticsFilter)) – Object containing the date range - * **options** (`Optional`[[`SubgraphOptions`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.SubgraphOptions)]) – Optional config for subgraph requests -* **Return type:** - [`PaymentStatistics`](#human_protocol_sdk.statistics.statistics_client.PaymentStatistics) -* **Returns:** - Payment statistics data -* **Example:** - ```python - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.statistics import StatisticsClient - from human_protocol_sdk.filter import StatisticsFilter - - statistics_client = StatisticsClient(ChainId.POLYGON_AMOY) - - print(statistics_client.get_payment_statistics()) - print( - statistics_client.get_payment_statistics( - StatisticsFilter( - date_from=datetime.datetime(2023, 5, 8), - date_to=datetime.datetime(2023, 6, 8), - ) - ) - ) - ``` - -#### get_worker_statistics(filter=, options=None) - -Get worker statistics data for the given date range. - -* **Parameters:** - * **filter** ([`StatisticsFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.StatisticsFilter)) – Object containing the date range - * **options** (`Optional`[[`SubgraphOptions`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.SubgraphOptions)]) – Optional config for subgraph requests -* **Return type:** - [`WorkerStatistics`](#human_protocol_sdk.statistics.statistics_client.WorkerStatistics) -* **Returns:** - Worker statistics data -* **Example:** - ```python - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.statistics import StatisticsClient - from human_protocol_sdk.filter import StatisticsFilter - - statistics_client = StatisticsClient(ChainId.POLYGON_AMOY) - - print(statistics_client.get_worker_statistics()) - print( - statistics_client.get_worker_statistics( - StatisticsFilter( - date_from=datetime.datetime(2023, 5, 8), - date_to=datetime.datetime(2023, 6, 8), - ) - ) - ) - ``` - -### *exception* human_protocol_sdk.statistics.statistics_client.StatisticsClientError - -Bases: `Exception` - -Raises when some error happens when getting data from subgraph. - -### *class* human_protocol_sdk.statistics.statistics_client.WorkerStatistics(daily_workers_data) - -Bases: `object` - -A class used to specify worker statistics. - -#### \_\_init_\_(daily_workers_data) - -Initializes a WorkerStatistics instance. - -* **Parameters:** - **daily_workers_data** (`List`[[`DailyWorkerData`](#human_protocol_sdk.statistics.statistics_client.DailyWorkerData)]) – Daily workers data diff --git a/docs/sdk/python/human_protocol_sdk.storage.md b/docs/sdk/python/human_protocol_sdk.storage.md deleted file mode 100644 index 039bef73dd..0000000000 --- a/docs/sdk/python/human_protocol_sdk.storage.md +++ /dev/null @@ -1,22 +0,0 @@ -# human_protocol_sdk.storage package - -This modules contains an s3 client and utilities for files sharing. - -## Submodules - -* [human_protocol_sdk.storage.storage_client module](human_protocol_sdk.storage.storage_client.md) - * [Code Example](human_protocol_sdk.storage.storage_client.md#code-example) - * [Module](human_protocol_sdk.storage.storage_client.md#module) - * [`Credentials`](human_protocol_sdk.storage.storage_client.md#human_protocol_sdk.storage.storage_client.Credentials) - * [`Credentials.__init__()`](human_protocol_sdk.storage.storage_client.md#human_protocol_sdk.storage.storage_client.Credentials.__init__) - * [`StorageClient`](human_protocol_sdk.storage.storage_client.md#human_protocol_sdk.storage.storage_client.StorageClient) - * [`StorageClient.__init__()`](human_protocol_sdk.storage.storage_client.md#human_protocol_sdk.storage.storage_client.StorageClient.__init__) - * [`StorageClient.bucket_exists()`](human_protocol_sdk.storage.storage_client.md#human_protocol_sdk.storage.storage_client.StorageClient.bucket_exists) - * [`StorageClient.download_files()`](human_protocol_sdk.storage.storage_client.md#human_protocol_sdk.storage.storage_client.StorageClient.download_files) - * [`StorageClient.list_objects()`](human_protocol_sdk.storage.storage_client.md#human_protocol_sdk.storage.storage_client.StorageClient.list_objects) - * [`StorageClient.upload_files()`](human_protocol_sdk.storage.storage_client.md#human_protocol_sdk.storage.storage_client.StorageClient.upload_files) - * [`StorageClientError`](human_protocol_sdk.storage.storage_client.md#human_protocol_sdk.storage.storage_client.StorageClientError) - * [`StorageFileNotFoundError`](human_protocol_sdk.storage.storage_client.md#human_protocol_sdk.storage.storage_client.StorageFileNotFoundError) -* [human_protocol_sdk.storage.storage_utils module](human_protocol_sdk.storage.storage_utils.md) - * [`StorageUtils`](human_protocol_sdk.storage.storage_utils.md#human_protocol_sdk.storage.storage_utils.StorageUtils) - * [`StorageUtils.download_file_from_url()`](human_protocol_sdk.storage.storage_utils.md#human_protocol_sdk.storage.storage_utils.StorageUtils.download_file_from_url) diff --git a/docs/sdk/python/human_protocol_sdk.storage.storage_client.md b/docs/sdk/python/human_protocol_sdk.storage.storage_client.md deleted file mode 100644 index e93da074af..0000000000 --- a/docs/sdk/python/human_protocol_sdk.storage.storage_client.md +++ /dev/null @@ -1,246 +0,0 @@ -# human_protocol_sdk.storage.storage_client module - -This client enables to interact with S3 cloud storage services like Amazon S3 Bucket, -Google Cloud Storage and others. - -If credentials are not provided, anonymous access will be used (for downloading files). - -## Code Example - -```python -from human_protocol_sdk.storage import ( - Credentials, - StorageClient, -) - -credentials = Credentials( - access_key="my-access-key", - secret_key="my-secret-key", -) - -storage_client = StorageClient( - endpoint_url="s3.us-west-2.amazonaws.com", - region="us-west-2", - credentials=credentials, -) -``` - -## Module - -### *class* human_protocol_sdk.storage.storage_client.Credentials(access_key, secret_key) - -Bases: `object` - -A class to represent the credentials required to authenticate with an S3-compatible service. - -Example: - -```default -credentials = Credentials( - access_key='my-access-key', - secret_key='my-secret-key' -) -``` - -#### \_\_init_\_(access_key, secret_key) - -Initializes a Credentials instance. - -* **Parameters:** - * **access_key** (`str`) – The access key for the S3-compatible service. - * **secret_key** (`str`) – The secret key for the S3-compatible service. - -### *class* human_protocol_sdk.storage.storage_client.StorageClient(endpoint_url, region=None, credentials=None, secure=True) - -Bases: `object` - -A class for downloading files from an S3-compatible service. - -* **Attribute:** - - client (Minio): The S3-compatible client used for interacting with the service. -* **Example:** - ```python - # Download a list of files from an S3-compatible service - client = StorageClient( - endpoint_url='https://s3.us-west-2.amazonaws.com', - region='us-west-2', - credentials=Credentials( - access_key='my-access-key', - secret_key='my-secret-key' - ) - ) - files = ['file1.txt', 'file2.txt'] - bucket = 'my-bucket' - result_files = client.download_files(files=files, bucket=bucket) - ``` - -#### \_\_init_\_(endpoint_url, region=None, credentials=None, secure=True) - -Initializes the StorageClient with the given endpoint_url, region, and credentials. - -If credentials are not provided, anonymous access will be used. - -* **Parameters:** - * **endpoint_url** (`str`) – The URL of the S3-compatible service. - * **region** (`Optional`[`str`]) – The region of the S3-compatible service. Defaults to None. - * **credentials** (`Optional`[[`Credentials`](#human_protocol_sdk.storage.storage_client.Credentials)]) – The credentials required to authenticate with the S3-compatible service. - Defaults to None for anonymous access. - * **secure** (`Optional`[`bool`]) – Flag to indicate to use secure (TLS) connection to S3 service or not. - Defaults to True. - -#### bucket_exists(bucket) - -Check if a given bucket exists. - -* **Parameters:** - **bucket** (`str`) – The name of the bucket to check. -* **Return type:** - `bool` -* **Returns:** - True if the bucket exists, False otherwise. -* **Raises:** - [**StorageClientError**](#human_protocol_sdk.storage.storage_client.StorageClientError) – If an error occurs while checking the bucket. -* **Example:** - ```python - from human_protocol_sdk.storage import ( - Credentials, - StorageClient, - ) - - credentials = Credentials( - access_key="my-access-key", - secret_key="my-secret-key", - ) - - storage_client = StorageClient( - endpoint_url="s3.us-west-2.amazonaws.com", - region="us-west-2", - credentials=credentials, - ) - - is_exists = storage_client.bucket_exists( - bucket = "my-bucket" - ) - ``` - -#### download_files(files, bucket) - -Downloads a list of files from the specified S3-compatible bucket. - -* **Parameters:** - * **files** (`List`[`str`]) – A list of file keys to download. - * **bucket** (`str`) – The name of the S3-compatible bucket to download from. -* **Return type:** - `List`[`bytes`] -* **Returns:** - A list of file contents (bytes) downloaded from the bucket. -* **Raises:** - * [**StorageClientError**](#human_protocol_sdk.storage.storage_client.StorageClientError) – If an error occurs while downloading the files. - * [**StorageFileNotFoundError**](#human_protocol_sdk.storage.storage_client.StorageFileNotFoundError) – If one of the specified files is not found in the bucket. -* **Example:** - ```python - from human_protocol_sdk.storage import ( - Credentials, - StorageClient, - ) - - credentials = Credentials( - access_key="my-access-key", - secret_key="my-secret-key", - ) - - storage_client = StorageClient( - endpoint_url="s3.us-west-2.amazonaws.com", - region="us-west-2", - credentials=credentials, - ) - - result = storage_client.download_files( - files = ["file1.txt", "file2.txt"], - bucket = "my-bucket" - ) - ``` - -#### list_objects(bucket) - -Return a list of all objects in a given bucket. - -* **Parameters:** - **bucket** (`str`) – The name of the bucket to list objects from. -* **Return type:** - `List`[`str`] -* **Returns:** - A list of object keys in the given bucket. -* **Raises:** - [**StorageClientError**](#human_protocol_sdk.storage.storage_client.StorageClientError) – If an error occurs while listing the objects. -* **Example:** - ```python - from human_protocol_sdk.storage import ( - Credentials, - StorageClient, - ) - - credentials = Credentials( - access_key="my-access-key", - secret_key="my-secret-key", - ) - - storage_client = StorageClient( - endpoint_url="s3.us-west-2.amazonaws.com", - region="us-west-2", - credentials=credentials, - ) - - result = storage_client.list_objects( - bucket = "my-bucket" - ) - ``` - -#### upload_files(files, bucket) - -Uploads a list of files to the specified S3-compatible bucket. - -* **Parameters:** - * **files** (`List`[`dict`]) – A list of files to upload. - * **bucket** (`str`) – The name of the S3-compatible bucket to upload to. -* **Return type:** - `List`[`dict`] -* **Returns:** - List of dict with key, url, hash fields -* **Raises:** - [**StorageClientError**](#human_protocol_sdk.storage.storage_client.StorageClientError) – If an error occurs while uploading the files. -* **Example:** - ```python - from human_protocol_sdk.storage import ( - Credentials, - StorageClient, - ) - - credentials = Credentials( - access_key="my-access-key", - secret_key="my-secret-key", - ) - - storage_client = StorageClient( - endpoint_url="s3.us-west-2.amazonaws.com", - region="us-west-2", - credentials=credentials, - ) - - result = storage_client.upload_files( - files = [{"file": "file content", "key": "file1.txt", "hash": "hash1"}], - bucket = "my-bucket" - ) - ``` - -### *exception* human_protocol_sdk.storage.storage_client.StorageClientError - -Bases: `Exception` - -Raises when some error happens when interacting with storage. - -### *exception* human_protocol_sdk.storage.storage_client.StorageFileNotFoundError - -Bases: [`StorageClientError`](#human_protocol_sdk.storage.storage_client.StorageClientError) - -Raises when some error happens when file is not found by its key. diff --git a/docs/sdk/python/human_protocol_sdk.storage.storage_utils.md b/docs/sdk/python/human_protocol_sdk.storage.storage_utils.md deleted file mode 100644 index 8b08a80370..0000000000 --- a/docs/sdk/python/human_protocol_sdk.storage.storage_utils.md +++ /dev/null @@ -1,30 +0,0 @@ -# human_protocol_sdk.storage.storage_utils module - -Utility class for storage-related operations. - -### *class* human_protocol_sdk.storage.storage_utils.StorageUtils - -Bases: `object` - -Utility class for storage-related operations. - -#### *static* download_file_from_url(url) - -Downloads a file from the specified URL. - -* **Parameters:** - **url** (`str`) – The URL of the file to download. -* **Return type:** - `bytes` -* **Returns:** - The content of the downloaded file. -* **Raises:** - [**StorageClientError**](human_protocol_sdk.storage.storage_client.md#human_protocol_sdk.storage.storage_client.StorageClientError) – If an error occurs while downloading the file. -* **Example:** - ```python - from human_protocol_sdk.storage import StorageUtils - - result = StorageUtils.download_file_from_url( - "https://www.example.com/file.txt" - ) - ``` diff --git a/docs/sdk/python/human_protocol_sdk.transaction.md b/docs/sdk/python/human_protocol_sdk.transaction.md deleted file mode 100644 index e9e877208c..0000000000 --- a/docs/sdk/python/human_protocol_sdk.transaction.md +++ /dev/null @@ -1,18 +0,0 @@ -# human_protocol_sdk.transaction package - -This module enables to obtain transaction information from -both the contracts and subgraph. - -## Submodules - -* [human_protocol_sdk.transaction.transaction_utils module](human_protocol_sdk.transaction.transaction_utils.md) - * [Code Example](human_protocol_sdk.transaction.transaction_utils.md#code-example) - * [Module](human_protocol_sdk.transaction.transaction_utils.md#module) - * [`InternalTransaction`](human_protocol_sdk.transaction.transaction_utils.md#human_protocol_sdk.transaction.transaction_utils.InternalTransaction) - * [`InternalTransaction.__init__()`](human_protocol_sdk.transaction.transaction_utils.md#human_protocol_sdk.transaction.transaction_utils.InternalTransaction.__init__) - * [`TransactionData`](human_protocol_sdk.transaction.transaction_utils.md#human_protocol_sdk.transaction.transaction_utils.TransactionData) - * [`TransactionData.__init__()`](human_protocol_sdk.transaction.transaction_utils.md#human_protocol_sdk.transaction.transaction_utils.TransactionData.__init__) - * [`TransactionUtils`](human_protocol_sdk.transaction.transaction_utils.md#human_protocol_sdk.transaction.transaction_utils.TransactionUtils) - * [`TransactionUtils.get_transaction()`](human_protocol_sdk.transaction.transaction_utils.md#human_protocol_sdk.transaction.transaction_utils.TransactionUtils.get_transaction) - * [`TransactionUtils.get_transactions()`](human_protocol_sdk.transaction.transaction_utils.md#human_protocol_sdk.transaction.transaction_utils.TransactionUtils.get_transactions) - * [`TransactionUtilsError`](human_protocol_sdk.transaction.transaction_utils.md#human_protocol_sdk.transaction.transaction_utils.TransactionUtilsError) diff --git a/docs/sdk/python/human_protocol_sdk.transaction.transaction_utils.md b/docs/sdk/python/human_protocol_sdk.transaction.transaction_utils.md deleted file mode 100644 index e2138632d9..0000000000 --- a/docs/sdk/python/human_protocol_sdk.transaction.transaction_utils.md +++ /dev/null @@ -1,105 +0,0 @@ -# human_protocol_sdk.transaction.transaction_utils module - -Utility class for transaction-related operations. - -## Code Example - -```python -from human_protocol_sdk.constants import ChainId -from human_protocol_sdk.transaction import TransactionUtils, TransactionFilter - -print( - TransactionUtils.get_transactions( - TransactionFilter( - chain_id=ChainId.POLYGON_AMOY, - from_address="0x1234567890123456789012345678901234567890", - to_address="0x0987654321098765432109876543210987654321", - start_date=datetime.datetime(2023, 5, 8), - end_date=datetime.datetime(2023, 6, 8), - ) - ) -) -``` - -## Module - -### *class* human_protocol_sdk.transaction.transaction_utils.InternalTransaction(from_address, to_address, value, method, receiver, escrow, token) - -Bases: `object` - -#### \_\_init_\_(from_address, to_address, value, method, receiver, escrow, token) - -### *class* human_protocol_sdk.transaction.transaction_utils.TransactionData(chain_id, block, tx_hash, from_address, to_address, timestamp, value, method, receiver, escrow, token, internal_transactions) - -Bases: `object` - -#### \_\_init_\_(chain_id, block, tx_hash, from_address, to_address, timestamp, value, method, receiver, escrow, token, internal_transactions) - -### *class* human_protocol_sdk.transaction.transaction_utils.TransactionUtils - -Bases: `object` - -A utility class that provides additional transaction-related functionalities. - -#### *static* get_transaction(chain_id, hash, options=None) - -Returns the transaction for a given hash. - -* **Parameters:** - * **chain_id** ([`ChainId`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId)) – Network in which the transaction was executed - * **hash** (`str`) – Hash of the transaction - * **options** (`Optional`[[`SubgraphOptions`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.SubgraphOptions)]) – Optional config for subgraph requests -* **Return type:** - `Optional`[[`TransactionData`](#human_protocol_sdk.transaction.transaction_utils.TransactionData)] -* **Returns:** - Transaction data -* **Example:** - ```python - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.transaction import TransactionUtils - - print( - TransactionUtils.get_transaction( - ChainId.POLYGON_AMOY, - "0x1234567890123456789012345678901234567891" - ) - ) - ``` - -#### *static* get_transactions(filter, options=None) - -Get an array of transactions based on the specified filter parameters. - -* **Parameters:** - * **filter** ([`TransactionFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.TransactionFilter)) – Object containing all the necessary parameters to filter - (chain_id, from_address, to_address, start_date, end_date, start_block, end_block, method, escrow, token, first, skip, order_direction) - * **options** (`Optional`[[`SubgraphOptions`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.SubgraphOptions)]) – Optional config for subgraph requests -* **Return type:** - `List`[[`TransactionData`](#human_protocol_sdk.transaction.transaction_utils.TransactionData)] -* **Returns:** - List of transactions -* **Example:** - ```python - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.transaction import TransactionUtils, TransactionFilter - - print( - TransactionUtils.get_transactions( - TransactionFilter( - chain_id=ChainId.POLYGON_AMOY, - from_address="0x1234567890123456789012345678901234567890", - to_address="0x0987654321098765432109876543210987654321", - method="transfer", - escrow="0x0987654321098765432109876543210987654321", - start_date=datetime.datetime(2023, 5, 8), - end_date=datetime.datetime(2023, 6, 8), - ) - ) - ) - ``` - -### *exception* human_protocol_sdk.transaction.transaction_utils.TransactionUtilsError - -Bases: `Exception` - -Raises when some error happens when getting data from subgraph. diff --git a/docs/sdk/python/human_protocol_sdk.utils.md b/docs/sdk/python/human_protocol_sdk.utils.md deleted file mode 100644 index e2b2289ca3..0000000000 --- a/docs/sdk/python/human_protocol_sdk.utils.md +++ /dev/null @@ -1,150 +0,0 @@ -# human_protocol_sdk.utils module - -### *class* human_protocol_sdk.utils.SubgraphOptions(max_retries=None, base_delay=None, indexer_id=None) - -Bases: `object` - -Configuration for subgraph logic. - -#### \_\_init_\_(max_retries=None, base_delay=None, indexer_id=None) - -#### base_delay *: `Optional`[`int`]* *= None* - -#### indexer_id *: `Optional`[`str`]* *= None* - -#### max_retries *: `Optional`[`int`]* *= None* - -### human_protocol_sdk.utils.custom_gql_fetch(network, query, params=None, options=None) - -Fetch data from the subgraph with optional logic. - -* **Parameters:** - * **network** (`dict`) – Network configuration dictionary - * **query** (`str`) – GraphQL query string - * **params** (`Optional`[`dict`]) – Query parameters - * **options** (`Optional`[[`SubgraphOptions`](#human_protocol_sdk.utils.SubgraphOptions)]) – Optional subgraph configuration -* **Returns:** - JSON response from the subgraph -* **Raises:** - **Exception** – If the subgraph query fails - -### human_protocol_sdk.utils.get_contract_interface(contract_entrypoint) - -Retrieve the contract interface of a given contract. - -* **Parameters:** - **contract_entrypoint** – the entrypoint of the JSON. -* **Returns:** - The contract interface containing the contract abi. - -### human_protocol_sdk.utils.get_erc20_interface() - -Retrieve the ERC20 interface. - -* **Returns:** - The ERC20 interface of smart contract. - -### human_protocol_sdk.utils.get_escrow_interface() - -Retrieve the RewardPool interface. - -* **Returns:** - The RewardPool interface of smart contract. - -### human_protocol_sdk.utils.get_factory_interface() - -Retrieve the EscrowFactory interface. - -* **Returns:** - The EscrowFactory interface of smart contract. - -### human_protocol_sdk.utils.get_hmt_balance(wallet_addr, token_addr, w3) - -Get HMT balance - -* **Parameters:** - * **wallet_addr** – wallet address - * **token_addr** – ERC-20 contract - * **w3** – Web3 instance -* **Returns:** - HMT balance (wei) - -### human_protocol_sdk.utils.get_kvstore_interface() - -Retrieve the KVStore interface. - -* **Returns:** - The KVStore interface of smart contract. - -### human_protocol_sdk.utils.get_staking_interface() - -Retrieve the Staking interface. - -* **Returns:** - The Staking interface of smart contract. - -### human_protocol_sdk.utils.handle_error(e, exception_class) - -Handles and translates errors raised during contract transactions. - -This function captures exceptions (especially ContractLogicError from web3.py), -extracts meaningful revert reasons if present, logs unexpected errors, and raises -a custom exception with a clear message for SDK users. - -* **Parameters:** - * **e** – The exception object raised during a transaction. - * **exception_class** – The custom exception class to raise (e.g., EscrowClientError). -* **Raises:** - **exception_class** – With a detailed error message, including contract revert reasons if available. -* **Example:** - try: - : tx_hash = contract.functions.someMethod(…).transact() - w3.eth.wait_for_transaction_receipt(tx_hash) - - except Exception as e: - : handle_error(e, EscrowClientError) - -### human_protocol_sdk.utils.is_indexer_error(error) - -Check if an error indicates that the indexer is down or not synced. -This function specifically checks for “bad indexers” errors from The Graph. - -* **Parameters:** - **error** (`Exception`) – The error to check -* **Return type:** - `bool` -* **Returns:** - True if the error indicates indexer issues - -### human_protocol_sdk.utils.parse_transfer_transaction(hmtoken_contract, tx_receipt) - -Parse a transfer transaction receipt. - -* **Parameters:** - * **hmtoken_contract** (`Contract`) – The HMT token contract - * **tx_receipt** (`Optional`[`TxReceipt`]) – The transaction receipt -* **Return type:** - `Tuple`[`bool`, `Optional`[`int`]] -* **Returns:** - A tuple indicating if HMT was transferred and the transaction balance - -### human_protocol_sdk.utils.validate_json(data) - -Validates if the given string is a valid JSON. -:type data: `str` -:param data: String to validate -:rtype: `bool` -:return: True if the string is a valid JSON, False otherwise - -### human_protocol_sdk.utils.validate_url(url) - -Validates the given URL. - -* **Parameters:** - **url** (`str`) – Public or private URL address -* **Return type:** - `bool` -* **Returns:** - True if URL is valid, False otherwise -* **Raises:** - **ValidationFailure** – If the URL is invalid diff --git a/docs/sdk/python/human_protocol_sdk.worker.md b/docs/sdk/python/human_protocol_sdk.worker.md deleted file mode 100644 index e62f9a998c..0000000000 --- a/docs/sdk/python/human_protocol_sdk.worker.md +++ /dev/null @@ -1,13 +0,0 @@ -# human_protocol_sdk.worker package - -This module enables to obtain worker information from subgraph. - -## Submodules - -* [human_protocol_sdk.worker.worker_utils module](human_protocol_sdk.worker.worker_utils.md) - * [`WorkerData`](human_protocol_sdk.worker.worker_utils.md#human_protocol_sdk.worker.worker_utils.WorkerData) - * [`WorkerData.__init__()`](human_protocol_sdk.worker.worker_utils.md#human_protocol_sdk.worker.worker_utils.WorkerData.__init__) - * [`WorkerUtils`](human_protocol_sdk.worker.worker_utils.md#human_protocol_sdk.worker.worker_utils.WorkerUtils) - * [`WorkerUtils.get_worker()`](human_protocol_sdk.worker.worker_utils.md#human_protocol_sdk.worker.worker_utils.WorkerUtils.get_worker) - * [`WorkerUtils.get_workers()`](human_protocol_sdk.worker.worker_utils.md#human_protocol_sdk.worker.worker_utils.WorkerUtils.get_workers) - * [`WorkerUtilsError`](human_protocol_sdk.worker.worker_utils.md#human_protocol_sdk.worker.worker_utils.WorkerUtilsError) diff --git a/docs/sdk/python/human_protocol_sdk.worker.worker_utils.md b/docs/sdk/python/human_protocol_sdk.worker.worker_utils.md deleted file mode 100644 index 7c574445ad..0000000000 --- a/docs/sdk/python/human_protocol_sdk.worker.worker_utils.md +++ /dev/null @@ -1,52 +0,0 @@ -# human_protocol_sdk.worker.worker_utils module - -### *class* human_protocol_sdk.worker.worker_utils.WorkerData(id, address, total_amount_received, payout_count) - -Bases: `object` - -#### \_\_init_\_(id, address, total_amount_received, payout_count) - -Initializes a WorkerData instance. - -* **Parameters:** - * **id** (`str`) – Worker ID - * **address** (`str`) – Worker address - * **total_amount_received** (`str`) – Total amount received by the worker - * **payout_count** (`str`) – Number of payouts received by the worker - -### *class* human_protocol_sdk.worker.worker_utils.WorkerUtils - -Bases: `object` - -A utility class that provides additional worker-related functionalities. - -#### *static* get_worker(chain_id, worker_address, options=None) - -Gets the worker details. - -* **Parameters:** - * **chain_id** ([`ChainId`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId)) – Network in which the worker exists - * **worker_address** (`str`) – Address of the worker - * **options** (`Optional`[[`SubgraphOptions`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.SubgraphOptions)]) – Optional config for subgraph requests -* **Return type:** - `Optional`[[`WorkerData`](#human_protocol_sdk.worker.worker_utils.WorkerData)] -* **Returns:** - Worker data if exists, otherwise None - -#### *static* get_workers(filter, options=None) - -Get workers data of the protocol. - -* **Parameters:** - * **filter** ([`WorkerFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.WorkerFilter)) – Worker filter - * **options** (`Optional`[[`SubgraphOptions`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.SubgraphOptions)]) – Optional config for subgraph requests -* **Return type:** - `List`[[`WorkerData`](#human_protocol_sdk.worker.worker_utils.WorkerData)] -* **Returns:** - List of workers data - -### *exception* human_protocol_sdk.worker.worker_utils.WorkerUtilsError - -Bases: `Exception` - -Raised when an error occurs when getting data from subgraph. diff --git a/docs/sdk/python/index.md b/docs/sdk/python/index.md deleted file mode 100644 index a8dc40c404..0000000000 --- a/docs/sdk/python/index.md +++ /dev/null @@ -1,83 +0,0 @@ - - -# Welcome to Human Protocol SDK’s documentation! - -## Installation - -To install the Human Protocol SDK, run the following command: - -```bash -pip install human-protocol-sdk -``` - -In case you want to use the features of the agreement module, make sure to install corresponding extras as well. - -```bash -pip install human-protocol-sdk[agreement] -``` - -## Contents: - -* [human_protocol_sdk package](human_protocol_sdk.md) - * [Subpackages](human_protocol_sdk.md#subpackages) - * [human_protocol_sdk.agreement package](human_protocol_sdk.agreement.md) - * [Getting Started](human_protocol_sdk.agreement.md#getting-started) - * [Submodules](human_protocol_sdk.agreement.md#submodules) - * [human_protocol_sdk.encryption package](human_protocol_sdk.encryption.md) - * [Submodules](human_protocol_sdk.encryption.md#submodules) - * [human_protocol_sdk.escrow package](human_protocol_sdk.escrow.md) - * [Submodules](human_protocol_sdk.escrow.md#submodules) - * [human_protocol_sdk.kvstore package](human_protocol_sdk.kvstore.md) - * [Submodules](human_protocol_sdk.kvstore.md#submodules) - * [human_protocol_sdk.operator package](human_protocol_sdk.operator.md) - * [Submodules](human_protocol_sdk.operator.md#submodules) - * [human_protocol_sdk.staking package](human_protocol_sdk.staking.md) - * [Submodules](human_protocol_sdk.staking.md#submodules) - * [human_protocol_sdk.statistics package](human_protocol_sdk.statistics.md) - * [Submodules](human_protocol_sdk.statistics.md#submodules) - * [human_protocol_sdk.storage package](human_protocol_sdk.storage.md) - * [Submodules](human_protocol_sdk.storage.md#submodules) - * [human_protocol_sdk.transaction package](human_protocol_sdk.transaction.md) - * [Submodules](human_protocol_sdk.transaction.md#submodules) - * [human_protocol_sdk.worker package](human_protocol_sdk.worker.md) - * [Submodules](human_protocol_sdk.worker.md#submodules) - * [Submodules](human_protocol_sdk.md#submodules) - * [human_protocol_sdk.constants module](human_protocol_sdk.constants.md) - * [`ChainId`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId) - * [`KVStoreKeys`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.KVStoreKeys) - * [`OperatorCategory`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.OperatorCategory) - * [`OrderDirection`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.OrderDirection) - * [`Role`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.Role) - * [`Status`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.Status) - * [human_protocol_sdk.filter module](human_protocol_sdk.filter.md) - * [`CancellationRefundFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.CancellationRefundFilter) - * [`EscrowFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.EscrowFilter) - * [`FilterError`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.FilterError) - * [`PayoutFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.PayoutFilter) - * [`StakersFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.StakersFilter) - * [`StatisticsFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.StatisticsFilter) - * [`StatusEventFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.StatusEventFilter) - * [`TransactionFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.TransactionFilter) - * [`WorkerFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.WorkerFilter) - * [human_protocol_sdk.legacy_encryption module](human_protocol_sdk.legacy_encryption.md) - * [`DecryptionError`](human_protocol_sdk.legacy_encryption.md#human_protocol_sdk.legacy_encryption.DecryptionError) - * [`Encryption`](human_protocol_sdk.legacy_encryption.md#human_protocol_sdk.legacy_encryption.Encryption) - * [`InvalidPublicKey`](human_protocol_sdk.legacy_encryption.md#human_protocol_sdk.legacy_encryption.InvalidPublicKey) - * [human_protocol_sdk.utils module](human_protocol_sdk.utils.md) - * [`SubgraphOptions`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.SubgraphOptions) - * [`custom_gql_fetch()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.custom_gql_fetch) - * [`get_contract_interface()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_contract_interface) - * [`get_erc20_interface()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_erc20_interface) - * [`get_escrow_interface()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_escrow_interface) - * [`get_factory_interface()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_factory_interface) - * [`get_hmt_balance()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_hmt_balance) - * [`get_kvstore_interface()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_kvstore_interface) - * [`get_staking_interface()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_staking_interface) - * [`handle_error()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.handle_error) - * [`is_indexer_error()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.is_indexer_error) - * [`parse_transfer_transaction()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.parse_transfer_transaction) - * [`validate_json()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.validate_json) - * [`validate_url()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.validate_url) diff --git a/docs/sdk/typescript/README.md b/docs/sdk/typescript/README.md deleted file mode 100644 index 7644187242..0000000000 --- a/docs/sdk/typescript/README.md +++ /dev/null @@ -1,37 +0,0 @@ -**@human-protocol/sdk** - -*** - -

- Human Protocol -

- -[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456 -[circleci-url]: https://circleci.com/gh/nestjs/nest - -

Human Protocol Node.js SDK

-

Node.js SDK to launch/manage escrows on Human Protocol -

- -

- - Node SDK Check - - - Node SDK deployment - -

- -## Installation - -This SDK is available on [NPM](https://www.npmjs.com/package/@human-protocol/sdk). - - yarn add @human-protocol/sdk - -## Documentation - -For detailed information about core, please refer to the [Human Protocol Docs](https://sdk.humanprotocol.org/). - -## License - -This project is licensed under the MIT License. See the [LICENSE](https://github.com/humanprotocol/human-protocol/blob/main/LICENSE) file for details. diff --git a/docs/sdk/typescript/base/README.md b/docs/sdk/typescript/base/README.md deleted file mode 100644 index 75875daaf1..0000000000 --- a/docs/sdk/typescript/base/README.md +++ /dev/null @@ -1,11 +0,0 @@ -[**@human-protocol/sdk**](../README.md) - -*** - -[@human-protocol/sdk](../modules.md) / base - -# base - -## Classes - -- [BaseEthersClient](classes/BaseEthersClient.md) diff --git a/docs/sdk/typescript/base/classes/BaseEthersClient.md b/docs/sdk/typescript/base/classes/BaseEthersClient.md deleted file mode 100644 index 67d2394395..0000000000 --- a/docs/sdk/typescript/base/classes/BaseEthersClient.md +++ /dev/null @@ -1,63 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [base](../README.md) / BaseEthersClient - -# Abstract Class: BaseEthersClient - -Defined in: [base.ts:10](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L10) - -## Introduction - -This class is used as a base class for other clients making on-chain calls. - -## Extended by - -- [`EscrowClient`](../../escrow/classes/EscrowClient.md) -- [`KVStoreClient`](../../kvstore/classes/KVStoreClient.md) -- [`StakingClient`](../../staking/classes/StakingClient.md) - -## Constructors - -### Constructor - -> **new BaseEthersClient**(`runner`, `networkData`): `BaseEthersClient` - -Defined in: [base.ts:20](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L20) - -**BaseClient constructor** - -#### Parameters - -##### runner - -`ContractRunner` - -The Signer or Provider object to interact with the Ethereum network - -##### networkData - -[`NetworkData`](../../types/type-aliases/NetworkData.md) - -The network information required to connect to the contracts - -#### Returns - -`BaseEthersClient` - -## Properties - -### networkData - -> **networkData**: [`NetworkData`](../../types/type-aliases/NetworkData.md) - -Defined in: [base.ts:12](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) - -*** - -### runner - -> `protected` **runner**: `ContractRunner` - -Defined in: [base.ts:11](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) diff --git a/docs/sdk/typescript/encryption/README.md b/docs/sdk/typescript/encryption/README.md deleted file mode 100644 index ca6e9bf8d7..0000000000 --- a/docs/sdk/typescript/encryption/README.md +++ /dev/null @@ -1,12 +0,0 @@ -[**@human-protocol/sdk**](../README.md) - -*** - -[@human-protocol/sdk](../modules.md) / encryption - -# encryption - -## Classes - -- [Encryption](classes/Encryption.md) -- [EncryptionUtils](classes/EncryptionUtils.md) diff --git a/docs/sdk/typescript/encryption/classes/Encryption.md b/docs/sdk/typescript/encryption/classes/Encryption.md deleted file mode 100644 index 1e622c6cfb..0000000000 --- a/docs/sdk/typescript/encryption/classes/Encryption.md +++ /dev/null @@ -1,257 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [encryption](../README.md) / Encryption - -# Class: Encryption - -Defined in: [encryption.ts:58](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L58) - -## Introduction - -Class for signing and decrypting messages. - -The algorithm includes the implementation of the [PGP encryption algorithm](https://github.com/openpgpjs/openpgpjs) multi-public key encryption on typescript, and uses the vanilla [ed25519](https://en.wikipedia.org/wiki/EdDSA#Ed25519) implementation Schnorr signature for signatures and [curve25519](https://en.wikipedia.org/wiki/Curve25519) for encryption. [Learn more](https://wiki.polkadot.network/docs/learn-cryptography). - -To get an instance of this class, initialization is recommended using the static `build` method. - -```ts -static async build(privateKeyArmored: string, passphrase?: string): Promise -``` - -## Installation - -### npm -```bash -npm install @human-protocol/sdk -``` - -### yarn -```bash -yarn install @human-protocol/sdk -``` - -## Input parameters - -- `privateKeyArmored` - The encrypted private key in armored format. -- `passphrase` - The passphrase for the private key. - -## Code example - -```ts -import { Encryption } from '@human-protocol/sdk'; - -const privateKey = 'Armored_priv_key'; -const passphrase = 'example_passphrase'; -const encryption = await Encryption.build(privateKey, passphrase); -``` - -## Constructors - -### Constructor - -> **new Encryption**(`privateKey`): `Encryption` - -Defined in: [encryption.ts:66](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L66) - -Constructor for the Encryption class. - -#### Parameters - -##### privateKey - -`PrivateKey` - -The private key. - -#### Returns - -`Encryption` - -## Methods - -### decrypt() - -> **decrypt**(`message`, `publicKey?`): `Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> - -Defined in: [encryption.ts:194](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L194) - -This function decrypts messages using the private key. In addition, the public key can be added for signature verification. - -#### Parameters - -##### message - -`string` - -Message to decrypt. - -##### publicKey? - -`string` - -Public key used to verify signature if needed. This is optional. - -#### Returns - -`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> - -Message decrypted. - -**Code example** - -```ts -import { Encryption } from '@human-protocol/sdk'; - -const privateKey = 'Armored_priv_key'; -const passphrase = 'example_passphrase'; -const encryption = await Encryption.build(privateKey, passphrase); - -const publicKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- -xjMEZKQEMxYJKwYBBAHaRw8BAQdA5oZTq4UPlS0IXn4kEaSqQdAa9+Cq522v -WYxJQn3vo1/NFEh1bWFuIDxodW1hbkBobXQuYWk+wowEEBYKAD4FAmSkBDME -CwkHCAkQJBFPuuhtQo4DFQgKBBYAAgECGQECGwMCHgEWIQTQ5fbVPB9CWIdf -XdYkEU+66G1CjgAAKYYA/jMyDCtJtqu6hj22kq9SW6fuV1FCT2ySJ9vBhumF -X8wWAP433zVFl4VECOkgGk8qFr8BgkYxaz16GOFAqYbfO6oMBc44BGSkBDMS -CisGAQQBl1UBBQEBB0AKR+A48zVVYZWQvgu7Opn2IGvzI9jePB/J8pzqRhg2 -YAMBCAfCeAQYFggAKgUCZKQEMwkQJBFPuuhtQo4CGwwWIQTQ5fbVPB9CWIdf -XdYkEU+66G1CjgAA0xgBAK4AIahFFnmWR2Mp6A3q021cZXpGklc0Xw1Hfswc -UYLqAQDfdym4kiUvKO1+REKASt0Gwykndl7hra9txqlUL5DXBQ===Vwgv ------END PGP PUBLIC KEY BLOCK-----`; - -const resultMessage = await encryption.decrypt('message'); -``` - -*** - -### sign() - -> **sign**(`message`): `Promise`\<`string`\> - -Defined in: [encryption.ts:251](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L251) - -This function signs a message using the private key used to initialize the client. - -#### Parameters - -##### message - -`string` - -Message to sign. - -#### Returns - -`Promise`\<`string`\> - -Message signed. - -**Code example** - -```ts -import { Encryption } from '@human-protocol/sdk'; - -const privateKey = 'Armored_priv_key'; -const passphrase = 'example_passphrase'; -const encryption = await Encryption.build(privateKey, passphrase); - -const resultMessage = await encryption.sign('message'); -``` - -*** - -### signAndEncrypt() - -> **signAndEncrypt**(`message`, `publicKeys`): `Promise`\<`string`\> - -Defined in: [encryption.ts:142](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L142) - -This function signs and encrypts a message using the private key used to initialize the client and the specified public keys. - -#### Parameters - -##### message - -`MessageDataType` - -Message to sign and encrypt. - -##### publicKeys - -`string`[] - -Array of public keys to use for encryption. - -#### Returns - -`Promise`\<`string`\> - -Message signed and encrypted. - -**Code example** - -```ts -import { Encryption } from '@human-protocol/sdk'; -import { EscrowClient } from '@human-protocol/sdk'; - -const privateKey = 'Armored_priv_key'; -const passphrase = 'example_passphrase'; -const encryption = await Encryption.build(privateKey, passphrase); -const publicKey1 = `-----BEGIN PGP PUBLIC KEY BLOCK----- -xjMEZKQEMxYJKwYBBAHaRw8BAQdA5oZTq4UPlS0IXn4kEaSqQdAa9+Cq522v -WYxJQn3vo1/NFEh1bWFuIDxodW1hbkBobXQuYWk+wowEEBYKAD4FAmSkBDME -CwkHCAkQJBFPuuhtQo4DFQgKBBYAAgECGQECGwMCHgEWIQTQ5fbVPB9CWIdf -XdYkEU+66G1CjgAAKYYA/jMyDCtJtqu6hj22kq9SW6fuV1FCT2ySJ9vBhumF -X8wWAP433zVFl4VECOkgGk8qFr8BgkYxaz16GOFAqYbfO6oMBc44BGSkBDMS -CisGAQQBl1UBBQEBB0AKR+A48zVVYZWQvgu7Opn2IGvzI9jePB/J8pzqRhg2 -YAMBCAfCeAQYFggAKgUCZKQEMwkQJBFPuuhtQo4CGwwWIQTQ5fbVPB9CWIdf -XdYkEU+66G1CjgAA0xgBAK4AIahFFnmWR2Mp6A3q021cZXpGklc0Xw1Hfswc -UYLqAQDfdym4kiUvKO1+REKASt0Gwykndl7hra9txqlUL5DXBQ===Vwgv ------END PGP PUBLIC KEY BLOCK-----`; - -const publicKey2 = `-----BEGIN PGP PUBLIC KEY BLOCK----- -xjMEZKQEMxYJKwYBBAHaRw8BAQdAG6h+E+6T/RV2tIHer3FP/jKThAyGcoVx -FzhnP0hncPzNFEh1bWFuIDxodW1hbkBobXQuYWk+wowEEBYKAD4FAmSkBDME -CwkHCAkQPIq5xLhlTYkDFQgKBBYAAgECGQECGwMCHgEWIQTcxtMgul/AeUvH -bio8irnEuGVNiQAA/HsBANpfFkxNYixpsBk8LlaaCaPy5f1/cWNPgODM9uzo -ciSTAQDtAYynu4dSJO9GbMuDuc0FaUHRWJK3mS6JkvedYL4oBM44BGSkBDMS -CisGAQQBl1UBBQEBB0DWbEG7DMhkeSc8ZPzrH8XNSCqS3t9y/oQidFR+xN3Z -bAMBCAfCeAQYFggAKgUCZKQEMwkQPIq5xLhlTYkCGwwWIQTcxtMgul/AeUvH -bio8irnEuGVNiQAAqt8BAM/4Lw0RVOb0L5Ki9CyxO/6AKvRg4ra3Q3WR+duP -s/88AQCDErzvn+SOX4s3gvZcM3Vr4wh4Q2syHV8Okgx8STYPDg===DsVk ------END PGP PUBLIC KEY BLOCK-----`; - -const publicKeys = [publicKey1, publicKey2]; -const resultMessage = await encryption.signAndEncrypt('message', publicKeys); -``` - -*** - -### build() - -> `static` **build**(`privateKeyArmored`, `passphrase?`): `Promise`\<`Encryption`\> - -Defined in: [encryption.ts:77](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L77) - -Builds an Encryption instance by decrypting the private key from an encrypted private key and passphrase. - -#### Parameters - -##### privateKeyArmored - -`string` - -The encrypted private key in armored format. - -##### passphrase? - -`string` - -Optional: The passphrase for the private key. - -#### Returns - -`Promise`\<`Encryption`\> - -- The Encryption instance. diff --git a/docs/sdk/typescript/encryption/classes/EncryptionUtils.md b/docs/sdk/typescript/encryption/classes/EncryptionUtils.md deleted file mode 100644 index 75f3cbcc88..0000000000 --- a/docs/sdk/typescript/encryption/classes/EncryptionUtils.md +++ /dev/null @@ -1,283 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [encryption](../README.md) / EncryptionUtils - -# Class: EncryptionUtils - -Defined in: [encryption.ts:290](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L290) - -## Introduction - -Utility class for encryption-related operations. - -## Installation - -### npm -```bash -npm install @human-protocol/sdk -``` - -### yarn -```bash -yarn install @human-protocol/sdk -``` - -## Code example - -```ts -import { EncryptionUtils } from '@human-protocol/sdk'; - -const keyPair = await EncryptionUtils.generateKeyPair('Human', 'human@hmt.ai'); -``` - -## Constructors - -### Constructor - -> **new EncryptionUtils**(): `EncryptionUtils` - -#### Returns - -`EncryptionUtils` - -## Methods - -### encrypt() - -> `static` **encrypt**(`message`, `publicKeys`): `Promise`\<`string`\> - -Defined in: [encryption.ts:444](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L444) - -This function encrypts a message using the specified public keys. - -#### Parameters - -##### message - -`MessageDataType` - -Message to encrypt. - -##### publicKeys - -`string`[] - -Array of public keys to use for encryption. - -#### Returns - -`Promise`\<`string`\> - -Message encrypted. - -**Code example** - -```ts -import { EncryptionUtils } from '@human-protocol/sdk'; - -const publicKey1 = `-----BEGIN PGP PUBLIC KEY BLOCK----- -xjMEZKQEMxYJKwYBBAHaRw8BAQdA5oZTq4UPlS0IXn4kEaSqQdAa9+Cq522v -WYxJQn3vo1/NFEh1bWFuIDxodW1hbkBobXQuYWk+wowEEBYKAD4FAmSkBDME -CwkHCAkQJBFPuuhtQo4DFQgKBBYAAgECGQECGwMCHgEWIQTQ5fbVPB9CWIdf -XdYkEU+66G1CjgAAKYYA/jMyDCtJtqu6hj22kq9SW6fuV1FCT2ySJ9vBhumF -X8wWAP433zVFl4VECOkgGk8qFr8BgkYxaz16GOFAqYbfO6oMBc44BGSkBDMS -CisGAQQBl1UBBQEBB0AKR+A48zVVYZWQvgu7Opn2IGvzI9jePB/J8pzqRhg2 -YAMBCAfCeAQYFggAKgUCZKQEMwkQJBFPuuhtQo4CGwwWIQTQ5fbVPB9CWIdf -XdYkEU+66G1CjgAA0xgBAK4AIahFFnmWR2Mp6A3q021cZXpGklc0Xw1Hfswc -UYLqAQDfdym4kiUvKO1+REKASt0Gwykndl7hra9txqlUL5DXBQ===Vwgv ------END PGP PUBLIC KEY BLOCK-----`; - -const publicKey2 = `-----BEGIN PGP PUBLIC KEY BLOCK----- -xjMEZKQEMxYJKwYBBAHaRw8BAQdAG6h+E+6T/RV2tIHer3FP/jKThAyGcoVx -FzhnP0hncPzNFEh1bWFuIDxodW1hbkBobXQuYWk+wowEEBYKAD4FAmSkBDME -CwkHCAkQPIq5xLhlTYkDFQgKBBYAAgECGQECGwMCHgEWIQTcxtMgul/AeUvH -bio8irnEuGVNiQAA/HsBANpfFkxNYixpsBk8LlaaCaPy5f1/cWNPgODM9uzo -ciSTAQDtAYynu4dSJO9GbMuDuc0FaUHRWJK3mS6JkvedYL4oBM44BGSkBDMS -CisGAQQBl1UBBQEBB0DWbEG7DMhkeSc8ZPzrH8XNSCqS3t9y/oQidFR+xN3Z -bAMBCAfCeAQYFggAKgUCZKQEMwkQPIq5xLhlTYkCGwwWIQTcxtMgul/AeUvH -bio8irnEuGVNiQAAqt8BAM/4Lw0RVOb0L5Ki9CyxO/6AKvRg4ra3Q3WR+duP -s/88AQCDErzvn+SOX4s3gvZcM3Vr4wh4Q2syHV8Okgx8STYPDg===DsVk ------END PGP PUBLIC KEY BLOCK-----`; - -const publicKeys = [publicKey1, publicKey2] -const result = await EncryptionUtils.encrypt('message', publicKeys); -``` - -*** - -### generateKeyPair() - -> `static` **generateKeyPair**(`name`, `email`, `passphrase`): `Promise`\<[`IKeyPair`](../../interfaces/interfaces/IKeyPair.md)\> - -Defined in: [encryption.ts:382](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L382) - -This function generates a key pair for encryption and decryption. - -#### Parameters - -##### name - -`string` - -Name for the key pair. - -##### email - -`string` - -Email for the key pair. - -##### passphrase - -`string` = `''` - -Passphrase to encrypt the private key. Optional. - -#### Returns - -`Promise`\<[`IKeyPair`](../../interfaces/interfaces/IKeyPair.md)\> - -Key pair generated. - -**Code example** - -```ts -import { EncryptionUtils } from '@human-protocol/sdk'; - -const name = 'YOUR_NAME'; -const email = 'YOUR_EMAIL'; -const passphrase = 'YOUR_PASSPHRASE'; -const result = await EncryptionUtils.generateKeyPair(name, email, passphrase); -``` - -*** - -### getSignedData() - -> `static` **getSignedData**(`message`): `Promise`\<`string`\> - -Defined in: [encryption.ts:351](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L351) - -This function gets signed data from a signed message. - -#### Parameters - -##### message - -`string` - -Message. - -#### Returns - -`Promise`\<`string`\> - -Signed data. - -**Code example** - -```ts -import { EncryptionUtils } from '@human-protocol/sdk'; - -const signedData = await EncryptionUtils.getSignedData('message'); -``` - -*** - -### isEncrypted() - -> `static` **isEncrypted**(`message`): `boolean` - -Defined in: [encryption.ts:494](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L494) - -Verifies if a message appears to be encrypted with OpenPGP. - -#### Parameters - -##### message - -`string` - -Message to verify. - -#### Returns - -`boolean` - -`true` if the message appears to be encrypted, `false` if not. - -**Code example:** - -```ts -const message = `-----BEGIN PGP MESSAGE----- - -wV4DqdeRpqH+jaISAQdAsvBFxikvjxRqC7ZlDe98cLd7/aeCEI/AcL8PpVKK -mC0wKlwxNg/ADi55z9jcYFuMC4kKE+C/teM+JqiI8DO9AwassQUvKFtULnpx -h2jaOjC/0sAQASjUsIFK8zbuDgk/P8T9Npn6px+GlJPg9K90iwtPWiIp0eyW -4zXamJZT51k2DyaUX/Rsc6P4PYhQRKjt0yxtH0jHPmKkLC/9eBeFf4GP0zlZ -18xMZ8uCpQCma708Gz0sJYxEz3u/eZdHD7Mc7tWQKyJG8MsTwM1P+fdK1X75 -L9UryJG2AY+6kKZhG4dqjNxiO4fWluiB2u7iMF+iLEyE3SQCEYorWMC+NDWi -QIJZ7oQ2w7BaPo1a991gvTOSNm5v2x44KfqPI1uj859BjsQTCA== -=tsmI ------END PGP MESSAGE-----`; - -const isEncrypted = await EncryptionUtils.isEncrypted(message); - -if (isEncrypted) { - console.log('The message is encrypted with OpenPGP.'); -} else { - console.log('The message is not encrypted with OpenPGP.'); -} -``` - -*** - -### verify() - -> `static` **verify**(`message`, `publicKey`): `Promise`\<`boolean`\> - -Defined in: [encryption.ts:318](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L318) - -This function verifies the signature of a signed message using the public key. - -#### Parameters - -##### message - -`string` - -Message to verify. - -##### publicKey - -`string` - -Public key to verify that the message was signed by a specific source. - -#### Returns - -`Promise`\<`boolean`\> - -True if verified. False if not verified. - -**Code example** - -```ts -import { EncryptionUtils } from '@human-protocol/sdk'; - -const publicKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- -xjMEZKQEMxYJKwYBBAHaRw8BAQdA5oZTq4UPlS0IXn4kEaSqQdAa9+Cq522v -WYxJQn3vo1/NFEh1bWFuIDxodW1hbkBobXQuYWk+wowEEBYKAD4FAmSkBDME -CwkHCAkQJBFPuuhtQo4DFQgKBBYAAgECGQECGwMCHgEWIQTQ5fbVPB9CWIdf -XdYkEU+66G1CjgAAKYYA/jMyDCtJtqu6hj22kq9SW6fuV1FCT2ySJ9vBhumF -X8wWAP433zVFl4VECOkgGk8qFr8BgkYxaz16GOFAqYbfO6oMBc44BGSkBDMS -CisGAQQBl1UBBQEBB0AKR+A48zVVYZWQvgu7Opn2IGvzI9jePB/J8pzqRhg2 -YAMBCAfCeAQYFggAKgUCZKQEMwkQJBFPuuhtQo4CGwwWIQTQ5fbVPB9CWIdf -XdYkEU+66G1CjgAA0xgBAK4AIahFFnmWR2Mp6A3q021cZXpGklc0Xw1Hfswc -UYLqAQDfdym4kiUvKO1+REKASt0Gwykndl7hra9txqlUL5DXBQ===Vwgv ------END PGP PUBLIC KEY BLOCK-----`; - -const result = await EncryptionUtils.verify('message', publicKey); -``` diff --git a/docs/sdk/typescript/enums/README.md b/docs/sdk/typescript/enums/README.md deleted file mode 100644 index fde5e39c53..0000000000 --- a/docs/sdk/typescript/enums/README.md +++ /dev/null @@ -1,13 +0,0 @@ -[**@human-protocol/sdk**](../README.md) - -*** - -[@human-protocol/sdk](../modules.md) / enums - -# enums - -## Enumerations - -- [ChainId](enumerations/ChainId.md) -- [OperatorCategory](enumerations/OperatorCategory.md) -- [OrderDirection](enumerations/OrderDirection.md) diff --git a/docs/sdk/typescript/enums/enumerations/ChainId.md b/docs/sdk/typescript/enums/enumerations/ChainId.md deleted file mode 100644 index 2a65625054..0000000000 --- a/docs/sdk/typescript/enums/enumerations/ChainId.md +++ /dev/null @@ -1,73 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [enums](../README.md) / ChainId - -# Enumeration: ChainId - -Defined in: [enums.ts:1](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/enums.ts#L1) - -## Enumeration Members - -### ALL - -> **ALL**: `-1` - -Defined in: [enums.ts:2](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/enums.ts#L2) - -*** - -### BSC\_MAINNET - -> **BSC\_MAINNET**: `56` - -Defined in: [enums.ts:5](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/enums.ts#L5) - -*** - -### BSC\_TESTNET - -> **BSC\_TESTNET**: `97` - -Defined in: [enums.ts:6](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/enums.ts#L6) - -*** - -### LOCALHOST - -> **LOCALHOST**: `1338` - -Defined in: [enums.ts:9](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/enums.ts#L9) - -*** - -### MAINNET - -> **MAINNET**: `1` - -Defined in: [enums.ts:3](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/enums.ts#L3) - -*** - -### POLYGON - -> **POLYGON**: `137` - -Defined in: [enums.ts:7](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/enums.ts#L7) - -*** - -### POLYGON\_AMOY - -> **POLYGON\_AMOY**: `80002` - -Defined in: [enums.ts:8](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/enums.ts#L8) - -*** - -### SEPOLIA - -> **SEPOLIA**: `11155111` - -Defined in: [enums.ts:4](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/enums.ts#L4) diff --git a/docs/sdk/typescript/enums/enumerations/OperatorCategory.md b/docs/sdk/typescript/enums/enumerations/OperatorCategory.md deleted file mode 100644 index dcfb8ec5f7..0000000000 --- a/docs/sdk/typescript/enums/enumerations/OperatorCategory.md +++ /dev/null @@ -1,25 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [enums](../README.md) / OperatorCategory - -# Enumeration: OperatorCategory - -Defined in: [enums.ts:17](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/enums.ts#L17) - -## Enumeration Members - -### MACHINE\_LEARNING - -> **MACHINE\_LEARNING**: `"machine_learning"` - -Defined in: [enums.ts:18](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/enums.ts#L18) - -*** - -### MARKET\_MAKING - -> **MARKET\_MAKING**: `"market_making"` - -Defined in: [enums.ts:19](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/enums.ts#L19) diff --git a/docs/sdk/typescript/enums/enumerations/OrderDirection.md b/docs/sdk/typescript/enums/enumerations/OrderDirection.md deleted file mode 100644 index e02a68c904..0000000000 --- a/docs/sdk/typescript/enums/enumerations/OrderDirection.md +++ /dev/null @@ -1,25 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [enums](../README.md) / OrderDirection - -# Enumeration: OrderDirection - -Defined in: [enums.ts:12](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/enums.ts#L12) - -## Enumeration Members - -### ASC - -> **ASC**: `"asc"` - -Defined in: [enums.ts:13](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/enums.ts#L13) - -*** - -### DESC - -> **DESC**: `"desc"` - -Defined in: [enums.ts:14](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/enums.ts#L14) diff --git a/docs/sdk/typescript/escrow/README.md b/docs/sdk/typescript/escrow/README.md deleted file mode 100644 index 0d8dc6fd93..0000000000 --- a/docs/sdk/typescript/escrow/README.md +++ /dev/null @@ -1,12 +0,0 @@ -[**@human-protocol/sdk**](../README.md) - -*** - -[@human-protocol/sdk](../modules.md) / escrow - -# escrow - -## Classes - -- [EscrowClient](classes/EscrowClient.md) -- [EscrowUtils](classes/EscrowUtils.md) diff --git a/docs/sdk/typescript/escrow/classes/EscrowClient.md b/docs/sdk/typescript/escrow/classes/EscrowClient.md deleted file mode 100644 index 6f353e103f..0000000000 --- a/docs/sdk/typescript/escrow/classes/EscrowClient.md +++ /dev/null @@ -1,1572 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [escrow](../README.md) / EscrowClient - -# Class: EscrowClient - -Defined in: [escrow.ts:148](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L148) - -## Introduction - -This client enables performing actions on Escrow contracts and obtaining information from both the contracts and subgraph. - -Internally, the SDK will use one network or another according to the network ID of the `runner`. -To use this client, it is recommended to initialize it using the static `build` method. - -```ts -static async build(runner: ContractRunner): Promise; -``` - -A `Signer` or a `Provider` should be passed depending on the use case of this module: - -- **Signer**: when the user wants to use this model to send transactions calling the contract functions. -- **Provider**: when the user wants to use this model to get information from the contracts or subgraph. - -## Installation - -### npm -```bash -npm install @human-protocol/sdk -``` - -### yarn -```bash -yarn install @human-protocol/sdk -``` - -## Code example - -### Signer - -**Using private key (backend)** - -```ts -import { EscrowClient } from '@human-protocol/sdk'; -import { Wallet, providers } from 'ethers'; - -const rpcUrl = 'YOUR_RPC_URL'; -const privateKey = 'YOUR_PRIVATE_KEY'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const signer = new Wallet(privateKey, provider); -const escrowClient = await EscrowClient.build(signer); -``` - -**Using Wagmi (frontend)** - -```ts -import { useSigner, useChainId } from 'wagmi'; -import { EscrowClient } from '@human-protocol/sdk'; - -const { data: signer } = useSigner(); -const escrowClient = await EscrowClient.build(signer); -``` - -### Provider - -```ts -import { EscrowClient } from '@human-protocol/sdk'; -import { providers } from 'ethers'; - -const rpcUrl = 'YOUR_RPC_URL'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const escrowClient = await EscrowClient.build(provider); -``` - -## Extends - -- [`BaseEthersClient`](../../base/classes/BaseEthersClient.md) - -## Constructors - -### Constructor - -> **new EscrowClient**(`runner`, `networkData`): `EscrowClient` - -Defined in: [escrow.ts:157](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L157) - -**EscrowClient constructor** - -#### Parameters - -##### runner - -`ContractRunner` - -The Runner object to interact with the Ethereum network - -##### networkData - -[`NetworkData`](../../types/type-aliases/NetworkData.md) - -The network information required to connect to the Escrow contract - -#### Returns - -`EscrowClient` - -#### Overrides - -[`BaseEthersClient`](../../base/classes/BaseEthersClient.md).[`constructor`](../../base/classes/BaseEthersClient.md#constructor) - -## Properties - -### networkData - -> **networkData**: [`NetworkData`](../../types/type-aliases/NetworkData.md) - -Defined in: [base.ts:12](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) - -#### Inherited from - -[`BaseEthersClient`](../../base/classes/BaseEthersClient.md).[`networkData`](../../base/classes/BaseEthersClient.md#networkdata) - -*** - -### runner - -> `protected` **runner**: `ContractRunner` - -Defined in: [base.ts:11](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) - -#### Inherited from - -[`BaseEthersClient`](../../base/classes/BaseEthersClient.md).[`runner`](../../base/classes/BaseEthersClient.md#runner) - -## Methods - -### bulkPayOut() - -#### Call Signature - -> **bulkPayOut**(`escrowAddress`, `recipients`, `amounts`, `finalResultsUrl`, `finalResultsHash`, `txId`, `forceComplete`, `txOptions?`): `Promise`\<`void`\> - -Defined in: [escrow.ts:803](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L803) - -This function pays out the amounts specified to the workers and sets the URL of the final results file. - -##### Parameters - -###### escrowAddress - -`string` - -Escrow address to payout. - -###### recipients - -`string`[] - -Array of recipient addresses. - -###### amounts - -`bigint`[] - -Array of amounts the recipients will receive. - -###### finalResultsUrl - -`string` - -Final results file URL. - -###### finalResultsHash - -`string` - -Final results file hash. - -###### txId - -`number` - -Transaction ID. - -###### forceComplete - -`boolean` - -Indicates if remaining balance should be transferred to the escrow creator (optional, defaults to false). - -###### txOptions? - -`Overrides` - -Additional transaction parameters (optional, defaults to an empty object). - -##### Returns - -`Promise`\<`void`\> - -Returns void if successful. Throws error if any. - -**Code example** - -> Only Reputation Oracle or admin can call it. - -```ts -import { ethers, Wallet, providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; -const privateKey = 'YOUR_PRIVATE_KEY'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const signer = new Wallet(privateKey, provider); -const escrowClient = await EscrowClient.build(signer); - -const recipients = ['0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266']; -const amounts = [ethers.parseUnits(5, 'ether'), ethers.parseUnits(10, 'ether')]; -const resultsUrl = 'http://localhost/results.json'; -const resultsHash = 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079'; -const txId = 1; - -await escrowClient.bulkPayOut('0x62dD51230A30401C455c8398d06F85e4EaB6309f', recipients, amounts, resultsUrl, resultsHash, txId, true); -``` - -#### Call Signature - -> **bulkPayOut**(`escrowAddress`, `recipients`, `amounts`, `finalResultsUrl`, `finalResultsHash`, `payoutId`, `forceComplete`, `txOptions?`): `Promise`\<`void`\> - -Defined in: [escrow.ts:853](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L853) - -This function pays out the amounts specified to the workers and sets the URL of the final results file. - -##### Parameters - -###### escrowAddress - -`string` - -Escrow address to payout. - -###### recipients - -`string`[] - -Array of recipient addresses. - -###### amounts - -`bigint`[] - -Array of amounts the recipients will receive. - -###### finalResultsUrl - -`string` - -Final results file URL. - -###### finalResultsHash - -`string` - -Final results file hash. - -###### payoutId - -`string` - -Payout ID. - -###### forceComplete - -`boolean` - -Indicates if remaining balance should be transferred to the escrow creator (optional, defaults to false). - -###### txOptions? - -`Overrides` - -Additional transaction parameters (optional, defaults to an empty object). - -##### Returns - -`Promise`\<`void`\> - -Returns void if successful. Throws error if any. - -**Code example** - -> Only Reputation Oracle or admin can call it. - -```ts -import { ethers, Wallet, providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; -import { v4 as uuidV4 } from 'uuid'; - -const rpcUrl = 'YOUR_RPC_URL'; -const privateKey = 'YOUR_PRIVATE_KEY'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const signer = new Wallet(privateKey, provider); -const escrowClient = await EscrowClient.build(signer); - -const recipients = ['0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266']; -const amounts = [ethers.parseUnits(5, 'ether'), ethers.parseUnits(10, 'ether')]; -const resultsUrl = 'http://localhost/results.json'; -const resultsHash = 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079'; -const payoutId = uuidV4(); - -await escrowClient.bulkPayOut('0x62dD51230A30401C455c8398d06F85e4EaB6309f', recipients, amounts, resultsUrl, resultsHash, payoutId, true); -``` - -*** - -### cancel() - -> **cancel**(`escrowAddress`, `txOptions?`): `Promise`\<`void`\> - -Defined in: [escrow.ts:952](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L952) - -This function cancels the specified escrow and sends the balance to the canceler. - -#### Parameters - -##### escrowAddress - -`string` - -Address of the escrow to cancel. - -##### txOptions? - -`Overrides` = `{}` - -Additional transaction parameters (optional, defaults to an empty object). - -**Code example** - -> Only Job Launcher or admin can call it. - -```ts -import { ethers, Wallet, providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; -const privateKey = 'YOUR_PRIVATE_KEY'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const signer = new Wallet(privateKey, provider); -const escrowClient = await EscrowClient.build(signer); - -await escrowClient.cancel('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` - -#### Returns - -`Promise`\<`void`\> - -*** - -### complete() - -> **complete**(`escrowAddress`, `txOptions?`): `Promise`\<`void`\> - -Defined in: [escrow.ts:743](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L743) - -This function sets the status of an escrow to completed. - -#### Parameters - -##### escrowAddress - -`string` - -Address of the escrow. - -##### txOptions? - -`Overrides` = `{}` - -Additional transaction parameters (optional, defaults to an empty object). - -#### Returns - -`Promise`\<`void`\> - -Returns void if successful. Throws error if any. - -**Code example** - -> Only Recording Oracle or admin can call it. - -```ts -import { Wallet, providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; -const privateKey = 'YOUR_PRIVATE_KEY'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const signer = new Wallet(privateKey, provider); -const escrowClient = await EscrowClient.build(signer); - -await escrowClient.complete('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` - -*** - -### createBulkPayoutTransaction() - -> **createBulkPayoutTransaction**(`escrowAddress`, `recipients`, `amounts`, `finalResultsUrl`, `finalResultsHash`, `payoutId`, `forceComplete`, `txOptions?`): `Promise`\<[`TransactionLikeWithNonce`](../../types/type-aliases/TransactionLikeWithNonce.md)\> - -Defined in: [escrow.ts:1150](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1150) - -Creates a prepared transaction for bulk payout without immediately sending it. - -#### Parameters - -##### escrowAddress - -`string` - -Escrow address to payout. - -##### recipients - -`string`[] - -Array of recipient addresses. - -##### amounts - -`bigint`[] - -Array of amounts the recipients will receive. - -##### finalResultsUrl - -`string` - -Final results file URL. - -##### finalResultsHash - -`string` - -Final results file hash. - -##### payoutId - -`string` - -Payout ID to identify the payout. - -##### forceComplete - -`boolean` = `false` - -Indicates if remaining balance should be transferred to the escrow creator (optional, defaults to false). - -##### txOptions? - -`Overrides` = `{}` - -Additional transaction parameters (optional, defaults to an empty object). - -#### Returns - -`Promise`\<[`TransactionLikeWithNonce`](../../types/type-aliases/TransactionLikeWithNonce.md)\> - -Returns object with raw transaction and signed transaction hash - -**Code example** - -> Only Reputation Oracle or admin can call it. - -```ts -import { ethers, Wallet, providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; -const privateKey = 'YOUR_PRIVATE_KEY' - -const provider = new providers.JsonRpcProvider(rpcUrl); -const signer = new Wallet(privateKey, provider); -const escrowClient = await EscrowClient.build(signer); - -const recipients = ['0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266']; -const amounts = [ethers.parseUnits(5, 'ether'), ethers.parseUnits(10, 'ether')]; -const resultsUrl = 'http://localhost/results.json'; -const resultsHash = 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079'; -const payoutId = '372f6916-fe34-4711-b6e3-274f682047de'; - -const rawTransaction = await escrowClient.createBulkPayoutTransaction('0x62dD51230A30401C455c8398d06F85e4EaB6309f', recipients, amounts, resultsUrl, resultsHash, txId); -console.log('Raw transaction:', rawTransaction); - -const signedTransaction = await signer.signTransaction(rawTransaction); -console.log('Tx hash:', ethers.keccak256(signedTransaction)); -(await signer.sendTransaction(rawTransaction)).wait(); - -*** - -### createEscrow() - -> **createEscrow**(`tokenAddress`, `jobRequesterId`, `txOptions?`): `Promise`\<`string`\> - -Defined in: [escrow.ts:235](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L235) - -This function creates an escrow contract that uses the token passed to pay oracle fees and reward workers. - -#### Parameters - -##### tokenAddress - -`string` - -The address of the token to use for escrow funding. - -##### jobRequesterId - -`string` - -Identifier for the job requester. - -##### txOptions? - -`Overrides` = `{}` - -Additional transaction parameters (optional, defaults to an empty object). - -#### Returns - -`Promise`\<`string`\> - -Returns the address of the escrow created. - -**Code example** - -> Need to have available stake. - -```ts -import { Wallet, providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; -const privateKey = 'YOUR_PRIVATE_KEY'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const signer = new Wallet(privateKey, provider); -const escrowClient = await EscrowClient.build(signer); - -const tokenAddress = '0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4'; -const jobRequesterId = "job-requester-id"; -const escrowAddress = await escrowClient.createEscrow(tokenAddress, jobRequesterId); -``` - -*** - -### createFundAndSetupEscrow() - -> **createFundAndSetupEscrow**(`tokenAddress`, `amount`, `jobRequesterId`, `escrowConfig`, `txOptions?`): `Promise`\<`string`\> - -Defined in: [escrow.ts:373](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L373) - -Creates, funds, and sets up a new escrow contract in a single transaction. - -#### Parameters - -##### tokenAddress - -`string` - -The ERC-20 token address used to fund the escrow. - -##### amount - -`bigint` - -The token amount to fund the escrow with. - -##### jobRequesterId - -`string` - -An off-chain identifier for the job requester. - -##### escrowConfig - -[`IEscrowConfig`](../../interfaces/interfaces/IEscrowConfig.md) - -Configuration parameters for escrow setup: - - `recordingOracle`: Address of the recording oracle. - - `reputationOracle`: Address of the reputation oracle. - - `exchangeOracle`: Address of the exchange oracle. - - `recordingOracleFee`: Fee (in basis points or percentage * 100) for the recording oracle. - - `reputationOracleFee`: Fee for the reputation oracle. - - `exchangeOracleFee`: Fee for the exchange oracle. - - `manifest`: URL to the manifest file. - - `manifestHash`: Hash of the manifest content. - -##### txOptions? - -`Overrides` = `{}` - -Additional transaction parameters (optional, defaults to an empty object). - -#### Returns - -`Promise`\<`string`\> - -Returns the address of the escrow created. - -#### Example - -```ts -import { Wallet, ethers } from 'ethers'; -import { EscrowClient, IERC20__factory } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; -const privateKey = 'YOUR_PRIVATE_KEY'; -const provider = new ethers.JsonRpcProvider(rpcUrl); -const signer = new Wallet(privateKey, provider); - -const escrowClient = await EscrowClient.build(signer); - -const tokenAddress = '0xTokenAddress'; -const amount = ethers.parseUnits('1000', 18); -const jobRequesterId = 'requester-123'; - -const token = IERC20__factory.connect(tokenAddress, signer); -await token.approve(escrowClient.escrowFactoryContract.target, amount); - -const escrowConfig = { - recordingOracle: '0xRecordingOracle', - reputationOracle: '0xReputationOracle', - exchangeOracle: '0xExchangeOracle', - recordingOracleFee: 5n, - reputationOracleFee: 5n, - exchangeOracleFee: 5n, - manifest: 'https://example.com/manifest.json', - manifestHash: 'manifestHash-123', -} satisfies IEscrowConfig; - -const escrowAddress = await escrowClient.createFundAndSetupEscrow( - tokenAddress, - amount, - jobRequesterId, - escrowConfig -); - -console.log('Escrow created at:', escrowAddress); -``` - -*** - -### fund() - -> **fund**(`escrowAddress`, `amount`, `txOptions?`): `Promise`\<`void`\> - -Defined in: [escrow.ts:546](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L546) - -This function adds funds of the chosen token to the escrow. - -#### Parameters - -##### escrowAddress - -`string` - -Address of the escrow to fund. - -##### amount - -`bigint` - -Amount to be added as funds. - -##### txOptions? - -`Overrides` = `{}` - -Additional transaction parameters (optional, defaults to an empty object). - -#### Returns - -`Promise`\<`void`\> - -Returns void if successful. Throws error if any. - -**Code example** - -```ts -import { ethers, Wallet, providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; -const privateKey = 'YOUR_PRIVATE_KEY'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const signer = new Wallet(privateKey, provider); -const escrowClient = await EscrowClient.build(signer); - -const amount = ethers.parseUnits(5, 'ether'); //convert from ETH to WEI -await escrowClient.fund('0x62dD51230A30401C455c8398d06F85e4EaB6309f', amount); -``` - -*** - -### getBalance() - -> **getBalance**(`escrowAddress`): `Promise`\<`bigint`\> - -Defined in: [escrow.ts:1295](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1295) - -This function returns the balance for a specified escrow address. - -#### Parameters - -##### escrowAddress - -`string` - -Address of the escrow. - -#### Returns - -`Promise`\<`bigint`\> - -Balance of the escrow in the token used to fund it. - -**Code example** - -```ts -import { providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const escrowClient = await EscrowClient.build(provider); - -const balance = await escrowClient.getBalance('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` - -*** - -### getExchangeOracleAddress() - -> **getExchangeOracleAddress**(`escrowAddress`): `Promise`\<`string`\> - -Defined in: [escrow.ts:1756](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1756) - -This function returns the exchange oracle address for a given escrow. - -#### Parameters - -##### escrowAddress - -`string` - -Address of the escrow. - -#### Returns - -`Promise`\<`string`\> - -Address of the Exchange Oracle. - -**Code example** - -```ts -import { providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const escrowClient = await EscrowClient.build(provider); - -const oracleAddress = await escrowClient.getExchangeOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` - -*** - -### getFactoryAddress() - -> **getFactoryAddress**(`escrowAddress`): `Promise`\<`string`\> - -Defined in: [escrow.ts:1794](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1794) - -This function returns the escrow factory address for a given escrow. - -#### Parameters - -##### escrowAddress - -`string` - -Address of the escrow. - -#### Returns - -`Promise`\<`string`\> - -Address of the escrow factory. - -**Code example** - -```ts -import { providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const escrowClient = await EscrowClient.build(provider); - -const factoryAddress = await escrowClient.getFactoryAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` - -*** - -### getIntermediateResultsHash() - -> **getIntermediateResultsHash**(`escrowAddress`): `Promise`\<`string`\> - -Defined in: [escrow.ts:1528](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1528) - -This function returns the intermediate results hash. - -#### Parameters - -##### escrowAddress - -`string` - -Address of the escrow. - -#### Returns - -`Promise`\<`string`\> - -Hash of the intermediate results file content. - -**Code example** - -```ts -import { providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const escrowClient = await EscrowClient.build(provider); - -const intermediateResultsHash = await escrowClient.getIntermediateResultsHash('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` - -*** - -### getIntermediateResultsUrl() - -> **getIntermediateResultsUrl**(`escrowAddress`): `Promise`\<`string`\> - -Defined in: [escrow.ts:1490](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1490) - -This function returns the intermediate results file URL. - -#### Parameters - -##### escrowAddress - -`string` - -Address of the escrow. - -#### Returns - -`Promise`\<`string`\> - -Url of the file that store results from Recording Oracle. - -**Code example** - -```ts -import { providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const escrowClient = await EscrowClient.build(provider); - -const intermediateResultsUrl = await escrowClient.getIntermediateResultsUrl('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` - -*** - -### getJobLauncherAddress() - -> **getJobLauncherAddress**(`escrowAddress`): `Promise`\<`string`\> - -Defined in: [escrow.ts:1680](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1680) - -This function returns the job launcher address for a given escrow. - -#### Parameters - -##### escrowAddress - -`string` - -Address of the escrow. - -#### Returns - -`Promise`\<`string`\> - -Address of the Job Launcher. - -**Code example** - -```ts -import { providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const escrowClient = await EscrowClient.build(provider); - -const jobLauncherAddress = await escrowClient.getJobLauncherAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` - -*** - -### getManifest() - -> **getManifest**(`escrowAddress`): `Promise`\<`string`\> - -Defined in: [escrow.ts:1414](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1414) - -This function returns the manifest. Could be a URL or a JSON string. - -#### Parameters - -##### escrowAddress - -`string` - -Address of the escrow. - -#### Returns - -`Promise`\<`string`\> - -Url of the manifest. - -**Code example** - -```ts -import { providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const escrowClient = await EscrowClient.build(provider); - -const manifest = await escrowClient.getManifest('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` - -*** - -### getManifestHash() - -> **getManifestHash**(`escrowAddress`): `Promise`\<`string`\> - -Defined in: [escrow.ts:1376](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1376) - -This function returns the manifest file hash. - -#### Parameters - -##### escrowAddress - -`string` - -Address of the escrow. - -#### Returns - -`Promise`\<`string`\> - -Hash of the manifest file content. - -**Code example** - -```ts -import { providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const escrowClient = await EscrowClient.build(provider); - -const manifestHash = await escrowClient.getManifestHash('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` - -*** - -### getRecordingOracleAddress() - -> **getRecordingOracleAddress**(`escrowAddress`): `Promise`\<`string`\> - -Defined in: [escrow.ts:1642](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1642) - -This function returns the recording oracle address for a given escrow. - -#### Parameters - -##### escrowAddress - -`string` - -Address of the escrow. - -#### Returns - -`Promise`\<`string`\> - -Address of the Recording Oracle. - -**Code example** - -```ts -import { providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const escrowClient = await EscrowClient.build(provider); - -const oracleAddress = await escrowClient.getRecordingOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` - -*** - -### getReputationOracleAddress() - -> **getReputationOracleAddress**(`escrowAddress`): `Promise`\<`string`\> - -Defined in: [escrow.ts:1718](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1718) - -This function returns the reputation oracle address for a given escrow. - -#### Parameters - -##### escrowAddress - -`string` - -Address of the escrow. - -#### Returns - -`Promise`\<`string`\> - -Address of the Reputation Oracle. - -**Code example** - -```ts -import { providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const escrowClient = await EscrowClient.build(provider); - -const oracleAddress = await escrowClient.getReputationOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` - -*** - -### getReservedFunds() - -> **getReservedFunds**(`escrowAddress`): `Promise`\<`bigint`\> - -Defined in: [escrow.ts:1339](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1339) - -This function returns the reserved funds for a specified escrow address. - -#### Parameters - -##### escrowAddress - -`string` - -Address of the escrow. - -#### Returns - -`Promise`\<`bigint`\> - -Reserved funds of the escrow in the token used to fund it. - -**Code example** - -```ts -import { providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const escrowClient = await EscrowClient.build(provider); - -const reservedFunds = await escrowClient.getReservedFunds('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` - -*** - -### getResultsUrl() - -> **getResultsUrl**(`escrowAddress`): `Promise`\<`string`\> - -Defined in: [escrow.ts:1452](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1452) - -This function returns the results file URL. - -#### Parameters - -##### escrowAddress - -`string` - -Address of the escrow. - -#### Returns - -`Promise`\<`string`\> - -Results file url. - -**Code example** - -```ts -import { providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const escrowClient = await EscrowClient.build(provider); - -const resultsUrl = await escrowClient.getResultsUrl('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` - -*** - -### getStatus() - -> **getStatus**(`escrowAddress`): `Promise`\<[`EscrowStatus`](../../types/enumerations/EscrowStatus.md)\> - -Defined in: [escrow.ts:1604](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1604) - -This function returns the current status of the escrow. - -#### Parameters - -##### escrowAddress - -`string` - -Address of the escrow. - -#### Returns - -`Promise`\<[`EscrowStatus`](../../types/enumerations/EscrowStatus.md)\> - -Current status of the escrow. - -**Code example** - -```ts -import { providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const escrowClient = await EscrowClient.build(provider); - -const status = await escrowClient.getStatus('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` - -*** - -### getTokenAddress() - -> **getTokenAddress**(`escrowAddress`): `Promise`\<`string`\> - -Defined in: [escrow.ts:1566](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1566) - -This function returns the token address used for funding the escrow. - -#### Parameters - -##### escrowAddress - -`string` - -Address of the escrow. - -#### Returns - -`Promise`\<`string`\> - -Address of the token used to fund the escrow. - -**Code example** - -```ts -import { providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const escrowClient = await EscrowClient.build(provider); - -const tokenAddress = await escrowClient.getTokenAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` - -*** - -### requestCancellation() - -> **requestCancellation**(`escrowAddress`, `txOptions?`): `Promise`\<`void`\> - -Defined in: [escrow.ts:998](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L998) - -This function requests the cancellation of the specified escrow (moves status to ToCancel or finalizes if expired). - -#### Parameters - -##### escrowAddress - -`string` - -Address of the escrow to request cancellation. - -##### txOptions? - -`Overrides` = `{}` - -Additional transaction parameters (optional, defaults to an empty object). - -#### Returns - -`Promise`\<`void`\> - -Returns void if successful. Throws error if any. - -**Code example** - -> Only Job Launcher or admin can call it. - -```ts -import { Wallet, providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; -const privateKey = 'YOUR_PRIVATE_KEY'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const signer = new Wallet(privateKey, provider); -const escrowClient = await EscrowClient.build(signer); - -await escrowClient.requestCancellation('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` - -*** - -### setup() - -> **setup**(`escrowAddress`, `escrowConfig`, `txOptions?`): `Promise`\<`void`\> - -Defined in: [escrow.ts:470](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L470) - -This function sets up the parameters of the escrow. - -#### Parameters - -##### escrowAddress - -`string` - -Address of the escrow to set up. - -##### escrowConfig - -[`IEscrowConfig`](../../interfaces/interfaces/IEscrowConfig.md) - -Escrow configuration parameters. - -##### txOptions? - -`Overrides` = `{}` - -Additional transaction parameters (optional, defaults to an empty object). - -#### Returns - -`Promise`\<`void`\> - -Returns void if successful. Throws error if any. - -**Code example** - -> Only Job Launcher or admin can call it. - -```ts -import { Wallet, providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; -const privateKey = 'YOUR_PRIVATE_KEY'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const signer = new Wallet(privateKey, provider); -const escrowClient = await EscrowClient.build(signer); - -const escrowAddress = '0x62dD51230A30401C455c8398d06F85e4EaB6309f'; -const escrowConfig = { - recordingOracle: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', - reputationOracle: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', - exchangeOracle: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', - recordingOracleFee: BigInt('10'), - reputationOracleFee: BigInt('10'), - exchangeOracleFee: BigInt('10'), - manifest: 'http://localhost/manifest.json', - manifestHash: 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079', -}; -await escrowClient.setup(escrowAddress, escrowConfig); -``` - -*** - -### storeResults() - -#### Call Signature - -> **storeResults**(`escrowAddress`, `url`, `hash`, `fundsToReserve`, `txOptions?`): `Promise`\<`void`\> - -Defined in: [escrow.ts:612](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L612) - -This function stores the results URL and hash. - -##### Parameters - -###### escrowAddress - -`string` - -Address of the escrow. - -###### url - -`string` - -Results file URL. - -###### hash - -`string` - -Results file hash. - -###### fundsToReserve - -`bigint` - -Funds to reserve for payouts - -###### txOptions? - -`Overrides` - -Additional transaction parameters (optional, defaults to an empty object). - -##### Returns - -`Promise`\<`void`\> - -Returns void if successful. Throws error if any. - -**Code example** - -> Only Recording Oracle or admin can call it. - -```ts -import { ethers, Wallet, providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; -const privateKey = 'YOUR_PRIVATE_KEY'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const signer = new Wallet(privateKey, provider); -const escrowClient = await EscrowClient.build(signer); - -await escrowClient.storeResults('0x62dD51230A30401C455c8398d06F85e4EaB6309f', 'http://localhost/results.json', 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079', ethers.parseEther('10')); -``` - -#### Call Signature - -> **storeResults**(`escrowAddress`, `url`, `hash`, `txOptions?`): `Promise`\<`void`\> - -Defined in: [escrow.ts:648](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L648) - -This function stores the results URL and hash. - -##### Parameters - -###### escrowAddress - -`string` - -Address of the escrow. - -###### url - -`string` - -Results file URL. - -###### hash - -`string` - -Results file hash. - -###### txOptions? - -`Overrides` - -Additional transaction parameters (optional, defaults to an empty object). - -##### Returns - -`Promise`\<`void`\> - -Returns void if successful. Throws error if any. - -**Code example** - -> Only Recording Oracle or admin can call it. - -```ts -import { ethers, Wallet, providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; -const privateKey = 'YOUR_PRIVATE_KEY'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const signer = new Wallet(privateKey, provider); -const escrowClient = await EscrowClient.build(signer); - -await escrowClient.storeResults('0x62dD51230A30401C455c8398d06F85e4EaB6309f', 'http://localhost/results.json', 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079'); -``` - -*** - -### withdraw() - -> **withdraw**(`escrowAddress`, `tokenAddress`, `txOptions?`): `Promise`\<[`IEscrowWithdraw`](../../interfaces/interfaces/IEscrowWithdraw.md)\> - -Defined in: [escrow.ts:1049](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1049) - -This function withdraws additional tokens in the escrow to the canceler. - -#### Parameters - -##### escrowAddress - -`string` - -Address of the escrow to withdraw. - -##### tokenAddress - -`string` - -Address of the token to withdraw. - -##### txOptions? - -`Overrides` = `{}` - -Additional transaction parameters (optional, defaults to an empty object). - -#### Returns - -`Promise`\<[`IEscrowWithdraw`](../../interfaces/interfaces/IEscrowWithdraw.md)\> - -Returns the escrow withdrawal data including transaction hash and withdrawal amount. Throws error if any. - -**Code example** - -> Only Job Launcher or admin can call it. - -```ts -import { ethers, Wallet, providers } from 'ethers'; -import { EscrowClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; -const privateKey = 'YOUR_PRIVATE_KEY'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const signer = new Wallet(privateKey, provider); -const escrowClient = await EscrowClient.build(signer); - -await escrowClient.withdraw( - '0x62dD51230A30401C455c8398d06F85e4EaB6309f', - '0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4' -); -``` - -*** - -### build() - -> `static` **build**(`runner`): `Promise`\<`EscrowClient`\> - -Defined in: [escrow.ts:175](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L175) - -Creates an instance of EscrowClient from a Runner. - -#### Parameters - -##### runner - -`ContractRunner` - -The Runner object to interact with the Ethereum network - -#### Returns - -`Promise`\<`EscrowClient`\> - -An instance of EscrowClient - -#### Throws - -Thrown if the provider does not exist for the provided Signer - -#### Throws - -Thrown if the network's chainId is not supported diff --git a/docs/sdk/typescript/escrow/classes/EscrowUtils.md b/docs/sdk/typescript/escrow/classes/EscrowUtils.md deleted file mode 100644 index 68694e7429..0000000000 --- a/docs/sdk/typescript/escrow/classes/EscrowUtils.md +++ /dev/null @@ -1,538 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [escrow](../README.md) / EscrowUtils - -# Class: EscrowUtils - -Defined in: [escrow.ts:1843](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1843) - -## Introduction - -Utility class for escrow-related operations. - -## Installation - -### npm -```bash -npm install @human-protocol/sdk -``` - -### yarn -```bash -yarn install @human-protocol/sdk -``` - -## Code example - -### Signer - -**Using private key(backend)** - -```ts -import { ChainId, EscrowUtils } from '@human-protocol/sdk'; - -const escrowAddresses = new EscrowUtils.getEscrows({ - chainId: ChainId.POLYGON_AMOY -}); -``` - -## Constructors - -### Constructor - -> **new EscrowUtils**(): `EscrowUtils` - -#### Returns - -`EscrowUtils` - -## Methods - -### getCancellationRefund() - -> `static` **getCancellationRefund**(`chainId`, `escrowAddress`, `options?`): `Promise`\<[`ICancellationRefund`](../../interfaces/interfaces/ICancellationRefund.md) \| `null`\> - -Defined in: [escrow.ts:2435](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L2435) - -This function returns the cancellation refund for a given escrow address. - -> This uses Subgraph - -**Input parameters** - -```ts -enum ChainId { - ALL = -1, - MAINNET = 1, - SEPOLIA = 11155111, - BSC_MAINNET = 56, - BSC_TESTNET = 97, - POLYGON = 137, - POLYGON_AMOY = 80002, - LOCALHOST = 1338, -} -``` - -```ts -interface ICancellationRefund { - id: string; - escrowAddress: string; - receiver: string; - amount: bigint; - block: number; - timestamp: number; - txHash: string; -}; -``` - -#### Parameters - -##### chainId - -[`ChainId`](../../enums/enumerations/ChainId.md) - -Network in which the escrow has been deployed - -##### escrowAddress - -`string` - -Address of the escrow - -##### options? - -[`SubgraphOptions`](../../interfaces/interfaces/SubgraphOptions.md) - -Optional configuration for subgraph requests. - -#### Returns - -`Promise`\<[`ICancellationRefund`](../../interfaces/interfaces/ICancellationRefund.md) \| `null`\> - -Cancellation refund data - -**Code example** - -```ts -import { ChainId, EscrowUtils } from '@human-protocol/sdk'; - -const cancellationRefund = await EscrowUtils.getCancellationRefund(ChainId.POLYGON_AMOY, "0x1234567890123456789012345678901234567890"); -``` - -*** - -### getCancellationRefunds() - -> `static` **getCancellationRefunds**(`filter`, `options?`): `Promise`\<[`ICancellationRefund`](../../interfaces/interfaces/ICancellationRefund.md)[]\> - -Defined in: [escrow.ts:2339](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L2339) - -This function returns the cancellation refunds for a given set of networks. - -> This uses Subgraph - -**Input parameters** - -```ts -enum ChainId { - ALL = -1, - MAINNET = 1, - SEPOLIA = 11155111, - BSC_MAINNET = 56, - BSC_TESTNET = 97, - POLYGON = 137, - POLYGON_AMOY = 80002, - LOCALHOST = 1338, -} -``` - -```ts -interface ICancellationRefund { - id: string; - escrowAddress: string; - receiver: string; - amount: bigint; - block: number; - timestamp: number; - txHash: string; -}; -``` - -#### Parameters - -##### filter - -[`ICancellationRefundFilter`](../../interfaces/interfaces/ICancellationRefundFilter.md) - -Filter parameters. - -##### options? - -[`SubgraphOptions`](../../interfaces/interfaces/SubgraphOptions.md) - -Optional configuration for subgraph requests. - -#### Returns - -`Promise`\<[`ICancellationRefund`](../../interfaces/interfaces/ICancellationRefund.md)[]\> - -List of cancellation refunds matching the filters. - -**Code example** - -```ts -import { ChainId, EscrowUtils } from '@human-protocol/sdk'; - -const cancellationRefunds = await EscrowUtils.getCancellationRefunds({ - chainId: ChainId.POLYGON_AMOY, - escrowAddress: '0x1234567890123456789012345678901234567890', -}); -console.log(cancellationRefunds); -``` - -*** - -### getEscrow() - -> `static` **getEscrow**(`chainId`, `escrowAddress`, `options?`): `Promise`\<[`IEscrow`](../../interfaces/interfaces/IEscrow.md) \| `null`\> - -Defined in: [escrow.ts:2068](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L2068) - -This function returns the escrow data for a given address. - -> This uses Subgraph - -**Input parameters** - -```ts -enum ChainId { - ALL = -1, - MAINNET = 1, - SEPOLIA = 11155111, - BSC_MAINNET = 56, - BSC_TESTNET = 97, - POLYGON = 137, - POLYGON_AMOY = 80002, - LOCALHOST = 1338, -} -``` - -```ts -interface IEscrow { - id: string; - address: string; - amountPaid: bigint; - balance: bigint; - count: bigint; - factoryAddress: string; - finalResultsUrl: string | null; - finalResultsHash: string | null; - intermediateResultsUrl: string | null; - intermediateResultsHash: string | null; - launcher: string; - jobRequesterId: string | null; - manifestHash: string | null; - manifest: string | null; - recordingOracle: string | null; - reputationOracle: string | null; - exchangeOracle: string | null; - recordingOracleFee: number | null; - reputationOracleFee: number | null; - exchangeOracleFee: number | null; - status: string; - token: string; - totalFundedAmount: bigint; - createdAt: number; - chainId: number; -}; -``` - -#### Parameters - -##### chainId - -[`ChainId`](../../enums/enumerations/ChainId.md) - -Network in which the escrow has been deployed - -##### escrowAddress - -`string` - -Address of the escrow - -##### options? - -[`SubgraphOptions`](../../interfaces/interfaces/SubgraphOptions.md) - -Optional configuration for subgraph requests. - -#### Returns - -`Promise`\<[`IEscrow`](../../interfaces/interfaces/IEscrow.md) \| `null`\> - -- Escrow data or null if not found. - -**Code example** - -```ts -import { ChainId, EscrowUtils } from '@human-protocol/sdk'; - -const escrow = new EscrowUtils.getEscrow(ChainId.POLYGON_AMOY, "0x1234567890123456789012345678901234567890"); -``` - -*** - -### getEscrows() - -> `static` **getEscrows**(`filter`, `options?`): `Promise`\<[`IEscrow`](../../interfaces/interfaces/IEscrow.md)[]\> - -Defined in: [escrow.ts:1947](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1947) - -This function returns an array of escrows based on the specified filter parameters. - -**Input parameters** - -```ts -interface IEscrowsFilter { - chainId: ChainId; - launcher?: string; - reputationOracle?: string; - recordingOracle?: string; - exchangeOracle?: string; - jobRequesterId?: string; - status?: EscrowStatus; - from?: Date; - to?: Date; - first?: number; - skip?: number; - orderDirection?: OrderDirection; -} -``` - -```ts -enum ChainId { - ALL = -1, - MAINNET = 1, - SEPOLIA = 11155111, - BSC_MAINNET = 56, - BSC_TESTNET = 97, - POLYGON = 137, - POLYGON_AMOY=80002, - LOCALHOST = 1338, -} -``` - -```ts -enum OrderDirection { - ASC = 'asc', - DESC = 'desc', -} -``` - -```ts -enum EscrowStatus { - Launched, - Pending, - Partial, - Paid, - Complete, - Cancelled, -} -``` - -```ts -interface IEscrow { - id: string; - address: string; - amountPaid: bigint; - balance: bigint; - count: bigint; - factoryAddress: string; - finalResultsUrl: string | null; - finalResultsHash: string | null; - intermediateResultsUrl: string | null; - intermediateResultsHash: string | null; - launcher: string; - jobRequesterId: string | null; - manifestHash: string | null; - manifest: string | null; - recordingOracle: string | null; - reputationOracle: string | null; - exchangeOracle: string | null; - recordingOracleFee: number | null; - reputationOracleFee: number | null; - exchangeOracleFee: number | null; - status: string; - token: string; - totalFundedAmount: bigint; - createdAt: number; - chainId: number; -}; -``` - -#### Parameters - -##### filter - -[`IEscrowsFilter`](../../interfaces/interfaces/IEscrowsFilter.md) - -Filter parameters. - -##### options? - -[`SubgraphOptions`](../../interfaces/interfaces/SubgraphOptions.md) - -Optional configuration for subgraph requests. - -#### Returns - -`Promise`\<[`IEscrow`](../../interfaces/interfaces/IEscrow.md)[]\> - -List of escrows that match the filter. - -**Code example** - -```ts -import { ChainId, EscrowUtils, EscrowStatus } from '@human-protocol/sdk'; - -const filters: IEscrowsFilter = { - status: EscrowStatus.Pending, - from: new Date(2023, 4, 8), - to: new Date(2023, 5, 8), - chainId: ChainId.POLYGON_AMOY -}; -const escrows = await EscrowUtils.getEscrows(filters); -``` - -*** - -### getPayouts() - -> `static` **getPayouts**(`filter`, `options?`): `Promise`\<[`IPayout`](../../interfaces/interfaces/IPayout.md)[]\> - -Defined in: [escrow.ts:2243](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L2243) - -This function returns the payouts for a given set of networks. - -> This uses Subgraph - -**Input parameters** -Fetch payouts from the subgraph. - -#### Parameters - -##### filter - -[`IPayoutFilter`](../../interfaces/interfaces/IPayoutFilter.md) - -Filter parameters. - -##### options? - -[`SubgraphOptions`](../../interfaces/interfaces/SubgraphOptions.md) - -Optional configuration for subgraph requests. - -#### Returns - -`Promise`\<[`IPayout`](../../interfaces/interfaces/IPayout.md)[]\> - -List of payouts matching the filters. - -**Code example** - -```ts -import { ChainId, EscrowUtils } from '@human-protocol/sdk'; - -const payouts = await EscrowUtils.getPayouts({ - chainId: ChainId.POLYGON, - escrowAddress: '0x1234567890123456789012345678901234567890', - recipient: '0xabcdefabcdefabcdefabcdefabcdefabcdefabcdef', - from: new Date('2023-01-01'), - to: new Date('2023-12-31') -}); -console.log(payouts); -``` - -*** - -### getStatusEvents() - -> `static` **getStatusEvents**(`filter`, `options?`): `Promise`\<[`IStatusEvent`](../../interfaces/interfaces/IStatusEvent.md)[]\> - -Defined in: [escrow.ts:2151](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L2151) - -This function returns the status events for a given set of networks within an optional date range. - -> This uses Subgraph - -**Input parameters** - -```ts -enum ChainId { - ALL = -1, - MAINNET = 1, - SEPOLIA = 11155111, - BSC_MAINNET = 56, - BSC_TESTNET = 97, - POLYGON = 137, - POLYGON_AMOY = 80002, - LOCALHOST = 1338, -} -``` - -```ts -enum OrderDirection { - ASC = 'asc', - DESC = 'desc', -} -``` - -```ts -type Status = { - escrowAddress: string; - timestamp: string; - status: string; -}; -``` - -#### Parameters - -##### filter - -[`IStatusEventFilter`](../../interfaces/interfaces/IStatusEventFilter.md) - -Filter parameters. - -##### options? - -[`SubgraphOptions`](../../interfaces/interfaces/SubgraphOptions.md) - -Optional configuration for subgraph requests. - -#### Returns - -`Promise`\<[`IStatusEvent`](../../interfaces/interfaces/IStatusEvent.md)[]\> - -- Array of status events with their corresponding statuses. - -**Code example** - -```ts -import { ChainId, EscrowUtils, EscrowStatus } from '@human-protocol/sdk'; - -(async () => { - const fromDate = new Date('2023-01-01'); - const toDate = new Date('2023-12-31'); - const statusEvents = await EscrowUtils.getStatusEvents({ - chainId: ChainId.POLYGON, - statuses: [EscrowStatus.Pending, EscrowStatus.Complete], - from: fromDate, - to: toDate - }); - console.log(statusEvents); -})(); -``` diff --git a/docs/sdk/typescript/graphql/types/README.md b/docs/sdk/typescript/graphql/types/README.md deleted file mode 100644 index 9e93a2e90f..0000000000 --- a/docs/sdk/typescript/graphql/types/README.md +++ /dev/null @@ -1,29 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / graphql/types - -# graphql/types - -## Interfaces - -- [IOperatorSubgraph](interfaces/IOperatorSubgraph.md) -- [IReputationNetworkSubgraph](interfaces/IReputationNetworkSubgraph.md) - -## Type Aliases - -- [CancellationRefundData](type-aliases/CancellationRefundData.md) -- [EscrowData](type-aliases/EscrowData.md) -- [EscrowStatisticsData](type-aliases/EscrowStatisticsData.md) -- [EventDayData](type-aliases/EventDayData.md) -- [HMTHolderData](type-aliases/HMTHolderData.md) -- [HMTStatisticsData](type-aliases/HMTStatisticsData.md) -- [InternalTransactionData](type-aliases/InternalTransactionData.md) -- [KVStoreData](type-aliases/KVStoreData.md) -- [PayoutData](type-aliases/PayoutData.md) -- [RewardAddedEventData](type-aliases/RewardAddedEventData.md) -- [StakerData](type-aliases/StakerData.md) -- [StatusEvent](type-aliases/StatusEvent.md) -- [TransactionData](type-aliases/TransactionData.md) -- [WorkerData](type-aliases/WorkerData.md) diff --git a/docs/sdk/typescript/graphql/types/interfaces/IOperatorSubgraph.md b/docs/sdk/typescript/graphql/types/interfaces/IOperatorSubgraph.md deleted file mode 100644 index d94e596899..0000000000 --- a/docs/sdk/typescript/graphql/types/interfaces/IOperatorSubgraph.md +++ /dev/null @@ -1,141 +0,0 @@ -[**@human-protocol/sdk**](../../../README.md) - -*** - -[@human-protocol/sdk](../../../modules.md) / [graphql/types](../README.md) / IOperatorSubgraph - -# Interface: IOperatorSubgraph - -Defined in: [graphql/types.ts:143](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L143) - -## Properties - -### address - -> **address**: `string` - -Defined in: [graphql/types.ts:145](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L145) - -*** - -### amountJobsProcessed - -> **amountJobsProcessed**: `string` - -Defined in: [graphql/types.ts:146](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L146) - -*** - -### category - -> **category**: `string` \| `null` - -Defined in: [graphql/types.ts:156](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L156) - -*** - -### fee - -> **fee**: `string` \| `null` - -Defined in: [graphql/types.ts:148](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L148) - -*** - -### id - -> **id**: `string` - -Defined in: [graphql/types.ts:144](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L144) - -*** - -### jobTypes - -> **jobTypes**: `string` \| `string`[] \| `null` - -Defined in: [graphql/types.ts:157](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L157) - -*** - -### name - -> **name**: `string` \| `null` - -Defined in: [graphql/types.ts:155](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L155) - -*** - -### publicKey - -> **publicKey**: `string` \| `null` - -Defined in: [graphql/types.ts:149](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L149) - -*** - -### registrationInstructions - -> **registrationInstructions**: `string` \| `null` - -Defined in: [graphql/types.ts:154](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L154) - -*** - -### registrationNeeded - -> **registrationNeeded**: `boolean` \| `null` - -Defined in: [graphql/types.ts:153](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L153) - -*** - -### reputationNetworks - -> **reputationNetworks**: `object`[] - -Defined in: [graphql/types.ts:158](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L158) - -#### address - -> **address**: `string` - -*** - -### role - -> **role**: `string` \| `null` - -Defined in: [graphql/types.ts:147](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L147) - -*** - -### staker - -> **staker**: \{ `lastDepositTimestamp`: `string`; `lockedAmount`: `string`; `lockedUntilTimestamp`: `string`; `slashedAmount`: `string`; `stakedAmount`: `string`; `withdrawnAmount`: `string`; \} \| `null` - -Defined in: [graphql/types.ts:159](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L159) - -*** - -### url - -> **url**: `string` \| `null` - -Defined in: [graphql/types.ts:152](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L152) - -*** - -### webhookUrl - -> **webhookUrl**: `string` \| `null` - -Defined in: [graphql/types.ts:150](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L150) - -*** - -### website - -> **website**: `string` \| `null` - -Defined in: [graphql/types.ts:151](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L151) diff --git a/docs/sdk/typescript/graphql/types/interfaces/IReputationNetworkSubgraph.md b/docs/sdk/typescript/graphql/types/interfaces/IReputationNetworkSubgraph.md deleted file mode 100644 index abeb311aa3..0000000000 --- a/docs/sdk/typescript/graphql/types/interfaces/IReputationNetworkSubgraph.md +++ /dev/null @@ -1,45 +0,0 @@ -[**@human-protocol/sdk**](../../../README.md) - -*** - -[@human-protocol/sdk](../../../modules.md) / [graphql/types](../README.md) / IReputationNetworkSubgraph - -# Interface: IReputationNetworkSubgraph - -Defined in: [graphql/types.ts:169](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L169) - -## Extends - -- `Omit`\<[`IReputationNetwork`](../../../interfaces/interfaces/IReputationNetwork.md), `"operators"`\> - -## Properties - -### address - -> **address**: `string` - -Defined in: [interfaces.ts:42](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L42) - -#### Inherited from - -[`IReputationNetwork`](../../../interfaces/interfaces/IReputationNetwork.md).[`address`](../../../interfaces/interfaces/IReputationNetwork.md#address) - -*** - -### id - -> **id**: `string` - -Defined in: [interfaces.ts:41](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L41) - -#### Inherited from - -[`IReputationNetwork`](../../../interfaces/interfaces/IReputationNetwork.md).[`id`](../../../interfaces/interfaces/IReputationNetwork.md#id) - -*** - -### operators - -> **operators**: [`IOperatorSubgraph`](IOperatorSubgraph.md)[] - -Defined in: [graphql/types.ts:171](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L171) diff --git a/docs/sdk/typescript/graphql/types/type-aliases/CancellationRefundData.md b/docs/sdk/typescript/graphql/types/type-aliases/CancellationRefundData.md deleted file mode 100644 index e0b294825e..0000000000 --- a/docs/sdk/typescript/graphql/types/type-aliases/CancellationRefundData.md +++ /dev/null @@ -1,67 +0,0 @@ -[**@human-protocol/sdk**](../../../README.md) - -*** - -[@human-protocol/sdk](../../../modules.md) / [graphql/types](../README.md) / CancellationRefundData - -# Type Alias: CancellationRefundData - -> **CancellationRefundData** = `object` - -Defined in: [graphql/types.ts:182](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L182) - -## Properties - -### amount - -> **amount**: `string` - -Defined in: [graphql/types.ts:186](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L186) - -*** - -### block - -> **block**: `string` - -Defined in: [graphql/types.ts:187](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L187) - -*** - -### escrowAddress - -> **escrowAddress**: `string` - -Defined in: [graphql/types.ts:184](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L184) - -*** - -### id - -> **id**: `string` - -Defined in: [graphql/types.ts:183](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L183) - -*** - -### receiver - -> **receiver**: `string` - -Defined in: [graphql/types.ts:185](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L185) - -*** - -### timestamp - -> **timestamp**: `string` - -Defined in: [graphql/types.ts:188](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L188) - -*** - -### txHash - -> **txHash**: `string` - -Defined in: [graphql/types.ts:189](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L189) diff --git a/docs/sdk/typescript/graphql/types/type-aliases/EscrowData.md b/docs/sdk/typescript/graphql/types/type-aliases/EscrowData.md deleted file mode 100644 index adefaab72c..0000000000 --- a/docs/sdk/typescript/graphql/types/type-aliases/EscrowData.md +++ /dev/null @@ -1,203 +0,0 @@ -[**@human-protocol/sdk**](../../../README.md) - -*** - -[@human-protocol/sdk](../../../modules.md) / [graphql/types](../README.md) / EscrowData - -# Type Alias: EscrowData - -> **EscrowData** = `object` - -Defined in: [graphql/types.ts:3](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L3) - -## Properties - -### address - -> **address**: `string` - -Defined in: [graphql/types.ts:5](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L5) - -*** - -### amountPaid - -> **amountPaid**: `string` - -Defined in: [graphql/types.ts:6](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L6) - -*** - -### balance - -> **balance**: `string` - -Defined in: [graphql/types.ts:7](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L7) - -*** - -### count - -> **count**: `string` - -Defined in: [graphql/types.ts:8](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L8) - -*** - -### createdAt - -> **createdAt**: `string` - -Defined in: [graphql/types.ts:27](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L27) - -*** - -### exchangeOracle - -> **exchangeOracle**: `string` \| `null` - -Defined in: [graphql/types.ts:20](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L20) - -*** - -### exchangeOracleFee - -> **exchangeOracleFee**: `string` \| `null` - -Defined in: [graphql/types.ts:23](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L23) - -*** - -### factoryAddress - -> **factoryAddress**: `string` - -Defined in: [graphql/types.ts:9](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L9) - -*** - -### finalResultsHash - -> **finalResultsHash**: `string` \| `null` - -Defined in: [graphql/types.ts:11](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L11) - -*** - -### finalResultsUrl - -> **finalResultsUrl**: `string` \| `null` - -Defined in: [graphql/types.ts:10](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L10) - -*** - -### id - -> **id**: `string` - -Defined in: [graphql/types.ts:4](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L4) - -*** - -### intermediateResultsHash - -> **intermediateResultsHash**: `string` \| `null` - -Defined in: [graphql/types.ts:13](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L13) - -*** - -### intermediateResultsUrl - -> **intermediateResultsUrl**: `string` \| `null` - -Defined in: [graphql/types.ts:12](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L12) - -*** - -### jobRequesterId - -> **jobRequesterId**: `string` \| `null` - -Defined in: [graphql/types.ts:15](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L15) - -*** - -### launcher - -> **launcher**: `string` - -Defined in: [graphql/types.ts:14](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L14) - -*** - -### manifest - -> **manifest**: `string` \| `null` - -Defined in: [graphql/types.ts:17](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L17) - -*** - -### manifestHash - -> **manifestHash**: `string` \| `null` - -Defined in: [graphql/types.ts:16](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L16) - -*** - -### recordingOracle - -> **recordingOracle**: `string` \| `null` - -Defined in: [graphql/types.ts:18](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L18) - -*** - -### recordingOracleFee - -> **recordingOracleFee**: `string` \| `null` - -Defined in: [graphql/types.ts:21](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L21) - -*** - -### reputationOracle - -> **reputationOracle**: `string` \| `null` - -Defined in: [graphql/types.ts:19](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L19) - -*** - -### reputationOracleFee - -> **reputationOracleFee**: `string` \| `null` - -Defined in: [graphql/types.ts:22](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L22) - -*** - -### status - -> **status**: `string` - -Defined in: [graphql/types.ts:24](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L24) - -*** - -### token - -> **token**: `string` - -Defined in: [graphql/types.ts:25](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L25) - -*** - -### totalFundedAmount - -> **totalFundedAmount**: `string` - -Defined in: [graphql/types.ts:26](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L26) diff --git a/docs/sdk/typescript/graphql/types/type-aliases/EscrowStatisticsData.md b/docs/sdk/typescript/graphql/types/type-aliases/EscrowStatisticsData.md deleted file mode 100644 index eb323e97c4..0000000000 --- a/docs/sdk/typescript/graphql/types/type-aliases/EscrowStatisticsData.md +++ /dev/null @@ -1,91 +0,0 @@ -[**@human-protocol/sdk**](../../../README.md) - -*** - -[@human-protocol/sdk](../../../modules.md) / [graphql/types](../README.md) / EscrowStatisticsData - -# Type Alias: EscrowStatisticsData - -> **EscrowStatisticsData** = `object` - -Defined in: [graphql/types.ts:71](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L71) - -## Properties - -### bulkPayoutEventCount - -> **bulkPayoutEventCount**: `string` - -Defined in: [graphql/types.ts:74](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L74) - -*** - -### cancelledStatusEventCount - -> **cancelledStatusEventCount**: `string` - -Defined in: [graphql/types.ts:76](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L76) - -*** - -### completedStatusEventCount - -> **completedStatusEventCount**: `string` - -Defined in: [graphql/types.ts:79](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L79) - -*** - -### fundEventCount - -> **fundEventCount**: `string` - -Defined in: [graphql/types.ts:72](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L72) - -*** - -### paidStatusEventCount - -> **paidStatusEventCount**: `string` - -Defined in: [graphql/types.ts:78](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L78) - -*** - -### partialStatusEventCount - -> **partialStatusEventCount**: `string` - -Defined in: [graphql/types.ts:77](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L77) - -*** - -### pendingStatusEventCount - -> **pendingStatusEventCount**: `string` - -Defined in: [graphql/types.ts:75](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L75) - -*** - -### storeResultsEventCount - -> **storeResultsEventCount**: `string` - -Defined in: [graphql/types.ts:73](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L73) - -*** - -### totalEscrowCount - -> **totalEscrowCount**: `string` - -Defined in: [graphql/types.ts:81](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L81) - -*** - -### totalEventCount - -> **totalEventCount**: `string` - -Defined in: [graphql/types.ts:80](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L80) diff --git a/docs/sdk/typescript/graphql/types/type-aliases/EventDayData.md b/docs/sdk/typescript/graphql/types/type-aliases/EventDayData.md deleted file mode 100644 index 45f63bd761..0000000000 --- a/docs/sdk/typescript/graphql/types/type-aliases/EventDayData.md +++ /dev/null @@ -1,155 +0,0 @@ -[**@human-protocol/sdk**](../../../README.md) - -*** - -[@human-protocol/sdk](../../../modules.md) / [graphql/types](../README.md) / EventDayData - -# Type Alias: EventDayData - -> **EventDayData** = `object` - -Defined in: [graphql/types.ts:84](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L84) - -## Properties - -### dailyBulkPayoutEventCount - -> **dailyBulkPayoutEventCount**: `string` - -Defined in: [graphql/types.ts:88](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L88) - -*** - -### dailyCancelledStatusEventCount - -> **dailyCancelledStatusEventCount**: `string` - -Defined in: [graphql/types.ts:90](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L90) - -*** - -### dailyCompletedStatusEventCount - -> **dailyCompletedStatusEventCount**: `string` - -Defined in: [graphql/types.ts:93](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L93) - -*** - -### dailyEscrowCount - -> **dailyEscrowCount**: `string` - -Defined in: [graphql/types.ts:95](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L95) - -*** - -### dailyFundEventCount - -> **dailyFundEventCount**: `string` - -Defined in: [graphql/types.ts:86](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L86) - -*** - -### dailyHMTPayoutAmount - -> **dailyHMTPayoutAmount**: `string` - -Defined in: [graphql/types.ts:98](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L98) - -*** - -### dailyHMTTransferAmount - -> **dailyHMTTransferAmount**: `string` - -Defined in: [graphql/types.ts:100](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L100) - -*** - -### dailyHMTTransferCount - -> **dailyHMTTransferCount**: `string` - -Defined in: [graphql/types.ts:99](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L99) - -*** - -### dailyPaidStatusEventCount - -> **dailyPaidStatusEventCount**: `string` - -Defined in: [graphql/types.ts:92](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L92) - -*** - -### dailyPartialStatusEventCount - -> **dailyPartialStatusEventCount**: `string` - -Defined in: [graphql/types.ts:91](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L91) - -*** - -### dailyPayoutCount - -> **dailyPayoutCount**: `string` - -Defined in: [graphql/types.ts:97](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L97) - -*** - -### dailyPendingStatusEventCount - -> **dailyPendingStatusEventCount**: `string` - -Defined in: [graphql/types.ts:89](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L89) - -*** - -### dailyStoreResultsEventCount - -> **dailyStoreResultsEventCount**: `string` - -Defined in: [graphql/types.ts:87](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L87) - -*** - -### dailyTotalEventCount - -> **dailyTotalEventCount**: `string` - -Defined in: [graphql/types.ts:94](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L94) - -*** - -### dailyUniqueReceivers - -> **dailyUniqueReceivers**: `string` - -Defined in: [graphql/types.ts:102](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L102) - -*** - -### dailyUniqueSenders - -> **dailyUniqueSenders**: `string` - -Defined in: [graphql/types.ts:101](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L101) - -*** - -### dailyWorkerCount - -> **dailyWorkerCount**: `string` - -Defined in: [graphql/types.ts:96](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L96) - -*** - -### timestamp - -> **timestamp**: `string` - -Defined in: [graphql/types.ts:85](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L85) diff --git a/docs/sdk/typescript/graphql/types/type-aliases/HMTHolderData.md b/docs/sdk/typescript/graphql/types/type-aliases/HMTHolderData.md deleted file mode 100644 index 081a4eecf1..0000000000 --- a/docs/sdk/typescript/graphql/types/type-aliases/HMTHolderData.md +++ /dev/null @@ -1,27 +0,0 @@ -[**@human-protocol/sdk**](../../../README.md) - -*** - -[@human-protocol/sdk](../../../modules.md) / [graphql/types](../README.md) / HMTHolderData - -# Type Alias: HMTHolderData - -> **HMTHolderData** = `object` - -Defined in: [graphql/types.ts:112](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L112) - -## Properties - -### address - -> **address**: `string` - -Defined in: [graphql/types.ts:113](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L113) - -*** - -### balance - -> **balance**: `string` - -Defined in: [graphql/types.ts:114](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L114) diff --git a/docs/sdk/typescript/graphql/types/type-aliases/HMTStatisticsData.md b/docs/sdk/typescript/graphql/types/type-aliases/HMTStatisticsData.md deleted file mode 100644 index 2359e61314..0000000000 --- a/docs/sdk/typescript/graphql/types/type-aliases/HMTStatisticsData.md +++ /dev/null @@ -1,59 +0,0 @@ -[**@human-protocol/sdk**](../../../README.md) - -*** - -[@human-protocol/sdk](../../../modules.md) / [graphql/types](../README.md) / HMTStatisticsData - -# Type Alias: HMTStatisticsData - -> **HMTStatisticsData** = `object` - -Defined in: [graphql/types.ts:62](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L62) - -## Properties - -### holders - -> **holders**: `string` - -Defined in: [graphql/types.ts:68](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L68) - -*** - -### totalApprovalEventCount - -> **totalApprovalEventCount**: `string` - -Defined in: [graphql/types.ts:65](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L65) - -*** - -### totalBulkApprovalEventCount - -> **totalBulkApprovalEventCount**: `string` - -Defined in: [graphql/types.ts:66](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L66) - -*** - -### totalBulkTransferEventCount - -> **totalBulkTransferEventCount**: `string` - -Defined in: [graphql/types.ts:64](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L64) - -*** - -### totalTransferEventCount - -> **totalTransferEventCount**: `string` - -Defined in: [graphql/types.ts:63](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L63) - -*** - -### totalValueTransfered - -> **totalValueTransfered**: `string` - -Defined in: [graphql/types.ts:67](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L67) diff --git a/docs/sdk/typescript/graphql/types/type-aliases/InternalTransactionData.md b/docs/sdk/typescript/graphql/types/type-aliases/InternalTransactionData.md deleted file mode 100644 index 1cd45eafa9..0000000000 --- a/docs/sdk/typescript/graphql/types/type-aliases/InternalTransactionData.md +++ /dev/null @@ -1,75 +0,0 @@ -[**@human-protocol/sdk**](../../../README.md) - -*** - -[@human-protocol/sdk](../../../modules.md) / [graphql/types](../README.md) / InternalTransactionData - -# Type Alias: InternalTransactionData - -> **InternalTransactionData** = `object` - -Defined in: [graphql/types.ts:37](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L37) - -## Properties - -### escrow - -> **escrow**: `string` \| `null` - -Defined in: [graphql/types.ts:43](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L43) - -*** - -### from - -> **from**: `string` - -Defined in: [graphql/types.ts:38](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L38) - -*** - -### id - -> **id**: `string` \| `null` - -Defined in: [graphql/types.ts:45](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L45) - -*** - -### method - -> **method**: `string` - -Defined in: [graphql/types.ts:41](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L41) - -*** - -### receiver - -> **receiver**: `string` \| `null` - -Defined in: [graphql/types.ts:42](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L42) - -*** - -### to - -> **to**: `string` - -Defined in: [graphql/types.ts:39](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L39) - -*** - -### token - -> **token**: `string` \| `null` - -Defined in: [graphql/types.ts:44](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L44) - -*** - -### value - -> **value**: `string` - -Defined in: [graphql/types.ts:40](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L40) diff --git a/docs/sdk/typescript/graphql/types/type-aliases/KVStoreData.md b/docs/sdk/typescript/graphql/types/type-aliases/KVStoreData.md deleted file mode 100644 index d7b229b9f0..0000000000 --- a/docs/sdk/typescript/graphql/types/type-aliases/KVStoreData.md +++ /dev/null @@ -1,59 +0,0 @@ -[**@human-protocol/sdk**](../../../README.md) - -*** - -[@human-protocol/sdk](../../../modules.md) / [graphql/types](../README.md) / KVStoreData - -# Type Alias: KVStoreData - -> **KVStoreData** = `object` - -Defined in: [graphql/types.ts:123](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L123) - -## Properties - -### address - -> **address**: `string` - -Defined in: [graphql/types.ts:125](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L125) - -*** - -### block - -> **block**: `string` - -Defined in: [graphql/types.ts:129](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L129) - -*** - -### id - -> **id**: `string` - -Defined in: [graphql/types.ts:124](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L124) - -*** - -### key - -> **key**: `string` - -Defined in: [graphql/types.ts:126](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L126) - -*** - -### timestamp - -> **timestamp**: `Date` - -Defined in: [graphql/types.ts:128](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L128) - -*** - -### value - -> **value**: `string` - -Defined in: [graphql/types.ts:127](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L127) diff --git a/docs/sdk/typescript/graphql/types/type-aliases/PayoutData.md b/docs/sdk/typescript/graphql/types/type-aliases/PayoutData.md deleted file mode 100644 index 31d0634ce1..0000000000 --- a/docs/sdk/typescript/graphql/types/type-aliases/PayoutData.md +++ /dev/null @@ -1,51 +0,0 @@ -[**@human-protocol/sdk**](../../../README.md) - -*** - -[@human-protocol/sdk](../../../modules.md) / [graphql/types](../README.md) / PayoutData - -# Type Alias: PayoutData - -> **PayoutData** = `object` - -Defined in: [graphql/types.ts:174](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L174) - -## Properties - -### amount - -> **amount**: `string` - -Defined in: [graphql/types.ts:178](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L178) - -*** - -### createdAt - -> **createdAt**: `string` - -Defined in: [graphql/types.ts:179](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L179) - -*** - -### escrowAddress - -> **escrowAddress**: `string` - -Defined in: [graphql/types.ts:176](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L176) - -*** - -### id - -> **id**: `string` - -Defined in: [graphql/types.ts:175](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L175) - -*** - -### recipient - -> **recipient**: `string` - -Defined in: [graphql/types.ts:177](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L177) diff --git a/docs/sdk/typescript/graphql/types/type-aliases/RewardAddedEventData.md b/docs/sdk/typescript/graphql/types/type-aliases/RewardAddedEventData.md deleted file mode 100644 index 0526b1f7dd..0000000000 --- a/docs/sdk/typescript/graphql/types/type-aliases/RewardAddedEventData.md +++ /dev/null @@ -1,43 +0,0 @@ -[**@human-protocol/sdk**](../../../README.md) - -*** - -[@human-protocol/sdk](../../../modules.md) / [graphql/types](../README.md) / RewardAddedEventData - -# Type Alias: RewardAddedEventData - -> **RewardAddedEventData** = `object` - -Defined in: [graphql/types.ts:105](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L105) - -## Properties - -### amount - -> **amount**: `string` - -Defined in: [graphql/types.ts:109](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L109) - -*** - -### escrowAddress - -> **escrowAddress**: `string` - -Defined in: [graphql/types.ts:106](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L106) - -*** - -### slasher - -> **slasher**: `string` - -Defined in: [graphql/types.ts:108](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L108) - -*** - -### staker - -> **staker**: `string` - -Defined in: [graphql/types.ts:107](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L107) diff --git a/docs/sdk/typescript/graphql/types/type-aliases/StakerData.md b/docs/sdk/typescript/graphql/types/type-aliases/StakerData.md deleted file mode 100644 index 7947db29fb..0000000000 --- a/docs/sdk/typescript/graphql/types/type-aliases/StakerData.md +++ /dev/null @@ -1,75 +0,0 @@ -[**@human-protocol/sdk**](../../../README.md) - -*** - -[@human-protocol/sdk](../../../modules.md) / [graphql/types](../README.md) / StakerData - -# Type Alias: StakerData - -> **StakerData** = `object` - -Defined in: [graphql/types.ts:132](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L132) - -## Properties - -### address - -> **address**: `string` - -Defined in: [graphql/types.ts:134](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L134) - -*** - -### id - -> **id**: `string` - -Defined in: [graphql/types.ts:133](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L133) - -*** - -### lastDepositTimestamp - -> **lastDepositTimestamp**: `string` - -Defined in: [graphql/types.ts:140](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L140) - -*** - -### lockedAmount - -> **lockedAmount**: `string` - -Defined in: [graphql/types.ts:136](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L136) - -*** - -### lockedUntilTimestamp - -> **lockedUntilTimestamp**: `string` - -Defined in: [graphql/types.ts:139](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L139) - -*** - -### slashedAmount - -> **slashedAmount**: `string` - -Defined in: [graphql/types.ts:138](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L138) - -*** - -### stakedAmount - -> **stakedAmount**: `string` - -Defined in: [graphql/types.ts:135](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L135) - -*** - -### withdrawnAmount - -> **withdrawnAmount**: `string` - -Defined in: [graphql/types.ts:137](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L137) diff --git a/docs/sdk/typescript/graphql/types/type-aliases/StatusEvent.md b/docs/sdk/typescript/graphql/types/type-aliases/StatusEvent.md deleted file mode 100644 index 97325a8485..0000000000 --- a/docs/sdk/typescript/graphql/types/type-aliases/StatusEvent.md +++ /dev/null @@ -1,35 +0,0 @@ -[**@human-protocol/sdk**](../../../README.md) - -*** - -[@human-protocol/sdk](../../../modules.md) / [graphql/types](../README.md) / StatusEvent - -# Type Alias: StatusEvent - -> **StatusEvent** = `object` - -Defined in: [graphql/types.ts:117](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L117) - -## Properties - -### escrowAddress - -> **escrowAddress**: `string` - -Defined in: [graphql/types.ts:119](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L119) - -*** - -### status - -> **status**: `string` - -Defined in: [graphql/types.ts:120](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L120) - -*** - -### timestamp - -> **timestamp**: `string` - -Defined in: [graphql/types.ts:118](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L118) diff --git a/docs/sdk/typescript/graphql/types/type-aliases/TransactionData.md b/docs/sdk/typescript/graphql/types/type-aliases/TransactionData.md deleted file mode 100644 index 97f53a8542..0000000000 --- a/docs/sdk/typescript/graphql/types/type-aliases/TransactionData.md +++ /dev/null @@ -1,99 +0,0 @@ -[**@human-protocol/sdk**](../../../README.md) - -*** - -[@human-protocol/sdk](../../../modules.md) / [graphql/types](../README.md) / TransactionData - -# Type Alias: TransactionData - -> **TransactionData** = `object` - -Defined in: [graphql/types.ts:48](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L48) - -## Properties - -### block - -> **block**: `string` - -Defined in: [graphql/types.ts:49](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L49) - -*** - -### escrow - -> **escrow**: `string` \| `null` - -Defined in: [graphql/types.ts:57](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L57) - -*** - -### from - -> **from**: `string` - -Defined in: [graphql/types.ts:51](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L51) - -*** - -### internalTransactions - -> **internalTransactions**: [`InternalTransactionData`](InternalTransactionData.md)[] - -Defined in: [graphql/types.ts:59](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L59) - -*** - -### method - -> **method**: `string` - -Defined in: [graphql/types.ts:55](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L55) - -*** - -### receiver - -> **receiver**: `string` \| `null` - -Defined in: [graphql/types.ts:56](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L56) - -*** - -### timestamp - -> **timestamp**: `string` - -Defined in: [graphql/types.ts:53](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L53) - -*** - -### to - -> **to**: `string` - -Defined in: [graphql/types.ts:52](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L52) - -*** - -### token - -> **token**: `string` \| `null` - -Defined in: [graphql/types.ts:58](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L58) - -*** - -### txHash - -> **txHash**: `string` - -Defined in: [graphql/types.ts:50](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L50) - -*** - -### value - -> **value**: `string` - -Defined in: [graphql/types.ts:54](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L54) diff --git a/docs/sdk/typescript/graphql/types/type-aliases/WorkerData.md b/docs/sdk/typescript/graphql/types/type-aliases/WorkerData.md deleted file mode 100644 index c7d57e521b..0000000000 --- a/docs/sdk/typescript/graphql/types/type-aliases/WorkerData.md +++ /dev/null @@ -1,43 +0,0 @@ -[**@human-protocol/sdk**](../../../README.md) - -*** - -[@human-protocol/sdk](../../../modules.md) / [graphql/types](../README.md) / WorkerData - -# Type Alias: WorkerData - -> **WorkerData** = `object` - -Defined in: [graphql/types.ts:30](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L30) - -## Properties - -### address - -> **address**: `string` - -Defined in: [graphql/types.ts:32](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L32) - -*** - -### id - -> **id**: `string` - -Defined in: [graphql/types.ts:31](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L31) - -*** - -### payoutCount - -> **payoutCount**: `string` - -Defined in: [graphql/types.ts:34](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L34) - -*** - -### totalHMTAmountReceived - -> **totalHMTAmountReceived**: `string` - -Defined in: [graphql/types.ts:33](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts#L33) diff --git a/docs/sdk/typescript/interfaces/README.md b/docs/sdk/typescript/interfaces/README.md deleted file mode 100644 index 8c3ffb229b..0000000000 --- a/docs/sdk/typescript/interfaces/README.md +++ /dev/null @@ -1,47 +0,0 @@ -[**@human-protocol/sdk**](../README.md) - -*** - -[@human-protocol/sdk](../modules.md) / interfaces - -# interfaces - -## Interfaces - -- [ICancellationRefund](interfaces/ICancellationRefund.md) -- [ICancellationRefundFilter](interfaces/ICancellationRefundFilter.md) -- [IDailyEscrow](interfaces/IDailyEscrow.md) -- [IDailyHMT](interfaces/IDailyHMT.md) -- [IDailyPayment](interfaces/IDailyPayment.md) -- [IDailyWorker](interfaces/IDailyWorker.md) -- [IEscrow](interfaces/IEscrow.md) -- [IEscrowConfig](interfaces/IEscrowConfig.md) -- [IEscrowsFilter](interfaces/IEscrowsFilter.md) -- [IEscrowStatistics](interfaces/IEscrowStatistics.md) -- [IEscrowWithdraw](interfaces/IEscrowWithdraw.md) -- [IHMTHolder](interfaces/IHMTHolder.md) -- [IHMTHoldersParams](interfaces/IHMTHoldersParams.md) -- [IHMTStatistics](interfaces/IHMTStatistics.md) -- [IKeyPair](interfaces/IKeyPair.md) -- [IKVStore](interfaces/IKVStore.md) -- [InternalTransaction](interfaces/InternalTransaction.md) -- [IOperator](interfaces/IOperator.md) -- [IOperatorsFilter](interfaces/IOperatorsFilter.md) -- [IPagination](interfaces/IPagination.md) -- [IPaymentStatistics](interfaces/IPaymentStatistics.md) -- [IPayout](interfaces/IPayout.md) -- [IPayoutFilter](interfaces/IPayoutFilter.md) -- [IReputationNetwork](interfaces/IReputationNetwork.md) -- [IReward](interfaces/IReward.md) -- [IStaker](interfaces/IStaker.md) -- [IStakersFilter](interfaces/IStakersFilter.md) -- [IStatisticsFilter](interfaces/IStatisticsFilter.md) -- [IStatusEvent](interfaces/IStatusEvent.md) -- [IStatusEventFilter](interfaces/IStatusEventFilter.md) -- [ITransaction](interfaces/ITransaction.md) -- [ITransactionsFilter](interfaces/ITransactionsFilter.md) -- [IWorker](interfaces/IWorker.md) -- [IWorkersFilter](interfaces/IWorkersFilter.md) -- [IWorkerStatistics](interfaces/IWorkerStatistics.md) -- [StakerInfo](interfaces/StakerInfo.md) -- [SubgraphOptions](interfaces/SubgraphOptions.md) diff --git a/docs/sdk/typescript/interfaces/interfaces/ICancellationRefund.md b/docs/sdk/typescript/interfaces/interfaces/ICancellationRefund.md deleted file mode 100644 index 2092fbeb8e..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/ICancellationRefund.md +++ /dev/null @@ -1,65 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / ICancellationRefund - -# Interface: ICancellationRefund - -Defined in: [interfaces.ts:292](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L292) - -## Properties - -### amount - -> **amount**: `bigint` - -Defined in: [interfaces.ts:296](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L296) - -*** - -### block - -> **block**: `number` - -Defined in: [interfaces.ts:297](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L297) - -*** - -### escrowAddress - -> **escrowAddress**: `string` - -Defined in: [interfaces.ts:294](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L294) - -*** - -### id - -> **id**: `string` - -Defined in: [interfaces.ts:293](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L293) - -*** - -### receiver - -> **receiver**: `string` - -Defined in: [interfaces.ts:295](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L295) - -*** - -### timestamp - -> **timestamp**: `number` - -Defined in: [interfaces.ts:298](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L298) - -*** - -### txHash - -> **txHash**: `string` - -Defined in: [interfaces.ts:299](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L299) diff --git a/docs/sdk/typescript/interfaces/interfaces/ICancellationRefundFilter.md b/docs/sdk/typescript/interfaces/interfaces/ICancellationRefundFilter.md deleted file mode 100644 index 656f138e73..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/ICancellationRefundFilter.md +++ /dev/null @@ -1,89 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / ICancellationRefundFilter - -# Interface: ICancellationRefundFilter - -Defined in: [interfaces.ts:224](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L224) - -## Extends - -- [`IPagination`](IPagination.md) - -## Properties - -### chainId - -> **chainId**: [`ChainId`](../../enums/enumerations/ChainId.md) - -Defined in: [interfaces.ts:225](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L225) - -*** - -### escrowAddress? - -> `optional` **escrowAddress**: `string` - -Defined in: [interfaces.ts:226](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L226) - -*** - -### first? - -> `optional` **first**: `number` - -Defined in: [interfaces.ts:164](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L164) - -#### Inherited from - -[`IPagination`](IPagination.md).[`first`](IPagination.md#first) - -*** - -### from? - -> `optional` **from**: `Date` - -Defined in: [interfaces.ts:228](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L228) - -*** - -### orderDirection? - -> `optional` **orderDirection**: [`OrderDirection`](../../enums/enumerations/OrderDirection.md) - -Defined in: [interfaces.ts:166](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L166) - -#### Inherited from - -[`IPagination`](IPagination.md).[`orderDirection`](IPagination.md#orderdirection) - -*** - -### receiver? - -> `optional` **receiver**: `string` - -Defined in: [interfaces.ts:227](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L227) - -*** - -### skip? - -> `optional` **skip**: `number` - -Defined in: [interfaces.ts:165](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L165) - -#### Inherited from - -[`IPagination`](IPagination.md).[`skip`](IPagination.md#skip) - -*** - -### to? - -> `optional` **to**: `Date` - -Defined in: [interfaces.ts:229](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L229) diff --git a/docs/sdk/typescript/interfaces/interfaces/IDailyEscrow.md b/docs/sdk/typescript/interfaces/interfaces/IDailyEscrow.md deleted file mode 100644 index 61395c4264..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IDailyEscrow.md +++ /dev/null @@ -1,57 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IDailyEscrow - -# Interface: IDailyEscrow - -Defined in: [interfaces.ts:232](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L232) - -## Properties - -### escrowsCancelled - -> **escrowsCancelled**: `number` - -Defined in: [interfaces.ts:238](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L238) - -*** - -### escrowsPaid - -> **escrowsPaid**: `number` - -Defined in: [interfaces.ts:237](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L237) - -*** - -### escrowsPending - -> **escrowsPending**: `number` - -Defined in: [interfaces.ts:235](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L235) - -*** - -### escrowsSolved - -> **escrowsSolved**: `number` - -Defined in: [interfaces.ts:236](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L236) - -*** - -### escrowsTotal - -> **escrowsTotal**: `number` - -Defined in: [interfaces.ts:234](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L234) - -*** - -### timestamp - -> **timestamp**: `number` - -Defined in: [interfaces.ts:233](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L233) diff --git a/docs/sdk/typescript/interfaces/interfaces/IDailyHMT.md b/docs/sdk/typescript/interfaces/interfaces/IDailyHMT.md deleted file mode 100644 index fd697e470f..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IDailyHMT.md +++ /dev/null @@ -1,49 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IDailyHMT - -# Interface: IDailyHMT - -Defined in: [interfaces.ts:277](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L277) - -## Properties - -### dailyUniqueReceivers - -> **dailyUniqueReceivers**: `number` - -Defined in: [interfaces.ts:282](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L282) - -*** - -### dailyUniqueSenders - -> **dailyUniqueSenders**: `number` - -Defined in: [interfaces.ts:281](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L281) - -*** - -### timestamp - -> **timestamp**: `number` - -Defined in: [interfaces.ts:278](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L278) - -*** - -### totalTransactionAmount - -> **totalTransactionAmount**: `bigint` - -Defined in: [interfaces.ts:279](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L279) - -*** - -### totalTransactionCount - -> **totalTransactionCount**: `number` - -Defined in: [interfaces.ts:280](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L280) diff --git a/docs/sdk/typescript/interfaces/interfaces/IDailyPayment.md b/docs/sdk/typescript/interfaces/interfaces/IDailyPayment.md deleted file mode 100644 index 2e12e938e8..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IDailyPayment.md +++ /dev/null @@ -1,41 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IDailyPayment - -# Interface: IDailyPayment - -Defined in: [interfaces.ts:255](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L255) - -## Properties - -### averageAmountPerWorker - -> **averageAmountPerWorker**: `bigint` - -Defined in: [interfaces.ts:259](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L259) - -*** - -### timestamp - -> **timestamp**: `number` - -Defined in: [interfaces.ts:256](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L256) - -*** - -### totalAmountPaid - -> **totalAmountPaid**: `bigint` - -Defined in: [interfaces.ts:257](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L257) - -*** - -### totalCount - -> **totalCount**: `number` - -Defined in: [interfaces.ts:258](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L258) diff --git a/docs/sdk/typescript/interfaces/interfaces/IDailyWorker.md b/docs/sdk/typescript/interfaces/interfaces/IDailyWorker.md deleted file mode 100644 index 935861839f..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IDailyWorker.md +++ /dev/null @@ -1,25 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IDailyWorker - -# Interface: IDailyWorker - -Defined in: [interfaces.ts:246](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L246) - -## Properties - -### activeWorkers - -> **activeWorkers**: `number` - -Defined in: [interfaces.ts:248](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L248) - -*** - -### timestamp - -> **timestamp**: `number` - -Defined in: [interfaces.ts:247](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L247) diff --git a/docs/sdk/typescript/interfaces/interfaces/IEscrow.md b/docs/sdk/typescript/interfaces/interfaces/IEscrow.md deleted file mode 100644 index 669953a6b8..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IEscrow.md +++ /dev/null @@ -1,209 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IEscrow - -# Interface: IEscrow - -Defined in: [interfaces.ts:46](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L46) - -## Properties - -### address - -> **address**: `string` - -Defined in: [interfaces.ts:48](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L48) - -*** - -### amountPaid - -> **amountPaid**: `bigint` - -Defined in: [interfaces.ts:49](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L49) - -*** - -### balance - -> **balance**: `bigint` - -Defined in: [interfaces.ts:50](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L50) - -*** - -### chainId - -> **chainId**: `number` - -Defined in: [interfaces.ts:71](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L71) - -*** - -### count - -> **count**: `number` - -Defined in: [interfaces.ts:51](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L51) - -*** - -### createdAt - -> **createdAt**: `number` - -Defined in: [interfaces.ts:70](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L70) - -*** - -### exchangeOracle - -> **exchangeOracle**: `string` \| `null` - -Defined in: [interfaces.ts:63](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L63) - -*** - -### exchangeOracleFee - -> **exchangeOracleFee**: `number` \| `null` - -Defined in: [interfaces.ts:66](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L66) - -*** - -### factoryAddress - -> **factoryAddress**: `string` - -Defined in: [interfaces.ts:52](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L52) - -*** - -### finalResultsHash - -> **finalResultsHash**: `string` \| `null` - -Defined in: [interfaces.ts:54](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L54) - -*** - -### finalResultsUrl - -> **finalResultsUrl**: `string` \| `null` - -Defined in: [interfaces.ts:53](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L53) - -*** - -### id - -> **id**: `string` - -Defined in: [interfaces.ts:47](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L47) - -*** - -### intermediateResultsHash - -> **intermediateResultsHash**: `string` \| `null` - -Defined in: [interfaces.ts:56](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L56) - -*** - -### intermediateResultsUrl - -> **intermediateResultsUrl**: `string` \| `null` - -Defined in: [interfaces.ts:55](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L55) - -*** - -### jobRequesterId - -> **jobRequesterId**: `string` \| `null` - -Defined in: [interfaces.ts:58](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L58) - -*** - -### launcher - -> **launcher**: `string` - -Defined in: [interfaces.ts:57](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L57) - -*** - -### manifest - -> **manifest**: `string` \| `null` - -Defined in: [interfaces.ts:60](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L60) - -*** - -### manifestHash - -> **manifestHash**: `string` \| `null` - -Defined in: [interfaces.ts:59](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L59) - -*** - -### recordingOracle - -> **recordingOracle**: `string` \| `null` - -Defined in: [interfaces.ts:61](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L61) - -*** - -### recordingOracleFee - -> **recordingOracleFee**: `number` \| `null` - -Defined in: [interfaces.ts:64](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L64) - -*** - -### reputationOracle - -> **reputationOracle**: `string` \| `null` - -Defined in: [interfaces.ts:62](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L62) - -*** - -### reputationOracleFee - -> **reputationOracleFee**: `number` \| `null` - -Defined in: [interfaces.ts:65](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L65) - -*** - -### status - -> **status**: `string` - -Defined in: [interfaces.ts:67](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L67) - -*** - -### token - -> **token**: `string` - -Defined in: [interfaces.ts:68](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L68) - -*** - -### totalFundedAmount - -> **totalFundedAmount**: `bigint` - -Defined in: [interfaces.ts:69](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L69) diff --git a/docs/sdk/typescript/interfaces/interfaces/IEscrowConfig.md b/docs/sdk/typescript/interfaces/interfaces/IEscrowConfig.md deleted file mode 100644 index 7704b93b03..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IEscrowConfig.md +++ /dev/null @@ -1,73 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IEscrowConfig - -# Interface: IEscrowConfig - -Defined in: [interfaces.ts:86](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L86) - -## Properties - -### exchangeOracle - -> **exchangeOracle**: `string` - -Defined in: [interfaces.ts:89](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L89) - -*** - -### exchangeOracleFee - -> **exchangeOracleFee**: `bigint` - -Defined in: [interfaces.ts:92](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L92) - -*** - -### manifest - -> **manifest**: `string` - -Defined in: [interfaces.ts:93](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L93) - -*** - -### manifestHash - -> **manifestHash**: `string` - -Defined in: [interfaces.ts:94](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L94) - -*** - -### recordingOracle - -> **recordingOracle**: `string` - -Defined in: [interfaces.ts:87](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L87) - -*** - -### recordingOracleFee - -> **recordingOracleFee**: `bigint` - -Defined in: [interfaces.ts:90](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L90) - -*** - -### reputationOracle - -> **reputationOracle**: `string` - -Defined in: [interfaces.ts:88](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L88) - -*** - -### reputationOracleFee - -> **reputationOracleFee**: `bigint` - -Defined in: [interfaces.ts:91](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L91) diff --git a/docs/sdk/typescript/interfaces/interfaces/IEscrowStatistics.md b/docs/sdk/typescript/interfaces/interfaces/IEscrowStatistics.md deleted file mode 100644 index 264b132811..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IEscrowStatistics.md +++ /dev/null @@ -1,25 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IEscrowStatistics - -# Interface: IEscrowStatistics - -Defined in: [interfaces.ts:241](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L241) - -## Properties - -### dailyEscrowsData - -> **dailyEscrowsData**: [`IDailyEscrow`](IDailyEscrow.md)[] - -Defined in: [interfaces.ts:243](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L243) - -*** - -### totalEscrows - -> **totalEscrows**: `number` - -Defined in: [interfaces.ts:242](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L242) diff --git a/docs/sdk/typescript/interfaces/interfaces/IEscrowWithdraw.md b/docs/sdk/typescript/interfaces/interfaces/IEscrowWithdraw.md deleted file mode 100644 index 81c22bcbc7..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IEscrowWithdraw.md +++ /dev/null @@ -1,33 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IEscrowWithdraw - -# Interface: IEscrowWithdraw - -Defined in: [interfaces.ts:310](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L310) - -## Properties - -### tokenAddress - -> **tokenAddress**: `string` - -Defined in: [interfaces.ts:312](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L312) - -*** - -### txHash - -> **txHash**: `string` - -Defined in: [interfaces.ts:311](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L311) - -*** - -### withdrawnAmount - -> **withdrawnAmount**: `bigint` - -Defined in: [interfaces.ts:313](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L313) diff --git a/docs/sdk/typescript/interfaces/interfaces/IEscrowsFilter.md b/docs/sdk/typescript/interfaces/interfaces/IEscrowsFilter.md deleted file mode 100644 index 1060470aa0..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IEscrowsFilter.md +++ /dev/null @@ -1,121 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IEscrowsFilter - -# Interface: IEscrowsFilter - -Defined in: [interfaces.ts:74](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L74) - -## Extends - -- [`IPagination`](IPagination.md) - -## Properties - -### chainId - -> **chainId**: [`ChainId`](../../enums/enumerations/ChainId.md) - -Defined in: [interfaces.ts:83](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L83) - -*** - -### exchangeOracle? - -> `optional` **exchangeOracle**: `string` - -Defined in: [interfaces.ts:78](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L78) - -*** - -### first? - -> `optional` **first**: `number` - -Defined in: [interfaces.ts:164](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L164) - -#### Inherited from - -[`IPagination`](IPagination.md).[`first`](IPagination.md#first) - -*** - -### from? - -> `optional` **from**: `Date` - -Defined in: [interfaces.ts:81](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L81) - -*** - -### jobRequesterId? - -> `optional` **jobRequesterId**: `string` - -Defined in: [interfaces.ts:79](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L79) - -*** - -### launcher? - -> `optional` **launcher**: `string` - -Defined in: [interfaces.ts:75](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L75) - -*** - -### orderDirection? - -> `optional` **orderDirection**: [`OrderDirection`](../../enums/enumerations/OrderDirection.md) - -Defined in: [interfaces.ts:166](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L166) - -#### Inherited from - -[`IPagination`](IPagination.md).[`orderDirection`](IPagination.md#orderdirection) - -*** - -### recordingOracle? - -> `optional` **recordingOracle**: `string` - -Defined in: [interfaces.ts:77](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L77) - -*** - -### reputationOracle? - -> `optional` **reputationOracle**: `string` - -Defined in: [interfaces.ts:76](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L76) - -*** - -### skip? - -> `optional` **skip**: `number` - -Defined in: [interfaces.ts:165](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L165) - -#### Inherited from - -[`IPagination`](IPagination.md).[`skip`](IPagination.md#skip) - -*** - -### status? - -> `optional` **status**: [`EscrowStatus`](../../types/enumerations/EscrowStatus.md) \| [`EscrowStatus`](../../types/enumerations/EscrowStatus.md)[] - -Defined in: [interfaces.ts:80](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L80) - -*** - -### to? - -> `optional` **to**: `Date` - -Defined in: [interfaces.ts:82](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L82) diff --git a/docs/sdk/typescript/interfaces/interfaces/IHMTHolder.md b/docs/sdk/typescript/interfaces/interfaces/IHMTHolder.md deleted file mode 100644 index 51af45bfaa..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IHMTHolder.md +++ /dev/null @@ -1,25 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IHMTHolder - -# Interface: IHMTHolder - -Defined in: [interfaces.ts:272](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L272) - -## Properties - -### address - -> **address**: `string` - -Defined in: [interfaces.ts:273](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L273) - -*** - -### balance - -> **balance**: `bigint` - -Defined in: [interfaces.ts:274](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L274) diff --git a/docs/sdk/typescript/interfaces/interfaces/IHMTHoldersParams.md b/docs/sdk/typescript/interfaces/interfaces/IHMTHoldersParams.md deleted file mode 100644 index e35e8e43ae..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IHMTHoldersParams.md +++ /dev/null @@ -1,57 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IHMTHoldersParams - -# Interface: IHMTHoldersParams - -Defined in: [interfaces.ts:109](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L109) - -## Extends - -- [`IPagination`](IPagination.md) - -## Properties - -### address? - -> `optional` **address**: `string` - -Defined in: [interfaces.ts:110](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L110) - -*** - -### first? - -> `optional` **first**: `number` - -Defined in: [interfaces.ts:164](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L164) - -#### Inherited from - -[`IPagination`](IPagination.md).[`first`](IPagination.md#first) - -*** - -### orderDirection? - -> `optional` **orderDirection**: [`OrderDirection`](../../enums/enumerations/OrderDirection.md) - -Defined in: [interfaces.ts:166](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L166) - -#### Inherited from - -[`IPagination`](IPagination.md).[`orderDirection`](IPagination.md#orderdirection) - -*** - -### skip? - -> `optional` **skip**: `number` - -Defined in: [interfaces.ts:165](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L165) - -#### Inherited from - -[`IPagination`](IPagination.md).[`skip`](IPagination.md#skip) diff --git a/docs/sdk/typescript/interfaces/interfaces/IHMTStatistics.md b/docs/sdk/typescript/interfaces/interfaces/IHMTStatistics.md deleted file mode 100644 index 1b73821946..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IHMTStatistics.md +++ /dev/null @@ -1,33 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IHMTStatistics - -# Interface: IHMTStatistics - -Defined in: [interfaces.ts:266](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L266) - -## Properties - -### totalHolders - -> **totalHolders**: `number` - -Defined in: [interfaces.ts:269](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L269) - -*** - -### totalTransferAmount - -> **totalTransferAmount**: `bigint` - -Defined in: [interfaces.ts:267](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L267) - -*** - -### totalTransferCount - -> **totalTransferCount**: `number` - -Defined in: [interfaces.ts:268](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L268) diff --git a/docs/sdk/typescript/interfaces/interfaces/IKVStore.md b/docs/sdk/typescript/interfaces/interfaces/IKVStore.md deleted file mode 100644 index ac67cd4bd9..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IKVStore.md +++ /dev/null @@ -1,25 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IKVStore - -# Interface: IKVStore - -Defined in: [interfaces.ts:121](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L121) - -## Properties - -### key - -> **key**: `string` - -Defined in: [interfaces.ts:122](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L122) - -*** - -### value - -> **value**: `string` - -Defined in: [interfaces.ts:123](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L123) diff --git a/docs/sdk/typescript/interfaces/interfaces/IKeyPair.md b/docs/sdk/typescript/interfaces/interfaces/IKeyPair.md deleted file mode 100644 index 3eaef5d813..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IKeyPair.md +++ /dev/null @@ -1,41 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IKeyPair - -# Interface: IKeyPair - -Defined in: [interfaces.ts:97](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L97) - -## Properties - -### passphrase - -> **passphrase**: `string` - -Defined in: [interfaces.ts:100](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L100) - -*** - -### privateKey - -> **privateKey**: `string` - -Defined in: [interfaces.ts:98](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L98) - -*** - -### publicKey - -> **publicKey**: `string` - -Defined in: [interfaces.ts:99](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L99) - -*** - -### revocationCertificate? - -> `optional` **revocationCertificate**: `string` - -Defined in: [interfaces.ts:101](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L101) diff --git a/docs/sdk/typescript/interfaces/interfaces/IOperator.md b/docs/sdk/typescript/interfaces/interfaces/IOperator.md deleted file mode 100644 index 958f25833a..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IOperator.md +++ /dev/null @@ -1,177 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IOperator - -# Interface: IOperator - -Defined in: [interfaces.ts:9](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L9) - -## Properties - -### address - -> **address**: `string` - -Defined in: [interfaces.ts:12](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L12) - -*** - -### amountJobsProcessed - -> **amountJobsProcessed**: `bigint` \| `null` - -Defined in: [interfaces.ts:18](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L18) - -*** - -### category - -> **category**: `string` \| `null` - -Defined in: [interfaces.ts:30](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L30) - -*** - -### chainId - -> **chainId**: [`ChainId`](../../enums/enumerations/ChainId.md) - -Defined in: [interfaces.ts:11](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L11) - -*** - -### fee - -> **fee**: `bigint` \| `null` - -Defined in: [interfaces.ts:20](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L20) - -*** - -### id - -> **id**: `string` - -Defined in: [interfaces.ts:10](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L10) - -*** - -### jobTypes - -> **jobTypes**: `string`[] \| `null` - -Defined in: [interfaces.ts:25](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L25) - -*** - -### lockedAmount - -> **lockedAmount**: `bigint` \| `null` - -Defined in: [interfaces.ts:14](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L14) - -*** - -### lockedUntilTimestamp - -> **lockedUntilTimestamp**: `number` \| `null` - -Defined in: [interfaces.ts:15](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L15) - -*** - -### name - -> **name**: `string` \| `null` - -Defined in: [interfaces.ts:29](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L29) - -*** - -### publicKey - -> **publicKey**: `string` \| `null` - -Defined in: [interfaces.ts:21](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L21) - -*** - -### registrationInstructions - -> **registrationInstructions**: `string` \| `null` - -Defined in: [interfaces.ts:27](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L27) - -*** - -### registrationNeeded - -> **registrationNeeded**: `boolean` \| `null` - -Defined in: [interfaces.ts:26](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L26) - -*** - -### reputationNetworks - -> **reputationNetworks**: `string`[] - -Defined in: [interfaces.ts:28](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L28) - -*** - -### role - -> **role**: `string` \| `null` - -Defined in: [interfaces.ts:19](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L19) - -*** - -### slashedAmount - -> **slashedAmount**: `bigint` \| `null` - -Defined in: [interfaces.ts:17](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L17) - -*** - -### stakedAmount - -> **stakedAmount**: `bigint` \| `null` - -Defined in: [interfaces.ts:13](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L13) - -*** - -### url - -> **url**: `string` \| `null` - -Defined in: [interfaces.ts:24](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L24) - -*** - -### webhookUrl - -> **webhookUrl**: `string` \| `null` - -Defined in: [interfaces.ts:22](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L22) - -*** - -### website - -> **website**: `string` \| `null` - -Defined in: [interfaces.ts:23](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L23) - -*** - -### withdrawnAmount - -> **withdrawnAmount**: `bigint` \| `null` - -Defined in: [interfaces.ts:16](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L16) diff --git a/docs/sdk/typescript/interfaces/interfaces/IOperatorsFilter.md b/docs/sdk/typescript/interfaces/interfaces/IOperatorsFilter.md deleted file mode 100644 index 7280f6f369..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IOperatorsFilter.md +++ /dev/null @@ -1,81 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IOperatorsFilter - -# Interface: IOperatorsFilter - -Defined in: [interfaces.ts:33](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L33) - -## Extends - -- [`IPagination`](IPagination.md) - -## Properties - -### chainId - -> **chainId**: [`ChainId`](../../enums/enumerations/ChainId.md) - -Defined in: [interfaces.ts:34](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L34) - -*** - -### first? - -> `optional` **first**: `number` - -Defined in: [interfaces.ts:164](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L164) - -#### Inherited from - -[`IPagination`](IPagination.md).[`first`](IPagination.md#first) - -*** - -### minStakedAmount? - -> `optional` **minStakedAmount**: `number` - -Defined in: [interfaces.ts:36](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L36) - -*** - -### orderBy? - -> `optional` **orderBy**: `string` - -Defined in: [interfaces.ts:37](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L37) - -*** - -### orderDirection? - -> `optional` **orderDirection**: [`OrderDirection`](../../enums/enumerations/OrderDirection.md) - -Defined in: [interfaces.ts:166](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L166) - -#### Inherited from - -[`IPagination`](IPagination.md).[`orderDirection`](IPagination.md#orderdirection) - -*** - -### roles? - -> `optional` **roles**: `string`[] - -Defined in: [interfaces.ts:35](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L35) - -*** - -### skip? - -> `optional` **skip**: `number` - -Defined in: [interfaces.ts:165](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L165) - -#### Inherited from - -[`IPagination`](IPagination.md).[`skip`](IPagination.md#skip) diff --git a/docs/sdk/typescript/interfaces/interfaces/IPagination.md b/docs/sdk/typescript/interfaces/interfaces/IPagination.md deleted file mode 100644 index c1019d2ad3..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IPagination.md +++ /dev/null @@ -1,46 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IPagination - -# Interface: IPagination - -Defined in: [interfaces.ts:163](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L163) - -## Extended by - -- [`IOperatorsFilter`](IOperatorsFilter.md) -- [`IEscrowsFilter`](IEscrowsFilter.md) -- [`IStatisticsFilter`](IStatisticsFilter.md) -- [`IHMTHoldersParams`](IHMTHoldersParams.md) -- [`IPayoutFilter`](IPayoutFilter.md) -- [`ITransactionsFilter`](ITransactionsFilter.md) -- [`IStatusEventFilter`](IStatusEventFilter.md) -- [`IWorkersFilter`](IWorkersFilter.md) -- [`IStakersFilter`](IStakersFilter.md) -- [`ICancellationRefundFilter`](ICancellationRefundFilter.md) - -## Properties - -### first? - -> `optional` **first**: `number` - -Defined in: [interfaces.ts:164](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L164) - -*** - -### orderDirection? - -> `optional` **orderDirection**: [`OrderDirection`](../../enums/enumerations/OrderDirection.md) - -Defined in: [interfaces.ts:166](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L166) - -*** - -### skip? - -> `optional` **skip**: `number` - -Defined in: [interfaces.ts:165](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L165) diff --git a/docs/sdk/typescript/interfaces/interfaces/IPaymentStatistics.md b/docs/sdk/typescript/interfaces/interfaces/IPaymentStatistics.md deleted file mode 100644 index 8c27f833ca..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IPaymentStatistics.md +++ /dev/null @@ -1,17 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IPaymentStatistics - -# Interface: IPaymentStatistics - -Defined in: [interfaces.ts:262](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L262) - -## Properties - -### dailyPaymentsData - -> **dailyPaymentsData**: [`IDailyPayment`](IDailyPayment.md)[] - -Defined in: [interfaces.ts:263](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L263) diff --git a/docs/sdk/typescript/interfaces/interfaces/IPayout.md b/docs/sdk/typescript/interfaces/interfaces/IPayout.md deleted file mode 100644 index aea8e9ac32..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IPayout.md +++ /dev/null @@ -1,49 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IPayout - -# Interface: IPayout - -Defined in: [interfaces.ts:302](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L302) - -## Properties - -### amount - -> **amount**: `bigint` - -Defined in: [interfaces.ts:306](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L306) - -*** - -### createdAt - -> **createdAt**: `number` - -Defined in: [interfaces.ts:307](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L307) - -*** - -### escrowAddress - -> **escrowAddress**: `string` - -Defined in: [interfaces.ts:304](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L304) - -*** - -### id - -> **id**: `string` - -Defined in: [interfaces.ts:303](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L303) - -*** - -### recipient - -> **recipient**: `string` - -Defined in: [interfaces.ts:305](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L305) diff --git a/docs/sdk/typescript/interfaces/interfaces/IPayoutFilter.md b/docs/sdk/typescript/interfaces/interfaces/IPayoutFilter.md deleted file mode 100644 index 5ae548411d..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IPayoutFilter.md +++ /dev/null @@ -1,89 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IPayoutFilter - -# Interface: IPayoutFilter - -Defined in: [interfaces.ts:113](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L113) - -## Extends - -- [`IPagination`](IPagination.md) - -## Properties - -### chainId - -> **chainId**: [`ChainId`](../../enums/enumerations/ChainId.md) - -Defined in: [interfaces.ts:114](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L114) - -*** - -### escrowAddress? - -> `optional` **escrowAddress**: `string` - -Defined in: [interfaces.ts:115](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L115) - -*** - -### first? - -> `optional` **first**: `number` - -Defined in: [interfaces.ts:164](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L164) - -#### Inherited from - -[`IPagination`](IPagination.md).[`first`](IPagination.md#first) - -*** - -### from? - -> `optional` **from**: `Date` - -Defined in: [interfaces.ts:117](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L117) - -*** - -### orderDirection? - -> `optional` **orderDirection**: [`OrderDirection`](../../enums/enumerations/OrderDirection.md) - -Defined in: [interfaces.ts:166](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L166) - -#### Inherited from - -[`IPagination`](IPagination.md).[`orderDirection`](IPagination.md#orderdirection) - -*** - -### recipient? - -> `optional` **recipient**: `string` - -Defined in: [interfaces.ts:116](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L116) - -*** - -### skip? - -> `optional` **skip**: `number` - -Defined in: [interfaces.ts:165](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L165) - -#### Inherited from - -[`IPagination`](IPagination.md).[`skip`](IPagination.md#skip) - -*** - -### to? - -> `optional` **to**: `Date` - -Defined in: [interfaces.ts:118](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L118) diff --git a/docs/sdk/typescript/interfaces/interfaces/IReputationNetwork.md b/docs/sdk/typescript/interfaces/interfaces/IReputationNetwork.md deleted file mode 100644 index e31e857b8f..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IReputationNetwork.md +++ /dev/null @@ -1,33 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IReputationNetwork - -# Interface: IReputationNetwork - -Defined in: [interfaces.ts:40](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L40) - -## Properties - -### address - -> **address**: `string` - -Defined in: [interfaces.ts:42](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L42) - -*** - -### id - -> **id**: `string` - -Defined in: [interfaces.ts:41](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L41) - -*** - -### operators - -> **operators**: [`IOperator`](IOperator.md)[] - -Defined in: [interfaces.ts:43](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L43) diff --git a/docs/sdk/typescript/interfaces/interfaces/IReward.md b/docs/sdk/typescript/interfaces/interfaces/IReward.md deleted file mode 100644 index a88ede941c..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IReward.md +++ /dev/null @@ -1,25 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IReward - -# Interface: IReward - -Defined in: [interfaces.ts:4](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L4) - -## Properties - -### amount - -> **amount**: `bigint` - -Defined in: [interfaces.ts:6](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L6) - -*** - -### escrowAddress - -> **escrowAddress**: `string` - -Defined in: [interfaces.ts:5](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L5) diff --git a/docs/sdk/typescript/interfaces/interfaces/IStaker.md b/docs/sdk/typescript/interfaces/interfaces/IStaker.md deleted file mode 100644 index f93db8d21d..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IStaker.md +++ /dev/null @@ -1,65 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IStaker - -# Interface: IStaker - -Defined in: [interfaces.ts:197](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L197) - -## Properties - -### address - -> **address**: `string` - -Defined in: [interfaces.ts:198](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L198) - -*** - -### lastDepositTimestamp - -> **lastDepositTimestamp**: `number` - -Defined in: [interfaces.ts:204](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L204) - -*** - -### lockedAmount - -> **lockedAmount**: `bigint` - -Defined in: [interfaces.ts:200](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L200) - -*** - -### lockedUntil - -> **lockedUntil**: `number` - -Defined in: [interfaces.ts:203](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L203) - -*** - -### slashedAmount - -> **slashedAmount**: `bigint` - -Defined in: [interfaces.ts:202](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L202) - -*** - -### stakedAmount - -> **stakedAmount**: `bigint` - -Defined in: [interfaces.ts:199](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L199) - -*** - -### withdrawableAmount - -> **withdrawableAmount**: `bigint` - -Defined in: [interfaces.ts:201](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L201) diff --git a/docs/sdk/typescript/interfaces/interfaces/IStakersFilter.md b/docs/sdk/typescript/interfaces/interfaces/IStakersFilter.md deleted file mode 100644 index f9d3aa5a99..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IStakersFilter.md +++ /dev/null @@ -1,129 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IStakersFilter - -# Interface: IStakersFilter - -Defined in: [interfaces.ts:207](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L207) - -## Extends - -- [`IPagination`](IPagination.md) - -## Properties - -### chainId - -> **chainId**: [`ChainId`](../../enums/enumerations/ChainId.md) - -Defined in: [interfaces.ts:208](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L208) - -*** - -### first? - -> `optional` **first**: `number` - -Defined in: [interfaces.ts:164](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L164) - -#### Inherited from - -[`IPagination`](IPagination.md).[`first`](IPagination.md#first) - -*** - -### maxLockedAmount? - -> `optional` **maxLockedAmount**: `string` - -Defined in: [interfaces.ts:212](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L212) - -*** - -### maxSlashedAmount? - -> `optional` **maxSlashedAmount**: `string` - -Defined in: [interfaces.ts:216](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L216) - -*** - -### maxStakedAmount? - -> `optional` **maxStakedAmount**: `string` - -Defined in: [interfaces.ts:210](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L210) - -*** - -### maxWithdrawnAmount? - -> `optional` **maxWithdrawnAmount**: `string` - -Defined in: [interfaces.ts:214](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L214) - -*** - -### minLockedAmount? - -> `optional` **minLockedAmount**: `string` - -Defined in: [interfaces.ts:211](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L211) - -*** - -### minSlashedAmount? - -> `optional` **minSlashedAmount**: `string` - -Defined in: [interfaces.ts:215](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L215) - -*** - -### minStakedAmount? - -> `optional` **minStakedAmount**: `string` - -Defined in: [interfaces.ts:209](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L209) - -*** - -### minWithdrawnAmount? - -> `optional` **minWithdrawnAmount**: `string` - -Defined in: [interfaces.ts:213](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L213) - -*** - -### orderBy? - -> `optional` **orderBy**: `"stakedAmount"` \| `"lockedAmount"` \| `"withdrawnAmount"` \| `"slashedAmount"` \| `"lastDepositTimestamp"` - -Defined in: [interfaces.ts:217](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L217) - -*** - -### orderDirection? - -> `optional` **orderDirection**: [`OrderDirection`](../../enums/enumerations/OrderDirection.md) - -Defined in: [interfaces.ts:166](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L166) - -#### Inherited from - -[`IPagination`](IPagination.md).[`orderDirection`](IPagination.md#orderdirection) - -*** - -### skip? - -> `optional` **skip**: `number` - -Defined in: [interfaces.ts:165](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L165) - -#### Inherited from - -[`IPagination`](IPagination.md).[`skip`](IPagination.md#skip) diff --git a/docs/sdk/typescript/interfaces/interfaces/IStatisticsFilter.md b/docs/sdk/typescript/interfaces/interfaces/IStatisticsFilter.md deleted file mode 100644 index 263048e88d..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IStatisticsFilter.md +++ /dev/null @@ -1,65 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IStatisticsFilter - -# Interface: IStatisticsFilter - -Defined in: [interfaces.ts:104](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L104) - -## Extends - -- [`IPagination`](IPagination.md) - -## Properties - -### first? - -> `optional` **first**: `number` - -Defined in: [interfaces.ts:164](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L164) - -#### Inherited from - -[`IPagination`](IPagination.md).[`first`](IPagination.md#first) - -*** - -### from? - -> `optional` **from**: `Date` - -Defined in: [interfaces.ts:105](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L105) - -*** - -### orderDirection? - -> `optional` **orderDirection**: [`OrderDirection`](../../enums/enumerations/OrderDirection.md) - -Defined in: [interfaces.ts:166](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L166) - -#### Inherited from - -[`IPagination`](IPagination.md).[`orderDirection`](IPagination.md#orderdirection) - -*** - -### skip? - -> `optional` **skip**: `number` - -Defined in: [interfaces.ts:165](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L165) - -#### Inherited from - -[`IPagination`](IPagination.md).[`skip`](IPagination.md#skip) - -*** - -### to? - -> `optional` **to**: `Date` - -Defined in: [interfaces.ts:106](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L106) diff --git a/docs/sdk/typescript/interfaces/interfaces/IStatusEvent.md b/docs/sdk/typescript/interfaces/interfaces/IStatusEvent.md deleted file mode 100644 index 21910c67da..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IStatusEvent.md +++ /dev/null @@ -1,41 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IStatusEvent - -# Interface: IStatusEvent - -Defined in: [interfaces.ts:285](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L285) - -## Properties - -### chainId - -> **chainId**: [`ChainId`](../../enums/enumerations/ChainId.md) - -Defined in: [interfaces.ts:289](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L289) - -*** - -### escrowAddress - -> **escrowAddress**: `string` - -Defined in: [interfaces.ts:287](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L287) - -*** - -### status - -> **status**: [`EscrowStatus`](../../types/enumerations/EscrowStatus.md) - -Defined in: [interfaces.ts:288](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L288) - -*** - -### timestamp - -> **timestamp**: `number` - -Defined in: [interfaces.ts:286](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L286) diff --git a/docs/sdk/typescript/interfaces/interfaces/IStatusEventFilter.md b/docs/sdk/typescript/interfaces/interfaces/IStatusEventFilter.md deleted file mode 100644 index 86b812d8d0..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IStatusEventFilter.md +++ /dev/null @@ -1,89 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IStatusEventFilter - -# Interface: IStatusEventFilter - -Defined in: [interfaces.ts:176](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L176) - -## Extends - -- [`IPagination`](IPagination.md) - -## Properties - -### chainId - -> **chainId**: [`ChainId`](../../enums/enumerations/ChainId.md) - -Defined in: [interfaces.ts:177](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L177) - -*** - -### first? - -> `optional` **first**: `number` - -Defined in: [interfaces.ts:164](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L164) - -#### Inherited from - -[`IPagination`](IPagination.md).[`first`](IPagination.md#first) - -*** - -### from? - -> `optional` **from**: `Date` - -Defined in: [interfaces.ts:179](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L179) - -*** - -### launcher? - -> `optional` **launcher**: `string` - -Defined in: [interfaces.ts:181](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L181) - -*** - -### orderDirection? - -> `optional` **orderDirection**: [`OrderDirection`](../../enums/enumerations/OrderDirection.md) - -Defined in: [interfaces.ts:166](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L166) - -#### Inherited from - -[`IPagination`](IPagination.md).[`orderDirection`](IPagination.md#orderdirection) - -*** - -### skip? - -> `optional` **skip**: `number` - -Defined in: [interfaces.ts:165](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L165) - -#### Inherited from - -[`IPagination`](IPagination.md).[`skip`](IPagination.md#skip) - -*** - -### statuses? - -> `optional` **statuses**: [`EscrowStatus`](../../types/enumerations/EscrowStatus.md)[] - -Defined in: [interfaces.ts:178](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L178) - -*** - -### to? - -> `optional` **to**: `Date` - -Defined in: [interfaces.ts:180](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L180) diff --git a/docs/sdk/typescript/interfaces/interfaces/ITransaction.md b/docs/sdk/typescript/interfaces/interfaces/ITransaction.md deleted file mode 100644 index 9481267b97..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/ITransaction.md +++ /dev/null @@ -1,97 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / ITransaction - -# Interface: ITransaction - -Defined in: [interfaces.ts:136](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L136) - -## Properties - -### block - -> **block**: `bigint` - -Defined in: [interfaces.ts:137](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L137) - -*** - -### escrow - -> **escrow**: `string` \| `null` - -Defined in: [interfaces.ts:145](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L145) - -*** - -### from - -> **from**: `string` - -Defined in: [interfaces.ts:139](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L139) - -*** - -### internalTransactions - -> **internalTransactions**: [`InternalTransaction`](InternalTransaction.md)[] - -Defined in: [interfaces.ts:147](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L147) - -*** - -### method - -> **method**: `string` - -Defined in: [interfaces.ts:143](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L143) - -*** - -### receiver - -> **receiver**: `string` \| `null` - -Defined in: [interfaces.ts:144](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L144) - -*** - -### timestamp - -> **timestamp**: `number` - -Defined in: [interfaces.ts:141](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L141) - -*** - -### to - -> **to**: `string` - -Defined in: [interfaces.ts:140](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L140) - -*** - -### token - -> **token**: `string` \| `null` - -Defined in: [interfaces.ts:146](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L146) - -*** - -### txHash - -> **txHash**: `string` - -Defined in: [interfaces.ts:138](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L138) - -*** - -### value - -> **value**: `bigint` - -Defined in: [interfaces.ts:142](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L142) diff --git a/docs/sdk/typescript/interfaces/interfaces/ITransactionsFilter.md b/docs/sdk/typescript/interfaces/interfaces/ITransactionsFilter.md deleted file mode 100644 index 425de8a393..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/ITransactionsFilter.md +++ /dev/null @@ -1,129 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / ITransactionsFilter - -# Interface: ITransactionsFilter - -Defined in: [interfaces.ts:150](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L150) - -## Extends - -- [`IPagination`](IPagination.md) - -## Properties - -### chainId - -> **chainId**: [`ChainId`](../../enums/enumerations/ChainId.md) - -Defined in: [interfaces.ts:151](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L151) - -*** - -### endBlock? - -> `optional` **endBlock**: `number` - -Defined in: [interfaces.ts:153](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L153) - -*** - -### endDate? - -> `optional` **endDate**: `Date` - -Defined in: [interfaces.ts:155](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L155) - -*** - -### escrow? - -> `optional` **escrow**: `string` - -Defined in: [interfaces.ts:159](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L159) - -*** - -### first? - -> `optional` **first**: `number` - -Defined in: [interfaces.ts:164](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L164) - -#### Inherited from - -[`IPagination`](IPagination.md).[`first`](IPagination.md#first) - -*** - -### fromAddress? - -> `optional` **fromAddress**: `string` - -Defined in: [interfaces.ts:156](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L156) - -*** - -### method? - -> `optional` **method**: `string` - -Defined in: [interfaces.ts:158](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L158) - -*** - -### orderDirection? - -> `optional` **orderDirection**: [`OrderDirection`](../../enums/enumerations/OrderDirection.md) - -Defined in: [interfaces.ts:166](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L166) - -#### Inherited from - -[`IPagination`](IPagination.md).[`orderDirection`](IPagination.md#orderdirection) - -*** - -### skip? - -> `optional` **skip**: `number` - -Defined in: [interfaces.ts:165](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L165) - -#### Inherited from - -[`IPagination`](IPagination.md).[`skip`](IPagination.md#skip) - -*** - -### startBlock? - -> `optional` **startBlock**: `number` - -Defined in: [interfaces.ts:152](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L152) - -*** - -### startDate? - -> `optional` **startDate**: `Date` - -Defined in: [interfaces.ts:154](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L154) - -*** - -### toAddress? - -> `optional` **toAddress**: `string` - -Defined in: [interfaces.ts:157](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L157) - -*** - -### token? - -> `optional` **token**: `string` - -Defined in: [interfaces.ts:160](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L160) diff --git a/docs/sdk/typescript/interfaces/interfaces/IWorker.md b/docs/sdk/typescript/interfaces/interfaces/IWorker.md deleted file mode 100644 index f6bbe9d7ca..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IWorker.md +++ /dev/null @@ -1,41 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IWorker - -# Interface: IWorker - -Defined in: [interfaces.ts:184](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L184) - -## Properties - -### address - -> **address**: `string` - -Defined in: [interfaces.ts:186](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L186) - -*** - -### id - -> **id**: `string` - -Defined in: [interfaces.ts:185](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L185) - -*** - -### payoutCount - -> **payoutCount**: `number` - -Defined in: [interfaces.ts:188](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L188) - -*** - -### totalHMTAmountReceived - -> **totalHMTAmountReceived**: `bigint` - -Defined in: [interfaces.ts:187](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L187) diff --git a/docs/sdk/typescript/interfaces/interfaces/IWorkerStatistics.md b/docs/sdk/typescript/interfaces/interfaces/IWorkerStatistics.md deleted file mode 100644 index d18cbdc5a9..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IWorkerStatistics.md +++ /dev/null @@ -1,17 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IWorkerStatistics - -# Interface: IWorkerStatistics - -Defined in: [interfaces.ts:251](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L251) - -## Properties - -### dailyWorkersData - -> **dailyWorkersData**: [`IDailyWorker`](IDailyWorker.md)[] - -Defined in: [interfaces.ts:252](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L252) diff --git a/docs/sdk/typescript/interfaces/interfaces/IWorkersFilter.md b/docs/sdk/typescript/interfaces/interfaces/IWorkersFilter.md deleted file mode 100644 index 9a2f129882..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/IWorkersFilter.md +++ /dev/null @@ -1,73 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / IWorkersFilter - -# Interface: IWorkersFilter - -Defined in: [interfaces.ts:191](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L191) - -## Extends - -- [`IPagination`](IPagination.md) - -## Properties - -### address? - -> `optional` **address**: `string` - -Defined in: [interfaces.ts:193](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L193) - -*** - -### chainId - -> **chainId**: [`ChainId`](../../enums/enumerations/ChainId.md) - -Defined in: [interfaces.ts:192](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L192) - -*** - -### first? - -> `optional` **first**: `number` - -Defined in: [interfaces.ts:164](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L164) - -#### Inherited from - -[`IPagination`](IPagination.md).[`first`](IPagination.md#first) - -*** - -### orderBy? - -> `optional` **orderBy**: `string` - -Defined in: [interfaces.ts:194](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L194) - -*** - -### orderDirection? - -> `optional` **orderDirection**: [`OrderDirection`](../../enums/enumerations/OrderDirection.md) - -Defined in: [interfaces.ts:166](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L166) - -#### Inherited from - -[`IPagination`](IPagination.md).[`orderDirection`](IPagination.md#orderdirection) - -*** - -### skip? - -> `optional` **skip**: `number` - -Defined in: [interfaces.ts:165](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L165) - -#### Inherited from - -[`IPagination`](IPagination.md).[`skip`](IPagination.md#skip) diff --git a/docs/sdk/typescript/interfaces/interfaces/InternalTransaction.md b/docs/sdk/typescript/interfaces/interfaces/InternalTransaction.md deleted file mode 100644 index b55dfbfd6e..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/InternalTransaction.md +++ /dev/null @@ -1,65 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / InternalTransaction - -# Interface: InternalTransaction - -Defined in: [interfaces.ts:126](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L126) - -## Properties - -### escrow - -> **escrow**: `string` \| `null` - -Defined in: [interfaces.ts:132](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L132) - -*** - -### from - -> **from**: `string` - -Defined in: [interfaces.ts:127](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L127) - -*** - -### method - -> **method**: `string` - -Defined in: [interfaces.ts:130](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L130) - -*** - -### receiver - -> **receiver**: `string` \| `null` - -Defined in: [interfaces.ts:131](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L131) - -*** - -### to - -> **to**: `string` - -Defined in: [interfaces.ts:128](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L128) - -*** - -### token - -> **token**: `string` \| `null` - -Defined in: [interfaces.ts:133](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L133) - -*** - -### value - -> **value**: `bigint` - -Defined in: [interfaces.ts:129](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L129) diff --git a/docs/sdk/typescript/interfaces/interfaces/StakerInfo.md b/docs/sdk/typescript/interfaces/interfaces/StakerInfo.md deleted file mode 100644 index 6ae97c9b48..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/StakerInfo.md +++ /dev/null @@ -1,41 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / StakerInfo - -# Interface: StakerInfo - -Defined in: [interfaces.ts:169](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L169) - -## Properties - -### lockedAmount - -> **lockedAmount**: `bigint` - -Defined in: [interfaces.ts:171](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L171) - -*** - -### lockedUntil - -> **lockedUntil**: `bigint` - -Defined in: [interfaces.ts:172](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L172) - -*** - -### stakedAmount - -> **stakedAmount**: `bigint` - -Defined in: [interfaces.ts:170](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L170) - -*** - -### withdrawableAmount - -> **withdrawableAmount**: `bigint` - -Defined in: [interfaces.ts:173](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L173) diff --git a/docs/sdk/typescript/interfaces/interfaces/SubgraphOptions.md b/docs/sdk/typescript/interfaces/interfaces/SubgraphOptions.md deleted file mode 100644 index 4cf671b12d..0000000000 --- a/docs/sdk/typescript/interfaces/interfaces/SubgraphOptions.md +++ /dev/null @@ -1,42 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [interfaces](../README.md) / SubgraphOptions - -# Interface: SubgraphOptions - -Defined in: [interfaces.ts:319](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L319) - -Configuration options for subgraph requests with retry logic. - -## Properties - -### baseDelay? - -> `optional` **baseDelay**: `number` - -Defined in: [interfaces.ts:323](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L323) - -Base delay between retries in milliseconds - -*** - -### indexerId? - -> `optional` **indexerId**: `string` - -Defined in: [interfaces.ts:328](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L328) - -Optional indexer identifier. When provided, requests target -`{gateway}/deployments/id//indexers/id/`. - -*** - -### maxRetries? - -> `optional` **maxRetries**: `number` - -Defined in: [interfaces.ts:321](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts#L321) - -Maximum number of retry attempts diff --git a/docs/sdk/typescript/kvstore/README.md b/docs/sdk/typescript/kvstore/README.md deleted file mode 100644 index e2a5d8f801..0000000000 --- a/docs/sdk/typescript/kvstore/README.md +++ /dev/null @@ -1,12 +0,0 @@ -[**@human-protocol/sdk**](../README.md) - -*** - -[@human-protocol/sdk](../modules.md) / kvstore - -# kvstore - -## Classes - -- [KVStoreClient](classes/KVStoreClient.md) -- [KVStoreUtils](classes/KVStoreUtils.md) diff --git a/docs/sdk/typescript/kvstore/classes/KVStoreClient.md b/docs/sdk/typescript/kvstore/classes/KVStoreClient.md deleted file mode 100644 index d27b0651c1..0000000000 --- a/docs/sdk/typescript/kvstore/classes/KVStoreClient.md +++ /dev/null @@ -1,378 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [kvstore](../README.md) / KVStoreClient - -# Class: KVStoreClient - -Defined in: [kvstore.ts:98](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L98) - -## Introduction - -This client enables performing actions on KVStore contract and obtaining information from both the contracts and subgraph. - -Internally, the SDK will use one network or another according to the network ID of the `runner`. -To use this client, it is recommended to initialize it using the static `build` method. - -```ts -static async build(runner: ContractRunner): Promise; -``` - -A `Signer` or a `Provider` should be passed depending on the use case of this module: - -- **Signer**: when the user wants to use this model to send transactions calling the contract functions. -- **Provider**: when the user wants to use this model to get information from the contracts or subgraph. - -## Installation - -### npm -```bash -npm install @human-protocol/sdk -``` - -### yarn -```bash -yarn install @human-protocol/sdk -``` - -## Code example - -### Signer - -**Using private key (backend)** - -```ts -import { KVStoreClient } from '@human-protocol/sdk'; -import { Wallet, providers } from 'ethers'; - -const rpcUrl = 'YOUR_RPC_URL'; -const privateKey = 'YOUR_PRIVATE_KEY'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const signer = new Wallet(privateKey, provider); -const kvstoreClient = await KVStoreClient.build(signer); -``` - -**Using Wagmi (frontend)** - -```ts -import { useSigner, useChainId } from 'wagmi'; -import { KVStoreClient } from '@human-protocol/sdk'; - -const { data: signer } = useSigner(); -const kvstoreClient = await KVStoreClient.build(signer); -``` - -### Provider - -```ts -import { KVStoreClient } from '@human-protocol/sdk'; -import { providers } from 'ethers'; - -const rpcUrl = 'YOUR_RPC_URL'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const kvstoreClient = await KVStoreClient.build(provider); -``` - -## Extends - -- [`BaseEthersClient`](../../base/classes/BaseEthersClient.md) - -## Constructors - -### Constructor - -> **new KVStoreClient**(`runner`, `networkData`): `KVStoreClient` - -Defined in: [kvstore.ts:107](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L107) - -**KVStoreClient constructor** - -#### Parameters - -##### runner - -`ContractRunner` - -The Runner object to interact with the Ethereum network - -##### networkData - -[`NetworkData`](../../types/type-aliases/NetworkData.md) - -The network information required to connect to the KVStore contract - -#### Returns - -`KVStoreClient` - -#### Overrides - -[`BaseEthersClient`](../../base/classes/BaseEthersClient.md).[`constructor`](../../base/classes/BaseEthersClient.md#constructor) - -## Properties - -### networkData - -> **networkData**: [`NetworkData`](../../types/type-aliases/NetworkData.md) - -Defined in: [base.ts:12](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) - -#### Inherited from - -[`BaseEthersClient`](../../base/classes/BaseEthersClient.md).[`networkData`](../../base/classes/BaseEthersClient.md#networkdata) - -*** - -### runner - -> `protected` **runner**: `ContractRunner` - -Defined in: [base.ts:11](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) - -#### Inherited from - -[`BaseEthersClient`](../../base/classes/BaseEthersClient.md).[`runner`](../../base/classes/BaseEthersClient.md#runner) - -## Methods - -### get() - -> **get**(`address`, `key`): `Promise`\<`string`\> - -Defined in: [kvstore.ts:308](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L308) - -Gets the value of a key-value pair in the contract. - -#### Parameters - -##### address - -`string` - -Address from which to get the key value. - -##### key - -`string` - -Key to obtain the value. - -#### Returns - -`Promise`\<`string`\> - -Value of the key. - -**Code example** - -> Need to have available stake. - -```ts -import { providers } from 'ethers'; -import { KVStoreClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const kvstoreClient = await KVStoreClient.build(provider); - -const value = await kvstoreClient.get('0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', 'Role'); -``` - -*** - -### set() - -> **set**(`key`, `value`, `txOptions?`): `Promise`\<`void`\> - -Defined in: [kvstore.ts:170](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L170) - -This function sets a key-value pair associated with the address that submits the transaction. - -#### Parameters - -##### key - -`string` - -Key of the key-value pair - -##### value - -`string` - -Value of the key-value pair - -##### txOptions? - -`Overrides` = `{}` - -Additional transaction parameters (optional, defaults to an empty object). - -#### Returns - -`Promise`\<`void`\> - -Returns void if successful. Throws error if any. - -**Code example** - -> Need to have available stake. - -```ts -import { Wallet, providers } from 'ethers'; -import { KVStoreClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; -const privateKey = 'YOUR_PRIVATE_KEY'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const signer = new Wallet(privateKey, provider); -const kvstoreClient = await KVStoreClient.build(signer); - -await kvstoreClient.set('Role', 'RecordingOracle'); -``` - -*** - -### setBulk() - -> **setBulk**(`keys`, `values`, `txOptions?`): `Promise`\<`void`\> - -Defined in: [kvstore.ts:213](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L213) - -This function sets key-value pairs in bulk associated with the address that submits the transaction. - -#### Parameters - -##### keys - -`string`[] - -Array of keys (keys and value must have the same order) - -##### values - -`string`[] - -Array of values - -##### txOptions? - -`Overrides` = `{}` - -Additional transaction parameters (optional, defaults to an empty object). - -#### Returns - -`Promise`\<`void`\> - -Returns void if successful. Throws error if any. - -**Code example** - -> Need to have available stake. - -```ts -import { Wallet, providers } from 'ethers'; -import { KVStoreClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; -const privateKey = 'YOUR_PRIVATE_KEY'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const signer = new Wallet(privateKey, provider); -const kvstoreClient = await KVStoreClient.build(signer); - -const keys = ['role', 'webhook_url']; -const values = ['RecordingOracle', 'http://localhost']; -await kvstoreClient.setBulk(keys, values); -``` - -*** - -### setFileUrlAndHash() - -> **setFileUrlAndHash**(`url`, `urlKey`, `txOptions?`): `Promise`\<`void`\> - -Defined in: [kvstore.ts:256](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L256) - -Sets a URL value for the address that submits the transaction, and its hash. - -#### Parameters - -##### url - -`string` - -URL to set - -##### urlKey - -`string` = `'url'` - -Configurable URL key. `url` by default. - -##### txOptions? - -`Overrides` = `{}` - -Additional transaction parameters (optional, defaults to an empty object). - -#### Returns - -`Promise`\<`void`\> - -Returns void if successful. Throws error if any. - -**Code example** - -```ts -import { Wallet, providers } from 'ethers'; -import { KVStoreClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; -const privateKey = 'YOUR_PRIVATE_KEY'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const signer = new Wallet(privateKey, provider); -const kvstoreClient = await KVStoreClient.build(signer); - -await kvstoreClient.setFileUrlAndHash('example.com'); -await kvstoreClient.setFileUrlAndHash('linkedin.com/example', 'linkedin_url'); -``` - -*** - -### build() - -> `static` **build**(`runner`): `Promise`\<`KVStoreClient`\> - -Defined in: [kvstore.ts:125](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L125) - -Creates an instance of KVStoreClient from a runner. - -#### Parameters - -##### runner - -`ContractRunner` - -The Runner object to interact with the Ethereum network - -#### Returns - -`Promise`\<`KVStoreClient`\> - -- An instance of KVStoreClient - -#### Throws - -- Thrown if the provider does not exist for the provided Signer - -#### Throws - -- Thrown if the network's chainId is not supported diff --git a/docs/sdk/typescript/kvstore/classes/KVStoreUtils.md b/docs/sdk/typescript/kvstore/classes/KVStoreUtils.md deleted file mode 100644 index 0f3f3bd30a..0000000000 --- a/docs/sdk/typescript/kvstore/classes/KVStoreUtils.md +++ /dev/null @@ -1,270 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [kvstore](../README.md) / KVStoreUtils - -# Class: KVStoreUtils - -Defined in: [kvstore.ts:354](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L354) - -## Introduction - -Utility class for KVStore-related operations. - -## Installation - -### npm -```bash -npm install @human-protocol/sdk -``` - -### yarn -```bash -yarn install @human-protocol/sdk -``` - -## Code example - -### Signer - -**Using private key (backend)** - -```ts -import { ChainId, KVStoreUtils } from '@human-protocol/sdk'; - -const KVStoreAddresses = await KVStoreUtils.getKVStoreData( - ChainId.POLYGON_AMOY, - "0x1234567890123456789012345678901234567890" -); -``` - -## Constructors - -### Constructor - -> **new KVStoreUtils**(): `KVStoreUtils` - -#### Returns - -`KVStoreUtils` - -## Methods - -### get() - -> `static` **get**(`chainId`, `address`, `key`, `options?`): `Promise`\<`string`\> - -Defined in: [kvstore.ts:429](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L429) - -Gets the value of a key-value pair in the KVStore using the subgraph. - -#### Parameters - -##### chainId - -[`ChainId`](../../enums/enumerations/ChainId.md) - -Network in which the KVStore is deployed - -##### address - -`string` - -Address from which to get the key value. - -##### key - -`string` - -Key to obtain the value. - -##### options? - -[`SubgraphOptions`](../../interfaces/interfaces/SubgraphOptions.md) - -Optional configuration for subgraph requests. - -#### Returns - -`Promise`\<`string`\> - -Value of the key. - -#### Throws - -- Thrown if the network's chainId is not supported - -#### Throws - -- Thrown if the Address sent is invalid - -#### Throws - -- Thrown if the key is empty - -**Code example** - -```ts -import { ChainId, KVStoreUtils } from '@human-protocol/sdk'; - -const chainId = ChainId.POLYGON_AMOY; -const address = '0x1234567890123456789012345678901234567890'; -const key = 'role'; - -const value = await KVStoreUtils.get(chainId, address, key); -console.log(value); -``` - -*** - -### getFileUrlAndVerifyHash() - -> `static` **getFileUrlAndVerifyHash**(`chainId`, `address`, `urlKey`, `options?`): `Promise`\<`string`\> - -Defined in: [kvstore.ts:479](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L479) - -Gets the URL value of the given entity, and verifies its hash. - -#### Parameters - -##### chainId - -[`ChainId`](../../enums/enumerations/ChainId.md) - -Network in which the KVStore is deployed - -##### address - -`string` - -Address from which to get the URL value. - -##### urlKey - -`string` = `'url'` - -Configurable URL key. `url` by default. - -##### options? - -[`SubgraphOptions`](../../interfaces/interfaces/SubgraphOptions.md) - -Optional configuration for subgraph requests. - -#### Returns - -`Promise`\<`string`\> - -URL value for the given address if it exists, and the content is valid - -**Code example** - -```ts -import { ChainId, KVStoreUtils } from '@human-protocol/sdk'; - -const chainId = ChainId.POLYGON_AMOY; -const address = '0x1234567890123456789012345678901234567890'; - -const url = await KVStoreUtils.getFileUrlAndVerifyHash(chainId, address); -console.log(url); -``` - -*** - -### getKVStoreData() - -> `static` **getKVStoreData**(`chainId`, `address`, `options?`): `Promise`\<[`IKVStore`](../../interfaces/interfaces/IKVStore.md)[]\> - -Defined in: [kvstore.ts:374](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L374) - -This function returns the KVStore data for a given address. - -#### Parameters - -##### chainId - -[`ChainId`](../../enums/enumerations/ChainId.md) - -Network in which the KVStore is deployed - -##### address - -`string` - -Address of the KVStore - -##### options? - -[`SubgraphOptions`](../../interfaces/interfaces/SubgraphOptions.md) - -Optional configuration for subgraph requests. - -#### Returns - -`Promise`\<[`IKVStore`](../../interfaces/interfaces/IKVStore.md)[]\> - -KVStore data - -#### Throws - -- Thrown if the network's chainId is not supported - -#### Throws - -- Thrown if the Address sent is invalid - -**Code example** - -```ts -import { ChainId, KVStoreUtils } from '@human-protocol/sdk'; - -const kvStoreData = await KVStoreUtils.getKVStoreData(ChainId.POLYGON_AMOY, "0x1234567890123456789012345678901234567890"); -console.log(kvStoreData); -``` - -*** - -### getPublicKey() - -> `static` **getPublicKey**(`chainId`, `address`, `options?`): `Promise`\<`string`\> - -Defined in: [kvstore.ts:540](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L540) - -Gets the public key of the given entity, and verifies its hash. - -#### Parameters - -##### chainId - -[`ChainId`](../../enums/enumerations/ChainId.md) - -Network in which the KVStore is deployed - -##### address - -`string` - -Address from which to get the public key. - -##### options? - -[`SubgraphOptions`](../../interfaces/interfaces/SubgraphOptions.md) - -#### Returns - -`Promise`\<`string`\> - -Public key for the given address if it exists, and the content is valid - -**Code example** - -```ts -import { ChainId, KVStoreUtils } from '@human-protocol/sdk'; - -const chainId = ChainId.POLYGON_AMOY; -const address = '0x1234567890123456789012345678901234567890'; - -const publicKey = await KVStoreUtils.getPublicKey(chainId, address); -console.log(publicKey); -``` diff --git a/docs/sdk/typescript/modules.md b/docs/sdk/typescript/modules.md deleted file mode 100644 index b36bd138ca..0000000000 --- a/docs/sdk/typescript/modules.md +++ /dev/null @@ -1,21 +0,0 @@ -[**@human-protocol/sdk**](README.md) - -*** - -# @human-protocol/sdk - -## Modules - -- [base](base/README.md) -- [encryption](encryption/README.md) -- [enums](enums/README.md) -- [escrow](escrow/README.md) -- [graphql/types](graphql/types/README.md) -- [interfaces](interfaces/README.md) -- [kvstore](kvstore/README.md) -- [operator](operator/README.md) -- [staking](staking/README.md) -- [statistics](statistics/README.md) -- [storage](storage/README.md) -- [transaction](transaction/README.md) -- [types](types/README.md) diff --git a/docs/sdk/typescript/operator/README.md b/docs/sdk/typescript/operator/README.md deleted file mode 100644 index 111fa065f0..0000000000 --- a/docs/sdk/typescript/operator/README.md +++ /dev/null @@ -1,11 +0,0 @@ -[**@human-protocol/sdk**](../README.md) - -*** - -[@human-protocol/sdk](../modules.md) / operator - -# operator - -## Classes - -- [OperatorUtils](classes/OperatorUtils.md) diff --git a/docs/sdk/typescript/operator/classes/OperatorUtils.md b/docs/sdk/typescript/operator/classes/OperatorUtils.md deleted file mode 100644 index 5cf1517005..0000000000 --- a/docs/sdk/typescript/operator/classes/OperatorUtils.md +++ /dev/null @@ -1,198 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [operator](../README.md) / OperatorUtils - -# Class: OperatorUtils - -Defined in: [operator.ts:29](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L29) - -## Constructors - -### Constructor - -> **new OperatorUtils**(): `OperatorUtils` - -#### Returns - -`OperatorUtils` - -## Methods - -### getOperator() - -> `static` **getOperator**(`chainId`, `address`, `options?`): `Promise`\<[`IOperator`](../../interfaces/interfaces/IOperator.md) \| `null`\> - -Defined in: [operator.ts:46](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L46) - -This function returns the operator data for the given address. - -#### Parameters - -##### chainId - -[`ChainId`](../../enums/enumerations/ChainId.md) - -Network in which the operator is deployed - -##### address - -`string` - -Operator address. - -##### options? - -[`SubgraphOptions`](../../interfaces/interfaces/SubgraphOptions.md) - -Optional configuration for subgraph requests. - -#### Returns - -`Promise`\<[`IOperator`](../../interfaces/interfaces/IOperator.md) \| `null`\> - -- Returns the operator details or null if not found. - -**Code example** - -```ts -import { OperatorUtils, ChainId } from '@human-protocol/sdk'; - -const operator = await OperatorUtils.getOperator(ChainId.POLYGON_AMOY, '0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` - -*** - -### getOperators() - -> `static` **getOperators**(`filter`, `options?`): `Promise`\<[`IOperator`](../../interfaces/interfaces/IOperator.md)[]\> - -Defined in: [operator.ts:92](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L92) - -This function returns all the operator details of the protocol. - -#### Parameters - -##### filter - -[`IOperatorsFilter`](../../interfaces/interfaces/IOperatorsFilter.md) - -Filter for the operators. - -##### options? - -[`SubgraphOptions`](../../interfaces/interfaces/SubgraphOptions.md) - -Optional configuration for subgraph requests. - -#### Returns - -`Promise`\<[`IOperator`](../../interfaces/interfaces/IOperator.md)[]\> - -Returns an array with all the operator details. - -**Code example** - -```ts -import { OperatorUtils, ChainId } from '@human-protocol/sdk'; - -const filter: IOperatorsFilter = { - chainId: ChainId.POLYGON -}; -const operators = await OperatorUtils.getOperators(filter); -``` - -*** - -### getReputationNetworkOperators() - -> `static` **getReputationNetworkOperators**(`chainId`, `address`, `role?`, `options?`): `Promise`\<[`IOperator`](../../interfaces/interfaces/IOperator.md)[]\> - -Defined in: [operator.ts:159](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L159) - -Retrieves the reputation network operators of the specified address. - -#### Parameters - -##### chainId - -[`ChainId`](../../enums/enumerations/ChainId.md) - -Network in which the reputation network is deployed - -##### address - -`string` - -Address of the reputation oracle. - -##### role? - -`string` - -(Optional) Role of the operator. - -##### options? - -[`SubgraphOptions`](../../interfaces/interfaces/SubgraphOptions.md) - -Optional configuration for subgraph requests. - -#### Returns - -`Promise`\<[`IOperator`](../../interfaces/interfaces/IOperator.md)[]\> - -- Returns an array of operator details. - -**Code example** - -```ts -import { OperatorUtils, ChainId } from '@human-protocol/sdk'; - -const operators = await OperatorUtils.getReputationNetworkOperators(ChainId.POLYGON_AMOY, '0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` - -*** - -### getRewards() - -> `static` **getRewards**(`chainId`, `slasherAddress`, `options?`): `Promise`\<[`IReward`](../../interfaces/interfaces/IReward.md)[]\> - -Defined in: [operator.ts:205](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L205) - -This function returns information about the rewards for a given slasher address. - -#### Parameters - -##### chainId - -[`ChainId`](../../enums/enumerations/ChainId.md) - -Network in which the rewards are deployed - -##### slasherAddress - -`string` - -Slasher address. - -##### options? - -[`SubgraphOptions`](../../interfaces/interfaces/SubgraphOptions.md) - -Optional configuration for subgraph requests. - -#### Returns - -`Promise`\<[`IReward`](../../interfaces/interfaces/IReward.md)[]\> - -Returns an array of Reward objects that contain the rewards earned by the user through slashing other users. - -**Code example** - -```ts -import { OperatorUtils, ChainId } from '@human-protocol/sdk'; - -const rewards = await OperatorUtils.getRewards(ChainId.POLYGON_AMOY, '0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` diff --git a/docs/sdk/typescript/staking/README.md b/docs/sdk/typescript/staking/README.md deleted file mode 100644 index 025e67e4d6..0000000000 --- a/docs/sdk/typescript/staking/README.md +++ /dev/null @@ -1,12 +0,0 @@ -[**@human-protocol/sdk**](../README.md) - -*** - -[@human-protocol/sdk](../modules.md) / staking - -# staking - -## Classes - -- [StakingClient](classes/StakingClient.md) -- [StakingUtils](classes/StakingUtils.md) diff --git a/docs/sdk/typescript/staking/classes/StakingClient.md b/docs/sdk/typescript/staking/classes/StakingClient.md deleted file mode 100644 index 63d86b550b..0000000000 --- a/docs/sdk/typescript/staking/classes/StakingClient.md +++ /dev/null @@ -1,482 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [staking](../README.md) / StakingClient - -# Class: StakingClient - -Defined in: [staking.ts:108](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L108) - -## Introduction - -This client enables performing actions on staking contracts and obtaining staking information from both the contracts and subgraph. - -Internally, the SDK will use one network or another according to the network ID of the `runner`. -To use this client, it is recommended to initialize it using the static `build` method. - -```ts -static async build(runner: ContractRunner): Promise; -``` - -A `Signer` or a `Provider` should be passed depending on the use case of this module: - -- **Signer**: when the user wants to use this model to send transactions calling the contract functions. -- **Provider**: when the user wants to use this model to get information from the contracts or subgraph. - -## Installation - -### npm -```bash -npm install @human-protocol/sdk -``` - -### yarn -```bash -yarn install @human-protocol/sdk -``` - -## Code example - -### Signer - -**Using private key (backend)** - -```ts -import { StakingClient } from '@human-protocol/sdk'; -import { Wallet, providers } from 'ethers'; - -const rpcUrl = 'YOUR_RPC_URL'; -const privateKey = 'YOUR_PRIVATE_KEY'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const signer = new Wallet(privateKey, provider); -const stakingClient = await StakingClient.build(signer); -``` - -**Using Wagmi (frontend)** - -```ts -import { useSigner, useChainId } from 'wagmi'; -import { StakingClient } from '@human-protocol/sdk'; - -const { data: signer } = useSigner(); -const stakingClient = await StakingClient.build(signer); -``` - -### Provider - -```ts -import { StakingClient } from '@human-protocol/sdk'; -import { providers } from 'ethers'; - -const rpcUrl = 'YOUR_RPC_URL'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const stakingClient = await StakingClient.build(provider); -``` - -## Extends - -- [`BaseEthersClient`](../../base/classes/BaseEthersClient.md) - -## Constructors - -### Constructor - -> **new StakingClient**(`runner`, `networkData`): `StakingClient` - -Defined in: [staking.ts:119](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L119) - -**StakingClient constructor** - -#### Parameters - -##### runner - -`ContractRunner` - -The Runner object to interact with the Ethereum network - -##### networkData - -[`NetworkData`](../../types/type-aliases/NetworkData.md) - -The network information required to connect to the Staking contract - -#### Returns - -`StakingClient` - -#### Overrides - -[`BaseEthersClient`](../../base/classes/BaseEthersClient.md).[`constructor`](../../base/classes/BaseEthersClient.md#constructor) - -## Properties - -### escrowFactoryContract - -> **escrowFactoryContract**: `EscrowFactory` - -Defined in: [staking.ts:111](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L111) - -*** - -### networkData - -> **networkData**: [`NetworkData`](../../types/type-aliases/NetworkData.md) - -Defined in: [base.ts:12](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) - -#### Inherited from - -[`BaseEthersClient`](../../base/classes/BaseEthersClient.md).[`networkData`](../../base/classes/BaseEthersClient.md#networkdata) - -*** - -### runner - -> `protected` **runner**: `ContractRunner` - -Defined in: [base.ts:11](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) - -#### Inherited from - -[`BaseEthersClient`](../../base/classes/BaseEthersClient.md).[`runner`](../../base/classes/BaseEthersClient.md#runner) - -*** - -### stakingContract - -> **stakingContract**: `Staking` - -Defined in: [staking.ts:110](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L110) - -*** - -### tokenContract - -> **tokenContract**: `HMToken` - -Defined in: [staking.ts:109](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L109) - -## Methods - -### approveStake() - -> **approveStake**(`amount`, `txOptions?`): `Promise`\<`void`\> - -Defined in: [staking.ts:204](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L204) - -This function approves the staking contract to transfer a specified amount of tokens when the user stakes. It increases the allowance for the staking contract. - -#### Parameters - -##### amount - -`bigint` - -Amount in WEI of tokens to approve for stake. - -##### txOptions? - -`Overrides` = `{}` - -Additional transaction parameters (optional, defaults to an empty object). - -#### Returns - -`Promise`\<`void`\> - -Returns void if successful. Throws error if any. - -**Code example** - -```ts -import { ethers, Wallet, providers } from 'ethers'; -import { StakingClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; -const privateKey = 'YOUR_PRIVATE_KEY'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const signer = new Wallet(privateKey, provider); -const stakingClient = await StakingClient.build(signer); - -const amount = ethers.parseUnits(5, 'ether'); //convert from ETH to WEI -await stakingClient.approveStake(amount); -``` - -*** - -### getStakerInfo() - -> **getStakerInfo**(`stakerAddress`): `Promise`\<[`StakerInfo`](../../interfaces/interfaces/StakerInfo.md)\> - -Defined in: [staking.ts:446](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L446) - -Retrieves comprehensive staking information for a staker. - -#### Parameters - -##### stakerAddress - -`string` - -The address of the staker. - -#### Returns - -`Promise`\<[`StakerInfo`](../../interfaces/interfaces/StakerInfo.md)\> - -**Code example** - -```ts -import { StakingClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const stakingClient = await StakingClient.build(provider); - -const stakingInfo = await stakingClient.getStakerInfo('0xYourStakerAddress'); -console.log(stakingInfo.tokensStaked); -``` - -*** - -### slash() - -> **slash**(`slasher`, `staker`, `escrowAddress`, `amount`, `txOptions?`): `Promise`\<`void`\> - -Defined in: [staking.ts:384](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L384) - -This function reduces the allocated amount by a staker in an escrow and transfers those tokens to the reward pool. This allows the slasher to claim them later. - -#### Parameters - -##### slasher - -`string` - -Wallet address from who requested the slash - -##### staker - -`string` - -Wallet address from who is going to be slashed - -##### escrowAddress - -`string` - -Address of the escrow that the slash is made - -##### amount - -`bigint` - -Amount in WEI of tokens to slash. - -##### txOptions? - -`Overrides` = `{}` - -Additional transaction parameters (optional, defaults to an empty object). - -#### Returns - -`Promise`\<`void`\> - -Returns void if successful. Throws error if any. - -**Code example** - -```ts -import { ethers, Wallet, providers } from 'ethers'; -import { StakingClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; -const privateKey = 'YOUR_PRIVATE_KEY'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const signer = new Wallet(privateKey, provider); -const stakingClient = await StakingClient.build(signer); - -const amount = ethers.parseUnits(5, 'ether'); //convert from ETH to WEI -await stakingClient.slash('0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', '0x62dD51230A30401C455c8398d06F85e4EaB6309f', amount); -``` - -*** - -### stake() - -> **stake**(`amount`, `txOptions?`): `Promise`\<`void`\> - -Defined in: [staking.ts:258](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L258) - -This function stakes a specified amount of tokens on a specific network. - -> `approveStake` must be called before - -#### Parameters - -##### amount - -`bigint` - -Amount in WEI of tokens to stake. - -##### txOptions? - -`Overrides` = `{}` - -Additional transaction parameters (optional, defaults to an empty object). - -#### Returns - -`Promise`\<`void`\> - -Returns void if successful. Throws error if any. - -**Code example** - -```ts -import { ethers, Wallet, providers } from 'ethers'; -import { StakingClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; -const privateKey = 'YOUR_PRIVATE_KEY'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const signer = new Wallet(privateKey, provider); -const stakingClient = await StakingClient.build(signer); - -const amount = ethers.parseUnits(5, 'ether'); //convert from ETH to WEI -await stakingClient.approveStake(amount); // if it was already approved before, this is not necessary -await stakingClient.stake(amount); -``` - -*** - -### unstake() - -> **unstake**(`amount`, `txOptions?`): `Promise`\<`void`\> - -Defined in: [staking.ts:302](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L302) - -This function unstakes tokens from staking contract. The unstaked tokens stay locked for a period of time. - -> Must have tokens available to unstake - -#### Parameters - -##### amount - -`bigint` - -Amount in WEI of tokens to unstake. - -##### txOptions? - -`Overrides` = `{}` - -Additional transaction parameters (optional, defaults to an empty object). - -#### Returns - -`Promise`\<`void`\> - -Returns void if successful. Throws error if any. - -**Code example** - -```ts -import { ethers, Wallet, providers } from 'ethers'; -import { StakingClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; -const privateKey = 'YOUR_PRIVATE_KEY'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const signer = new Wallet(privateKey, provider); -const stakingClient = await StakingClient.build(signer); - -const amount = ethers.parseUnits(5, 'ether'); //convert from ETH to WEI -await stakingClient.unstake(amount); -``` - -*** - -### withdraw() - -> **withdraw**(`txOptions?`): `Promise`\<`void`\> - -Defined in: [staking.ts:347](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L347) - -This function withdraws unstaked and non-locked tokens from staking contract to the user wallet. - -> Must have tokens available to withdraw - -#### Parameters - -##### txOptions? - -`Overrides` = `{}` - -Additional transaction parameters (optional, defaults to an empty object). - -#### Returns - -`Promise`\<`void`\> - -Returns void if successful. Throws error if any. - -**Code example** - -```ts -import { Wallet, providers } from 'ethers'; -import { StakingClient } from '@human-protocol/sdk'; - -const rpcUrl = 'YOUR_RPC_URL'; -const privateKey = 'YOUR_PRIVATE_KEY'; - -const provider = new providers.JsonRpcProvider(rpcUrl); -const signer = new Wallet(privateKey, provider); -const stakingClient = await StakingClient.build(signer); - -await stakingClient.withdraw(); -``` - -*** - -### build() - -> `static` **build**(`runner`): `Promise`\<`StakingClient`\> - -Defined in: [staking.ts:147](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L147) - -Creates an instance of StakingClient from a Runner. - -#### Parameters - -##### runner - -`ContractRunner` - -The Runner object to interact with the Ethereum network - -#### Returns - -`Promise`\<`StakingClient`\> - -- An instance of StakingClient - -#### Throws - -- Thrown if the provider does not exist for the provided Signer - -#### Throws - -- Thrown if the network's chainId is not supported diff --git a/docs/sdk/typescript/staking/classes/StakingUtils.md b/docs/sdk/typescript/staking/classes/StakingUtils.md deleted file mode 100644 index 7d60d0498a..0000000000 --- a/docs/sdk/typescript/staking/classes/StakingUtils.md +++ /dev/null @@ -1,87 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [staking](../README.md) / StakingUtils - -# Class: StakingUtils - -Defined in: [staking.ts:484](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L484) - -Utility class for Staking-related subgraph queries. - -## Constructors - -### Constructor - -> **new StakingUtils**(): `StakingUtils` - -#### Returns - -`StakingUtils` - -## Methods - -### getStaker() - -> `static` **getStaker**(`chainId`, `stakerAddress`, `options?`): `Promise`\<[`IStaker`](../../interfaces/interfaces/IStaker.md)\> - -Defined in: [staking.ts:493](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L493) - -Gets staking info for a staker from the subgraph. - -#### Parameters - -##### chainId - -[`ChainId`](../../enums/enumerations/ChainId.md) - -Network in which the staking contract is deployed - -##### stakerAddress - -`string` - -Address of the staker - -##### options? - -[`SubgraphOptions`](../../interfaces/interfaces/SubgraphOptions.md) - -Optional configuration for subgraph requests. - -#### Returns - -`Promise`\<[`IStaker`](../../interfaces/interfaces/IStaker.md)\> - -Staker info from subgraph - -*** - -### getStakers() - -> `static` **getStakers**(`filter`, `options?`): `Promise`\<[`IStaker`](../../interfaces/interfaces/IStaker.md)[]\> - -Defined in: [staking.ts:528](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L528) - -Gets all stakers from the subgraph with filters, pagination and ordering. - -#### Parameters - -##### filter - -[`IStakersFilter`](../../interfaces/interfaces/IStakersFilter.md) - -Stakers filter with pagination and ordering - -##### options? - -[`SubgraphOptions`](../../interfaces/interfaces/SubgraphOptions.md) - -Optional configuration for subgraph requests. - -#### Returns - -`Promise`\<[`IStaker`](../../interfaces/interfaces/IStaker.md)[]\> - -Array of stakers diff --git a/docs/sdk/typescript/statistics/README.md b/docs/sdk/typescript/statistics/README.md deleted file mode 100644 index e40888e983..0000000000 --- a/docs/sdk/typescript/statistics/README.md +++ /dev/null @@ -1,11 +0,0 @@ -[**@human-protocol/sdk**](../README.md) - -*** - -[@human-protocol/sdk](../modules.md) / statistics - -# statistics - -## Classes - -- [StatisticsClient](classes/StatisticsClient.md) diff --git a/docs/sdk/typescript/statistics/classes/StatisticsClient.md b/docs/sdk/typescript/statistics/classes/StatisticsClient.md deleted file mode 100644 index 67b75646e3..0000000000 --- a/docs/sdk/typescript/statistics/classes/StatisticsClient.md +++ /dev/null @@ -1,474 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [statistics](../README.md) / StatisticsClient - -# Class: StatisticsClient - -Defined in: [statistics.ts:64](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L64) - -## Introduction - -This client enables obtaining statistical information from the subgraph. - -Unlike other SDK clients, `StatisticsClient` does not require `signer` or `provider` to be provided. -We just need to create a client object using relevant network data. - -```ts -constructor(network: NetworkData) -``` - -## Installation - -### npm -```bash -npm install @human-protocol/sdk -``` - -### yarn -```bash -yarn install @human-protocol/sdk -``` - -## Code example - -```ts -import { StatisticsClient, ChainId, NETWORKS } from '@human-protocol/sdk'; - -const statisticsClient = new StatisticsClient(NETWORKS[ChainId.POLYGON_AMOY]); -``` - -## Constructors - -### Constructor - -> **new StatisticsClient**(`networkData`): `StatisticsClient` - -Defined in: [statistics.ts:73](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L73) - -**StatisticsClient constructor** - -#### Parameters - -##### networkData - -[`NetworkData`](../../types/type-aliases/NetworkData.md) - -The network information required to connect to the Statistics contract - -#### Returns - -`StatisticsClient` - -## Properties - -### networkData - -> **networkData**: [`NetworkData`](../../types/type-aliases/NetworkData.md) - -Defined in: [statistics.ts:65](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L65) - -*** - -### subgraphUrl - -> **subgraphUrl**: `string` - -Defined in: [statistics.ts:66](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L66) - -## Methods - -### getEscrowStatistics() - -> **getEscrowStatistics**(`filter`, `options?`): `Promise`\<[`IEscrowStatistics`](../../interfaces/interfaces/IEscrowStatistics.md)\> - -Defined in: [statistics.ts:127](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L127) - -This function returns the statistical data of escrows. - -**Input parameters** - -```ts -interface IStatisticsFilter { - from?: Date; - to?: Date; - first?: number; // (Optional) Number of transactions per page. Default is 10. - skip?: number; // (Optional) Number of transactions to skip. Default is 0. - orderDirection?: OrderDirection; // (Optional) Order of the results. Default is ASC. -} -``` - -```ts -interface IDailyEscrow { - timestamp: number; - escrowsTotal: number; - escrowsPending: number; - escrowsSolved: number; - escrowsPaid: number; - escrowsCancelled: number; -}; - -interface IEscrowStatistics { - totalEscrows: number; - dailyEscrowsData: IDailyEscrow[]; -}; -``` - -#### Parameters - -##### filter - -[`IStatisticsFilter`](../../interfaces/interfaces/IStatisticsFilter.md) = `{}` - -Statistics params with duration data - -##### options? - -[`SubgraphOptions`](../../interfaces/interfaces/SubgraphOptions.md) - -Optional configuration for subgraph requests. - -#### Returns - -`Promise`\<[`IEscrowStatistics`](../../interfaces/interfaces/IEscrowStatistics.md)\> - -Escrow statistics data. - -**Code example** - -```ts -import { StatisticsClient, ChainId, NETWORKS } from '@human-protocol/sdk'; - -const statisticsClient = new StatisticsClient(NETWORKS[ChainId.POLYGON_AMOY]); - -const escrowStatistics = await statisticsClient.getEscrowStatistics(); -const escrowStatisticsApril = await statisticsClient.getEscrowStatistics({ - from: new Date('2021-04-01'), - to: new Date('2021-04-30'), -}); -``` - -*** - -### getHMTDailyData() - -> **getHMTDailyData**(`filter`, `options?`): `Promise`\<[`IDailyHMT`](../../interfaces/interfaces/IDailyHMT.md)[]\> - -Defined in: [statistics.ts:510](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L510) - -This function returns the statistical data of HMToken day by day. - -**Input parameters** - -```ts -interface IStatisticsFilter { - from?: Date; - to?: Date; - first?: number; // (Optional) Number of transactions per page. Default is 10. - skip?: number; // (Optional) Number of transactions to skip. Default is 0. - orderDirection?: OrderDirection; // (Optional) Order of the results. Default is ASC. -} -``` - -```ts -interface IDailyHMT { - timestamp: number; - totalTransactionAmount: bigint; - totalTransactionCount: number; - dailyUniqueSenders: number; - dailyUniqueReceivers: number; -} -``` - -#### Parameters - -##### filter - -[`IStatisticsFilter`](../../interfaces/interfaces/IStatisticsFilter.md) = `{}` - -Statistics params with duration data - -##### options? - -[`SubgraphOptions`](../../interfaces/interfaces/SubgraphOptions.md) - -Optional configuration for subgraph requests. - -#### Returns - -`Promise`\<[`IDailyHMT`](../../interfaces/interfaces/IDailyHMT.md)[]\> - -Daily HMToken statistics data. - -**Code example** - -```ts -import { StatisticsClient, ChainId, NETWORKS } from '@human-protocol/sdk'; - -const statisticsClient = new StatisticsClient(NETWORKS[ChainId.POLYGON_AMOY]); - -const dailyHMTStats = await statisticsClient.getHMTStatistics(); - -console.log('Daily HMT statistics:', dailyHMTStats); - -const hmtStatisticsRange = await statisticsClient.getHMTStatistics({ - from: new Date(2023, 4, 8), - to: new Date(2023, 5, 8), -}); - -console.log('HMT statistics from 5/8 - 6/8:', hmtStatisticsRange); -``` - -*** - -### getHMTHolders() - -> **getHMTHolders**(`params`, `options?`): `Promise`\<[`IHMTHolder`](../../interfaces/interfaces/IHMTHolder.md)[]\> - -Defined in: [statistics.ts:434](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L434) - -This function returns the holders of the HMToken with optional filters and ordering. - -**Input parameters** - -#### Parameters - -##### params - -[`IHMTHoldersParams`](../../interfaces/interfaces/IHMTHoldersParams.md) = `{}` - -HMT Holders params with filters and ordering - -##### options? - -[`SubgraphOptions`](../../interfaces/interfaces/SubgraphOptions.md) - -Optional configuration for subgraph requests. - -#### Returns - -`Promise`\<[`IHMTHolder`](../../interfaces/interfaces/IHMTHolder.md)[]\> - -List of HMToken holders. - -**Code example** - -```ts -import { StatisticsClient, ChainId, NETWORKS } from '@human-protocol/sdk'; - -const statisticsClient = new StatisticsClient(NETWORKS[ChainId.POLYGON_AMOY]); - -const hmtHolders = await statisticsClient.getHMTHolders({ - orderDirection: 'asc', -}); - -console.log('HMT holders:', hmtHolders.map((h) => ({ - ...h, - balance: h.balance.toString(), -}))); -``` - -*** - -### getHMTStatistics() - -> **getHMTStatistics**(`options?`): `Promise`\<[`IHMTStatistics`](../../interfaces/interfaces/IHMTStatistics.md)\> - -Defined in: [statistics.ts:392](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L392) - -This function returns the statistical data of HMToken. - -```ts -interface IHMTStatistics { - totalTransferAmount: bigint; - totalTransferCount: number; - totalHolders: number; -}; -``` - -#### Parameters - -##### options? - -[`SubgraphOptions`](../../interfaces/interfaces/SubgraphOptions.md) - -Optional configuration for subgraph requests. - -#### Returns - -`Promise`\<[`IHMTStatistics`](../../interfaces/interfaces/IHMTStatistics.md)\> - -HMToken statistics data. - -**Code example** - -```ts -import { StatisticsClient, ChainId, NETWORKS } from '@human-protocol/sdk'; - -const statisticsClient = new StatisticsClient(NETWORKS[ChainId.POLYGON_AMOY]); - -const hmtStatistics = await statisticsClient.getHMTStatistics(); - -console.log('HMT statistics:', { - ...hmtStatistics, - totalTransferAmount: hmtStatistics.totalTransferAmount.toString(), -}); -``` - -*** - -### getPaymentStatistics() - -> **getPaymentStatistics**(`filter`, `options?`): `Promise`\<[`IPaymentStatistics`](../../interfaces/interfaces/IPaymentStatistics.md)\> - -Defined in: [statistics.ts:321](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L321) - -This function returns the statistical data of payments. - -**Input parameters** - -```ts -interface IStatisticsFilter { - from?: Date; - to?: Date; - first?: number; // (Optional) Number of transactions per page. Default is 10. - skip?: number; // (Optional) Number of transactions to skip. Default is 0. - orderDirection?: OrderDirection; // (Optional) Order of the results. Default is ASC. -} -``` - -```ts -interface IDailyPayment { - timestamp: number; - totalAmountPaid: bigint; - totalCount: number; - averageAmountPerWorker: bigint; -}; - -interface IPaymentStatistics { - dailyPaymentsData: IDailyPayment[]; -}; -``` - -#### Parameters - -##### filter - -[`IStatisticsFilter`](../../interfaces/interfaces/IStatisticsFilter.md) = `{}` - -Statistics params with duration data - -##### options? - -[`SubgraphOptions`](../../interfaces/interfaces/SubgraphOptions.md) - -Optional configuration for subgraph requests. - -#### Returns - -`Promise`\<[`IPaymentStatistics`](../../interfaces/interfaces/IPaymentStatistics.md)\> - -Payment statistics data. - -**Code example** - -```ts -import { StatisticsClient, ChainId, NETWORKS } from '@human-protocol/sdk'; - -const statisticsClient = new StatisticsClient(NETWORKS[ChainId.POLYGON_AMOY]); - -console.log( - 'Payment statistics:', - (await statisticsClient.getPaymentStatistics()).dailyPaymentsData.map( - (p) => ({ - ...p, - totalAmountPaid: p.totalAmountPaid.toString(), - averageAmountPerJob: p.averageAmountPerJob.toString(), - averageAmountPerWorker: p.averageAmountPerWorker.toString(), - }) - ) -); - -console.log( - 'Payment statistics from 5/8 - 6/8:', - ( - await statisticsClient.getPaymentStatistics({ - from: new Date(2023, 4, 8), - to: new Date(2023, 5, 8), - }) - ).dailyPaymentsData.map((p) => ({ - ...p, - totalAmountPaid: p.totalAmountPaid.toString(), - averageAmountPerJob: p.averageAmountPerJob.toString(), - averageAmountPerWorker: p.averageAmountPerWorker.toString(), - })) -); -``` - -*** - -### getWorkerStatistics() - -> **getWorkerStatistics**(`filter`, `options?`): `Promise`\<[`IWorkerStatistics`](../../interfaces/interfaces/IWorkerStatistics.md)\> - -Defined in: [statistics.ts:218](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L218) - -This function returns the statistical data of workers. - -**Input parameters** - -```ts -interface IStatisticsFilter { - from?: Date; - to?: Date; - first?: number; // (Optional) Number of transactions per page. Default is 10. - skip?: number; // (Optional) Number of transactions to skip. Default is 0. - orderDirection?: OrderDirection; // (Optional) Order of the results. Default is ASC. -} -``` - -```ts -interface IDailyWorker { - timestamp: number; - activeWorkers: number; -}; - -interface IWorkerStatistics { - dailyWorkersData: IDailyWorker[]; -}; -``` - -#### Parameters - -##### filter - -[`IStatisticsFilter`](../../interfaces/interfaces/IStatisticsFilter.md) = `{}` - -Statistics params with duration data - -##### options? - -[`SubgraphOptions`](../../interfaces/interfaces/SubgraphOptions.md) - -Optional configuration for subgraph requests. - -#### Returns - -`Promise`\<[`IWorkerStatistics`](../../interfaces/interfaces/IWorkerStatistics.md)\> - -Worker statistics data. - -**Code example** - -```ts -import { StatisticsClient, ChainId, NETWORKS } from '@human-protocol/sdk'; - -const statisticsClient = new StatisticsClient(NETWORKS[ChainId.POLYGON_AMOY]); - -const workerStatistics = await statisticsClient.getWorkerStatistics(); -const workerStatisticsApril = await statisticsClient.getWorkerStatistics({ - from: new Date('2021-04-01'), - to: new Date('2021-04-30'), -}); -``` diff --git a/docs/sdk/typescript/storage/README.md b/docs/sdk/typescript/storage/README.md deleted file mode 100644 index c36d3267b7..0000000000 --- a/docs/sdk/typescript/storage/README.md +++ /dev/null @@ -1,11 +0,0 @@ -[**@human-protocol/sdk**](../README.md) - -*** - -[@human-protocol/sdk](../modules.md) / storage - -# storage - -## Classes - -- [~~StorageClient~~](classes/StorageClient.md) diff --git a/docs/sdk/typescript/storage/classes/StorageClient.md b/docs/sdk/typescript/storage/classes/StorageClient.md deleted file mode 100644 index f50a29d10d..0000000000 --- a/docs/sdk/typescript/storage/classes/StorageClient.md +++ /dev/null @@ -1,305 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [storage](../README.md) / StorageClient - -# ~~Class: StorageClient~~ - -Defined in: [storage.ts:63](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L63) - -## Deprecated - -StorageClient is deprecated. Use Minio.Client directly. - -## Introduction - -This client enables interacting with S3 cloud storage services like Amazon S3 Bucket, Google Cloud Storage, and others. - -The instance creation of `StorageClient` should be made using its constructor: - -```ts -constructor(params: StorageParams, credentials?: StorageCredentials) -``` - -> If credentials are not provided, it uses anonymous access to the bucket for downloading files. - -## Installation - -### npm -```bash -npm install @human-protocol/sdk -``` - -### yarn -```bash -yarn install @human-protocol/sdk -``` - -## Code example - -```ts -import { StorageClient, StorageCredentials, StorageParams } from '@human-protocol/sdk'; - -const credentials: StorageCredentials = { - accessKey: 'ACCESS_KEY', - secretKey: 'SECRET_KEY', -}; -const params: StorageParams = { - endPoint: 'http://localhost', - port: 9000, - useSSL: false, - region: 'us-east-1' -}; - -const storageClient = new StorageClient(params, credentials); -``` - -## Constructors - -### Constructor - -> **new StorageClient**(`params`, `credentials?`): `StorageClient` - -Defined in: [storage.ts:73](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L73) - -**Storage client constructor** - -#### Parameters - -##### params - -[`StorageParams`](../../types/type-aliases/StorageParams.md) - -Cloud storage params - -##### credentials? - -[`StorageCredentials`](../../types/type-aliases/StorageCredentials.md) - -Optional. Cloud storage access data. If credentials are not provided - use anonymous access to the bucket - -#### Returns - -`StorageClient` - -## Methods - -### ~~bucketExists()~~ - -> **bucketExists**(`bucket`): `Promise`\<`boolean`\> - -Defined in: [storage.ts:262](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L262) - -This function checks if a bucket exists. - -#### Parameters - -##### bucket - -`string` - -Bucket name. - -#### Returns - -`Promise`\<`boolean`\> - -Returns `true` if exists, `false` if it doesn't. - -**Code example** - -```ts -import { StorageClient, StorageCredentials, StorageParams } from '@human-protocol/sdk'; - -const credentials: StorageCredentials = { - accessKey: 'ACCESS_KEY', - secretKey: 'SECRET_KEY', -}; -const params: StorageParams = { - endPoint: 'http://localhost', - port: 9000, - useSSL: false, - region: 'us-east-1' -}; - -const storageClient = new StorageClient(params, credentials); -const exists = await storageClient.bucketExists('bucket-name'); -``` - -*** - -### ~~downloadFiles()~~ - -> **downloadFiles**(`keys`, `bucket`): `Promise`\<`any`[]\> - -Defined in: [storage.ts:112](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L112) - -This function downloads files from a bucket. - -#### Parameters - -##### keys - -`string`[] - -Array of filenames to download. - -##### bucket - -`string` - -Bucket name. - -#### Returns - -`Promise`\<`any`[]\> - -Returns an array of JSON files downloaded and parsed into objects. - -**Code example** - -```ts -import { StorageClient, StorageCredentials, StorageParams } from '@human-protocol/sdk'; - -const params: StorageParams = { - endPoint: 'http://localhost', - port: 9000, - useSSL: false, - region: 'us-east-1' -}; - -const storageClient = new StorageClient(params); - -const keys = ['file1.json', 'file2.json']; -const files = await storageClient.downloadFiles(keys, 'bucket-name'); -``` - -*** - -### ~~listObjects()~~ - -> **listObjects**(`bucket`): `Promise`\<`string`[]\> - -Defined in: [storage.ts:292](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L292) - -This function lists all file names contained in the bucket. - -#### Parameters - -##### bucket - -`string` - -Bucket name. - -#### Returns - -`Promise`\<`string`[]\> - -Returns the list of file names contained in the bucket. - -**Code example** - -```ts -import { StorageClient, StorageCredentials, StorageParams } from '@human-protocol/sdk'; - -const credentials: StorageCredentials = { - accessKey: 'ACCESS_KEY', - secretKey: 'SECRET_KEY', -}; -const params: StorageParams = { - endPoint: 'http://localhost', - port: 9000, - useSSL: false, - region: 'us-east-1' -}; - -const storageClient = new StorageClient(params, credentials); -const fileNames = await storageClient.listObjects('bucket-name'); -``` - -*** - -### ~~uploadFiles()~~ - -> **uploadFiles**(`files`, `bucket`): `Promise`\<[`UploadFile`](../../types/type-aliases/UploadFile.md)[]\> - -Defined in: [storage.ts:198](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L198) - -This function uploads files to a bucket. - -#### Parameters - -##### files - -`any`[] - -Array of objects to upload serialized into JSON. - -##### bucket - -`string` - -Bucket name. - -#### Returns - -`Promise`\<[`UploadFile`](../../types/type-aliases/UploadFile.md)[]\> - -Returns an array of uploaded file metadata. - -**Code example** - -```ts -import { StorageClient, StorageCredentials, StorageParams } from '@human-protocol/sdk'; - -const credentials: StorageCredentials = { - accessKey: 'ACCESS_KEY', - secretKey: 'SECRET_KEY', -}; -const params: StorageParams = { - endPoint: 'http://localhost', - port: 9000, - useSSL: false, - region: 'us-east-1' -}; - -const storageClient = new StorageClient(params, credentials); -const file1 = { name: 'file1', description: 'description of file1' }; -const file2 = { name: 'file2', description: 'description of file2' }; -const files = [file1, file2]; -const uploadedFiles = await storageClient.uploadFiles(files, 'bucket-name'); -``` - -*** - -### ~~downloadFileFromUrl()~~ - -> `static` **downloadFileFromUrl**(`url`): `Promise`\<`any`\> - -Defined in: [storage.ts:146](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L146) - -This function downloads files from a URL. - -#### Parameters - -##### url - -`string` - -URL of the file to download. - -#### Returns - -`Promise`\<`any`\> - -Returns the JSON file downloaded and parsed into an object. - -**Code example** - -```ts -import { StorageClient } from '@human-protocol/sdk'; - -const file = await StorageClient.downloadFileFromUrl('http://localhost/file.json'); -``` diff --git a/docs/sdk/typescript/transaction/README.md b/docs/sdk/typescript/transaction/README.md deleted file mode 100644 index 23e8276725..0000000000 --- a/docs/sdk/typescript/transaction/README.md +++ /dev/null @@ -1,11 +0,0 @@ -[**@human-protocol/sdk**](../README.md) - -*** - -[@human-protocol/sdk](../modules.md) / transaction - -# transaction - -## Classes - -- [TransactionUtils](classes/TransactionUtils.md) diff --git a/docs/sdk/typescript/transaction/classes/TransactionUtils.md b/docs/sdk/typescript/transaction/classes/TransactionUtils.md deleted file mode 100644 index 5bf2a6d329..0000000000 --- a/docs/sdk/typescript/transaction/classes/TransactionUtils.md +++ /dev/null @@ -1,184 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [transaction](../README.md) / TransactionUtils - -# Class: TransactionUtils - -Defined in: [transaction.ts:22](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts#L22) - -## Constructors - -### Constructor - -> **new TransactionUtils**(): `TransactionUtils` - -#### Returns - -`TransactionUtils` - -## Methods - -### getTransaction() - -> `static` **getTransaction**(`chainId`, `hash`, `options?`): `Promise`\<[`ITransaction`](../../interfaces/interfaces/ITransaction.md) \| `null`\> - -Defined in: [transaction.ts:67](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts#L67) - -This function returns the transaction data for the given hash. - -```ts -type ITransaction = { - block: bigint; - txHash: string; - from: string; - to: string; - timestamp: bigint; - value: bigint; - method: string; - receiver?: string; - escrow?: string; - token?: string; - internalTransactions: InternalTransaction[]; -}; -``` - -```ts -type InternalTransaction = { - from: string; - to: string; - value: bigint; - method: string; - receiver?: string; - escrow?: string; - token?: string; -}; -``` - -#### Parameters - -##### chainId - -[`ChainId`](../../enums/enumerations/ChainId.md) - -The chain ID. - -##### hash - -`string` - -The transaction hash. - -##### options? - -[`SubgraphOptions`](../../interfaces/interfaces/SubgraphOptions.md) - -Optional configuration for subgraph requests. - -#### Returns - -`Promise`\<[`ITransaction`](../../interfaces/interfaces/ITransaction.md) \| `null`\> - -- Returns the transaction details or null if not found. - -**Code example** - -```ts -import { TransactionUtils, ChainId } from '@human-protocol/sdk'; - -const transaction = await TransactionUtils.getTransaction(ChainId.POLYGON, '0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` - -*** - -### getTransactions() - -> `static` **getTransactions**(`filter`, `options?`): `Promise`\<[`ITransaction`](../../interfaces/interfaces/ITransaction.md)[]\> - -Defined in: [transaction.ts:169](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts#L169) - -This function returns all transaction details based on the provided filter. - -> This uses Subgraph - -**Input parameters** - -```ts -interface ITransactionsFilter { - chainId: ChainId; // List of chain IDs to query. - fromAddress?: string; // (Optional) The address from which transactions are sent. - toAddress?: string; // (Optional) The address to which transactions are sent. - method?: string; // (Optional) The method of the transaction to filter by. - escrow?: string; // (Optional) The escrow address to filter transactions. - token?: string; // (Optional) The token address to filter transactions. - startDate?: Date; // (Optional) The start date to filter transactions (inclusive). - endDate?: Date; // (Optional) The end date to filter transactions (inclusive). - startBlock?: number; // (Optional) The start block number to filter transactions (inclusive). - endBlock?: number; // (Optional) The end block number to filter transactions (inclusive). - first?: number; // (Optional) Number of transactions per page. Default is 10. - skip?: number; // (Optional) Number of transactions to skip. Default is 0. - orderDirection?: OrderDirection; // (Optional) Order of the results. Default is DESC. -} - -```ts -type InternalTransaction = { - from: string; - to: string; - value: bigint; - method: string; - receiver?: string; - escrow?: string; - token?: string; -}; -``` - -```ts -type ITransaction = { - block: bigint; - txHash: string; - from: string; - to: string; - timestamp: bigint; - value: bigint; - method: string; - receiver?: string; - escrow?: string; - token?: string; - internalTransactions: InternalTransaction[]; -}; -``` - -@param {ITransactionsFilter} filter Filter for the transactions. -@param {SubgraphOptions} options Optional configuration for subgraph requests. -@returns {Promise} Returns an array with all the transaction details. - -**Code example** - -```ts -import { TransactionUtils, ChainId, OrderDirection } from '@human-protocol/sdk'; - -const filter: ITransactionsFilter = { - chainId: ChainId.POLYGON, - startDate: new Date('2022-01-01'), - endDate: new Date('2022-12-31'), - first: 10, - skip: 0, - orderDirection: OrderDirection.DESC, -}; -const transactions = await TransactionUtils.getTransactions(filter); -``` - -#### Parameters - -##### filter - -[`ITransactionsFilter`](../../interfaces/interfaces/ITransactionsFilter.md) - -##### options? - -[`SubgraphOptions`](../../interfaces/interfaces/SubgraphOptions.md) - -#### Returns - -`Promise`\<[`ITransaction`](../../interfaces/interfaces/ITransaction.md)[]\> diff --git a/docs/sdk/typescript/types/README.md b/docs/sdk/typescript/types/README.md deleted file mode 100644 index aad778dd0b..0000000000 --- a/docs/sdk/typescript/types/README.md +++ /dev/null @@ -1,19 +0,0 @@ -[**@human-protocol/sdk**](../README.md) - -*** - -[@human-protocol/sdk](../modules.md) / types - -# types - -## Enumerations - -- [EscrowStatus](enumerations/EscrowStatus.md) - -## Type Aliases - -- [NetworkData](type-aliases/NetworkData.md) -- [~~StorageCredentials~~](type-aliases/StorageCredentials.md) -- [~~StorageParams~~](type-aliases/StorageParams.md) -- [TransactionLikeWithNonce](type-aliases/TransactionLikeWithNonce.md) -- [UploadFile](type-aliases/UploadFile.md) diff --git a/docs/sdk/typescript/types/enumerations/EscrowStatus.md b/docs/sdk/typescript/types/enumerations/EscrowStatus.md deleted file mode 100644 index 65a776ba14..0000000000 --- a/docs/sdk/typescript/types/enumerations/EscrowStatus.md +++ /dev/null @@ -1,81 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [types](../README.md) / EscrowStatus - -# Enumeration: EscrowStatus - -Defined in: [types.ts:8](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L8) - -Enum for escrow statuses. - -## Enumeration Members - -### Cancelled - -> **Cancelled**: `5` - -Defined in: [types.ts:32](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L32) - -Escrow is cancelled. - -*** - -### Complete - -> **Complete**: `4` - -Defined in: [types.ts:28](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L28) - -Escrow is finished. - -*** - -### Launched - -> **Launched**: `0` - -Defined in: [types.ts:12](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L12) - -Escrow is launched. - -*** - -### Paid - -> **Paid**: `3` - -Defined in: [types.ts:24](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L24) - -Escrow is fully paid. - -*** - -### Partial - -> **Partial**: `2` - -Defined in: [types.ts:20](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L20) - -Escrow is partially paid out. - -*** - -### Pending - -> **Pending**: `1` - -Defined in: [types.ts:16](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L16) - -Escrow is funded, and waiting for the results to be submitted. - -*** - -### ToCancel - -> **ToCancel**: `6` - -Defined in: [types.ts:36](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L36) - -Escrow is cancelled. diff --git a/docs/sdk/typescript/types/type-aliases/NetworkData.md b/docs/sdk/typescript/types/type-aliases/NetworkData.md deleted file mode 100644 index b3868ee662..0000000000 --- a/docs/sdk/typescript/types/type-aliases/NetworkData.md +++ /dev/null @@ -1,123 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [types](../README.md) / NetworkData - -# Type Alias: NetworkData - -> **NetworkData** = `object` - -Defined in: [types.ts:99](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L99) - -Network data - -## Properties - -### chainId - -> **chainId**: `number` - -Defined in: [types.ts:103](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L103) - -Network chain id - -*** - -### factoryAddress - -> **factoryAddress**: `string` - -Defined in: [types.ts:119](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L119) - -Escrow Factory contract address - -*** - -### hmtAddress - -> **hmtAddress**: `string` - -Defined in: [types.ts:115](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L115) - -HMT Token contract address - -*** - -### kvstoreAddress - -> **kvstoreAddress**: `string` - -Defined in: [types.ts:127](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L127) - -KVStore contract address - -*** - -### oldFactoryAddress - -> **oldFactoryAddress**: `string` - -Defined in: [types.ts:143](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L143) - -Old Escrow Factory contract address - -*** - -### oldSubgraphUrl - -> **oldSubgraphUrl**: `string` - -Defined in: [types.ts:139](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L139) - -Old subgraph URL - -*** - -### scanUrl - -> **scanUrl**: `string` - -Defined in: [types.ts:111](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L111) - -Network scanner URL - -*** - -### stakingAddress - -> **stakingAddress**: `string` - -Defined in: [types.ts:123](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L123) - -Staking contract address - -*** - -### subgraphUrl - -> **subgraphUrl**: `string` - -Defined in: [types.ts:131](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L131) - -Subgraph URL - -*** - -### subgraphUrlApiKey - -> **subgraphUrlApiKey**: `string` - -Defined in: [types.ts:135](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L135) - -Subgraph URL API key - -*** - -### title - -> **title**: `string` - -Defined in: [types.ts:107](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L107) - -Network title diff --git a/docs/sdk/typescript/types/type-aliases/StorageCredentials.md b/docs/sdk/typescript/types/type-aliases/StorageCredentials.md deleted file mode 100644 index 628674af66..0000000000 --- a/docs/sdk/typescript/types/type-aliases/StorageCredentials.md +++ /dev/null @@ -1,37 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [types](../README.md) / StorageCredentials - -# ~~Type Alias: StorageCredentials~~ - -> `readonly` **StorageCredentials** = `object` - -Defined in: [types.ts:44](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L44) - -AWS/GCP cloud storage access data - -## Deprecated - -StorageClient is deprecated. Use Minio.Client directly. - -## Properties - -### ~~accessKey~~ - -> **accessKey**: `string` - -Defined in: [types.ts:48](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L48) - -Access Key - -*** - -### ~~secretKey~~ - -> **secretKey**: `string` - -Defined in: [types.ts:52](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L52) - -Secret Key diff --git a/docs/sdk/typescript/types/type-aliases/StorageParams.md b/docs/sdk/typescript/types/type-aliases/StorageParams.md deleted file mode 100644 index 188ee87bd4..0000000000 --- a/docs/sdk/typescript/types/type-aliases/StorageParams.md +++ /dev/null @@ -1,55 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [types](../README.md) / StorageParams - -# ~~Type Alias: StorageParams~~ - -> **StorageParams** = `object` - -Defined in: [types.ts:58](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L58) - -## Deprecated - -StorageClient is deprecated. Use Minio.Client directly. - -## Properties - -### ~~endPoint~~ - -> **endPoint**: `string` - -Defined in: [types.ts:62](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L62) - -Request endPoint - -*** - -### ~~port?~~ - -> `optional` **port**: `number` - -Defined in: [types.ts:74](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L74) - -TCP/IP port number. Default value set to 80 for HTTP and 443 for HTTPs - -*** - -### ~~region?~~ - -> `optional` **region**: `string` - -Defined in: [types.ts:70](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L70) - -Region - -*** - -### ~~useSSL~~ - -> **useSSL**: `boolean` - -Defined in: [types.ts:66](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L66) - -Enable secure (HTTPS) access. Default value set to false diff --git a/docs/sdk/typescript/types/type-aliases/TransactionLikeWithNonce.md b/docs/sdk/typescript/types/type-aliases/TransactionLikeWithNonce.md deleted file mode 100644 index efa93be4e3..0000000000 --- a/docs/sdk/typescript/types/type-aliases/TransactionLikeWithNonce.md +++ /dev/null @@ -1,17 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [types](../README.md) / TransactionLikeWithNonce - -# Type Alias: TransactionLikeWithNonce - -> **TransactionLikeWithNonce** = `TransactionLike` & `object` - -Defined in: [types.ts:146](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L146) - -## Type Declaration - -### nonce - -> **nonce**: `number` diff --git a/docs/sdk/typescript/types/type-aliases/UploadFile.md b/docs/sdk/typescript/types/type-aliases/UploadFile.md deleted file mode 100644 index 22e3859877..0000000000 --- a/docs/sdk/typescript/types/type-aliases/UploadFile.md +++ /dev/null @@ -1,43 +0,0 @@ -[**@human-protocol/sdk**](../../README.md) - -*** - -[@human-protocol/sdk](../../modules.md) / [types](../README.md) / UploadFile - -# Type Alias: UploadFile - -> `readonly` **UploadFile** = `object` - -Defined in: [types.ts:81](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L81) - -Upload file data - -## Properties - -### hash - -> **hash**: `string` - -Defined in: [types.ts:93](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L93) - -Hash of uploaded object key - -*** - -### key - -> **key**: `string` - -Defined in: [types.ts:85](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L85) - -Uploaded object key - -*** - -### url - -> **url**: `string` - -Defined in: [types.ts:89](https://github.com/humanprotocol/human-protocol/blob/0661934b14ae802af3f939783433c196862268e2/packages/sdk/typescript/human-protocol-sdk/src/types.ts#L89) - -Uploaded object URL diff --git a/packages/sdk/python/human-protocol-sdk/Makefile b/packages/sdk/python/human-protocol-sdk/Makefile index de798571ca..89c7f9141d 100644 --- a/packages/sdk/python/human-protocol-sdk/Makefile +++ b/packages/sdk/python/human-protocol-sdk/Makefile @@ -29,12 +29,3 @@ publish-package: run-example: pipenv run python3 example.py - -generate-autodoc: - pipenv run sphinx-apidoc -l -e -M -o ./docs ./human_protocol_sdk */gql && rm -rf ./docs/modules.rst - -clean-doc-md: - rm -rf docs/_build && rm -rf ../../../../docs/sdk/python/* - -generate-doc-md: - make clean-doc-md && cd docs && make markdown && cp -r _build/markdown/* ../../../../../docs/sdk/python diff --git a/packages/sdk/python/human-protocol-sdk/docs/Makefile b/packages/sdk/python/human-protocol-sdk/docs/Makefile deleted file mode 100644 index a2d36df643..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -# Minimal makefile for Sphinx documentation -# - -# You can set these variables from the command line, and also -# from the environment for the first two. -SPHINXOPTS ?= -SPHINXBUILD ?= pipenv run sphinx-build -SOURCEDIR = . -BUILDDIR = _build - -# Put it first so that "make" without argument is like "make help". -help: - @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) - -.PHONY: help Makefile - -# Catch-all target: route all unknown targets to Sphinx using the new -# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). -%: Makefile - @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/packages/sdk/python/human-protocol-sdk/docs/conf.py b/packages/sdk/python/human-protocol-sdk/docs/conf.py deleted file mode 100644 index 78bde18085..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/conf.py +++ /dev/null @@ -1,54 +0,0 @@ -# Configuration file for the Sphinx documentation builder. -# -# For the full list of built-in configuration values, see the documentation: -# https://www.sphinx-doc.org/en/master/usage/configuration.html - -import os -import sys - -sys.path.insert(0, os.path.abspath("..")) - - -def skip(app, what, name, obj, would_skip, options): - if name in ("__init__",): - return False - return would_skip - - -def setup(app): - app.connect("autodoc-skip-member", skip) - - -# -- Project information ----------------------------------------------------- -# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information - -project = "human_protocol_sdk" -copyright = "2025, HUMAN Protocol" -author = "HUMAN Protocol" - -# -- General configuration --------------------------------------------------- -# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration - -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.viewcode", - "sphinx.ext.todo", - "sphinx_markdown_builder", - "sphinx_autodoc_typehints", -] - -templates_path = ["_templates"] -exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] - -language = "en" - -# -- Options for HTML output ------------------------------------------------- -# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output - -html_theme = "alabaster" -html_static_path = ["_static"] - -# -- Options for todo extension ---------------------------------------------- -# https://www.sphinx-doc.org/en/master/usage/extensions/todo.html#configuration - -todo_include_todos = True diff --git a/packages/sdk/python/human-protocol-sdk/docs/core.md b/packages/sdk/python/human-protocol-sdk/docs/core.md new file mode 100644 index 0000000000..4322e215dc --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/core.md @@ -0,0 +1,19 @@ +# Core utilities + +Shared constants, filters, decorators, and helpers used across the SDK. + +## Constants + +::: human_protocol_sdk.constants + +## Filters + +::: human_protocol_sdk.filter + +## Decorators + +::: human_protocol_sdk.decorators + +## General utilities + +::: human_protocol_sdk.utils diff --git a/packages/sdk/python/human-protocol-sdk/docs/encryption.md b/packages/sdk/python/human-protocol-sdk/docs/encryption.md new file mode 100644 index 0000000000..a74ff0a99a --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/encryption.md @@ -0,0 +1 @@ +::: human_protocol_sdk.encryption.encryption \ No newline at end of file diff --git a/packages/sdk/python/human-protocol-sdk/docs/encryption_utils.md b/packages/sdk/python/human-protocol-sdk/docs/encryption_utils.md new file mode 100644 index 0000000000..1bd4261de8 --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/encryption_utils.md @@ -0,0 +1 @@ +::: human_protocol_sdk.encryption.encryption_utils diff --git a/packages/sdk/python/human-protocol-sdk/docs/escrow_client.md b/packages/sdk/python/human-protocol-sdk/docs/escrow_client.md new file mode 100644 index 0000000000..7a82318136 --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/escrow_client.md @@ -0,0 +1 @@ +::: human_protocol_sdk.escrow.escrow_client \ No newline at end of file diff --git a/packages/sdk/python/human-protocol-sdk/docs/escrow_utils.md b/packages/sdk/python/human-protocol-sdk/docs/escrow_utils.md new file mode 100644 index 0000000000..74beb57b57 --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/escrow_utils.md @@ -0,0 +1 @@ +::: human_protocol_sdk.escrow.escrow_utils diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.agreement.bootstrap.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.agreement.bootstrap.rst deleted file mode 100644 index 753d4f78da..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.agreement.bootstrap.rst +++ /dev/null @@ -1,7 +0,0 @@ -human\_protocol\_sdk.agreement.bootstrap module -=============================================== - -.. automodule:: human_protocol_sdk.agreement.bootstrap - :members: - :undoc-members: - :show-inheritance: diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.agreement.measures.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.agreement.measures.rst deleted file mode 100644 index a7a77dca16..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.agreement.measures.rst +++ /dev/null @@ -1,7 +0,0 @@ -human\_protocol\_sdk.agreement.measures module -============================================== - -.. automodule:: human_protocol_sdk.agreement.measures - :members: - :undoc-members: - :show-inheritance: diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.agreement.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.agreement.rst deleted file mode 100644 index 02077ef7e7..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.agreement.rst +++ /dev/null @@ -1,17 +0,0 @@ -human\_protocol\_sdk.agreement package -====================================== - -.. automodule:: human_protocol_sdk.agreement - :members: - :undoc-members: - :show-inheritance: - -Submodules ----------- - -.. toctree:: - :maxdepth: 4 - - human_protocol_sdk.agreement.bootstrap - human_protocol_sdk.agreement.measures - human_protocol_sdk.agreement.utils diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.agreement.utils.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.agreement.utils.rst deleted file mode 100644 index 0ae1792d36..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.agreement.utils.rst +++ /dev/null @@ -1,7 +0,0 @@ -human\_protocol\_sdk.agreement.utils module -=========================================== - -.. automodule:: human_protocol_sdk.agreement.utils - :members: - :undoc-members: - :show-inheritance: diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.constants.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.constants.rst deleted file mode 100644 index 2d1ec1a28f..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.constants.rst +++ /dev/null @@ -1,7 +0,0 @@ -human\_protocol\_sdk.constants module -===================================== - -.. automodule:: human_protocol_sdk.constants - :members: - :undoc-members: - :show-inheritance: diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.decorators.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.decorators.rst deleted file mode 100644 index 40a6fe5c3b..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.decorators.rst +++ /dev/null @@ -1,7 +0,0 @@ -human\_protocol\_sdk.decorators module -====================================== - -.. automodule:: human_protocol_sdk.decorators - :members: - :undoc-members: - :show-inheritance: diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.encryption.encryption.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.encryption.encryption.rst deleted file mode 100644 index 0f65c3a743..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.encryption.encryption.rst +++ /dev/null @@ -1,7 +0,0 @@ -human\_protocol\_sdk.encryption.encryption module -================================================= - -.. automodule:: human_protocol_sdk.encryption.encryption - :members: - :undoc-members: - :show-inheritance: diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.encryption.encryption_utils.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.encryption.encryption_utils.rst deleted file mode 100644 index 8950eda862..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.encryption.encryption_utils.rst +++ /dev/null @@ -1,7 +0,0 @@ -human\_protocol\_sdk.encryption.encryption\_utils module -======================================================== - -.. automodule:: human_protocol_sdk.encryption.encryption_utils - :members: - :undoc-members: - :show-inheritance: diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.encryption.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.encryption.rst deleted file mode 100644 index 7feea3a095..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.encryption.rst +++ /dev/null @@ -1,16 +0,0 @@ -human\_protocol\_sdk.encryption package -======================================= - -.. automodule:: human_protocol_sdk.encryption - :members: - :undoc-members: - :show-inheritance: - -Submodules ----------- - -.. toctree:: - :maxdepth: 4 - - human_protocol_sdk.encryption.encryption - human_protocol_sdk.encryption.encryption_utils diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.escrow.escrow_client.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.escrow.escrow_client.rst deleted file mode 100644 index 5315de4f81..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.escrow.escrow_client.rst +++ /dev/null @@ -1,7 +0,0 @@ -human\_protocol\_sdk.escrow.escrow\_client module -================================================= - -.. automodule:: human_protocol_sdk.escrow.escrow_client - :members: - :undoc-members: - :show-inheritance: diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.escrow.escrow_utils.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.escrow.escrow_utils.rst deleted file mode 100644 index 283e6847b8..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.escrow.escrow_utils.rst +++ /dev/null @@ -1,7 +0,0 @@ -human\_protocol\_sdk.escrow.escrow\_utils module -================================================ - -.. automodule:: human_protocol_sdk.escrow.escrow_utils - :members: - :undoc-members: - :show-inheritance: diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.escrow.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.escrow.rst deleted file mode 100644 index 5e91589ec0..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.escrow.rst +++ /dev/null @@ -1,16 +0,0 @@ -human\_protocol\_sdk.escrow package -=================================== - -.. automodule:: human_protocol_sdk.escrow - :members: - :undoc-members: - :show-inheritance: - -Submodules ----------- - -.. toctree:: - :maxdepth: 4 - - human_protocol_sdk.escrow.escrow_client - human_protocol_sdk.escrow.escrow_utils diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.filter.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.filter.rst deleted file mode 100644 index c5d77fc6a6..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.filter.rst +++ /dev/null @@ -1,7 +0,0 @@ -human\_protocol\_sdk.filter module -================================== - -.. automodule:: human_protocol_sdk.filter - :members: - :undoc-members: - :show-inheritance: diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.kvstore.kvstore_client.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.kvstore.kvstore_client.rst deleted file mode 100644 index fbca059a94..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.kvstore.kvstore_client.rst +++ /dev/null @@ -1,7 +0,0 @@ -human\_protocol\_sdk.kvstore.kvstore\_client module -=================================================== - -.. automodule:: human_protocol_sdk.kvstore.kvstore_client - :members: - :undoc-members: - :show-inheritance: diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.kvstore.kvstore_utils.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.kvstore.kvstore_utils.rst deleted file mode 100644 index f03e99b689..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.kvstore.kvstore_utils.rst +++ /dev/null @@ -1,7 +0,0 @@ -human\_protocol\_sdk.kvstore.kvstore\_utils module -================================================== - -.. automodule:: human_protocol_sdk.kvstore.kvstore_utils - :members: - :undoc-members: - :show-inheritance: diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.kvstore.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.kvstore.rst deleted file mode 100644 index 19b2b74847..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.kvstore.rst +++ /dev/null @@ -1,16 +0,0 @@ -human\_protocol\_sdk.kvstore package -==================================== - -.. automodule:: human_protocol_sdk.kvstore - :members: - :undoc-members: - :show-inheritance: - -Submodules ----------- - -.. toctree:: - :maxdepth: 4 - - human_protocol_sdk.kvstore.kvstore_client - human_protocol_sdk.kvstore.kvstore_utils diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.legacy_encryption.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.legacy_encryption.rst deleted file mode 100644 index b769d604f8..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.legacy_encryption.rst +++ /dev/null @@ -1,7 +0,0 @@ -human\_protocol\_sdk.legacy\_encryption module -============================================== - -.. automodule:: human_protocol_sdk.legacy_encryption - :members: - :undoc-members: - :show-inheritance: diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.operator.operator_utils.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.operator.operator_utils.rst deleted file mode 100644 index 1bdfe2a4d1..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.operator.operator_utils.rst +++ /dev/null @@ -1,7 +0,0 @@ -human\_protocol\_sdk.operator.operator\_utils module -==================================================== - -.. automodule:: human_protocol_sdk.operator.operator_utils - :members: - :undoc-members: - :show-inheritance: diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.operator.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.operator.rst deleted file mode 100644 index 87470ef171..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.operator.rst +++ /dev/null @@ -1,15 +0,0 @@ -human\_protocol\_sdk.operator package -===================================== - -.. automodule:: human_protocol_sdk.operator - :members: - :undoc-members: - :show-inheritance: - -Submodules ----------- - -.. toctree:: - :maxdepth: 4 - - human_protocol_sdk.operator.operator_utils diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.rst deleted file mode 100644 index 6e7277a299..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.rst +++ /dev/null @@ -1,35 +0,0 @@ -human\_protocol\_sdk package -============================ - -.. automodule:: human_protocol_sdk - :members: - :undoc-members: - :show-inheritance: - -Subpackages ------------ - -.. toctree:: - :maxdepth: 4 - - human_protocol_sdk.agreement - human_protocol_sdk.encryption - human_protocol_sdk.escrow - human_protocol_sdk.kvstore - human_protocol_sdk.operator - human_protocol_sdk.staking - human_protocol_sdk.statistics - human_protocol_sdk.storage - human_protocol_sdk.transaction - human_protocol_sdk.worker - -Submodules ----------- - -.. toctree:: - :maxdepth: 4 - - human_protocol_sdk.constants - human_protocol_sdk.filter - human_protocol_sdk.legacy_encryption - human_protocol_sdk.utils diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.staking.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.staking.rst deleted file mode 100644 index b23caacd20..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.staking.rst +++ /dev/null @@ -1,16 +0,0 @@ -human\_protocol\_sdk.staking package -==================================== - -.. automodule:: human_protocol_sdk.staking - :members: - :undoc-members: - :show-inheritance: - -Submodules ----------- - -.. toctree:: - :maxdepth: 4 - - human_protocol_sdk.staking.staking_client - human_protocol_sdk.staking.staking_utils diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.staking.staking_client.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.staking.staking_client.rst deleted file mode 100644 index a28b650821..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.staking.staking_client.rst +++ /dev/null @@ -1,7 +0,0 @@ -human\_protocol\_sdk.staking.staking\_client module -=================================================== - -.. automodule:: human_protocol_sdk.staking.staking_client - :members: - :undoc-members: - :show-inheritance: diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.staking.staking_utils.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.staking.staking_utils.rst deleted file mode 100644 index 65cbdc1fd0..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.staking.staking_utils.rst +++ /dev/null @@ -1,7 +0,0 @@ -human\_protocol\_sdk.staking.staking\_utils module -================================================== - -.. automodule:: human_protocol_sdk.staking.staking_utils - :members: - :undoc-members: - :show-inheritance: diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.statistics.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.statistics.rst deleted file mode 100644 index c0016e8625..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.statistics.rst +++ /dev/null @@ -1,15 +0,0 @@ -human\_protocol\_sdk.statistics package -======================================= - -.. automodule:: human_protocol_sdk.statistics - :members: - :undoc-members: - :show-inheritance: - -Submodules ----------- - -.. toctree:: - :maxdepth: 4 - - human_protocol_sdk.statistics.statistics_client diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.statistics.statistics_client.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.statistics.statistics_client.rst deleted file mode 100644 index f8dea7552b..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.statistics.statistics_client.rst +++ /dev/null @@ -1,7 +0,0 @@ -human\_protocol\_sdk.statistics.statistics\_client module -========================================================= - -.. automodule:: human_protocol_sdk.statistics.statistics_client - :members: - :undoc-members: - :show-inheritance: diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.storage.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.storage.rst deleted file mode 100644 index 032db98655..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.storage.rst +++ /dev/null @@ -1,16 +0,0 @@ -human\_protocol\_sdk.storage package -==================================== - -.. automodule:: human_protocol_sdk.storage - :members: - :undoc-members: - :show-inheritance: - -Submodules ----------- - -.. toctree:: - :maxdepth: 4 - - human_protocol_sdk.storage.storage_client - human_protocol_sdk.storage.storage_utils diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.storage.storage_client.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.storage.storage_client.rst deleted file mode 100644 index 120e1d662d..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.storage.storage_client.rst +++ /dev/null @@ -1,7 +0,0 @@ -human\_protocol\_sdk.storage.storage\_client module -=================================================== - -.. automodule:: human_protocol_sdk.storage.storage_client - :members: - :undoc-members: - :show-inheritance: diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.storage.storage_utils.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.storage.storage_utils.rst deleted file mode 100644 index 67d384fca5..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.storage.storage_utils.rst +++ /dev/null @@ -1,7 +0,0 @@ -human\_protocol\_sdk.storage.storage\_utils module -================================================== - -.. automodule:: human_protocol_sdk.storage.storage_utils - :members: - :undoc-members: - :show-inheritance: diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.transaction.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.transaction.rst deleted file mode 100644 index cffcd0c213..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.transaction.rst +++ /dev/null @@ -1,15 +0,0 @@ -human\_protocol\_sdk.transaction package -======================================== - -.. automodule:: human_protocol_sdk.transaction - :members: - :undoc-members: - :show-inheritance: - -Submodules ----------- - -.. toctree:: - :maxdepth: 4 - - human_protocol_sdk.transaction.transaction_utils diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.transaction.transaction_utils.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.transaction.transaction_utils.rst deleted file mode 100644 index 9c71eeff3f..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.transaction.transaction_utils.rst +++ /dev/null @@ -1,7 +0,0 @@ -human\_protocol\_sdk.transaction.transaction\_utils module -========================================================== - -.. automodule:: human_protocol_sdk.transaction.transaction_utils - :members: - :undoc-members: - :show-inheritance: diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.utils.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.utils.rst deleted file mode 100644 index 0c28f44b0c..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.utils.rst +++ /dev/null @@ -1,7 +0,0 @@ -human\_protocol\_sdk.utils module -================================= - -.. automodule:: human_protocol_sdk.utils - :members: - :undoc-members: - :show-inheritance: diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.worker.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.worker.rst deleted file mode 100644 index 64b0149c33..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.worker.rst +++ /dev/null @@ -1,15 +0,0 @@ -human\_protocol\_sdk.worker package -=================================== - -.. automodule:: human_protocol_sdk.worker - :members: - :undoc-members: - :show-inheritance: - -Submodules ----------- - -.. toctree:: - :maxdepth: 4 - - human_protocol_sdk.worker.worker_utils diff --git a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.worker.worker_utils.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.worker.worker_utils.rst deleted file mode 100644 index c45ab7bdcc..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.worker.worker_utils.rst +++ /dev/null @@ -1,7 +0,0 @@ -human\_protocol\_sdk.worker.worker\_utils module -================================================ - -.. automodule:: human_protocol_sdk.worker.worker_utils - :members: - :undoc-members: - :show-inheritance: diff --git a/packages/sdk/python/human-protocol-sdk/docs/index.md b/packages/sdk/python/human-protocol-sdk/docs/index.md new file mode 100644 index 0000000000..54585e09c3 --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/index.md @@ -0,0 +1,215 @@ +# HUMAN Protocol Python SDK + +The **HUMAN Protocol Python SDK** provides a comprehensive, Pythonic interface for interacting with HUMAN Protocol smart contracts and off-chain services. It enables developers to build decentralized job marketplaces, data labeling platforms, and other human-in-the-loop applications on blockchain networks. + +## Overview + +HUMAN Protocol is a decentralized infrastructure for coordinating human work at scale. The Python SDK simplifies integration by providing high-level abstractions for: + +- **Escrow Management**: Create, fund, and manage escrow contracts for job distribution +- **Staking Operations**: Stake HMT tokens and manage operator allocations +- **On-chain Storage**: Store and retrieve configuration data using KVStore +- **Operator Discovery**: Query and filter operators by role, reputation, and capabilities +- **Worker Analytics**: Track worker performance and payout history +- **Statistics**: Access protocol-wide metrics and analytics +- **Encryption**: Secure message encryption using PGP for private communications + +!!! info "Subgraph access and rate limits" + The SDK calls public subgraph endpoints by default. Unauthenticated requests are rate-limited and may return errors. For higher limits, use your own [API key](https://thegraph.com/docs/it/subgraphs/querying/managing-api-keys/). + +## Key Features + +### Smart Contract Interactions + +- **Escrow Client**: Full lifecycle management of escrow contracts + - Create, fund, and configure escrows + - Bulk payout distribution + - Store and verify results with hash validation + - Cancel and refund mechanisms +- **Staking Client**: Manage HMT token staking + - Stake, unstake, and withdraw operations + - Slash malicious operators + - Query staking information +- **KVStore Client**: On-chain key-value storage + - Store operator configuration + - Manage URLs with automatic hash verification + - Retrieve public keys and metadata + +### Subgraph Utilities + +- **EscrowUtils**: Query escrow data, status events, and payouts +- **OperatorUtils**: Discover operators by role, reputation network, and rewards +- **WorkerUtils**: Access worker statistics and payout history +- **StatisticsUtils**: Retrieve protocol statistics and HMT token metrics +- **TransactionUtils**: Query on-chain transactions with advanced filters + +### Developer Tools + +- **Encryption**: PGP-based message encryption and signing +- **Filters**: Flexible query builders for subgraph data +- **Type Safety**: Comprehensive type hints for better IDE support +- **Error Handling**: Descriptive exceptions with clear error messages + +## Installation + +Install the SDK using pip: + +```bash +pip install human-protocol-sdk +``` + +For development installations with additional dependencies: + +```bash +pip install human-protocol-sdk[dev] +``` + +## Quick Start + +### Read-Only Operations + +Query escrow data without a signer: + +```python +from web3 import Web3 +from human_protocol_sdk.constants import ChainId +from human_protocol_sdk.escrow import EscrowUtils, EscrowFilter + +# Get escrows from the subgraph +escrows = EscrowUtils.get_escrows( + EscrowFilter( + chain_id=ChainId.POLYGON_AMOY, + status=Status.Pending, + ) +) + +for escrow in escrows: + print(f"Escrow: {escrow.address}") + print(f"Balance: {escrow.balance}") + print(f"Status: {escrow.status}") +``` + +### Write Operations + +Create and fund an escrow with a signer: + +```python +from web3 import Web3 +from web3.middleware import SignAndSendRawMiddlewareBuilder +from human_protocol_sdk.escrow import EscrowClient, EscrowConfig + +# Initialize Web3 with signer +w3 = Web3(Web3.HTTPProvider("https://polygon-amoy-rpc.com")) +private_key = "YOUR_PRIVATE_KEY" +account = w3.eth.account.from_key(private_key) +w3.eth.default_account = account.address +w3.middleware_onion.inject( + SignAndSendRawMiddlewareBuilder.build(private_key), + "SignAndSendRawMiddlewareBuilder", + layer=0, +) + +# Create escrow client +escrow_client = EscrowClient(w3) + +# Create escrow configuration +config = EscrowConfig( + recording_oracle_address="0x...", + reputation_oracle_address="0x...", + exchange_oracle_address="0x...", + recording_oracle_fee=10, + reputation_oracle_fee=10, + exchange_oracle_fee=10, + manifest="https://example.com/manifest.json", + hash="manifest_hash", +) + +# Create and setup escrow +escrow_address = escrow_client.create_fund_and_setup_escrow( + token_address="0x...", + amount=Web3.to_wei(100, "ether"), + job_requester_id="job-123", + escrow_config=config, +) + +print(f"Created escrow: {escrow_address}") +``` + +### Query Statistics + +Access protocol-wide statistics: + +```python +from human_protocol_sdk.constants import ChainId +from human_protocol_sdk.statistics import StatisticsUtils + +# Get escrow statistics +stats = StatisticsUtils.get_escrow_statistics(ChainId.POLYGON_AMOY) +print(f"Total escrows: {stats.total_escrows}") + +# Get HMT token statistics +hmt_stats = StatisticsUtils.get_hmt_statistics(ChainId.POLYGON_AMOY) +print(f"Total holders: {hmt_stats.total_holders}") +print(f"Total transfers: {hmt_stats.total_transfer_count}") +``` + +### Operator Discovery + +Find operators by role and reputation: + +```python +from human_protocol_sdk.constants import ChainId +from human_protocol_sdk.operator import OperatorUtils, OperatorFilter + +# Find recording oracles +operators = OperatorUtils.get_operators( + OperatorFilter( + chain_id=ChainId.POLYGON_AMOY, + roles=["Recording Oracle"], + ) +) + +for operator in operators: + print(f"Operator: {operator.address}") + print(f"Role: {operator.role}") + print(f"Staked: {operator.staked_amount}") +``` + +## Supported Networks + +The SDK supports multiple blockchain networks: + +- **Mainnet**: Ethereum, Polygon, BSC +- **Testnets**: Sepolia, Polygon Amoy, BSC Testnet +- **Local Development**: Localhost (Hardhat/Ganache) + +Network configurations are automatically loaded based on the Web3 chain ID. + +## Architecture + +The SDK is organized into several modules: + +- **`escrow`**: Escrow contract client and utilities +- **`staking`**: Staking contract client and utilities +- **`kvstore`**: Key-value store client and utilities +- **`operator`**: Operator discovery and management utilities +- **`worker`**: Worker statistics utilities +- **`statistics`**: Protocol statistics utilities +- **`transaction`**: Transaction query utilities +- **`encryption`**: PGP encryption helpers +- **`constants`**: Network configurations and enums +- **`filter`**: Query filter builders + +## Requirements + +- Python 3.8 or higher +- Web3.py 6.0+ +- Access to an Ethereum-compatible RPC endpoint +- (Optional) Private key for transaction signing + +## Resources + +- [GitHub Repository](https://github.com/humanprotocol/human-protocol) +- [HUMAN Protocol Documentation](https://docs.humanprotocol.org/) +- [Discord Community](https://discord.gg/humanprotocol) +- [Website](https://www.humanprotocol.org/) diff --git a/packages/sdk/python/human-protocol-sdk/docs/index.rst b/packages/sdk/python/human-protocol-sdk/docs/index.rst deleted file mode 100644 index 69f27a5333..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/index.rst +++ /dev/null @@ -1,28 +0,0 @@ -.. Human Protocol SDK documentation master file, created by - sphinx-quickstart on Mon Nov 6 07:49:01 2023. - You can adapt this file completely to your liking, but it should at least - contain the root `toctree` directive. - -Welcome to Human Protocol SDK's documentation! -============================================== - -Installation ------------- - -To install the Human Protocol SDK, run the following command: - -.. code-block:: bash - - pip install human-protocol-sdk - -In case you want to use the features of the agreement module, make sure to install corresponding extras as well. - -.. code-block:: bash - - pip install human-protocol-sdk[agreement] - -.. toctree:: - :maxdepth: 4 - :caption: Contents: - - human_protocol_sdk diff --git a/packages/sdk/python/human-protocol-sdk/docs/kvstore_client.md b/packages/sdk/python/human-protocol-sdk/docs/kvstore_client.md new file mode 100644 index 0000000000..a15ceba06a --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/kvstore_client.md @@ -0,0 +1 @@ +::: human_protocol_sdk.kvstore.kvstore_client \ No newline at end of file diff --git a/packages/sdk/python/human-protocol-sdk/docs/kvstore_utils.md b/packages/sdk/python/human-protocol-sdk/docs/kvstore_utils.md new file mode 100644 index 0000000000..2f8dd26e77 --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/kvstore_utils.md @@ -0,0 +1 @@ +::: human_protocol_sdk.kvstore.kvstore_utils diff --git a/packages/sdk/python/human-protocol-sdk/docs/legacy_encryption.md b/packages/sdk/python/human-protocol-sdk/docs/legacy_encryption.md new file mode 100644 index 0000000000..029badfba0 --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/legacy_encryption.md @@ -0,0 +1 @@ +::: human_protocol_sdk.legacy_encryption \ No newline at end of file diff --git a/packages/sdk/python/human-protocol-sdk/docs/make.bat b/packages/sdk/python/human-protocol-sdk/docs/make.bat deleted file mode 100644 index 32bb24529f..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/make.bat +++ /dev/null @@ -1,35 +0,0 @@ -@ECHO OFF - -pushd %~dp0 - -REM Command file for Sphinx documentation - -if "%SPHINXBUILD%" == "" ( - set SPHINXBUILD=sphinx-build -) -set SOURCEDIR=. -set BUILDDIR=_build - -%SPHINXBUILD% >NUL 2>NUL -if errorlevel 9009 ( - echo. - echo.The 'sphinx-build' command was not found. Make sure you have Sphinx - echo.installed, then set the SPHINXBUILD environment variable to point - echo.to the full path of the 'sphinx-build' executable. Alternatively you - echo.may add the Sphinx directory to PATH. - echo. - echo.If you don't have Sphinx installed, grab it from - echo.https://www.sphinx-doc.org/ - exit /b 1 -) - -if "%1" == "" goto help - -%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% -goto end - -:help -%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% - -:end -popd diff --git a/packages/sdk/python/human-protocol-sdk/docs/operator_utils.md b/packages/sdk/python/human-protocol-sdk/docs/operator_utils.md new file mode 100644 index 0000000000..e27818c5c9 --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/operator_utils.md @@ -0,0 +1 @@ +::: human_protocol_sdk.operator.operator_utils diff --git a/packages/sdk/python/human-protocol-sdk/docs/staking_client.md b/packages/sdk/python/human-protocol-sdk/docs/staking_client.md new file mode 100644 index 0000000000..8da1761f9d --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/staking_client.md @@ -0,0 +1 @@ +::: human_protocol_sdk.staking.staking_client \ No newline at end of file diff --git a/packages/sdk/python/human-protocol-sdk/docs/staking_utils.md b/packages/sdk/python/human-protocol-sdk/docs/staking_utils.md new file mode 100644 index 0000000000..2fe082b8c7 --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/staking_utils.md @@ -0,0 +1 @@ +::: human_protocol_sdk.staking.staking_utils diff --git a/packages/sdk/python/human-protocol-sdk/docs/statistics_utils.md b/packages/sdk/python/human-protocol-sdk/docs/statistics_utils.md new file mode 100644 index 0000000000..bfb3c48dc9 --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/statistics_utils.md @@ -0,0 +1 @@ +::: human_protocol_sdk.statistics.statistics_utils diff --git a/packages/sdk/python/human-protocol-sdk/docs/transaction_utils.md b/packages/sdk/python/human-protocol-sdk/docs/transaction_utils.md new file mode 100644 index 0000000000..f2e6b4132e --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/transaction_utils.md @@ -0,0 +1 @@ +::: human_protocol_sdk.transaction.transaction_utils diff --git a/packages/sdk/python/human-protocol-sdk/docs/worker_utils.md b/packages/sdk/python/human-protocol-sdk/docs/worker_utils.md new file mode 100644 index 0000000000..b8c639b1f3 --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/worker_utils.md @@ -0,0 +1,7 @@ +# Worker + +Helpers for retrieving worker information from the protocol. + +## Utilities + +::: human_protocol_sdk.worker.worker_utils diff --git a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/agreement/__init__.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/agreement/__init__.py deleted file mode 100644 index 8b06fbdc66..0000000000 --- a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/agreement/__init__.py +++ /dev/null @@ -1,85 +0,0 @@ -""" -**A subpackage for calculating Inter Rater Agreement measures for annotated data.** - -This module contains methods that estimate the agreement -between annotatorsin a data labelling project. -Its role is to provide easy access to means of estimating data quality -for developers of Reputation and Recording Oracles. - -Getting Started -=============== -This module is an optional extra of the HUMAN Protocol SDK. -In order to use it, run the following command: - -.. code-block:: bash - - pip install human_protocol_sdk[agreement] - -A simple example ----------------- -The main functionality of the module is provided by a single function called [`agreement`](human_protocol_sdk.agreement.measures.md#human_protocol_sdk.agreement.measures.agreement). -Suppose we have a very small annotation, where 3 annotators label 4 different images. -The goal is to find find if an image contain a cat or not, -so they label them either `cat` or `not`. - -After processing, the data might look look like that: - -.. code-block:: python - - from numpy import nan - annotations = [ - ['cat', 'not', 'cat'], - ['cat', 'cat', 'cat'], - ['not', 'not', 'not'], - ['cat', nan, 'not'], - ] - -Each row contains the annotations for a single item and -each column contains the annotations of an individual annotator. -We call this format `'annotation'` format, -which is the default format expected by the `agreement` function -and all measures implemented in this package. - -Our data contains a missing value, indicated by the `nan` entry. -Annotator 2 did not provide an annotation for item 4. -All missing values must be marked in this way. - -So, we can simply plug our annotations into the function. - -.. code-block:: python - - agreement_report = agreement(annotations, measure="fleiss_kappa") - print(agreement_report) - # { - # 'results': { - # 'measure': 'fleiss_kappa', - # 'score': 0.3950000000000001, - # 'ci': None, - # 'confidence_level': None - # }, - # 'config': { - # 'measure': 'fleiss_kappa', - # 'labels': array(['cat', 'not'], dtype=' Tuple[Tuple[float, float], np.ndarray]: - """Returns a tuple, containing the confidence interval for the boostrap estimates of the given statistic and statistics of the bootstrap samples. - - :param data: Data to estimate the statistic. - :param statistic_fn: Function to calculate the statistic. statistic_fn(data) must return a number. - :param n_iterations: Number of bootstrap samples to use for the estimate. - :param n_sample: If provided, determines the size of each bootstrap sample - drawn from the data. If omitted, is equal to the length of the data. - :param confidence_level: Size of the confidence interval. - :param algorithm: Which algorithm to use for the confidence interval - estimation. "bca" uses the "Bias Corrected Bootstrap with - Acceleration", "percentile" simply takes the appropriate - percentiles from the bootstrap distribution. - :param seed: Random seed to use. - - :return: Confidence interval and bootstrap distribution. - - :example: - .. code-block:: python - - from human_protocol_sdk.agreement.bootstrap import confidence_interval - import numpy as np - - np.random.seed(42) - data = np.random.randn(10_000) - fn = np.mean - sample_mean = fn(data) - print(f"Sample mean is {sample_mean:.3f}") - # Sample mean is -0.002 - - cl = 0.99 - ci, _ = confidence_interval(data, fn, confidence_level=cl) - print(f"Population mean is between {ci[0]:.2f} and {ci[1]:.2f} with a probablity of {cl}") - # Population mean is between -0.02 and 0.02 with a probablity of 0.99 - - """ - # set random seed for reproducibility - if seed is not None: - np.random.seed(seed) - random.seed(seed) - - data = np.asarray(data) - - if n_iterations < 1: - raise ValueError( - f"n_iterations must be a positive integer, but were {n_iterations}" - ) - - n_data = len(data) - if n_data < 30: - warn( - "Dataset size is low, bootstrap estimate might be inaccurate. For accurate results, make sure to provide at least 30 data points." - ) - - if n_sample is None: - n_sample = n_data - elif n_sample < 1: - raise ValueError(f"n_sample must be a positive integer, but was {n_sample}") - - if not (0.0 <= confidence_level <= 1.0): - raise ValueError( - f"ci must be a float within [0.0, 1.0], but was {confidence_level}" - ) - - # bootstrap estimates - theta_b = np.empty(n_iterations, dtype=float) - for i in range(n_iterations): - idx = np.random.randint(n_data - 1, size=(n_sample,)) - sample = data[idx] - theta_b[i] = statistic_fn(sample) - theta_b = theta_b[~np.isnan(theta_b)] - - match algorithm: - case "percentile": - alpha = 1.0 - confidence_level - alpha /= 2.0 - q = np.asarray([alpha, 1.0 - alpha]) - case "bca": - # acceleration: estimate a from jackknife bootstrap - theta_hat = statistic_fn(data) - jn_idxs = ~np.eye(n_data, dtype=bool) - theta_jn = np.empty(n_data, dtype=float) - for i in range(n_data): - theta_jn[i] = (n_data - 1) * ( - theta_hat - statistic_fn(data[jn_idxs[i]]) - ) - theta_jn = theta_jn[~np.isnan(theta_jn)] - - a = (np.sum(theta_jn**3) / np.sum(theta_jn**2, axis=-1) ** 1.5) / 6 - - alpha = 1.0 - confidence_level - alpha /= 2 - q = np.asarray([alpha, 1.0 - alpha]) - - # bias correction - N = NormalDistribution() - ppf = np.vectorize(N.ppf) - cdf = np.vectorize(N.cdf) - - # bias term. discrepancy between bootrap values and estimated value - z_0 = ppf(np.mean(theta_b < theta_hat)) - z_u = ppf(q) - z_diff = z_0 + z_u - - q = cdf(z_0 + (z_diff / (1 - a * z_diff))) - case _: - raise ValueError(f"Algorithm '{algorithm}' is not available!") - - # sanity checks - if np.any(np.isnan(q)): - warn( - f"q contains NaN values. Input data is probably invalid. Interval will be (nan, nan). data: {data}" - ) - ci_low = ci_high = np.nan - else: - if np.any((q < 0.0) | (q > 1.0)): - warn( - f"q ({q}) out of bounds. Input data is probably invalid. q will be clipped into interval [0.0, 1.0]. data: {data}" - ) - q = np.clip(q, 0.0, 1.0) - ci_low, ci_high = np.percentile(theta_b, q * 100) - - return (ci_low, ci_high), theta_b diff --git a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/agreement/measures.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/agreement/measures.py deleted file mode 100644 index b0ccf3a7a0..0000000000 --- a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/agreement/measures.py +++ /dev/null @@ -1,377 +0,0 @@ -"""Module containing Inter Rater Agreement Measures.""" - -from copy import copy -from functools import partial -from typing import Sequence, Optional, Callable, Union -from warnings import warn - -import numpy as np - -from .bootstrap import confidence_intervals -from .utils import label_counts, confusion_matrix, observed_and_expected_differences - - -def agreement( - annotations: Sequence, - measure="krippendorffs_alpha", - labels: Optional[Sequence] = None, - bootstrap_method: Optional[str] = None, - bootstrap_kwargs: Optional[dict] = None, - measure_kwargs: Optional[dict] = None, -) -> dict: - """ - Calculates agreement across the given data using the given method. - - :param annotations: Annotation data. - Must be a N x M Matrix, where N is the number of annotated items and - M is the number of annotators. Missing values must be indicated by nan. - :param measure: Specifies the method to use. - Must be one of 'cohens_kappa', 'percentage', 'fleiss_kappa', - 'sigma' or 'krippendorffs_alpha'. - :param labels: List of labels to use for the annotation. - If set to None, labels are inferred from the data. - If provided, values not in the labels are set to nan. - :param bootstrap_method: Name of the bootstrap method to use - for calculating confidence intervals. - If set to None, no confidence intervals are calculated. - If provided, must be one of 'percentile' or 'bca'. - :param bootstrap_kwargs: Dictionary of keyword arguments to be passed - to the bootstrap function. - :param measure_kwargs: Dictionary of keyword arguments to be - passed to the measure function. - - :return: A dictionary containing the keys "results" and "config". - Results contains the scores, while config contains parameters - that produced the results. - - :example: - .. code-block:: python - - from human_protocol_sdk.agreement import agreement - - annotations = [ - ['cat', 'not', 'cat'], - ['cat', 'cat', 'cat'], - ['not', 'not', 'not'], - ['cat', 'nan', 'not'], - ] - - agreement_report = agreement(annotations, measure="fleiss_kappa") - print(agreement_report) - # { - # 'results': { - # 'measure': 'fleiss_kappa', - # 'score': 0.3950000000000001, - # 'ci': None, - # 'confidence_level': None - # }, - # 'config': { - # 'measure': 'fleiss_kappa', - # 'labels': array(['cat', 'not'], dtype=' float: - """ - Returns the overall agreement percentage observed across the data. - - :param annotations: Annotation data. - Must be a N x M Matrix, where N is the number of annotated items and - M is the number of annotators. Missing values must be indicated by nan. - - :return: Value between 0.0 and 1.0, indicating the percentage of agreement. - - :example: - .. code-block:: python - - from human_protocol_sdk.agreement.measures import percentage - import numpy as np - - annotations = np.asarray([ - ["cat", "not", "cat"], - ["cat", "cat", "cat"], - ["not", "not", "not"], - ["cat", "cat", "not"], - ]) - print(percentage(annotations)) - # 0.7 - """ - annotations = np.asarray(annotations) - return _percentage_from_label_counts(label_counts(annotations)) - - -def _percentage_from_label_counts(label_counts): - n_raters = np.sum(label_counts, 1) - item_agreements = (np.sum(label_counts * label_counts, 1) - n_raters).sum() - max_item_agreements = (n_raters * (n_raters - 1)).sum() - - if max_item_agreements == 0: - warn( - """ - All annotations were made by a single annotator, - check your data to ensure this is not an error. - Returning 1.0 - """ - ) - return 1.0 - - return item_agreements / max_item_agreements - - -def _kappa(agreement_observed, agreement_expected): - if agreement_expected == 1.0: - warn( - """ - Annotations contained only a single value, - check your data to ensure this is not an error. - Returning 1.0. - """ - ) - return 1.0 - - return (agreement_observed - agreement_expected) / (1 - agreement_expected) - - -def cohens_kappa(annotations: np.ndarray) -> float: - """ - Returns Cohen's Kappa for the provided annotations. - - :param annotations: Annotation data. - Must be a N x M Matrix, where N is the number of annotated items and M - is the number of annotators. Missing values must be indicated by nan. - - :return: Value between -1.0 and 1.0, - indicating the degree of agreement between both raters. - - :example: - .. code-block:: python - - from human_protocol_sdk.agreement.measures import cohens_kappa - import numpy as np - - annotations = np.asarray([ - ["cat", "cat"], - ["cat", "cat"], - ["not", "cat"], - ["not", "cat"], - ["cat", "not"], - ["not", "not"], - ["not", "not"], - ["not", "not"], - ["not", "not"], - ["not", "not"], - ]) - print(cohens_kappa(annotations)) - # 0.348 - """ - annotations = np.asarray(annotations) - cm = confusion_matrix(annotations) - - agreement_observed = np.diag(cm).sum() / cm.sum() - agreement_expected = np.matmul(cm.sum(0), cm.sum(1)) / cm.sum() ** 2 - - return _kappa(agreement_observed, agreement_expected) - - -def fleiss_kappa(annotations: np.ndarray) -> float: - """ - Returns Fleisss' Kappa for the provided annotations. - - :param annotations: Annotation data. - Must be a N x M Matrix, where N is the number of items and - M is the number of annotators. - - :return: Value between -1.0 and 1.0, - indicating the degree of agreement between all raters. - - :example: - .. code-block:: python - - from human_protocol_sdk.agreement.measures import fleiss_kappa - import numpy as np - - # 3 raters, 2 classes - annotations = np.asarray([ - ["cat", "not", "cat"], - ["cat", "cat", "cat"], - ["not", "not", "not"], - ["cat", "cat", "not"], - ]) - print(f"{fleiss_kappa(annotations):.3f}") - # 0.395 - """ - annotations = np.asarray(annotations) - im = label_counts(annotations) - - agreement_observed = _percentage_from_label_counts(im) - class_probabilities = im.sum(0) / im.sum() - agreement_expected = np.power(class_probabilities, 2).sum() - - return _kappa(agreement_observed, agreement_expected) - - -def krippendorffs_alpha( - annotations: np.ndarray, distance_function: Union[Callable, str] -) -> float: - """ - Calculates Krippendorff's Alpha for the given annotations (item-value pairs), - using the given distance function. - - :param annotations: Annotation data. - Must be a N x M Matrix, where N is the number of annotated items and - M is the number of annotators. Missing values must be indicated by nan. - :param distance_function: Function to calculate distance between two values. - Calling `distance_fn(annotations[i, j], annotations[p, q])` must return a number. - Can also be one of 'nominal', 'ordinal', 'interval' or 'ratio' for - default functions pertaining to the level of measurement of the data. - - :return: Value between -1.0 and 1.0, - indicating the degree of agreement. - - :example: - .. code-block:: python - - from human_protocol_sdk.agreement.measures import krippendorffs_alpha - import numpy as np - - annotations = np.asarray([ - [0, 0, 0], - [0, 1, 1]] - ) - print(krippendorffs_alpha(annotations, distance_function="nominal")) - # 0.375 - - """ - difference_observed, difference_expected = observed_and_expected_differences( - annotations, distance_function - ) - return 1 - difference_observed.mean() / difference_expected.mean() - - -def sigma( - annotations: np.ndarray, distance_function: Union[Callable, str], p=0.05 -) -> float: - """ - Calculates the Sigma Agreement Measure for the given annotations (item-value pairs), - using the given distance function. - For details, see https://dl.acm.org/doi/fullHtml/10.1145/3485447.3512242. - - :param annotations: Annotation data. - Must be a N x M Matrix, where N is the number of annotated items and - M is the number of annotators. Missing values must be indicated by nan. - :param distance_function: Function to calculate distance between two values. - Calling `distance_fn(annotations[i, j], annotations[p, q])` must return a number. - Can also be one of 'nominal', 'ordinal', 'interval' or 'ratio' for - default functions pertaining to the level of measurement of the data. - :param p: Probability threshold between 0.0 and 1.0 - determining statistical significant difference. The lower, the stricter. - - :return: Value between 0.0 and 1.0, indicating the degree of agreement. - - :example: - .. code-block:: python - - from human_protocol_sdk.agreement.measures import sigma - import numpy as np - - np.random.seed(42) - n_items = 500 - n_annotators = 5 - - # create annotations - annotations = np.random.rand(n_items, n_annotators) - means = np.random.rand(n_items, 1) * 100 - scales = np.random.randn(n_items, 1) * 10 - annotations = annotations * scales + means - d = "interval" - - print(sigma(annotations, d)) - # 0.6538 - """ - if p < 0.0 or p > 1.0: - raise ValueError(f"Parameter 'p' must be between 0.0 and 1.0") - - difference_observed, difference_expected = observed_and_expected_differences( - annotations, distance_function - ) - difference_crit = np.quantile(difference_expected, p) - return np.mean(difference_observed < difference_crit) diff --git a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/agreement/utils.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/agreement/utils.py deleted file mode 100644 index 8267537315..0000000000 --- a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/agreement/utils.py +++ /dev/null @@ -1,417 +0,0 @@ -"""Module containing helper functions for calculating agreement measures.""" - -from collections import Counter -from math import nan -from typing import Sequence, Optional, Tuple - -import numpy as np -from pyerf import erf, erfinv - - -def _filter_labels(labels: Sequence): - """ - Filters None and nan values from the given labels. - - :param labels: The labels to filter. - - :return: A list of labels without the given list of labels to exclude. - - """ - # map to preserve label order if user defined labels are passed - nan_values = {np.nan, nan, None, "nan"} - return np.asarray([label for label in labels if label not in nan_values]) - - -def _is_nan(data: np.ndarray, axis=None): - """np.isnan but for any data type.""" - try: - mask = np.isnan(data) - except TypeError: - mask = data == "nan" - - if axis is not None: - mask = np.any(mask, axis=axis) - - return mask - - -def _is_in(data: np.ndarray, elements: np.ndarray): - """Checks if data is in elements. Faster than using np.isin.""" - return data[..., np.newaxis] == elements - - -def label_counts( - annotations: Sequence, - labels=None, - return_labels=False, -): - """Converts the given sequence of item annotations to an array of label counts per item. - - :param annotations: A two-dimensional sequence. Rows represent items, columns represent annotators. - :param labels: List of labels to be counted. Entries not found in the list are omitted. If - omitted, all labels in the annotations are counted. - :param nan_values: Values in the records to be counted as invalid. - :param return_labels: Whether to return labels with the counts. Automatically set to true if labels are - inferred. - - :return: A two-dimensional array of integers. Rows represent items, columns represent labels. - - :example: - .. code-block:: python - - from human_protocol_sdk.agreement.utils import label_counts - - annotations = [ - ["white", "black", "white"], - ["white", "white", "white"], - ["black", "black", "black"], - ["white", "nan", "black"], - ] - - # infer labels automatically - counts, labels = label_counts(annotations, return_labels=True) - print(counts) - # [[1 2] - # [0 3] - # [3 0] - # [1 1]] - - # labels are inferred and sorted automatically - print(labels) - # ['black' 'white'] - - .. code-block:: python - - # labels are provided, label order is preserved - counts, labels = label_counts( - annotations, - labels=['white', 'black'], - return_labels=True - ) - print(counts) - # [[2 1] - # [3 0] - # [0 3] - # [1 1]] - - print(labels) - # ['white' 'black'] - - .. code-block:: python - - # can be achieved using nan values - counts, labels = label_counts( - annotations, - nan_values=[''], - return_labels=True - ) - - print(counts) - # [[1 2] - # [0 3] - # [3 0] - # [1 1]] - - print(labels) - # ['black' 'white'] - - """ - annotations = np.asarray(annotations) - - if labels is None: - labels = np.unique(annotations) - - labels = _filter_labels(labels) - - def lcs(annotations, labels): - c = Counter(annotations) - return [c.get(label, 0) for label in labels] - - counts = np.asarray([lcs(row, labels) for row in annotations]) - - if return_labels: - return counts, labels - - return counts - - -def confusion_matrix( - annotations: np.ndarray, - labels: Optional[Sequence] = None, - return_labels=False, -): - """Generate an N X N confusion matrix from the given sequence of values a and b, - where N is the number of unique labels. - - :param annotations: Annotation data to be converted into confusion matrix. - Must be a N x 2 Matrix, where N is the number of items and 2 is the number of annotators. - :param labels: Sequence of labels to be counted. - Entries not found in the list are omitted. - No labels are provided, the list of labels is inferred from the given annotations. - :param return_labels: Whether to return labels with the counts. - - :return: A confusion matrix. - Rows represent labels assigned by b, columns represent labels assigned by a. - - :example: - .. code-block:: python - - from human_protocol_sdk.agreement.utils import confusion_matrix - import numpy as np - - annotations = np.asarray([ - ["a", "a"], - ["b", "a"], - ["c", "c"] - ]) - - # infer labels automatically - cm = confusion_matrix(annotations, return_labels=False) - print(cm) - # [[1 0 0] - # [1 0 0] - # [0 0 1]] - """ - annotations = np.asarray(annotations) - - # create list of unique labels - if labels is None: - labels = np.unique(annotations) - - labels = _filter_labels(labels) - n_labels = len(labels) - - # map labels to ids - label_to_id = {label: i for i, label in enumerate(labels)} - map_fn = np.vectorize(lambda x: label_to_id.get(x, -1)) - M = map_fn(annotations) - - # filter NaN values - mask = np.all(M != -1, axis=1) - - # get indices and counts to populate confusion matrix - cm = np.zeros((n_labels, n_labels), dtype=int) - (i, j), counts = np.unique(M[mask].T, axis=1, return_counts=True) - cm[i, j] = counts - - if return_labels: - return cm, labels - - return cm - - -class NormalDistribution: - """Continuous Normal Distribution. - - See: https://en.wikipedia.org/wiki/Normal_distribution - """ - - def __init__(self, location: float = 0.0, scale: float = 1.0): - """Creates a NormalDistribution from the given parameters. - - :param location: Location of the distribution. - :param scale: Scale of the distribution. Must be positive. - """ - if scale < 0.0: - raise ValueError(f"scale parameter needs to be positive, but was {scale}") - - self.location = location - self.scale = scale - - def cdf(self, x: float) -> float: - """Cumulative Distribution Function of the Normal Distribution. Returns - the probability that a random sample will be less than the given - point. - - :param x: Point within the distribution's domain. - """ - return (1 + erf((x - self.location) / (self.scale * 2**0.5))) / 2 - - def pdf(self, x: float) -> float: - """Probability Density Function of the Normal Distribution. Returns the - probability for observing the given sample in the distribution. - - :param x: Point within the distribution's domain. - """ - return np.exp(-0.5 * (x - self.location / self.scale) ** 2) / ( - self.scale * (2 * np.pi) ** 0.5 - ) - - def ppf(self, p: float) -> float: - """Probability Point function of the Normal Distribution. Returns - the maximum point to which cumulated probabilities equal the given - probability. Also called quantile. Inverse of the cdf. - - :param p: Percentile of the distribution to be covered by the ppf. - """ - if not (0.0 <= p <= 1.0): - raise ValueError(f"p must be a float within [0.0, 1.0], but was {p}") - - return self.location + self.scale * 2**0.5 * erfinv(2 * p - 1.0) - - -def _distance_matrix(values, distance_fn, dtype=np.float64): - """ - Calculates a matrix containing the distances between each pair of given - values using the given distance function. - - :param values: A sequence of values to compute distances between. Assumed to be - unique. - :param distance_fn: Function to calculate distance between two values. Calling - `distance_fn(values[i], values[j])` must return a number. - :param dtype: The datatype of the returned ndarray. - - :return: The distance matrix as a 2d ndarray. - """ - n = len(values) - dist_matrix = np.zeros((n, n), dtype) - i, j = np.triu_indices(n, k=1) - distances = np.vectorize(distance_fn)(values[i], values[j]) - dist_matrix[i, j] = distances - dist_matrix[j, i] = distances - return dist_matrix - - -def _pair_indices(items: np.ndarray): - """ - Returns indices of pairs of identical items. Indices are represented as a numpy ndarray, where the first row contains indices for the first parts of the pairs and the second row contains the second pair index. - - :param items: The items for which to generate pair indices. - - :return: A numpy ndarray, containing indices for pairs of identical items. - """ - items = np.asarray(items) - identical = ( - items[np.newaxis, ...] == items[..., np.newaxis] - ) # elementwise comparison of each item. returns n*n indicator matrix - return np.vstack(np.where(np.triu(identical, 1))) - - -def observed_and_expected_differences(annotations, distance_function): - """ - Returns observed and expected differences for given annotations (item-value - pairs), as used in Krippendorff's alpha agreement measure and the Sigma - agreement measure. - - :param annotations: Annotation data. - Must be a N x M Matrix, where N is the number of items and M is the number of annotators. - :param distance_function: Function to calculate distance between two values. - Calling `distance_fn(annotations[i, j], annotations[p, q])` must return a number. - Can also be one of 'nominal', 'ordinal', 'interval' or 'ratio' for - default functions pertaining to the level of measurement of the data. - - :return: A tuple consisting of numpy ndarrays, - containing the observed and expected differences in annotations. - - """ - values, items, _ = records_from_annotations(annotations) - - if isinstance(distance_function, str): - match distance_function: - case "nominal": - distance_function = lambda a, b: a != b - case "ordinal": - distance_function = lambda a, b: (a - b) ** 2 - case "interval": - distance_function = lambda a, b: (a - b) ** 2 - case "ratio": - distance_function = lambda a, b: ((a - b) / (a + b)) ** 2 - case _: - raise ValueError( - f"Distance function '{distance_function}' not supported." - ) - - unique_values, value_ids = np.unique(values, return_inverse=True) - dist_matrix = _distance_matrix(unique_values, distance_function) - - intra_item_pairs = _pair_indices(items) - i, j = value_ids[intra_item_pairs] - observed_differences = dist_matrix[i, j] - - all_item_pairs = np.vstack(np.triu_indices(n=items.size, k=1)) - i, j = value_ids[all_item_pairs] - expected_differences = dist_matrix[i, j] - - return observed_differences, expected_differences - - -def records_from_annotations( - annotations: np.ndarray, annotators=None, items=None, labels=None -) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: - """ - Turns given annotations into sequences of records. - - :param annotations: Annotation matrix (2d array) to convert. Columns represent - :param annotators: List of annotator ids. Must be the same length as columns in annotations. - :param items: List of item ids. Must be the same length as rows in annotations. - :param labels: The to be included in the matrix. - - :return: Tuple containing arrays of item value ids, item ids and annotator ids - - :example: - .. code-block:: python - - from human_protocol_sdk.agreement.utils import records_from_annotations - import numpy as np - - annotations = np.asarray([ - ["cat", "not", "cat"], - ["cat", "cat", "cat"], - ["not", "not", "not"], - ["cat", np.nan, "not"], - ]) - - # nan values are automatically filtered - values, items, annotators = records_from_annotations(annotations) - print(values) - # ['cat' 'not' 'cat' 'cat' 'cat' 'cat' 'not' 'not' 'not' 'cat' 'not'] - print(items) - # [0 0 0 1 1 1 2 2 2 3 3] - print(annotators) - # [0 1 2 0 1 2 0 1 2 0 2] - - .. code-block:: python - - annotators = np.asarray(["bob", "alice", "charlie"]) - items = np.asarray(["item_1", "item_2", "item_3", "item_4"]) - - values, items, annotators = records_from_annotations( - annotations, - annotators, - items - ) - print(values) - # ['cat' 'not' 'cat' 'cat' 'cat' 'cat' 'not' 'not' 'not' 'cat' 'not'] - print(items) - # ['item_1' 'item_1' 'item_1' 'item_2' 'item_2' 'item_2' 'item_3' 'item_3' 'item_3' 'item_4' 'item_4'] - print(annotators) - # ['bob' 'alice' 'charlie' 'bob' 'alice' 'charlie' 'bob' 'alice' 'charlie' 'bob' 'charlie'] - """ - annotations = np.asarray(annotations) - n_items, n_annotators = annotations.shape - - if items is None: - items = np.arange(n_items) - else: - items = np.asarray(items) - if len(items) != n_items: - raise ValueError( - "Number of items does not correspond to number of rows in annotations." - ) - - if annotators is None: - annotators = np.arange(n_annotators) - else: - annotators = np.asarray(annotators) - if len(annotators) != n_annotators: - raise ValueError( - "Number of annotators does not correspond to number of columns in annotations." - ) - - values = annotations.ravel() - items = np.repeat(items, n_annotators) - annotators = np.tile(annotators, n_items) - - mask = ~_is_nan(values) - - return values[mask], items[mask], annotators[mask] diff --git a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/constants.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/constants.py index 4c0abcf005..04960c348b 100644 --- a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/constants.py +++ b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/constants.py @@ -4,7 +4,17 @@ class ChainId(Enum): - """Enum for chain IDs.""" + """Supported blockchain network identifiers. + + Attributes: + MAINNET: Ethereum Mainnet (Chain ID: 1) + SEPOLIA: Ethereum Sepolia Testnet (Chain ID: 11155111) + BSC_MAINNET: Binance Smart Chain Mainnet (Chain ID: 56) + BSC_TESTNET: Binance Smart Chain Testnet (Chain ID: 97) + POLYGON: Polygon Mainnet (Chain ID: 137) + POLYGON_AMOY: Polygon Amoy Testnet (Chain ID: 80002) + LOCALHOST: Local development network (Chain ID: 1338) + """ MAINNET = 1 SEPOLIA = 11155111 @@ -16,14 +26,24 @@ class ChainId(Enum): class OrderDirection(Enum): - """Enum for chain IDs.""" + """Sort order for query results. + + Attributes: + ASC: Ascending order (lowest to highest). + DESC: Descending order (highest to lowest). + """ ASC = "asc" DESC = "desc" class OperatorCategory(Enum): - """Enum for operator categories""" + """Categories for operator classification. + + Attributes: + MACHINE_LEARNING: Operators providing machine learning services. + MARKET_MAKING: Operators providing market making services. + """ MACHINE_LEARNING = "machine_learning" MARKET_MAKING = "market_making" @@ -146,10 +166,21 @@ class OperatorCategory(Enum): SUBGRAPH_API_KEY_PLACEHOLDER = "[SUBGRAPH_API_KEY]" +"""Placeholder string in subgraph URLs that gets replaced with the actual API key from environment variables.""" class Status(Enum): - """Enum for escrow statuses.""" + """Escrow contract lifecycle statuses. + + Attributes: + Launched: Escrow created but not yet funded or configured. + Pending: Escrow funded and awaiting oracle actions. + Partial: Escrow partially paid out to workers. + Paid: All funds distributed but not yet marked complete. + Complete: Escrow fully processed and finalized. + Cancelled: Escrow cancelled and funds refunded. + ToCancel: Cancellation requested, awaiting finalization. + """ Launched = 0 Pending = 1 @@ -161,7 +192,14 @@ class Status(Enum): class Role(Enum): - """Enum for roles.""" + """Oracle and operator role identifiers. + + Attributes: + job_launcher: Entity that creates and funds escrows. + exchange_oracle: Oracle handling job distribution and exchange. + reputation_oracle: Oracle managing worker reputation scoring. + recording_oracle: Oracle recording and validating job results. + """ job_launcher = "job_launcher" exchange_oracle = "exchange_oracle" @@ -170,10 +208,28 @@ class Role(Enum): ARTIFACTS_FOLDER = os.path.join(os.path.dirname(os.path.dirname(__file__)), "artifacts") +"""Path to the directory containing compiled smart contract artifacts (ABIs and bytecode).""" class KVStoreKeys(Enum): - """Enum for KVStore keys""" + """Standard key names for the on-chain key-value store. + + These keys are used by operators to store configuration and metadata on-chain. + + Attributes: + category: Operator category classification. + fee: Operator fee percentage. + job_types: Comma-separated list of supported job types. + operator_name: Display name of the operator. + public_key: PGP public key for encrypted communication. + public_key_hash: Hash of the public key file. + registration_instructions: Instructions for worker registration. + registration_needed: Whether registration is required (boolean). + role: Operator role identifier. + url: Primary URL for the operator. + website: Public-facing website URL. + webhook_url: Webhook endpoint for notifications. + """ category = "category" fee = "fee" @@ -190,3 +246,4 @@ class KVStoreKeys(Enum): ESCROW_BULK_PAYOUT_MAX_ITEMS = 99 +"""Maximum number of recipients allowed in a single bulk payout transaction.""" diff --git a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/decorators.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/decorators.py index f153b93bd1..0760b95854 100644 --- a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/decorators.py +++ b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/decorators.py @@ -1,11 +1,55 @@ +"""Decorators for SDK functionality.""" + +from typing import Callable, Any + + class RequiresSignerError(Exception): - """Raised when a signer or required middleware is missing in the Web3 instance.""" + """Raised when a transaction-signing method is called without proper Web3 account configuration. + + This exception is raised by the `@requires_signer` decorator when a method requiring + transaction signing capabilities is invoked on a Web3 instance that lacks: + + - A default account (w3.eth.default_account) + - SignAndSendRawMiddlewareBuilder middleware for transaction signing + """ pass -def requires_signer(method): - def wrapper(self, *args, **kwargs): +def requires_signer(method: Callable[..., Any]) -> Callable[..., Any]: + """Decorator that ensures Web3 instance has signing capabilities before executing a method. + + This decorator validates that the Web3 instance has both a default account configured + and the SignAndSendRawMiddlewareBuilder middleware installed. These are required for + methods that need to sign and send transactions. + + Args: + method (Callable[..., Any]): The method to decorate (must be a method of a class with a `w3` attribute). + + Returns: + Wrapped method that performs validation before execution. + + Raises: + RequiresSignerError: If the Web3 instance lacks a default account or signing middleware. + + Example: + ```python + from web3 import Web3 + from web3.middleware import SignAndSendRawMiddlewareBuilder + from human_protocol_sdk.decorators import requires_signer + + class MyClient: + def __init__(self, w3): + self.w3 = w3 + + @requires_signer + def send_transaction(self): + # This method requires a signer + pass + ``` + """ + + def wrapper(self: Any, *args: Any, **kwargs: Any) -> Any: if not self.w3.eth.default_account: raise RequiresSignerError("You must add an account to Web3 instance") if not self.w3.middleware_onion.get("SignAndSendRawMiddlewareBuilder"): diff --git a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/encryption/encryption.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/encryption/encryption.py index 284b30fbd1..1bf00a16e2 100644 --- a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/encryption/encryption.py +++ b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/encryption/encryption.py @@ -1,44 +1,4 @@ -""" -This class allows signing, verifying, encrypting, and -decrypting messages at all levels of escrow processing. - -The algorithm includes the implementation of the -[PGP encryption algorithm](https://github.com/openpgpjs/openpgpjs) -multi-public key encryption in Python. -Using the vanilla [ed25519](https://en.wikipedia.org/wiki/EdDSA#Ed25519) -implementation Schnorr signatures for signature and -[curve25519](https://en.wikipedia.org/wiki/Curve25519) for encryption. -Learn [more](https://wiki.polkadot.network/docs/learn-cryptography). - -Code Example ------------- - -.. code-block:: python - - from human_protocol_sdk.encryption import Encryption - - private_key = \"\"\"-----BEGIN PGP PRIVATE KEY BLOCK----- - - xVgEZJ1mYRYJKwYBBAHaRw8BAQdAGLLi15zjuVhD4eUOYR5v40kDyRb3nrkh - 0tO5pPNXBIkAAQCXERVkGLDJadkZ3yzerGQeJyxM0Xl5IaEWrzQsSCt/mwz7 - zRRIdW1hbiA8aHVtYW5AaG10LmFpPsKMBBAWCgA+BQJknWZhBAsJBwgJEAyX - rIbvfPxlAxUICgQWAAIBAhkBAhsDAh4BFiEEGWQNXhKpp2hxuxetDJeshu98 - /GUAAFldAP4/HVRKEso+QiphYxfAIPbCbrZ+xy6RTFAW0tdjpDQwJQD+P81w - 74pFhmBFjb8Aio87M1lLRzLSXjEVpKEciGerkQjHXQRknWZhEgorBgEEAZdV - AQUBAQdA+/XEHJiIC5GtJPxgybd2TyJe5kzTyh0+uzwAgD33R3cDAQgHAAD/ - brJ3/2P+H4wOTV25YBp+UVvE0MqiVrCLk5kBNJdpN8AQn8J4BBgWCAAqBQJk - nWZhCRAMl6yG73z8ZQIbDBYhBBlkDV4SqadocbsXrQyXrIbvfPxlAAC04QD+ - Jyyd/rDd4bEuAvsHFQHK2HMC2r0OLVHdMjygPELEA+sBANNtHfc60ts3++D7 - dhjPN+xEYS1/BntokSSwC8mi56AJ - =GMlv - -----END PGP PRIVATE KEY BLOCK-----\"\"\" - passphrase = "passphrase" - - encryption = Encryption(private_key, passphrase) - -Module ------- -""" +"""Encrypt, decrypt, sign, and verify messages using PGP.""" from typing import Optional, List, Union from pgpy import PGPKey, PGPMessage @@ -47,16 +7,36 @@ class Encryption: - """ - A class that provides encryption and decryption functionality using PGP (Pretty Good Privacy). + """Encryption and decryption helper using PGP (Pretty Good Privacy). + + This class provides methods to sign, encrypt, decrypt, and verify messages + using PGP encryption with private/public key pairs. + + Attributes: + private_key (PGPKey): The unlocked PGP private key. + passphrase (Optional[str]): Passphrase used to unlock the private key. """ def __init__(self, private_key_armored: str, passphrase: Optional[str] = None): - """ - Initializes an Encryption instance. + """Initialize an Encryption instance with a private key. + + Args: + private_key_armored (str): Armored representation of the PGP private key. + passphrase (Optional[str]): Passphrase to unlock the private key if it's locked. - :param private_key_armored: Armored representation of the private key - :param passphrase: Passphrase to unlock the private key. Defaults to None. + Raises: + ValueError: If the private key is invalid, cannot be unlocked with the passphrase, + or is locked and no passphrase is provided. + + Example: + ```python + from human_protocol_sdk.encryption import Encryption + + encryption = Encryption( + "-----BEGIN PGP PRIVATE KEY BLOCK-----...", + "your-passphrase" + ) + ``` """ try: self.private_key, _ = PGPKey.from_blob(private_key_armored) @@ -77,69 +57,30 @@ def __init__(self, private_key_armored: str, passphrase: Optional[str] = None): def sign_and_encrypt( self, message: Union[str, bytes], public_keys: List[str] ) -> str: - """ - Signs and encrypts a message using the private key and recipient's public keys. - - :param message: Message to sign and encrypt - :param public_keys: List of armored public keys of the recipients - - :return: Armored and signed/encrypted message - - :example: - .. code-block:: python - - from human_protocol_sdk.encryption import Encryption - - private_key = \"\"\"-----BEGIN PGP PRIVATE KEY BLOCK----- - - xVgEZJ1mYRYJKwYBBAHaRw8BAQdAGLLi15zjuVhD4eUOYR5v40kDyRb3nrkh - 0tO5pPNXBIkAAQCXERVkGLDJadkZ3yzerGQeJyxM0Xl5IaEWrzQsSCt/mwz7 - zRRIdW1hbiA8aHVtYW5AaG10LmFpPsKMBBAWCgA+BQJknWZhBAsJBwgJEAyX - rIbvfPxlAxUICgQWAAIBAhkBAhsDAh4BFiEEGWQNXhKpp2hxuxetDJeshu98 - /GUAAFldAP4/HVRKEso+QiphYxfAIPbCbrZ+xy6RTFAW0tdjpDQwJQD+P81w - 74pFhmBFjb8Aio87M1lLRzLSXjEVpKEciGerkQjHXQRknWZhEgorBgEEAZdV - AQUBAQdA+/XEHJiIC5GtJPxgybd2TyJe5kzTyh0+uzwAgD33R3cDAQgHAAD/ - brJ3/2P+H4wOTV25YBp+UVvE0MqiVrCLk5kBNJdpN8AQn8J4BBgWCAAqBQJk - nWZhCRAMl6yG73z8ZQIbDBYhBBlkDV4SqadocbsXrQyXrIbvfPxlAAC04QD+ - Jyyd/rDd4bEuAvsHFQHK2HMC2r0OLVHdMjygPELEA+sBANNtHfc60ts3++D7 - dhjPN+xEYS1/BntokSSwC8mi56AJ - =GMlv - -----END PGP PRIVATE KEY BLOCK-----\"\"\" - - passphrase = "passphrase" - - public_key2 = \"\"\"-----BEGIN PGP PUBLIC KEY BLOCK----- - - xjMEZKKJZRYJKwYBBAHaRw8BAQdAiy9Cvf7Stb5uGaPWTxhk2kEWgwHI75PK - JAN1Re+mZ/7NFEh1bWFuIDxodW1hbkBobXQuYWk+wowEEBYKAD4FAmSiiWUE - CwkHCAkQLJTUgF16PUcDFQgKBBYAAgECGQECGwMCHgEWIQRHZsSFAPBxClHV - TEYslNSAXXo9RwAAUYYA+gJKoCHiEl/1AUNKZrWBmvS3J9BRAFgvGHFmUKSQ - qvCJAP9+M55C/K0QjO1B9N14TPsnENaB0IIlvavhNUgKow9sBc44BGSiiWUS - CisGAQQBl1UBBQEBB0DWVuH+76KUCwGbLNnrTAGxysoo6TWpkG1upYQvZztB - cgMBCAfCeAQYFggAKgUCZKKJZQkQLJTUgF16PUcCGwwWIQRHZsSFAPBxClHV - TEYslNSAXXo9RwAA0dMBAJ0cd1OM/yWJdaVQcPp4iQOFh7hAOZlcOPF2NTRr - 1AvDAQC4Xx6swMIiu2Nx/2JYXr3QdUO/tBtC/QvU8LPQETo9Cg== - =4PJh - -----END PGP PUBLIC KEY BLOCK-----\"\"\" - - public_key3 = \"\"\"-----BEGIN PGP PUBLIC KEY BLOCK----- - - xjMEZKLMDhYJKwYBBAHaRw8BAQdAufXwhFItFe4j2IuTa3Yc4lZMNAxV/B+k - X8mJ5PzqY4fNFEh1bWFuIDxodW1hbkBobXQuYWk+wowEEBYKAD4FAmSizA4E - CwkHCAkQsGTIZV9ne20DFQgKBBYAAgECGQECGwMCHgEWIQTviv8XOCeYpubG - OoWwZMhlX2d7bQAAYAUA/35sTPhzQjm7uPpSTw2ahUfRijlxfKRWc5p36x0L - NX+mAQCxwUgrbR2ngZOa5E+AQM8tyq8fh1qMvrM5hNeNRNf/Cc44BGSizA4S - CisGAQQBl1UBBQEBB0D8B9TjjY+KyoYR9wUE1tCaCi1N4ZoGFKscey3H5y80 - AAMBCAfCeAQYFggAKgUCZKLMDgkQsGTIZV9ne20CGwwWIQTviv8XOCeYpubG - OoWwZMhlX2d7bQAARg0BAMuQnhXzyIbbARtV3dobO7nw+VwCHVs9E7OtzLUi - 25TEAP4m0jWfjq8w+0dM9U+/+r1FqMk/q7RU8Ib8HJXUOMaGBw== - =62qY - -----END PGP PUBLIC KEY BLOCK-----\"\"\" - - encryption = Encryption(private_key, passphrase) - encrypted_message = encryption.sign_and_encrypt( - "your message", [public_key2, public_key3] - ) + """Sign and encrypt a message with recipient public keys. + + Signs the message with the private key and encrypts it for all specified recipients. + + Args: + message (Union[str, bytes]): Message content to sign and encrypt. + public_keys (List[str]): List of armored PGP public keys of the recipients. + + Returns: + Armored, signed, and encrypted PGP message. + + Raises: + ValueError: If the private key cannot be unlocked or encryption fails. + + Example: + ```python + from human_protocol_sdk.encryption import Encryption + + encryption = Encryption("-----BEGIN PGP PRIVATE KEY BLOCK-----...", "passphrase") + encrypted_message = encryption.sign_and_encrypt( + "your message", + ["-----BEGIN PGP PUBLIC KEY BLOCK-----..."], + ) + ``` """ pgp_message = PGPMessage.new(message) @@ -164,39 +105,35 @@ def sign_and_encrypt( return pgp_message.__str__() def decrypt(self, message: str, public_key: Optional[str] = None) -> bytes: - """ - Decrypts a message using the private key. - - :param message: Armored message to decrypt - :param public_key: Armored public key used for signature verification. Defaults to None. + """Decrypt a message using the private key. - :return: Decrypted message + Decrypts an encrypted message and optionally verifies the signature using + the sender's public key. - :example: - .. code-block:: python + Args: + message (str): Armored PGP message to decrypt. + public_key (Optional[str]): Optional armored public key to verify the message signature. - from human_protocol_sdk.encryption import Encryption + Returns: + Decrypted message as bytes. - private_key = \"\"\"-----BEGIN PGP PRIVATE KEY BLOCK----- + Raises: + ValueError: If the private key cannot be unlocked, decryption fails, + or signature verification fails when a public key is provided. - xVgEZJ1mYRYJKwYBBAHaRw8BAQdAGLLi15zjuVhD4eUOYR5v40kDyRb3nrkh - 0tO5pPNXBIkAAQCXERVkGLDJadkZ3yzerGQeJyxM0Xl5IaEWrzQsSCt/mwz7 - zRRIdW1hbiA8aHVtYW5AaG10LmFpPsKMBBAWCgA+BQJknWZhBAsJBwgJEAyX - rIbvfPxlAxUICgQWAAIBAhkBAhsDAh4BFiEEGWQNXhKpp2hxuxetDJeshu98 - /GUAAFldAP4/HVRKEso+QiphYxfAIPbCbrZ+xy6RTFAW0tdjpDQwJQD+P81w - 74pFhmBFjb8Aio87M1lLRzLSXjEVpKEciGerkQjHXQRknWZhEgorBgEEAZdV - AQUBAQdA+/XEHJiIC5GtJPxgybd2TyJe5kzTyh0+uzwAgD33R3cDAQgHAAD/ - brJ3/2P+H4wOTV25YBp+UVvE0MqiVrCLk5kBNJdpN8AQn8J4BBgWCAAqBQJk - nWZhCRAMl6yG73z8ZQIbDBYhBBlkDV4SqadocbsXrQyXrIbvfPxlAAC04QD+ - Jyyd/rDd4bEuAvsHFQHK2HMC2r0OLVHdMjygPELEA+sBANNtHfc60ts3++D7 - dhjPN+xEYS1/BntokSSwC8mi56AJ - =GMlv - -----END PGP PRIVATE KEY BLOCK-----\"\"\" + Example: + ```python + from human_protocol_sdk.encryption import Encryption - passphrase = "passphrase" + encryption = Encryption("-----BEGIN PGP PRIVATE KEY BLOCK-----...", "passphrase") + decrypted_message = encryption.decrypt(encrypted_message) - encryption = Encryption(private_key, passphrase) - decrypted_message = encryption.decrypt(encrypted_message) + # Or with signature verification: + decrypted_message = encryption.decrypt( + encrypted_message, + public_key="-----BEGIN PGP PUBLIC KEY BLOCK-----..." + ) + ``` """ pgp_message = PGPMessage.from_blob(message) decrypted_message = "" @@ -229,38 +166,27 @@ def decrypt(self, message: str, public_key: Optional[str] = None) -> bytes: raise ValueError("Failed to decrypt message: {}".format(str(e))) def sign(self, message: Union[str, bytes]) -> str: - """ - Signs a message using the private key. - - :param message: Message to sign - - :return: Armored and signed message + """Sign a message with the private key. - :example: - .. code-block:: python + Creates a cleartext signed message that can be verified by anyone with + the corresponding public key. - from human_protocol_sdk.encryption import Encryption + Args: + message (Union[str, bytes]): Message content to sign. - private_key = \"\"\"-----BEGIN PGP PRIVATE KEY BLOCK----- + Returns: + Armored signed PGP message in cleartext format. - xVgEZJ1mYRYJKwYBBAHaRw8BAQdAGLLi15zjuVhD4eUOYR5v40kDyRb3nrkh - 0tO5pPNXBIkAAQCXERVkGLDJadkZ3yzerGQeJyxM0Xl5IaEWrzQsSCt/mwz7 - zRRIdW1hbiA8aHVtYW5AaG10LmFpPsKMBBAWCgA+BQJknWZhBAsJBwgJEAyX - rIbvfPxlAxUICgQWAAIBAhkBAhsDAh4BFiEEGWQNXhKpp2hxuxetDJeshu98 - /GUAAFldAP4/HVRKEso+QiphYxfAIPbCbrZ+xy6RTFAW0tdjpDQwJQD+P81w - 74pFhmBFjb8Aio87M1lLRzLSXjEVpKEciGerkQjHXQRknWZhEgorBgEEAZdV - AQUBAQdA+/XEHJiIC5GtJPxgybd2TyJe5kzTyh0+uzwAgD33R3cDAQgHAAD/ - brJ3/2P+H4wOTV25YBp+UVvE0MqiVrCLk5kBNJdpN8AQn8J4BBgWCAAqBQJk - nWZhCRAMl6yG73z8ZQIbDBYhBBlkDV4SqadocbsXrQyXrIbvfPxlAAC04QD+ - Jyyd/rDd4bEuAvsHFQHK2HMC2r0OLVHdMjygPELEA+sBANNtHfc60ts3++D7 - dhjPN+xEYS1/BntokSSwC8mi56AJ - =GMlv - -----END PGP PRIVATE KEY BLOCK-----\"\"\" + Raises: + ValueError: If the private key cannot be unlocked or signing fails. - passphrase = "passphrase" + Example: + ```python + from human_protocol_sdk.encryption import Encryption - encryption = Encryption(private_key, passphrase) - signed_message = await encryption.sign("MESSAGE") + encryption = Encryption("-----BEGIN PGP PRIVATE KEY BLOCK-----...", "passphrase") + signed_message = encryption.sign("MESSAGE") + ``` """ message = PGPMessage.new(message, cleartext=True) if not self.private_key.is_unlocked: diff --git a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/encryption/encryption_utils.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/encryption/encryption_utils.py index 98b853d64c..b966eaaead 100644 --- a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/encryption/encryption_utils.py +++ b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/encryption/encryption_utils.py @@ -1,49 +1,4 @@ -""" -Utility class for encryption-related operations. - -Code Example ------------- - -.. code-block:: python - - from human_protocol_sdk.encryption import EncryptionUtils - - public_key2 = \"\"\"-----BEGIN PGP PUBLIC KEY BLOCK----- - - xjMEZKKJZRYJKwYBBAHaRw8BAQdAiy9Cvf7Stb5uGaPWTxhk2kEWgwHI75PK - JAN1Re+mZ/7NFEh1bWFuIDxodW1hbkBobXQuYWk+wowEEBYKAD4FAmSiiWUE - CwkHCAkQLJTUgF16PUcDFQgKBBYAAgECGQECGwMCHgEWIQRHZsSFAPBxClHV - TEYslNSAXXo9RwAAUYYA+gJKoCHiEl/1AUNKZrWBmvS3J9BRAFgvGHFmUKSQ - qvCJAP9+M55C/K0QjO1B9N14TPsnENaB0IIlvavhNUgKow9sBc44BGSiiWUS - CisGAQQBl1UBBQEBB0DWVuH+76KUCwGbLNnrTAGxysoo6TWpkG1upYQvZztB - cgMBCAfCeAQYFggAKgUCZKKJZQkQLJTUgF16PUcCGwwWIQRHZsSFAPBxClHV - TEYslNSAXXo9RwAA0dMBAJ0cd1OM/yWJdaVQcPp4iQOFh7hAOZlcOPF2NTRr - 1AvDAQC4Xx6swMIiu2Nx/2JYXr3QdUO/tBtC/QvU8LPQETo9Cg== - =4PJh - -----END PGP PUBLIC KEY BLOCK-----\"\"\" - - public_key3 = \"\"\"-----BEGIN PGP PUBLIC KEY BLOCK----- - - xjMEZKLMDhYJKwYBBAHaRw8BAQdAufXwhFItFe4j2IuTa3Yc4lZMNAxV/B+k - X8mJ5PzqY4fNFEh1bWFuIDxodW1hbkBobXQuYWk+wowEEBYKAD4FAmSizA4E - CwkHCAkQsGTIZV9ne20DFQgKBBYAAgECGQECGwMCHgEWIQTviv8XOCeYpubG - OoWwZMhlX2d7bQAAYAUA/35sTPhzQjm7uPpSTw2ahUfRijlxfKRWc5p36x0L - NX+mAQCxwUgrbR2ngZOa5E+AQM8tyq8fh1qMvrM5hNeNRNf/Cc44BGSizA4S - CisGAQQBl1UBBQEBB0D8B9TjjY+KyoYR9wUE1tCaCi1N4ZoGFKscey3H5y80 - AAMBCAfCeAQYFggAKgUCZKLMDgkQsGTIZV9ne20CGwwWIQTviv8XOCeYpubG - OoWwZMhlX2d7bQAARg0BAMuQnhXzyIbbARtV3dobO7nw+VwCHVs9E7OtzLUi - 25TEAP4m0jWfjq8w+0dM9U+/+r1FqMk/q7RU8Ib8HJXUOMaGBw== - =62qY - -----END PGP PUBLIC KEY BLOCK-----\"\"\" - - encrypted_message = EncryptionUtils.encrypt( - "MESSAGE", - [public_key2, public_key3] - ) - -Module ------- -""" +"""Utility helpers for PGP encryption tasks.""" from typing import List @@ -53,57 +8,39 @@ class EncryptionUtils: - """ - A utility class that provides additional encryption-related functionalities. + """Utility class providing static methods for PGP encryption operations. + + This class offers helper methods for encrypting messages, verifying signatures, + extracting signed data, and checking message encryption status without requiring + a private key instance. """ @staticmethod def encrypt(message: str, public_keys: List[str]) -> str: - """ - Encrypts a message using the recipient's public keys. - - :param message: Message to encrypt - :param public_keys: List of armored public keys of the recipients - - :return: Armored and encrypted message - - :example: - .. code-block:: python - - from human_protocol_sdk.encryption import EncryptionUtils - - public_key2 = \"\"\"-----BEGIN PGP PUBLIC KEY BLOCK----- - - xjMEZKKJZRYJKwYBBAHaRw8BAQdAiy9Cvf7Stb5uGaPWTxhk2kEWgwHI75PK - JAN1Re+mZ/7NFEh1bWFuIDxodW1hbkBobXQuYWk+wowEEBYKAD4FAmSiiWUE - CwkHCAkQLJTUgF16PUcDFQgKBBYAAgECGQECGwMCHgEWIQRHZsSFAPBxClHV - TEYslNSAXXo9RwAAUYYA+gJKoCHiEl/1AUNKZrWBmvS3J9BRAFgvGHFmUKSQ - qvCJAP9+M55C/K0QjO1B9N14TPsnENaB0IIlvavhNUgKow9sBc44BGSiiWUS - CisGAQQBl1UBBQEBB0DWVuH+76KUCwGbLNnrTAGxysoo6TWpkG1upYQvZztB - cgMBCAfCeAQYFggAKgUCZKKJZQkQLJTUgF16PUcCGwwWIQRHZsSFAPBxClHV - TEYslNSAXXo9RwAA0dMBAJ0cd1OM/yWJdaVQcPp4iQOFh7hAOZlcOPF2NTRr - 1AvDAQC4Xx6swMIiu2Nx/2JYXr3QdUO/tBtC/QvU8LPQETo9Cg== - =4PJh - -----END PGP PUBLIC KEY BLOCK-----\"\"\" - - public_key3 = \"\"\"-----BEGIN PGP PUBLIC KEY BLOCK----- - - xjMEZKLMDhYJKwYBBAHaRw8BAQdAufXwhFItFe4j2IuTa3Yc4lZMNAxV/B+k - X8mJ5PzqY4fNFEh1bWFuIDxodW1hbkBobXQuYWk+wowEEBYKAD4FAmSizA4E - CwkHCAkQsGTIZV9ne20DFQgKBBYAAgECGQECGwMCHgEWIQTviv8XOCeYpubG - OoWwZMhlX2d7bQAAYAUA/35sTPhzQjm7uPpSTw2ahUfRijlxfKRWc5p36x0L - NX+mAQCxwUgrbR2ngZOa5E+AQM8tyq8fh1qMvrM5hNeNRNf/Cc44BGSizA4S - CisGAQQBl1UBBQEBB0D8B9TjjY+KyoYR9wUE1tCaCi1N4ZoGFKscey3H5y80 - AAMBCAfCeAQYFggAKgUCZKLMDgkQsGTIZV9ne20CGwwWIQTviv8XOCeYpubG - OoWwZMhlX2d7bQAARg0BAMuQnhXzyIbbARtV3dobO7nw+VwCHVs9E7OtzLUi - 25TEAP4m0jWfjq8w+0dM9U+/+r1FqMk/q7RU8Ib8HJXUOMaGBw== - =62qY - -----END PGP PUBLIC KEY BLOCK-----\"\"\" - - encrypted_message = EncryptionUtils.encrypt( - "MESSAGE", - [public_key2, public_key3] - ) + """Encrypt a message using recipient public keys. + + Encrypts a message so that only holders of the corresponding private keys + can decrypt it. Does not sign the message. + + Args: + message (str): Plain text message to encrypt. + public_keys (List[str]): List of armored PGP public keys of the recipients. + + Returns: + Armored encrypted PGP message. + + Raises: + PGPError: If encryption fails or public keys are invalid. + + Example: + ```python + from human_protocol_sdk.encryption import EncryptionUtils + + encrypted_message = EncryptionUtils.encrypt( + "MESSAGE", + ["-----BEGIN PGP PUBLIC KEY BLOCK-----..."], + ) + ``` """ pgp_message = PGPMessage.new(message) cipher = SymmetricKeyAlgorithm.AES256 @@ -118,57 +55,27 @@ def encrypt(message: str, public_keys: List[str]) -> str: @staticmethod def verify(message: str, public_key: str) -> bool: - """ - Verifies the signature of a message using the corresponding public key. - - :param message: Armored message to verify - :param public_key: Armored public key - - :return: True if the signature is valid, False otherwise - - :example: - .. code-block:: python - - from human_protocol_sdk.encryption import Encryption, EncryptionUtils - - private_key3 = \"\"\"-----BEGIN PGP PRIVATE KEY BLOCK----- - - xYYEZKLMDhYJKwYBBAHaRw8BAQdAufXwhFItFe4j2IuTa3Yc4lZMNAxV/B+k - X8mJ5PzqY4f+CQMISyqDKFlj2s/gu7LzRcFRveVbtXvQJ6lvwWEpUgkc0NAL - HykIe1gLJhsoR+v5J5fXTYwDridyL4YPLJCp7yF1K3FtyOV8Cqg46N5ijbGd - Gs0USHVtYW4gPGh1bWFuQGhtdC5haT7CjAQQFgoAPgUCZKLMDgQLCQcICRCw - ZMhlX2d7bQMVCAoEFgACAQIZAQIbAwIeARYhBO+K/xc4J5im5sY6hbBkyGVf - Z3ttAABgBQD/fmxM+HNCObu4+lJPDZqFR9GKOXF8pFZzmnfrHQs1f6YBALHB - SCttHaeBk5rkT4BAzy3Krx+HWoy+szmE141E1/8Jx4sEZKLMDhIKKwYBBAGX - VQEFAQEHQPwH1OONj4rKhhH3BQTW0JoKLU3hmgYUqxx7LcfnLzQAAwEIB/4J - Awhl3IXvo7mhyuAZwgOcvaH1X9ijw5l/VffBLYBhtmEnvN62iNZPNashQL26 - GOhrAB/v5I1XLacKNrwNP47UVGl/jz014ZBYTPGabhGl2kVQwngEGBYIACoF - AmSizA4JELBkyGVfZ3ttAhsMFiEE74r/FzgnmKbmxjqFsGTIZV9ne20AAEYN - AQDLkJ4V88iG2wEbVd3aGzu58PlcAh1bPROzrcy1ItuUxAD+JtI1n46vMPtH - TPVPv/q9RajJP6u0VPCG/ByV1DjGhgc= - =uaJU - -----END PGP PRIVATE KEY BLOCK-----\"\"\" - - passphrase = "passphrase" - - public_key = \"\"\"-----BEGIN PGP PUBLIC KEY BLOCK----- - - xjMEZJ1mYRYJKwYBBAHaRw8BAQdAGLLi15zjuVhD4eUOYR5v40kDyRb3nrkh - 0tO5pPNXBInNFEh1bWFuIDxodW1hbkBobXQuYWk+wowEEBYKAD4FAmSdZmEE - CwkHCAkQDJeshu98/GUDFQgKBBYAAgECGQECGwMCHgEWIQQZZA1eEqmnaHG7 - F60Ml6yG73z8ZQAAWV0A/j8dVEoSyj5CKmFjF8Ag9sJutn7HLpFMUBbS12Ok - NDAlAP4/zXDvikWGYEWNvwCKjzszWUtHMtJeMRWkoRyIZ6uRCM44BGSdZmES - CisGAQQBl1UBBQEBB0D79cQcmIgLka0k/GDJt3ZPIl7mTNPKHT67PACAPfdH - dwMBCAfCeAQYFggAKgUCZJ1mYQkQDJeshu98/GUCGwwWIQQZZA1eEqmnaHG7 - F60Ml6yG73z8ZQAAtOEA/icsnf6w3eGxLgL7BxUBythzAtq9Di1R3TI8oDxC - xAPrAQDTbR33OtLbN/vg+3YYzzfsRGEtfwZ7aJEksAvJouegCQ== - =GU20 - -----END PGP PUBLIC KEY BLOCK-----\"\"\" - - encryption = Encryption(private_key3, passphrase) - signed_message = encryption.sign("MESSAGE") - - is_valid = EncryptionUtils.verify(signed_message, public_key) + """Verify the signature of a message. + + Checks if a signed message has a valid signature from the holder of + the private key corresponding to the provided public key. + + Args: + message (str): Armored PGP message to verify. + public_key (str): Armored PGP public key to verify the signature against. + + Returns: + ``True`` if the signature is valid, ``False`` otherwise. + + Example: + ```python + from human_protocol_sdk.encryption import EncryptionUtils + + is_valid = EncryptionUtils.verify( + signed_message, + "-----BEGIN PGP PUBLIC KEY BLOCK-----..." + ) + ``` """ try: signed_message = ( @@ -182,56 +89,23 @@ def verify(message: str, public_key: str) -> bool: @staticmethod def get_signed_data(message: str) -> str: - """ - Extracts the signed data from an armored signed message. - - :param message: Armored message - - :return: Extracted signed data - - :example: - .. code-block:: python - - from human_protocol_sdk.encryption import Encryption, EncryptionUtils - - private_key3 = \"\"\"-----BEGIN PGP PRIVATE KEY BLOCK----- - - xYYEZKLMDhYJKwYBBAHaRw8BAQdAufXwhFItFe4j2IuTa3Yc4lZMNAxV/B+k - X8mJ5PzqY4f+CQMISyqDKFlj2s/gu7LzRcFRveVbtXvQJ6lvwWEpUgkc0NAL - HykIe1gLJhsoR+v5J5fXTYwDridyL4YPLJCp7yF1K3FtyOV8Cqg46N5ijbGd - Gs0USHVtYW4gPGh1bWFuQGhtdC5haT7CjAQQFgoAPgUCZKLMDgQLCQcICRCw - ZMhlX2d7bQMVCAoEFgACAQIZAQIbAwIeARYhBO+K/xc4J5im5sY6hbBkyGVf - Z3ttAABgBQD/fmxM+HNCObu4+lJPDZqFR9GKOXF8pFZzmnfrHQs1f6YBALHB - SCttHaeBk5rkT4BAzy3Krx+HWoy+szmE141E1/8Jx4sEZKLMDhIKKwYBBAGX - VQEFAQEHQPwH1OONj4rKhhH3BQTW0JoKLU3hmgYUqxx7LcfnLzQAAwEIB/4J - Awhl3IXvo7mhyuAZwgOcvaH1X9ijw5l/VffBLYBhtmEnvN62iNZPNashQL26 - GOhrAB/v5I1XLacKNrwNP47UVGl/jz014ZBYTPGabhGl2kVQwngEGBYIACoF - AmSizA4JELBkyGVfZ3ttAhsMFiEE74r/FzgnmKbmxjqFsGTIZV9ne20AAEYN - AQDLkJ4V88iG2wEbVd3aGzu58PlcAh1bPROzrcy1ItuUxAD+JtI1n46vMPtH - TPVPv/q9RajJP6u0VPCG/ByV1DjGhgc= - =uaJU - -----END PGP PRIVATE KEY BLOCK-----\"\"\" - - passphrase = "passphrase" - - public_key = \"\"\"-----BEGIN PGP PUBLIC KEY BLOCK----- - - xjMEZJ1mYRYJKwYBBAHaRw8BAQdAGLLi15zjuVhD4eUOYR5v40kDyRb3nrkh - 0tO5pPNXBInNFEh1bWFuIDxodW1hbkBobXQuYWk+wowEEBYKAD4FAmSdZmEE - CwkHCAkQDJeshu98/GUDFQgKBBYAAgECGQECGwMCHgEWIQQZZA1eEqmnaHG7 - F60Ml6yG73z8ZQAAWV0A/j8dVEoSyj5CKmFjF8Ag9sJutn7HLpFMUBbS12Ok - NDAlAP4/zXDvikWGYEWNvwCKjzszWUtHMtJeMRWkoRyIZ6uRCM44BGSdZmES - CisGAQQBl1UBBQEBB0D79cQcmIgLka0k/GDJt3ZPIl7mTNPKHT67PACAPfdH - dwMBCAfCeAQYFggAKgUCZJ1mYQkQDJeshu98/GUCGwwWIQQZZA1eEqmnaHG7 - F60Ml6yG73z8ZQAAtOEA/icsnf6w3eGxLgL7BxUBythzAtq9Di1R3TI8oDxC - xAPrAQDTbR33OtLbN/vg+3YYzzfsRGEtfwZ7aJEksAvJouegCQ== - =GU20 - -----END PGP PUBLIC KEY BLOCK-----\"\"\" - - encryption = Encryption(private_key3, passphrase) - signed_message = encryption.sign("MESSAGE") - - result = EncryptionUtils.get_signed_data(signed_message) + """Extract the signed data from an armored signed message. + + Retrieves the original message content from a PGP signed message without + verifying the signature. + + Args: + message (str): Armored PGP signed message. + + Returns: + Extracted message content, or ``False`` if extraction fails. + + Example: + ```python + from human_protocol_sdk.encryption import EncryptionUtils + + original_message = EncryptionUtils.get_signed_data(signed_message) + ``` """ try: signed_message = ( @@ -243,30 +117,24 @@ def get_signed_data(message: str) -> str: @staticmethod def is_encrypted(message: str) -> bool: - """ - Checks whether a provided message is encrypted or not - - :param message: Text to check - - :return: True if the message is a PGP message, False otherwise + """Check whether a message is armored and encrypted. - :example: - .. code-block:: python + Determines if the provided text is a valid PGP encrypted message by checking + the message header. - from human_protocol_sdk.encryption import EncryptionUtils + Args: + message (str): Text to check for encryption. - message_1 = "message" - message_2 = \"\"\"-----BEGIN PGP MESSAGE----- + Returns: + ``True`` if the message is a PGP encrypted message, ``False`` otherwise. - wV4Dh8BoKHkyM3YSAQdAMGVFo+Meahw422JdMyDkxPA4LXeN94bOqsS9OhYGliYw - 72HgGdhoRHrRBKmRyD+Bb2HUrGptx8YRYqYJXiFVs4ev1USt6pF/5XjH+pM0d44B - 0j0BcVevrVhjdBia8kEr74NJKB2qiPAffbFJFRE1asYqQgFTjNC60/egqfzpdRay - Tj8C+e0IXRMECIXnrOaw - =SjJh - -----END PGP MESSAGE-----\"\"\" + Example: + ```python + from human_protocol_sdk.encryption import EncryptionUtils - print("The message_1 is encrypted: ", EncryptionUtils.is_encrypted(message_1)) - print("The message_2 is encrypted: ", EncryptionUtils.is_encrypted(message_2)) + if EncryptionUtils.is_encrypted(some_text): + print("Message is encrypted") + ``` """ try: unarmored = PGPMessage.ascii_unarmor(message) diff --git a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/escrow/escrow_client.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/escrow/escrow_client.py index 4d26bc20df..64bb1aa4de 100644 --- a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/escrow/escrow_client.py +++ b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/escrow/escrow_client.py @@ -1,18 +1,11 @@ -""" -This client enables to perform actions on Escrow contracts and -obtain information from both the contracts and subgraph. - -Internally, the SDK will use one network or another according to the network ID of the web3. -To use this client, you need to create Web3 instance, and configure default account, -as well as some middlewares. - -Code Example ------------- +"""Client to perform actions on Escrow contracts and obtain information from the contracts. -* With Signer - -.. code-block:: python +Selects the network based on the Web3 chain id. Configure Web3 with an account +and signer middleware for writes; read operations work without a signer. +Examples: + With signer: + ```python from eth_typing import URI from web3 import Web3 from web3.middleware import SignAndSendRawMiddlewareBuilder @@ -33,11 +26,11 @@ def get_w3_with_priv_key(priv_key: str): (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') escrow_client = EscrowClient(w3) + ``` -* Without Signer (For read operations only) - -.. code-block:: python + Read-only: + ```python from eth_typing import URI from web3 import Web3 from web3.providers.auto import load_provider_from_uri @@ -46,9 +39,7 @@ def get_w3_with_priv_key(priv_key: str): w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) escrow_client = EscrowClient(w3) - -Module ------- + ``` """ import logging @@ -78,42 +69,51 @@ def get_w3_with_priv_key(priv_key: str): class EscrowCancel: - def __init__(self, tx_hash: str, amount_refunded: any): - """ - Represents the result of an escrow cancellation transaction. + """Represents the result of an escrow cancellation transaction. - :param tx_hash: The hash of the transaction that cancelled the escrow. - :param amount_refunded: The amount refunded during the escrow cancellation. - """ + Attributes: + txHash (str): The hash of the transaction that cancelled the escrow. + amountRefunded (int): The amount refunded during the escrow cancellation. + """ + + def __init__(self, tx_hash: str, amount_refunded: any): self.txHash = tx_hash self.amountRefunded = amount_refunded class EscrowWithdraw: - def __init__(self, tx_hash: str, token_address: str, withdrawn_amount: any): - """ - Represents the result of an escrow cancellation transaction. + """Represents the result of an escrow withdrawal transaction. - :param tx_hash: The hash of the transaction associated with the escrow withdrawal. - :param token_address: The address of the token used for the withdrawal. - :param withdrawn_amount: The amount withdrawn from the escrow. - """ + Attributes: + txHash (str): The hash of the transaction associated with the escrow withdrawal. + token_address (str): The address of the token used for the withdrawal. + withdrawn_amount (int): The amount withdrawn from the escrow. + """ + + def __init__(self, tx_hash: str, token_address: str, withdrawn_amount: any): self.txHash = tx_hash self.token_address = token_address self.withdrawn_amount = withdrawn_amount class EscrowClientError(Exception): - """ - Raises when some error happens when interacting with escrow. - """ + """Exception raised when errors occur during escrow operations.""" pass class EscrowConfig: - """ - A class used to manage escrow parameters. + """Configuration parameters for escrow setup. + + Attributes: + recording_oracle_address (str): Address of the recording oracle. + reputation_oracle_address (str): Address of the reputation oracle. + exchange_oracle_address (str): Address of the exchange oracle. + recording_oracle_fee (int): Recording oracle fee percentage (0-100). + reputation_oracle_fee (int): Reputation oracle fee percentage (0-100). + exchange_oracle_fee (int): Exchange oracle fee percentage (0-100). + manifest (str): Manifest payload (URL or JSON string). + hash (str): Manifest file hash. """ def __init__( @@ -128,14 +128,9 @@ def __init__( hash: str, ): """ - Initializes a Escrow instance. - - :param recording_oracle_address: Address of the Recording Oracle - :param reputation_oracle_address: Address of the Reputation Oracle - :param recording_oracle_fee: Fee percentage of the Recording Oracle - :param reputation_oracle_fee: Fee percentage of the Reputation Oracle - :param manifest: Manifest data (can be a URL or JSON string) - :param hash: Manifest file hash + Raises: + EscrowClientError: If addresses are invalid, fees are out of range, + total fees exceed 100%, or manifest data is invalid. """ if not Web3.is_address(recording_oracle_address): raise EscrowClientError( @@ -174,15 +169,27 @@ def __init__( class EscrowClient: - """ - A client class to interact with the escrow smart contract. + """A client for interacting with escrow smart contracts. + + This client provides methods to create, fund, configure, and manage escrow contracts + on the Human Protocol network. It handles transaction signing, validation, and + event processing for escrow operations. + + Attributes: + w3 (Web3): Web3 instance configured for the target network. + network (dict): Network configuration for the current chain. + factory_contract (Contract): Contract instance for the escrow factory. """ def __init__(self, web3: Web3): - """ - Initializes a Escrow instance. + """Initialize an EscrowClient instance. + + Args: + web3 (Web3): Web3 instance configured for the target network. + Must have a valid provider and chain ID. - :param web3: The Web3 object + Raises: + EscrowClientError: If chain ID is invalid or network configuration is missing. """ # Initialize web3 instance @@ -216,46 +223,26 @@ def create_escrow( job_requester_id: str, tx_options: Optional[TxParams] = None, ) -> str: - """ - Creates a new escrow contract. - - :param token_address: Address of the token to be used in the escrow - :param job_requester_id: An off-chain identifier for the job requester - :param tx_options: (Optional) Transaction options - - :return: Address of the created escrow contract - - :example: - .. code-block:: python - - from eth_typing import URI - from web3 import Web3 - from web3.middleware import SignAndSendRawMiddlewareBuilder - from web3.providers.auto import load_provider_from_uri - - from human_protocol_sdk.escrow import EscrowClient - - def get_w3_with_priv_key(priv_key: str): - w3 = Web3(load_provider_from_uri( - URI("http://localhost:8545"))) - gas_payer = w3.eth.account.from_key(priv_key) - w3.eth.default_account = gas_payer.address - w3.middleware_onion.inject( - SignAndSendRawMiddlewareBuilder.build(priv_key), - 'SignAndSendRawMiddlewareBuilder', - layer=0, - ) - return (w3, gas_payer) - - (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') - escrow_client = EscrowClient(w3) - - token_address = '0x1234567890abcdef1234567890abcdef12345678' - job_requester_id = 'job-requester' - escrow_address = escrow_client.create_escrow( - token_address, - job_requester_id - ) + """Create a new escrow contract. + + Args: + token_address (str): ERC-20 token address to fund the escrow. + job_requester_id (str): Off-chain identifier for the job requester. + tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. + + Returns: + Address of the newly created escrow contract. + + Raises: + EscrowClientError: If the token address is invalid or the transaction fails. + + Example: + ```python + escrow_address = escrow_client.create_escrow( + "0x1234567890abcdef1234567890abcdef12345678", + "job-requester", + ) + ``` """ if not Web3.is_address(token_address): raise EscrowClientError(f"Invalid token address: {token_address}") @@ -286,65 +273,34 @@ def create_fund_and_setup_escrow( escrow_config: EscrowConfig, tx_options: Optional[TxParams] = None, ) -> str: - """ - Creates, funds, and sets up a new escrow contract in a single transaction. - - :param token_address: Address of the token to be used in the escrow - :param amount: The token amount to fund the escrow with - :param job_requester_id: An off-chain identifier for the job requester - :param escrow_config: Configuration parameters for escrow setup - :param tx_options: (Optional) Transaction options - - :return: Address of the created escrow contract - - :example: - .. code-block:: python - - from eth_typing import URI - from web3 import Web3 - from web3.middleware import SignAndSendRawMiddlewareBuilder - from web3.providers.auto import load_provider_from_uri - - from human_protocol_sdk.escrow import EscrowClient - - def get_w3_with_priv_key(priv_key: str): - w3 = Web3(load_provider_from_uri( - URI("http://localhost:8545"))) - gas_payer = w3.eth.account.from_key(priv_key) - w3.eth.default_account = gas_payer.address - w3.middleware_onion.inject( - SignAndSendRawMiddlewareBuilder.build(priv_key), - 'SignAndSendRawMiddlewareBuilder', - layer=0, - ) - return (w3, gas_payer) - - (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') - escrow_client = EscrowClient(w3) - - token_address = '0x1234567890abcdef1234567890abcdef12345678' - job_requester_id = 'job-requester' - amount = Web3.to_wei(5, 'ether') # convert from ETH to WEI - escrow_config = EscrowConfig( - recording_oracle_address='0xabcdefabcdefabcdefabcdefabcdefabcdefabcdef', - reputation_oracle_address='0xabcdefabcdefabcdefabcdefabcdefabcdefabcdef', - exchange_oracle_address='0xabcdefabcdefabcdefabcdefabcdefabcdefabcdef', - recording_oracle_fee=100, - reputation_oracle_fee=100, - exchange_oracle_fee=100, - recording_oracle_url='https://example.com/recording', - reputation_oracle_url='https://example.com/reputation', - exchange_oracle_url='https://example.com/exchange', - manifest_url='https://example.com/manifest', - manifest_hash='0xabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdef' - ) - - escrow_address = escrow_client.create_fund_and_setup_escrow( - token_address, - amount, - job_requester_id, - escrow_config - ) + """Create, fund, and configure an escrow in a single transaction. + + This is a convenience method that combines escrow creation, funding, and setup + into one atomic operation. + + Args: + token_address (str): ERC-20 token address to fund the escrow. + amount (int): Token amount to fund (in token's smallest unit). + job_requester_id (str): Off-chain identifier for the job requester. + escrow_config (EscrowConfig): Escrow configuration parameters including + oracle addresses, fees, and manifest data. + tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. + + Returns: + Address of the newly created and configured escrow contract. + + Raises: + EscrowClientError: If inputs are invalid or the transaction fails. + + Example: + ```python + escrow_address = escrow_client.create_fund_and_setup_escrow( + "0x1234567890abcdef1234567890abcdef12345678", + Web3.to_wei(5, "ether"), + "job-requester", + escrow_config, + ) + ``` """ if not Web3.is_address(token_address): raise EscrowClientError(f"Invalid token address: {token_address}") @@ -383,56 +339,26 @@ def setup( escrow_config: EscrowConfig, tx_options: Optional[TxParams] = None, ) -> None: - """ - Sets up the parameters of the escrow. - - :param escrow_address: Address of the escrow contract - :param escrow_config: Configuration parameters for the escrow - :param tx_options: (Optional) Transaction options - - :example: - .. code-block:: python - - from eth_typing import URI - from web3 import Web3 - from web3.middleware import SignAndSendRawMiddlewareBuilder - from web3.providers.auto import load_provider_from_uri - - from human_protocol_sdk.escrow import EscrowClient - - def get_w3_with_priv_key(priv_key: str): - w3 = Web3(load_provider_from_uri( - URI("http://localhost:8545"))) - gas_payer = w3.eth.account.from_key(priv_key) - w3.eth.default_account = gas_payer.address - w3.middleware_onion.inject( - SignAndSendRawMiddlewareBuilder.build(priv_key), - 'SignAndSendRawMiddlewareBuilder', - layer=0, - ) - return (w3, gas_payer) - - (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') - escrow_client = EscrowClient(w3) - - escrow_address = "0x1234567890abcdef1234567890abcdef12345678" - escrow_config = EscrowConfig( - recording_oracle_address='0xabcdefabcdefabcdefabcdefabcdefabcdefabcdef', - reputation_oracle_address='0xabcdefabcdefabcdefabcdefabcdefabcdefabcdef', - exchange_oracle_address='0xabcdefabcdefabcdefabcdefabcdefabcdefabcdef', - recording_oracle_fee=100, - reputation_oracle_fee=100, - exchange_oracle_fee=100, - recording_oracle_url='https://example.com/recording', - reputation_oracle_url='https://example.com/reputation', - exchange_oracle_url='https://example.com/exchange', - manifest_url='https://example.com/manifest', - manifest_hash='0xabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdef' - ) - escrow_client.setup( - escrow_address, - escrow_config - ) + """Set escrow roles, fees, and manifest metadata. + + Configures the escrow with oracle addresses, fee percentages, and manifest information. + + Args: + escrow_address (str): Address of the escrow contract to configure. + escrow_config (EscrowConfig): Escrow configuration parameters including + oracle addresses, fees, and manifest data. + tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. + + Returns: + None + + Raises: + EscrowClientError: If the escrow address is invalid or the transaction fails. + + Example: + ```python + escrow_client.setup("0xYourEscrow", escrow_config) + ``` """ if not Web3.is_address(escrow_address): raise EscrowClientError(f"Invalid escrow address: {escrow_address}") @@ -463,45 +389,26 @@ def fund( amount: int, tx_options: Optional[TxParams] = None, ) -> None: - """ - Adds funds to the escrow. - - :param escrow_address: Address of the escrow to fund - :param amount: Amount to be added as funds - :param tx_options: (Optional) Additional transaction parameters - - :return: None + """Add funds to the escrow. - :raise EscrowClientError: If an error occurs while checking the parameters + Transfers tokens from the caller's account to the escrow contract. - :example: - .. code-block:: python + Args: + escrow_address (str): Address of the escrow to fund. + amount (int): Amount of tokens to transfer (must be positive, in token's smallest unit). + tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. - from eth_typing import URI - from web3 import Web3 - from web3.middleware import SignAndSendRawMiddlewareBuilder - from web3.providers.auto import load_provider_from_uri + Returns: + None - from human_protocol_sdk.escrow import EscrowClient + Raises: + EscrowClientError: If inputs are invalid or the transfer fails. - def get_w3_with_priv_key(priv_key: str): - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - gas_payer = w3.eth.account.from_key(priv_key) - w3.eth.default_account = gas_payer.address - w3.middleware_onion.inject( - SignAndSendRawMiddlewareBuilder.build(priv_key), - 'SignAndSendRawMiddlewareBuilder', - layer=0, - ) - return (w3, gas_payer) - - (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') - escrow_client = EscrowClient(w3) - - amount = Web3.to_wei(5, 'ether') # convert from ETH to WEI - escrow_client.fund( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f", amount - ) + Example: + ```python + amount = Web3.to_wei(5, "ether") + escrow_client.fund("0x62dD51230A30401C455c8398d06F85e4EaB6309f", amount) + ``` """ if not Web3.is_address(escrow_address): raise EscrowClientError(f"Invalid escrow address: {escrow_address}") @@ -529,48 +436,33 @@ def store_results( funds_to_reserve: Optional[int] = None, tx_options: Optional[TxParams] = None, ) -> None: - """ - Stores the results URL and hash, with optional funds to reserve. - - :param escrow_address: Address of the escrow - :param url: Results file URL - :param hash: Results file hash - :param funds_to_reserve: (Optional) Funds to reserve for payouts - :param tx_options: (Optional) Additional transaction parameters - - :return: None - - :raise EscrowClientError: If an error occurs while checking the parameters - - :example: - .. code-block:: python - - from eth_typing import URI - from web3 import Web3 - from web3.middleware import SignAndSendRawMiddlewareBuilder - from web3.providers.auto import load_provider_from_uri - - from human_protocol_sdk.escrow import EscrowClient - - def get_w3_with_priv_key(priv_key: str): - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - gas_payer = w3.eth.account.from_key(priv_key) - w3.eth.default_account = gas_payer.address - w3.middleware_onion.inject( - SignAndSendRawMiddlewareBuilder.build(priv_key), - 'SignAndSendRawMiddlewareBuilder', - layer=0, - ) - return (w3, gas_payer) - - (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') - escrow_client = EscrowClient(w3) - - escrow_client.store_results( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f", - "http://localhost/results.json", - "b5dad76bf6772c0f07fd5e048f6e75a5f86ee079" - ) + """Store results URL and hash, with optional funds reservation. + + Stores the intermediate or final results location and hash. Optionally reserves + funds for future payouts. + + Args: + escrow_address (str): Address of the escrow. + url (str): Results file URL. + hash (str): Results file hash. + funds_to_reserve (Optional[int]): Optional funds to reserve for payouts. + If None, uses legacy signature without reservation. + tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. + + Returns: + None + + Raises: + EscrowClientError: If validation fails or the transaction reverts. + + Example: + ```python + escrow_client.store_results( + "0x62dD51230A30401C455c8398d06F85e4EaB6309f", + "http://localhost/results.json", + "b5dad76bf6772c0f07fd5e048f6e75a5f86ee079", + ) + ``` """ if not Web3.is_address(escrow_address): raise EscrowClientError(f"Invalid escrow address: {escrow_address}") @@ -614,41 +506,24 @@ def get_w3_with_priv_key(priv_key: str): def complete( self, escrow_address: str, tx_options: Optional[TxParams] = None ) -> None: - """ - Sets the status of an escrow to completed. - - :param escrow_address: Address of the escrow to complete - :param tx_options: (Optional) Additional transaction parameters - - :return: None + """Set the status of an escrow to completed. - :raise EscrowClientError: If an error occurs while checking the parameters + Marks the escrow as completed, preventing further modifications. - :example: - .. code-block:: python + Args: + escrow_address (str): Address of the escrow to complete. + tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. - from eth_typing import URI - from web3 import Web3 - from web3.middleware import SignAndSendRawMiddlewareBuilder - from web3.providers.auto import load_provider_from_uri + Returns: + None - from human_protocol_sdk.escrow import EscrowClient + Raises: + EscrowClientError: If validation fails or the transaction reverts. - def get_w3_with_priv_key(priv_key: str): - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - gas_payer = w3.eth.account.from_key(priv_key) - w3.eth.default_account = gas_payer.address - w3.middleware_onion.inject( - SignAndSendRawMiddlewareBuilder.build(priv_key), - 'SignAndSendRawMiddlewareBuilder', - layer=0, - ) - return (w3, gas_payer) - - (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') - escrow_client = EscrowClient(w3) - - escrow_client.complete("0x62dD51230A30401C455c8398d06F85e4EaB6309f") + Example: + ```python + escrow_client.complete("0x62dD51230A30401C455c8398d06F85e4EaB6309f") + ``` """ if not Web3.is_address(escrow_address): raise EscrowClientError(f"Invalid escrow address: {escrow_address}") @@ -675,65 +550,40 @@ def bulk_payout( force_complete: bool, tx_options: Optional[TxParams] = None, ) -> None: - """ - Pays out to recipients, supporting both payoutId (str) and txId (int) signatures and sets the URL of the final results file. - - :param escrow_address: Address of the escrow - :param recipients: List of recipient addresses - :param amounts: List of amounts - :param final_results_url: Final results file URL - :param final_results_hash: Final results file hash - :param payout_id: Payout ID (str) or Transaction ID (int) - :param force_complete: (Optional) Whether to force completion - :param tx_options: (Optional) Transaction options - - :return: None - - :raise EscrowClientError: If an error occurs while checking the parameters - - :example: - .. code-block:: python - - from eth_typing import URI - from web3 import Web3 - from web3.middleware import SignAndSendRawMiddlewareBuilder - from web3.providers.auto import load_provider_from_uri - - from human_protocol_sdk.escrow import EscrowClient - - def get_w3_with_priv_key(priv_key: str): - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - gas_payer = w3.eth.account.from_key(priv_key) - w3.eth.default_account = gas_payer.address - w3.middleware_onion.inject( - SignAndSendRawMiddlewareBuilder.build(priv_key), - 'SignAndSendRawMiddlewareBuilder', - layer=0, - ) - return (w3, gas_payer) - - (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') - escrow_client = EscrowClient(w3) - - recipients = [ - '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', - '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92267' - ] - amounts = [ - Web3.to_wei(5, 'ether'), - Web3.to_wei(10, 'ether') - ] - results_url = 'http://localhost/results.json' - results_hash = 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079' - - escrow_client.bulk_payout( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f", - recipients, - amounts, - results_url, - results_hash, - 1 - ) + """Distribute payouts to recipients and set final results. + + Performs bulk payment distribution to multiple recipients and records the final + results URL and hash. + + Args: + escrow_address (str): Address of the escrow. + recipients (List[str]): List of recipient addresses. + amounts (List[int]): Token amounts for each recipient (in token's smallest unit). + final_results_url (str): Final results file URL. + final_results_hash (str): Final results file hash. + payout_id (Union[str, int]): Payout identifier. String for newer contracts, + integer transaction ID for older contracts. + force_complete (bool): Whether to force completion after payout (if supported). + tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. + + Returns: + None + + Raises: + EscrowClientError: If validation fails or the transaction reverts. + + Example: + ```python + escrow_client.bulk_payout( + "0x62dD51230A30401C455c8398d06F85e4EaB6309f", + ["0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"], + [Web3.to_wei(5, "ether")], + "http://localhost/results.json", + "b5dad76bf6772c0f07fd5e048f6e75a5f86ee079", + payout_id="payout-1", + force_complete=True, + ) + ``` """ self.ensure_correct_bulk_payout_input( escrow_address, recipients, amounts, final_results_url, final_results_hash @@ -784,77 +634,42 @@ def create_bulk_payout_transaction( force_complete: Optional[bool] = False, tx_options: Optional[TxParams] = None, ) -> TxParams: - """ - Creates a prepared transaction for bulk payout without signing or sending it. - - :param escrow_address: Address of the escrow - :param recipients: Array of recipient addresses - :param amounts: Array of amounts the recipients will receive - :param final_results_url: Final results file URL - :param final_results_hash: Final results file hash - :param payoutId: Unique identifier for the payout - :param tx_options: (Optional) Additional transaction parameters - - :return: A dictionary containing the prepared transaction - - :raise EscrowClientError: If an error occurs while checking the parameters - - :example: - .. code-block:: python - - from eth_typing import URI - from web3 import Web3 - from web3.middleware import SignAndSendRawMiddlewareBuilder - from web3.providers.auto import load_provider_from_uri - - from human_protocol_sdk.escrow import EscrowClient - - def get_w3_with_priv_key(priv_key: str): - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - gas_payer = w3.eth.account.from_key(priv_key) - w3.eth.default_account = gas_payer.address - w3.middleware_onion.inject( - SignAndSendRawMiddlewareBuilder.build(priv_key), - 'SignAndSendRawMiddlewareBuilder', - layer=0, - ) - return (w3, gas_payer) - - (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') - escrow_client = EscrowClient(w3) - - recipients = [ - '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', - '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92267' - ] - amounts = [ - Web3.to_wei(5, 'ether'), - Web3.to_wei(10, 'ether') - ] - results_url = 'http://localhost/results.json' - results_hash = 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079' - - transaction = escrow_client.create_bulk_payout_transaction( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f", - recipients, - amounts, - results_url, - results_hash, - 1, - false - ) - - print(f"Transaction: {transaction}") - - signed_transaction = w3.eth.account.sign_transaction( - transaction, private_key - ) - tx_hash = w3.eth.send_raw_transaction( - signed_transaction.raw_transaction - ) - tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash) - print(f"Transaction sent with hash: {tx_hash.hex()}") - print(f"Transaction receipt: {tx_receipt}") + """Prepare an unsigned bulk payout transaction. + + Creates a transaction dictionary that can be signed and sent externally. + Useful for offline signing or custom transaction handling. + + Args: + escrow_address (str): Address of the escrow. + recipients (List[str]): List of recipient addresses. + amounts (List[int]): Token amounts for each recipient (in token's smallest unit). + final_results_url (str): Final results file URL. + final_results_hash (str): Final results file hash. + payoutId (str): Unique identifier for the payout (string signature). + force_complete (Optional[bool]): Whether to force completion after payout. Defaults to False. + tx_options (Optional[TxParams]): Optional transaction parameters to seed the transaction. + + Returns: + A populated transaction dictionary ready to sign and send, + including nonce, gas estimate, gas price/fees, and chain ID. + + Raises: + EscrowClientError: If validation fails. + + Example: + ```python + tx = escrow_client.create_bulk_payout_transaction( + "0x62dD51230A30401C455c8398d06F85e4EaB6309f", + ["0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"], + [Web3.to_wei(5, "ether")], + "http://localhost/results.json", + "b5dad76bf6772c0f07fd5e048f6e75a5f86ee079", + "payout-1", + force_complete=False, + ) + signed = w3.eth.account.sign_transaction(tx, "PRIVATE_KEY") + w3.eth.send_raw_transaction(signed.raw_transaction) + ``` """ self.ensure_correct_bulk_payout_input( escrow_address, recipients, amounts, final_results_url, final_results_hash @@ -904,18 +719,28 @@ def ensure_correct_bulk_payout_input( final_results_url: str, final_results_hash: str, ) -> None: - """ - Validates input parameters for bulk payout operations. - - :param escrow_address: Address of the escrow - :param recipients: Array of recipient addresses - :param amounts: Array of amounts the recipients will receive - :param final_results_url: Final results file URL - :param final_results_hash: Final results file hash - - :return: None - - :raise EscrowClientError: If validation fails + """Validate inputs for bulk payout operations. + + Performs comprehensive validation of all bulk payout parameters including + address validity, array lengths, amounts, and escrow balance. + + Args: + escrow_address (str): Address of the escrow. + recipients (List[str]): List of recipient addresses. + amounts (List[int]): Token amounts for each recipient (in token's smallest unit). + final_results_url (str): Final results file URL. + final_results_hash (str): Final results file hash. + + Returns: + None + + Raises: + EscrowClientError: If any parameter is invalid, including: + - Invalid escrow or recipient addresses + - Empty or mismatched arrays + - Too many recipients (exceeds maximum) + - Invalid amounts (negative, zero, or exceeding escrow balance) + - Invalid URL or hash """ if not Web3.is_address(escrow_address): raise EscrowClientError(f"Invalid escrow address: {escrow_address}") @@ -947,38 +772,27 @@ def ensure_correct_bulk_payout_input( def request_cancellation( self, escrow_address: str, tx_options: Optional[TxParams] = None ) -> None: - """Requests the cancellation of the specified escrow (moves status to ToCancel or finalizes if expired). + """Request cancellation of the specified escrow. - :param escrow_address: Address of the escrow to request cancellation - :param tx_options: (Optional) Additional transaction parameters + Initiates the cancellation process. If the escrow is expired, it may finalize + immediately; otherwise, it transitions to ToCancel status. - :example: - .. code-block:: python + Args: + escrow_address (str): Address of the escrow to request cancellation. + tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. - from eth_typing import URI - from web3 import Web3 - from web3.middleware import SignAndSendRawMiddlewareBuilder - from web3.providers.auto import load_provider_from_uri + Returns: + None - from human_protocol_sdk.escrow import EscrowClient + Raises: + EscrowClientError: If validation fails or the transaction reverts. - def get_w3_with_priv_key(priv_key: str): - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - gas_payer = w3.eth.account.from_key(priv_key) - w3.eth.default_account = gas_payer.address - w3.middleware_onion.inject( - SignAndSendRawMiddlewareBuilder.build(priv_key), - 'SignAndSendRawMiddlewareBuilder', - layer=0, - ) - return (w3, gas_payer) - - (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') - escrow_client = EscrowClient(w3) - - escrow_client.request_cancellation( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + Example: + ```python + escrow_client.request_cancellation( + "0x62dD51230A30401C455c8398d06F85e4EaB6309f" + ) + ``` """ if not Web3.is_address(escrow_address): raise EscrowClientError(f"Invalid escrow address: {escrow_address}") @@ -997,47 +811,26 @@ def get_w3_with_priv_key(priv_key: str): def cancel( self, escrow_address: str, tx_options: Optional[TxParams] = None ) -> EscrowCancel: - """ - Cancels the specified escrow and sends the balance to the canceler. - - :param escrow_address: Address of the escrow to cancel - :param tx_options: (Optional) Additional transaction parameters - - :return: EscrowCancel: - An instance of the EscrowCancel class containing details of the cancellation transaction, - including the transaction hash and the amount refunded. - - :raise EscrowClientError: If an error occurs while checking the parameters - :raise EscrowClientError: If the transfer event associated with the cancellation - is not found in the transaction logs - - :example: - .. code-block:: python + """Cancel the specified escrow and refund the balance. - from eth_typing import URI - from web3 import Web3 - from web3.middleware import SignAndSendRawMiddlewareBuilder - from web3.providers.auto import load_provider_from_uri + Finalizes the cancellation and transfers remaining funds to the canceler. - from human_protocol_sdk.escrow import EscrowClient + Args: + escrow_address (str): Address of the escrow to cancel. + tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. - def get_w3_with_priv_key(priv_key: str): - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - gas_payer = w3.eth.account.from_key(priv_key) - w3.eth.default_account = gas_payer.address - w3.middleware_onion.inject( - SignAndSendRawMiddlewareBuilder.build(priv_key), - 'SignAndSendRawMiddlewareBuilder', - layer=0, - ) - return (w3, gas_payer) + Returns: + Cancellation details including transaction hash and refunded amount. - (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') - escrow_client = EscrowClient(w3) + Raises: + EscrowClientError: If validation fails or the transfer event is missing. - escrow_cancel_data = escrow_client.cancel( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + Example: + ```python + escrow_cancel_data = escrow_client.cancel( + "0x62dD51230A30401C455c8398d06F85e4EaB6309f" + ) + ``` """ if not Web3.is_address(escrow_address): raise EscrowClientError(f"Invalid escrow address: {escrow_address}") @@ -1059,49 +852,29 @@ def withdraw( token_address: str, tx_options: Optional[TxParams] = None, ) -> EscrowWithdraw: - """ - Withdraws additional tokens in the escrow to the canceler. - - :param escrow_address: Address of the escrow to withdraw - :param token_address: Address of the token to withdraw - :param tx_options: (Optional) Additional transaction parameters - - :return: EscrowWithdraw: - An instance of the EscrowWithdraw class containing details of the withdrawal transaction, - including the transaction hash and the token address and amount withdrawn. - - :raise EscrowClientError: If an error occurs while checking the parameters - :raise EscrowClientError: If the transfer event associated with the withdrawal - is not found in the transaction logs - - :example: - .. code-block:: python - - from eth_typing import URI - from web3 import Web3 - from web3.middleware import SignAndSendRawMiddlewareBuilder - from web3.providers.auto import load_provider_from_uri - - from human_protocol_sdk.escrow import EscrowClient - - def get_w3_with_priv_key(priv_key: str): - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - gas_payer = w3.eth.account.from_key(priv_key) - w3.eth.default_account = gas_payer.address - w3.middleware_onion.inject( - SignAndSendRawMiddlewareBuilder.build(priv_key), - 'SignAndSendRawMiddlewareBuilder', - layer=0, - ) - return (w3, gas_payer) - - (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') - escrow_client = EscrowClient(w3) - - escrow_cancel_data = escrow_client.withdraw( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f", - "0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4" - ) + """Withdraw additional tokens from the escrow. + + Withdraws tokens (other than the primary escrow token) to the canceler's address. + Useful for recovering accidentally sent tokens. + + Args: + escrow_address (str): Address of the escrow to withdraw from. + token_address (str): Address of the token to withdraw. + tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. + + Returns: + Withdrawal details including transaction hash, token address, and amount. + + Raises: + EscrowClientError: If validation fails or transfer event is missing. + + Example: + ```python + withdrawal = escrow_client.withdraw( + "0x62dD51230A30401C455c8398d06F85e4EaB6309f", + "0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4", + ) + ``` """ if not Web3.is_address(escrow_address): @@ -1146,30 +919,18 @@ def get_w3_with_priv_key(priv_key: str): handle_error(e, EscrowClientError) def get_balance(self, escrow_address: str) -> int: - """ - Gets the balance for a specified escrow address. + """Get the remaining balance for a specified escrow. - :param escrow_address: Address of the escrow + Queries the current available balance in the escrow that can be used for payouts. - :return: Value of the balance + Args: + escrow_address (str): Address of the escrow. - :raise EscrowClientError: If an error occurs while checking the parameters + Returns: + Remaining escrow balance in token's smallest unit. - :example: - .. code-block:: python - - from eth_typing import URI - from web3 import Web3 - from web3.providers.auto import load_provider_from_uri - - from human_protocol_sdk.escrow import EscrowClient - - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) - - balance = escrow_client.get_balance( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + Raises: + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1188,30 +949,18 @@ def get_balance(self, escrow_address: str) -> int: return self._get_escrow_contract(escrow_address).functions.getBalance().call() def get_reserved_funds(self, escrow_address: str) -> int: - """ - Gets the reserved funds for a specified escrow address. + """Get the reserved funds for a specified escrow. - :param escrow_address: Address of the escrow + Queries the amount of funds that have been reserved for future payouts. - :return: Value of the reserved funds + Args: + escrow_address (str): Address of the escrow. - :raise EscrowClientError: If an error occurs while checking the parameters + Returns: + Reserved funds amount in token's smallest unit. - :example: - .. code-block:: python - - from eth_typing import URI - from web3 import Web3 - from web3.providers.auto import load_provider_from_uri - - from human_protocol_sdk.escrow import EscrowClient - - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) - - reserved_funds = escrow_client.get_reserved_funds( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + Raises: + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1222,30 +971,18 @@ def get_reserved_funds(self, escrow_address: str) -> int: ) def get_manifest_hash(self, escrow_address: str) -> str: - """ - Gets the manifest file hash. + """Get the manifest file hash. - :param escrow_address: Address of the escrow + Retrieves the hash of the manifest that defines the job requirements. - :return: Manifest file hash + Args: + escrow_address (str): Address of the escrow. - :raise EscrowClientError: If an error occurs while checking the parameters + Returns: + Manifest file hash. - :example: - .. code-block:: python - - from eth_typing import URI - from web3 import Web3 - from web3.providers.auto import load_provider_from_uri - - from human_protocol_sdk.escrow import EscrowClient - - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) - - manifest_hash = escrow_client.get_manifest_hash( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + Raises: + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1254,30 +991,18 @@ def get_manifest_hash(self, escrow_address: str) -> str: return self._get_escrow_contract(escrow_address).functions.manifestHash().call() def get_manifest(self, escrow_address: str) -> str: - """ - Gets the manifest data (can be a URL or JSON string). - - :param escrow_address: Address of the escrow - - :return str: Manifest data + """Get the manifest data. - :raise EscrowClientError: If an error occurs while checking the parameters + Retrieves the manifest URL or JSON string that defines the job requirements. - :example: - .. code-block:: python + Args: + escrow_address (str): Address of the escrow. - from eth_typing import URI - from web3 import Web3 - from web3.providers.auto import load_provider_from_uri + Returns: + str: Manifest data (URL or JSON string). - from human_protocol_sdk.escrow import EscrowClient - - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) - - manifest = escrow_client.get_manifest( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + Raises: + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1286,30 +1011,18 @@ def get_manifest(self, escrow_address: str) -> str: return self._get_escrow_contract(escrow_address).functions.manifestUrl().call() def get_results_url(self, escrow_address: str) -> str: - """ - Gets the results file URL. - - :param escrow_address: Address of the escrow - - :return: Results file url + """Get the final results file URL. - :raise EscrowClientError: If an error occurs while checking the parameters + Retrieves the URL where final results are stored. - :example: - .. code-block:: python + Args: + escrow_address (str): Address of the escrow. - from eth_typing import URI - from web3 import Web3 - from web3.providers.auto import load_provider_from_uri + Returns: + Final results URL. - from human_protocol_sdk.escrow import EscrowClient - - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) - - url = escrow_client.get_results_url( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + Raises: + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1320,30 +1033,18 @@ def get_results_url(self, escrow_address: str) -> str: ) def get_intermediate_results_url(self, escrow_address: str) -> str: - """ - Gets the intermediate results file URL. - - :param escrow_address: Address of the escrow - - :return: Intermediate results file url + """Get the intermediate results file URL. - :raise EscrowClientError: If an error occurs while checking the parameters + Retrieves the URL where intermediate results are stored. - :example: - .. code-block:: python + Args: + escrow_address (str): Address of the escrow. - from eth_typing import URI - from web3 import Web3 - from web3.providers.auto import load_provider_from_uri + Returns: + Intermediate results URL. - from human_protocol_sdk.escrow import EscrowClient - - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) - - url = escrow_client.get_intermediate_results_url( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + Raises: + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1356,30 +1057,18 @@ def get_intermediate_results_url(self, escrow_address: str) -> str: ) def get_intermediate_results_hash(self, escrow_address: str) -> str: - """ - Gets the intermediate results file hash. - - :param escrow_address: Address of the escrow - - :return: Intermediate results file hash - - :raise EscrowClientError: If an error occurs while checking the parameters - - :example: - .. code-block:: python + """Get the intermediate results file hash. - from eth_typing import URI - from web3 import Web3 - from web3.providers.auto import load_provider_from_uri + Retrieves the hash of the intermediate results file. - from human_protocol_sdk.escrow import EscrowClient + Args: + escrow_address (str): Address of the escrow. - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) + Returns: + Intermediate results file hash. - hash = escrow_client.get_intermediate_results_hash( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + Raises: + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1392,30 +1081,18 @@ def get_intermediate_results_hash(self, escrow_address: str) -> str: ) def get_token_address(self, escrow_address: str) -> str: - """ - Gets the address of the token used to fund the escrow. - - :param escrow_address: Address of the escrow - - :return: Address of the token - - :raise EscrowClientError: If an error occurs while checking the parameters - - :example: - .. code-block:: python + """Get the token address used to fund the escrow. - from eth_typing import URI - from web3 import Web3 - from web3.providers.auto import load_provider_from_uri + Retrieves the ERC-20 token contract address used for this escrow. - from human_protocol_sdk.escrow import EscrowClient + Args: + escrow_address (str): Address of the escrow. - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) + Returns: + Token address used to fund the escrow. - token_address = escrow_client.get_token_address( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + Raises: + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1424,30 +1101,18 @@ def get_token_address(self, escrow_address: str) -> str: return self._get_escrow_contract(escrow_address).functions.token().call() def get_status(self, escrow_address: str) -> Status: - """ - Gets the current status of the escrow. - - :param escrow_address: Address of the escrow - - :return: Current escrow status - - :raise EscrowClientError: If an error occurs while checking the parameters - - :example: - .. code-block:: python + """Get the current status of the escrow. - from eth_typing import URI - from web3 import Web3 - from web3.providers.auto import load_provider_from_uri + Retrieves the current state of the escrow (e.g., Launched, Pending, Completed). - from human_protocol_sdk.escrow import EscrowClient + Args: + escrow_address (str): Address of the escrow. - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) + Returns: + Current escrow status enum value. - status = escrow_client.get_status( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + Raises: + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1458,30 +1123,18 @@ def get_status(self, escrow_address: str) -> Status: ) def get_recording_oracle_address(self, escrow_address: str) -> str: - """ - Gets the recording oracle address of the escrow. - - :param escrow_address: Address of the escrow - - :return: Recording oracle address - - :raise EscrowClientError: If an error occurs while checking the parameters - - :example: - .. code-block:: python + """Get the recording oracle address of the escrow. - from eth_typing import URI - from web3 import Web3 - from web3.providers.auto import load_provider_from_uri + Retrieves the address of the oracle responsible for recording job results. - from human_protocol_sdk.escrow import EscrowClient + Args: + escrow_address (str): Address of the escrow. - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) + Returns: + Recording oracle address. - recording_oracle = escrow_client.get_recording_oracle_address( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + Raises: + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1492,30 +1145,18 @@ def get_recording_oracle_address(self, escrow_address: str) -> str: ) def get_reputation_oracle_address(self, escrow_address: str) -> str: - """ - Gets the reputation oracle address of the escrow. - - :param escrow_address: Address of the escrow - - :return: Reputation oracle address - - :raise EscrowClientError: If an error occurs while checking the parameters + """Get the reputation oracle address of the escrow. - :example: - .. code-block:: python + Retrieves the address of the oracle responsible for reputation tracking. - from eth_typing import URI - from web3 import Web3 - from web3.providers.auto import load_provider_from_uri + Args: + escrow_address (str): Address of the escrow. - from human_protocol_sdk.escrow import EscrowClient + Returns: + Reputation oracle address. - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) - - reputation_oracle = escrow_client.get_reputation_oracle_address( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + Raises: + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1528,30 +1169,18 @@ def get_reputation_oracle_address(self, escrow_address: str) -> str: ) def get_exchange_oracle_address(self, escrow_address: str) -> str: - """ - Gets the exchange oracle address of the escrow. - - :param escrow_address: Address of the escrow - - :return: Exchange oracle address - - :raise EscrowClientError: If an error occurs while checking the parameters + """Get the exchange oracle address of the escrow. - :example: - .. code-block:: python + Retrieves the address of the oracle responsible for exchange rate data. - from eth_typing import URI - from web3 import Web3 - from web3.providers.auto import load_provider_from_uri + Args: + escrow_address (str): Address of the escrow. - from human_protocol_sdk.escrow import EscrowClient + Returns: + Exchange oracle address. - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) - - exchange_oracle = escrow_client.get_exchange_oracle_address( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + Raises: + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1562,30 +1191,18 @@ def get_exchange_oracle_address(self, escrow_address: str) -> str: ) def get_job_launcher_address(self, escrow_address: str) -> str: - """ - Gets the job launcher address of the escrow. - - :param escrow_address: Address of the escrow - - :return: Job launcher address + """Get the job launcher address of the escrow. - :raise EscrowClientError: If an error occurs while checking the parameters + Retrieves the address of the account that launched/created this escrow. - :example: - .. code-block:: python + Args: + escrow_address (str): Address of the escrow. - from eth_typing import URI - from web3 import Web3 - from web3.providers.auto import load_provider_from_uri + Returns: + Job launcher address. - from human_protocol_sdk.escrow import EscrowClient - - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) - - job_launcher = escrow_client.get_job_launcher_address( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + Raises: + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1594,30 +1211,18 @@ def get_job_launcher_address(self, escrow_address: str) -> str: return self._get_escrow_contract(escrow_address).functions.launcher().call() def get_factory_address(self, escrow_address: str) -> str: - """ - Gets the escrow factory address of the escrow. - - :param escrow_address: Address of the escrow - - :return: Escrow factory address + """Get the escrow factory address of the escrow. - :raise EscrowClientError: If an error occurs while checking the parameters + Retrieves the address of the factory contract that created this escrow. - :example: - .. code-block:: python + Args: + escrow_address (str): Address of the escrow. - from eth_typing import URI - from web3 import Web3 - from web3.providers.auto import load_provider_from_uri + Returns: + Escrow factory address. - from human_protocol_sdk.escrow import EscrowClient - - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) - - escrow_factory = escrow_client.get_factory_address( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + Raises: + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1628,13 +1233,19 @@ def get_factory_address(self, escrow_address: str) -> str: ) def _get_escrow_contract(self, address: str) -> contract.Contract: - """ - Returns the escrow contract instance. + """Get the escrow contract instance. + + Internal method to retrieve a contract instance for the given escrow address. + Validates that the address is a valid escrow from the factory. - :param escrow_address: Address of the deployed escrow + Args: + address (str): Address of the deployed escrow. - :return: The instance of the escrow contract + Returns: + The instance of the escrow contract. + Raises: + EscrowClientError: If the address is not a valid escrow from the factory. """ if not self.factory_contract.functions.hasEscrow(address): diff --git a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/escrow/escrow_utils.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/escrow/escrow_utils.py index 5a5531e591..fa759799d1 100644 --- a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/escrow/escrow_utils.py +++ b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/escrow/escrow_utils.py @@ -1,11 +1,7 @@ -""" -Utility class for escrow-related operations. - -Code Example ------------- - -.. code-block:: python +"""Utility helpers for escrow-related queries. +Example: + ```python from human_protocol_sdk.constants import ChainId from human_protocol_sdk.escrow import EscrowUtils, EscrowFilter, Status @@ -19,9 +15,7 @@ ) ) ) - -Module ------- + ``` """ import logging @@ -47,6 +41,36 @@ class EscrowData: + """Represents escrow data retrieved from the subgraph. + + Attributes: + id (str): Unique escrow identifier. + address (str): Escrow contract address. + amount_paid (int): Total amount paid out. + balance (int): Remaining balance in the escrow. + count (int): Number of payouts executed. + factory_address (str): Address of the factory that created this escrow. + final_results_url (Optional[str]): URL for final results file. + final_results_hash (Optional[str]): Hash of final results file. + intermediate_results_url (Optional[str]): URL for intermediate results file. + intermediate_results_hash (Optional[str]): Hash of intermediate results file. + launcher (str): Address of the job launcher. + job_requester_id (Optional[str]): Off-chain job requester identifier. + manifest_hash (Optional[str]): Hash of the manifest file. + manifest (Optional[str]): Manifest data (URL or JSON string). + recording_oracle (Optional[str]): Address of the recording oracle. + reputation_oracle (Optional[str]): Address of the reputation oracle. + exchange_oracle (Optional[str]): Address of the exchange oracle. + recording_oracle_fee (Optional[int]): Recording oracle fee percentage. + reputation_oracle_fee (Optional[int]): Reputation oracle fee percentage. + exchange_oracle_fee (Optional[int]): Exchange oracle fee percentage. + status (str): Current escrow status. + token (str): Address of the payment token. + total_funded_amount (int): Total amount funded to the escrow. + created_at (int): Creation timestamp in milliseconds. + chain_id (ChainId): Chain where the escrow is deployed. + """ + def __init__( self, chain_id: ChainId, @@ -75,36 +99,6 @@ def __init__( reputation_oracle_fee: Optional[str] = None, exchange_oracle_fee: Optional[str] = None, ): - """ - Initializes an EscrowData instance. - - :param chain_id: Chain identifier - :param id: Identifier - :param address: Address - :param amount_paid: Amount paid - :param balance: Balance - :param count: Count - :param factory_address: Factory address - :param launcher: Launcher - :param job_requester_id: Job requester identifier - :param status: Status - :param token: Token - :param total_funded_amount: Total funded amount - :param created_at: Creation timestamp in milliseconds - :param final_results_url: URL for final results. - :param final_results_hash: Hash for final results. - :param intermediate_results_url: URL for intermediate results. - :param intermediate_results_hash: Hash for intermediate results. - :param manifest_hash: Manifest hash. - :param manifest: Manifest data (JSON/URL). - :param recording_oracle: Recording Oracle address. - :param reputation_oracle: Reputation Oracle address. - :param exchange_oracle: Exchange Oracle address. - :param recording_oracle_fee: Fee for the Recording Oracle. - :param reputation_oracle_fee: Fee for the Reputation Oracle. - :param exchange_oracle_fee: Fee for the Exchange Oracle. - """ - self.id = id self.address = address self.amount_paid = int(amount_paid) @@ -139,13 +133,13 @@ def __init__( class StatusEvent: - """ - Initializes a StatusEvent instance. + """Represents an escrow status change event. - :param timestamp: The timestamp of the event in milliseconds. - :param status: The status of the escrow. - :param chain_id: The chain identifier where the event occurred. - :param escrow_address: The address of the escrow. + Attributes: + timestamp (int): Event timestamp in milliseconds. + status (str): The new status of the escrow. + chain_id (ChainId): Chain where the event occurred. + escrow_address (str): Address of the escrow that changed status. """ def __init__( @@ -158,15 +152,14 @@ def __init__( class Payout: - """ - Initializes a Payout instance. - - :param id: The id of the payout. - :param chain_id: The chain identifier where the payout occurred. - :param escrow_address: The address of the escrow that executed the payout. - :param recipient: The address of the recipient. - :param amount: The amount of the payout. - :param created_at: The time of creation of the payout in milliseconds. + """Represents a payout distributed by an escrow. + + Attributes: + id (str): Unique payout identifier. + escrow_address (str): Address of the escrow that executed the payout. + recipient (str): Address of the payout recipient. + amount (int): Amount paid in token's smallest unit. + created_at (int): Payout creation timestamp in milliseconds. """ def __init__( @@ -180,16 +173,16 @@ def __init__( class CancellationRefund: - """ - Represents a cancellation refund event. - - :param id: The unique identifier for the cancellation refund event. - :param escrow_address: The address of the escrow associated with the refund. - :param receiver: The address of the recipient receiving the refund. - :param amount: The amount being refunded. - :param block: The block number in which the refund was processed. - :param timestamp: The timestamp of the refund event in milliseconds. - :param tx_hash: The transaction hash of the refund event. + """Represents a cancellation refund event. + + Attributes: + id (str): Unique refund identifier. + escrow_address (str): Address of the escrow associated with the refund. + receiver (str): Address receiving the refund. + amount (int): Refunded amount in token's smallest unit. + block (int): Block number where the refund was processed. + timestamp (int): Refund timestamp in milliseconds. + tx_hash (str): Transaction hash of the refund. """ def __init__( @@ -212,8 +205,10 @@ def __init__( class EscrowUtils: - """ - A utility class that provides additional escrow-related functionalities. + """Utility class providing escrow-related query and data retrieval functions. + + This class offers static methods to fetch escrow data, status events, payouts, + and cancellation refunds from the Human Protocol subgraph. """ @staticmethod @@ -221,29 +216,37 @@ def get_escrows( filter: EscrowFilter, options: Optional[SubgraphOptions] = None, ) -> List[EscrowData]: - """Get an array of escrow addresses based on the specified filter parameters. - - :param filter: Object containing all the necessary parameters to filter - :param options: Optional config for subgraph requests - - :return: List of escrows - - :example: - .. code-block:: python - - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.escrow import EscrowUtils, EscrowFilter, Status - - print( - EscrowUtils.get_escrows( - EscrowFilter( - networks=[ChainId.POLYGON_AMOY], - status=Status.Pending, - date_from=datetime.datetime(2023, 5, 8), - date_to=datetime.datetime(2023, 6, 8), - ) + """Retrieve a list of escrows matching the provided filter criteria. + + Queries the subgraph for escrow contracts that match the specified parameters + including status, date range, and oracle addresses. + + Args: + filter (EscrowFilter): Filter parameters including chain ID, status, date range, + and oracle addresses. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests + such as custom endpoints or timeout settings. + + Returns: + A list of escrow records matching the filter criteria. + Returns an empty list if no matches are found. + + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.escrow import EscrowUtils, EscrowFilter, Status + + print( + EscrowUtils.get_escrows( + EscrowFilter( + networks=[ChainId.POLYGON_AMOY], + status=Status.Pending, + date_from=datetime.datetime(2023, 5, 8), + date_to=datetime.datetime(2023, 6, 8), ) ) + ) + ``` """ from human_protocol_sdk.gql.escrow import get_escrows_query @@ -339,26 +342,33 @@ def get_escrow( escrow_address: str, options: Optional[SubgraphOptions] = None, ) -> Optional[EscrowData]: - """Returns the escrow for a given address. + """Fetch a single escrow by its address. - :param chain_id: Network in which the escrow has been deployed - :param escrow_address: Address of the escrow - :param options: Optional config for subgraph requests + Retrieves detailed information about a specific escrow contract from the subgraph. - :return: Escrow data + Args: + chain_id (ChainId): Network where the escrow has been deployed. + escrow_address (str): Address of the escrow contract. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. - :example: - .. code-block:: python + Returns: + Escrow data if found, otherwise ``None``. - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.escrow import EscrowUtils + Raises: + EscrowClientError: If the chain ID is invalid or the escrow address is malformed. - print( - EscrowUtils.get_escrow( - ChainId.POLYGON_AMOY, - "0x1234567890123456789012345678901234567890" - ) + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.escrow import EscrowUtils + + print( + EscrowUtils.get_escrow( + ChainId.POLYGON_AMOY, + "0x1234567890123456789012345678901234567890", ) + ) + ``` """ from human_protocol_sdk.gql.escrow import ( get_escrow_query, @@ -424,15 +434,39 @@ def get_status_events( filter: StatusEventFilter, options: Optional[SubgraphOptions] = None, ) -> List[StatusEvent]: - """ - Retrieve status events for specified networks and statuses within a date range. - - :param filter: Object containing all the necessary parameters to filter status events. - :param options: Optional config for subgraph requests - - :return List[StatusEvent]: List of status events matching the query parameters. - - :raise EscrowClientError: If an unsupported chain ID or invalid launcher address is provided. + """Retrieve status change events for escrows. + + Queries the subgraph for escrow status change events within the specified + date range and matching the provided statuses. + + Args: + filter (StatusEventFilter): Filter parameters including chain ID, statuses, + date range, and oracle addresses. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. + + Returns: + A list of status change events matching the filter criteria. + Returns an empty list if no matches are found. + + Raises: + EscrowClientError: If an unsupported chain ID or invalid launcher address is provided. + + Example: + ```python + from human_protocol_sdk.constants import ChainId, Status + from human_protocol_sdk.escrow import EscrowUtils + from human_protocol_sdk.filter import StatusEventFilter + import datetime + + events = EscrowUtils.get_status_events( + StatusEventFilter( + chain_id=ChainId.POLYGON_AMOY, + statuses=[Status.Pending, Status.Completed], + date_from=datetime.datetime(2023, 5, 8), + date_to=datetime.datetime(2023, 6, 8), + ) + ) + ``` """ from human_protocol_sdk.gql.escrow import get_status_query @@ -487,15 +521,36 @@ def get_payouts( filter: PayoutFilter, options: Optional[SubgraphOptions] = None, ) -> List[Payout]: - """ - Fetch payouts from the subgraph based on the provided filter. + """Fetch payout records from the subgraph. + + Retrieves payout transactions for escrows based on the provided filter criteria + including escrow address, recipient, and date range. - :param filter: Object containing all the necessary parameters to filter payouts. - :param options: Optional config for subgraph requests + Args: + filter (PayoutFilter): Filter parameters including chain ID, escrow address, + recipient address, date range, pagination, and sorting options. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. - :return List[Payout]: List of payouts matching the query parameters. + Returns: + A list of payout records matching the query parameters. + Returns an empty list if no matches are found. - :raise EscrowClientError: If an unsupported chain ID or invalid addresses are provided. + Raises: + EscrowClientError: If an unsupported chain ID or invalid addresses are provided. + + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.escrow import EscrowUtils + from human_protocol_sdk.filter import PayoutFilter + + payouts = EscrowUtils.get_payouts( + PayoutFilter( + chain_id=ChainId.POLYGON_AMOY, + escrow_address="0x1234567890123456789012345678901234567890", + ) + ) + ``` """ from human_protocol_sdk.gql.payout import get_payouts_query @@ -554,15 +609,36 @@ def get_cancellation_refunds( filter: CancellationRefundFilter, options: Optional[SubgraphOptions] = None, ) -> List[CancellationRefund]: - """ - Fetch cancellation refunds from the subgraph based on the provided filter. + """Fetch cancellation refund events from the subgraph. + + Retrieves cancellation refund transactions for escrows based on the provided + filter criteria including escrow address, receiver, and date range. - :param filter: Object containing all the necessary parameters to filter cancellation refunds. - :param options: Optional config for subgraph requests + Args: + filter (CancellationRefundFilter): Filter parameters including chain ID, + escrow address, receiver address, date range, pagination, and sorting options. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. - :return List[CancellationRefund]: List of cancellation refunds matching the query parameters. + Returns: + A list of cancellation refunds matching the query parameters. + Returns an empty list if no matches are found. - :raise EscrowClientError: If an unsupported chain ID or invalid addresses are provided. + Raises: + EscrowClientError: If an unsupported chain ID or invalid addresses are provided. + + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.escrow import EscrowUtils + from human_protocol_sdk.filter import CancellationRefundFilter + + refunds = EscrowUtils.get_cancellation_refunds( + CancellationRefundFilter( + chain_id=ChainId.POLYGON_AMOY, + escrow_address="0x1234567890123456789012345678901234567890", + ) + ) + ``` """ from human_protocol_sdk.gql.cancel import get_cancellation_refunds_query @@ -624,27 +700,32 @@ def get_cancellation_refund( escrow_address: str, options: Optional[SubgraphOptions] = None, ) -> CancellationRefund: - """ - Returns the cancellation refund for a given escrow address. + """Retrieve the cancellation refund for a specific escrow. - :param chain_id: Network in which the escrow has been deployed - :param escrow_address: Address of the escrow - :param options: Optional config for subgraph requests + Fetches the cancellation refund event associated with a given escrow address. + Each escrow can have at most one cancellation refund. - :return: CancellationRefund data or None + Args: + chain_id (ChainId): Network where the escrow has been deployed. + escrow_address (str): Address of the escrow contract. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. - :raise EscrowClientError: If an unsupported chain ID or invalid address is provided. + Returns: + Cancellation refund data if found, otherwise ``None``. - :example: - .. code-block:: python + Raises: + EscrowClientError: If an unsupported chain ID or invalid escrow address is provided. - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.escrow import EscrowUtils + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.escrow import EscrowUtils - refund = EscrowUtils.get_cancellation_refund( - ChainId.POLYGON_AMOY, - "0x1234567890123456789012345678901234567890" - ) + refund = EscrowUtils.get_cancellation_refund( + ChainId.POLYGON_AMOY, + "0x1234567890123456789012345678901234567890", + ) + ``` """ from human_protocol_sdk.gql.cancel import ( get_cancellation_refund_by_escrow_query, diff --git a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/filter.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/filter.py index da3f6b9bff..896bc09fd2 100644 --- a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/filter.py +++ b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/filter.py @@ -1,5 +1,11 @@ #!/usr/bin/env python3 +"""Filter classes for querying Human Protocol subgraph data. + +This module provides filter classes for various query operations including escrows, +payouts, transactions, statistics, and more. +""" + from datetime import datetime from typing import List, Optional @@ -10,16 +16,27 @@ class FilterError(Exception): - """ - Raises when some error happens when building filter object. - """ + """Exception raised when filter construction or validation fails.""" pass class EscrowFilter: - """ - A class used to filter escrow requests. + """Filter configuration for querying escrows from the subgraph. + + Attributes: + chain_id (ChainId): Network to request data from. + launcher (Optional[str]): Launcher address to filter by. + reputation_oracle (Optional[str]): Reputation oracle address to filter by. + recording_oracle (Optional[str]): Recording oracle address to filter by. + exchange_oracle (Optional[str]): Exchange oracle address to filter by. + job_requester_id (Optional[str]): Job requester identifier to filter by. + status (Optional[Status | List[Status]]): Escrow status or list of statuses to filter by. + date_from (Optional[datetime]): Filter escrows created from this date. + date_to (Optional[datetime]): Filter escrows created until this date. + first (int): Number of items per page (max 1000). + skip (int): Number of items to skip for pagination. + order_direction (OrderDirection): Sort order for results. """ def __init__( @@ -38,20 +55,9 @@ def __init__( order_direction: OrderDirection = OrderDirection.DESC, ): """ - Initializes a EscrowFilter instance. - - :param chain_id: Network to request data - :param launcher: Launcher address - :param reputation_oracle: Reputation oracle address - :param recording_oracle: Recording oracle address - :param exchange_oracle: Exchange oracle address - :param job_requester_id: Job requester id - :param status: Escrow status - :param date_from: Created from date - :param date_to: Created to date - :param first: Number of items per page - :param skip: Page number to retrieve - :param order_direction: Order of results, "asc" or "desc" + Raises: + FilterError: If chain ID is invalid, addresses are malformed, date range is invalid, + or order direction is invalid. """ if chain_id.value not in set(chain_id.value for chain_id in ChainId): @@ -94,8 +100,17 @@ def __init__( class PayoutFilter: - """ - A class used to filter payout requests. + """Filter configuration for querying payout events from the subgraph. + + Attributes: + chain_id (ChainId): Chain where payouts were recorded. + escrow_address (Optional[str]): Escrow address to filter payouts by. + recipient (Optional[str]): Recipient address to filter payouts by. + date_from (Optional[datetime]): Filter payouts from this date. + date_to (Optional[datetime]): Filter payouts until this date. + first (int): Number of items per page. + skip (int): Number of items to skip for pagination. + order_direction (OrderDirection): Sort order for results. """ def __init__( @@ -110,16 +125,8 @@ def __init__( order_direction: OrderDirection = OrderDirection.DESC, ): """ - Initializes a filter for payouts. - - :param chain_id: The chain ID where the payouts are recorded. - :param escrow_address: Optional escrow address to filter payouts. - :param recipient: Optional recipient address to filter payouts. - :param date_from: Optional start date for filtering. - :param date_to: Optional end date for filtering. - :param first: Optional number of payouts per page. Default is 10. - :param skip: Optional number of payouts to skip. Default is 0. - :param order_direction: Optional order direction. Default is DESC. + Raises: + FilterError: If addresses are malformed or date range is invalid. """ if escrow_address and not Web3.is_address(escrow_address): @@ -144,8 +151,22 @@ def __init__( class TransactionFilter: - """ - A class used to filter transactions. + """Filter configuration for querying blockchain transactions from the subgraph. + + Attributes: + chain_id (ChainId): Chain to filter transactions from. + from_address (Optional[str]): Sender address to filter by. + to_address (Optional[str]): Recipient address to filter by. + start_date (Optional[datetime]): Filter transactions from this date. + end_date (Optional[datetime]): Filter transactions until this date. + start_block (Optional[int]): Filter transactions from this block number. + end_block (Optional[int]): Filter transactions until this block number. + method (Optional[str]): Method signature to filter transactions by. + escrow (Optional[str]): Escrow address to filter transactions by. + token (Optional[str]): Token address to filter transactions by. + first (int): Number of items per page (max 1000). + skip (int): Number of items to skip for pagination. + order_direction (OrderDirection): Sort order for results. """ def __init__( @@ -165,23 +186,9 @@ def __init__( order_direction: OrderDirection = OrderDirection.DESC, ): """ - Initializes a TransactionsFilter instance. - - :param chain_id: Chain ID to filter transactions from - :param from_address: Sender address - :param to_address: Receiver address - :param start_date: Start date for filtering transactions - :param end_date: End date for filtering transactions - :param start_block: Start block number for filtering transactions - :param end_block: End block number for filtering transactions - :param method: Method name to filter transactions - :param escrow: Escrow address to filter transactions - :param token: Token address to filter transactions - :param first: Number of items per page - :param skip: Page number to retrieve - :param order: Order of results, "asc" or "desc" - - :raises ValueError: If start_date is after end_date + Raises: + ValueError: If addresses are malformed, date/block ranges are invalid, + or order direction is invalid. """ if from_address and not Web3.is_address(from_address): @@ -231,28 +238,29 @@ def __init__( class StatisticsFilter: - """ - A class used to filter statistical data. - - :param date_from: Start date for the query range. - :param date_to: End date for the query range. - :param first: Number of items per page. - :param skip: Page number to retrieve. - :param order_direction: Order of results, "asc" or "desc". - - :example: - .. code-block:: python - - from datetime import datetime - from human_protocol_sdk.filter import StatisticsFilter - - filter = StatisticsFilter( - date_from=datetime(2023, 1, 1), - date_to=datetime(2023, 12, 31), - first=10, - skip=0, - order_direction=OrderDirection.ASC - ) + """Filter configuration for querying statistical data from the subgraph. + + Attributes: + date_from (Optional[datetime]): Start date for the query range. + date_to (Optional[datetime]): End date for the query range. + first (int): Number of items per page (max 1000). + skip (int): Number of items to skip for pagination. + order_direction (OrderDirection): Sort order for results. + + Example: + ```python + from datetime import datetime + from human_protocol_sdk.filter import StatisticsFilter + from human_protocol_sdk.constants import OrderDirection + + filter = StatisticsFilter( + date_from=datetime(2023, 1, 1), + date_to=datetime(2023, 12, 31), + first=10, + skip=0, + order_direction=OrderDirection.ASC + ) + ``` """ def __init__( @@ -263,6 +271,11 @@ def __init__( skip: int = 0, order_direction: OrderDirection = OrderDirection.ASC, ): + """ + Raises: + FilterError: If date range is invalid or order direction is invalid. + """ + if date_from and date_to and date_from > date_to: raise FilterError( f"Invalid dates: {date_from} must be earlier than {date_to}" @@ -281,6 +294,19 @@ def __init__( class StatusEventFilter: + """Filter configuration for querying escrow status change events. + + Attributes: + chain_id (ChainId): Chain where status events were recorded. + statuses (List[Status]): List of statuses to filter by. + date_from (Optional[datetime]): Filter events from this date. + date_to (Optional[datetime]): Filter events until this date. + launcher (Optional[str]): Launcher address to filter by. + first (int): Number of items per page. + skip (int): Number of items to skip for pagination. + order_direction (OrderDirection): Sort order for results. + """ + def __init__( self, chain_id: ChainId, @@ -322,8 +348,15 @@ def __init__( class WorkerFilter: - """ - A class used to filter workers. + """Filter configuration for querying worker data from the subgraph. + + Attributes: + chain_id (ChainId): Chain to request worker data from. + worker_address (Optional[str]): Worker address to filter by. + order_by (Optional[str]): Property to order results by (e.g., "payoutCount"). + order_direction (OrderDirection): Sort order for results. + first (int): Number of items per page (1-1000). + skip (int): Number of items to skip for pagination. """ def __init__( @@ -336,15 +369,10 @@ def __init__( skip: int = 0, ): """ - Initializes a WorkerFilter instance. - - :param chain_id: Chain ID to request data - :param worker_address: Address to filter by - :param order_by: Property to order by, e.g., "payoutCount" - :param order_direction: Order direction of results, "asc" or "desc" - :param first: Number of items per page - :param skip: Number of items to skip (for pagination) + Raises: + FilterError: If order direction is invalid. """ + if order_direction.value not in set( order_direction.value for order_direction in OrderDirection ): @@ -359,6 +387,24 @@ def __init__( class StakersFilter: + """Filter configuration for querying staker data from the subgraph. + + Attributes: + chain_id (ChainId): Chain to request staker data from. + min_staked_amount (Optional[str]): Minimum staked amount to filter by. + max_staked_amount (Optional[str]): Maximum staked amount to filter by. + min_locked_amount (Optional[str]): Minimum locked amount to filter by. + max_locked_amount (Optional[str]): Maximum locked amount to filter by. + min_withdrawn_amount (Optional[str]): Minimum withdrawn amount to filter by. + max_withdrawn_amount (Optional[str]): Maximum withdrawn amount to filter by. + min_slashed_amount (Optional[str]): Minimum slashed amount to filter by. + max_slashed_amount (Optional[str]): Maximum slashed amount to filter by. + order_by (Optional[str]): Property to order results by (e.g., "lastDepositTimestamp"). + order_direction (OrderDirection): Sort order for results. + first (Optional[int]): Number of items per page. + skip (Optional[int]): Number of items to skip for pagination. + """ + def __init__( self, chain_id: ChainId, @@ -391,8 +437,17 @@ def __init__( class CancellationRefundFilter: - """ - A class used to filter cancellation refunds. + """Filter configuration for querying cancellation refund events. + + Attributes: + chain_id (ChainId): Chain to request refund data from. + escrow_address (Optional[str]): Escrow address to filter by. + receiver (Optional[str]): Receiver address to filter by. + date_from (Optional[datetime]): Filter refunds from this date. + date_to (Optional[datetime]): Filter refunds until this date. + first (int): Number of items per page. + skip (int): Number of items to skip for pagination. + order_direction (OrderDirection): Sort order for results. """ def __init__( @@ -407,16 +462,11 @@ def __init__( order_direction: OrderDirection = OrderDirection.DESC, ): """ - Initializes a CancellationRefundFilter instance. - :param chain_id: Chain ID to request data - :param escrow_address: Address of the escrow to filter by - :param receiver: Address of the receiver to filter by - :param date_from: Start date for filtering - :param date_to: End date for filtering - :param first: Number of items per page - :param skip: Number of items to skip (for pagination) - :param order_direction: Order direction of results, "asc" or "desc" + Raises: + FilterError: If chain ID is invalid, addresses are malformed, + or date range is invalid. """ + if chain_id.value not in set(chain_id.value for chain_id in ChainId): raise FilterError(f"Invalid ChainId") if escrow_address and not Web3.is_address(escrow_address): diff --git a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/kvstore/kvstore_client.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/kvstore/kvstore_client.py index db199fc264..d5b4abf33e 100644 --- a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/kvstore/kvstore_client.py +++ b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/kvstore/kvstore_client.py @@ -1,23 +1,15 @@ -""" -This client enables performing actions on the KVStore contract and -obtaining information from both the contracts and subgraph. - -Internally, the SDK will use one network or another according to the network ID of the web3. -To use this client, you need to create a Web3 instance and configure the default account, -as well as some middlewares. - -Code Example ------------- +"""Client for interacting with the KVStore contract. -* With Signer - -.. code-block:: python +Selects the network based on the Web3 chain id. Configure Web3 with an account +and signer middleware for writes; read operations work without a signer. +Examples: + With signer: + ```python from eth_typing import URI from web3 import Web3 from web3.middleware import SignAndSendRawMiddlewareBuilder from web3.providers.auto import load_provider_from_uri - from human_protocol_sdk.kvstore import KVStoreClient def get_w3_with_priv_key(priv_key: str): @@ -26,29 +18,25 @@ def get_w3_with_priv_key(priv_key: str): w3.eth.default_account = gas_payer.address w3.middleware_onion.inject( SignAndSendRawMiddlewareBuilder.build(priv_key), - 'SignAndSendRawMiddlewareBuilder', + "SignAndSendRawMiddlewareBuilder", layer=0, ) - return (w3, gas_payer) + return w3 - (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') + w3 = get_w3_with_priv_key("YOUR_PRIVATE_KEY") kvstore_client = KVStoreClient(w3) + ``` -* Without Signer (For read operations only) - -.. code-block:: python - + Read-only: + ```python from eth_typing import URI from web3 import Web3 from web3.providers.auto import load_provider_from_uri - from human_protocol_sdk.kvstore import KVStoreClient w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) kvstore_client = KVStoreClient(w3) - -Module ------- + ``` """ import logging @@ -71,24 +59,44 @@ def get_w3_with_priv_key(priv_key: str): class KVStoreClientError(Exception): - """ - Raises when some error happens when interacting with kvstore. - """ + """Exception raised when errors occur during KVStore operations.""" pass class KVStoreClient: - """ - A class used to manage kvstore on the HUMAN network. + """Client for interacting with the KVStore smart contract. + + This client provides methods to read and write key-value pairs on-chain, + supporting both individual and bulk operations, as well as URL storage with + content hash verification. + + Attributes: + w3 (Web3): Web3 instance configured for the target network. + network (dict): Network configuration for the current chain. + kvstore_contract (Contract): Contract instance for the KVStore. + gas_limit (Optional[int]): Optional gas limit for transactions. """ def __init__(self, web3: Web3, gas_limit: Optional[int] = None): - """ - Initializes a KVStore instance. + """Initialize a KVStoreClient instance. - :param web3: The Web3 object - :param gas_limit: (Optional) Gas limit for transactions + Args: + web3 (Web3): Web3 instance configured for the target network. + Must have a valid provider and chain ID. + gas_limit (Optional[int]): Optional gas limit for transactions. + + Raises: + KVStoreClientError: If chain ID is invalid or network configuration is missing. + + Example: + ```python + from web3 import Web3 + from human_protocol_sdk.kvstore import KVStoreClient + + w3 = Web3(Web3.HTTPProvider("http://localhost:8545")) + kvstore_client = KVStoreClient(w3) + ``` """ # Initialize web3 instance @@ -118,39 +126,25 @@ def __init__(self, web3: Web3, gas_limit: Optional[int] = None): @requires_signer def set(self, key: str, value: str, tx_options: Optional[TxParams] = None) -> None: - """ - Sets the value of a key-value pair in the contract. - - :param key: The key of the key-value pair to set - :param value: The value of the key-value pair to set - :param tx_options: (Optional) Additional transaction parameters - - :return: None - - :example: - .. code-block:: python - - from eth_typing import URI - from web3 import Web3 - from web3.middleware import SignAndSendRawMiddlewareBuilder - from web3.providers.auto import load_provider_from_uri - - from human_protocol_sdk.kvstore import KVStoreClient - - def get_w3_with_priv_key(priv_key: str): - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - gas_payer = w3.eth.account.from_key(priv_key) - w3.eth.default_account = gas_payer.address - w3.middleware_onion.inject( - SignAndSendRawMiddlewareBuilder.build(priv_key), - 'SignAndSendRawMiddlewareBuilder', - layer=0, - ) - return (w3, gas_payer) - - (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') - kvstore_client = KVStoreClient(w3) - kvstore_client.set('Role', 'RecordingOracle') + """Set a key-value pair in the KVStore contract. + + Stores a single key-value pair on-chain associated with the sender's address. + + Args: + key (str): Key to set (cannot be empty). + value (str): Value to assign to the key. + tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. + + Returns: + None + + Raises: + KVStoreClientError: If the key is empty or the transaction fails. + + Example: + ```python + kvstore_client.set("Role", "RecordingOracle") + ``` """ if not key: @@ -168,42 +162,30 @@ def get_w3_with_priv_key(priv_key: str): def set_bulk( self, keys: List[str], values: List[str], tx_options: Optional[TxParams] = None ) -> None: - """ - Sets multiple key-value pairs in the contract. - - :param keys: A list of keys to set - :param values: A list of values to set - :param tx_options: (Optional) Additional transaction parameters - - :return: None + """Set multiple key-value pairs in the KVStore contract. - :example: - .. code-block:: python + Stores multiple key-value pairs on-chain in a single transaction, + all associated with the sender's address. - from eth_typing import URI - from web3 import Web3 - from web3.middleware import SignAndSendRawMiddlewareBuilder - from web3.providers.auto import load_provider_from_uri + Args: + keys (List[str]): List of keys to set (no key can be empty). + values (List[str]): Corresponding list of values (must match keys length). + tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. - from human_protocol_sdk.kvstore import KVStoreClient + Returns: + None - def get_w3_with_priv_key(priv_key: str): - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - gas_payer = w3.eth.account.from_key(priv_key) - w3.eth.default_account = gas_payer.address - w3.middleware_onion.inject( - SignAndSendRawMiddlewareBuilder.build(priv_key), - 'SignAndSendRawMiddlewareBuilder', - layer=0, - ) - return (w3, gas_payer) + Raises: + KVStoreClientError: If any key is empty, arrays are empty, arrays have different + lengths, or the transaction fails. - (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') - kvstore_client = KVStoreClient(w3) - - keys = ['Role', 'Webhook_url'] - values = ['RecordingOracle', 'http://localhost'] - kvstore_client.set_bulk(keys, values) + Example: + ```python + kvstore_client.set_bulk( + ["Role", "Webhook_url"], + ["RecordingOracle", "http://localhost"], + ) + ``` """ if "" in keys: @@ -228,43 +210,31 @@ def set_file_url_and_hash( key: Optional[str] = "url", tx_options: Optional[TxParams] = None, ) -> None: - """ - Sets a URL value for the address that submits the transaction, and its hash. - - :param url: URL to set - :param key: Configurable URL key. `url` by default. - :param tx_options: (Optional) Additional transaction parameters - - :return: None - - :raise KVStoreClientError: If an error occurs while validating URL, or handling transaction - - :example: - .. code-block:: python + """Set a URL value and its content hash in the KVStore. - from eth_typing import URI - from web3 import Web3 - from web3.middleware import SignAndSendRawMiddlewareBuilder - from web3.providers.auto import load_provider_from_uri + Fetches the content from the URL, computes its hash, and stores both + the URL and hash on-chain. The hash key is automatically generated + by appending ``_hash`` to the provided key. - from human_protocol_sdk.kvstore import KVStoreClient + Args: + url (str): URL to store (must be valid and accessible). + key (Optional[str]): Configurable URL key. Defaults to ``"url"``. + The hash will be stored with key ``"{key}_hash"``. + tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. - def get_w3_with_priv_key(priv_key: str): - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - gas_payer = w3.eth.account.from_key(priv_key) - w3.eth.default_account = gas_payer.address - w3.middleware_onion.inject( - SignAndSendRawMiddlewareBuilder.build(priv_key), - 'SignAndSendRawMiddlewareBuilder', - layer=0, - ) - return (w3, gas_payer) + Returns: + None - (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') - kvstore_client = KVStoreClient(w3) + Raises: + KVStoreClientError: If the URL is invalid, unreachable, or the transaction fails. - kvstore_client.set_file_url_and_hash('http://localhost') - kvstore_client.set_file_url_and_hash('https://linkedin.com/me', 'linkedin_url') + Example: + ```python + kvstore_client.set_file_url_and_hash("http://localhost/manifest.json") + kvstore_client.set_file_url_and_hash( + "https://linkedin.com/me", "linkedin_url" + ) + ``` """ if not validate_url(url): raise KVStoreClientError(f"Invalid URL: {url}") @@ -280,24 +250,28 @@ def get_w3_with_priv_key(priv_key: str): handle_error(e, KVStoreClientError) def get(self, address: str, key: str) -> str: - """ - Gets the value of a key-value pair in the contract. - :param address: The Ethereum address associated with the key-value pair - :param key: The key of the key-value pair to get + """Get the value of a key-value pair from the KVStore. - :return: The value of the key-value pair if it exists + Retrieves the value associated with a key for a specific address. - :example: - .. code-block:: python + Args: + address (str): Ethereum address associated with the key-value pair. + key (str): Key to retrieve (cannot be empty). - from eth_typing import URI - from web3 import Web3 - from web3.providers.auto import load_provider_from_uri - from human_protocol_sdk.kvstore import KVStoreClient + Returns: + Value of the key-value pair if it exists, empty string otherwise. - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - kvstore_client = KVStoreClient(w3) - role = kvstore_client.get('0x62dD51230A30401C455c8398d06F85e4EaB6309f', 'Role') + Raises: + KVStoreClientError: If the key is empty, address is invalid, or the query fails. + + Example: + ```python + role = kvstore_client.get( + "0x62dD51230A30401C455c8398d06F85e4EaB6309f", + "Role", + ) + print(role) # "RecordingOracle" + ``` """ if not key: diff --git a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/kvstore/kvstore_utils.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/kvstore/kvstore_utils.py index fdb371ddf2..2672136569 100644 --- a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/kvstore/kvstore_utils.py +++ b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/kvstore/kvstore_utils.py @@ -1,23 +1,17 @@ -""" -Utility class for KVStore-related operations. - -Code Example ------------- - -.. code-block:: python +"""Utility helpers for KVStore queries. +Example: + ```python from human_protocol_sdk.constants import ChainId from human_protocol_sdk.kvstore import KVStoreUtils print( KVStoreUtils.get_kvstore_data( ChainId.POLYGON_AMOY, - "0x15d34aaf54267db7d7c367839aaf71a00a2c6a65" + "0x15d34aaf54267db7d7c367839aaf71a00a2c6a65", ) ) - -Module ------- + ``` """ from datetime import datetime @@ -37,20 +31,24 @@ class KVStoreData: - def __init__(self, key: str, value: str): - """ - Initializes a KVStoreData instance. + """Represents a key-value pair from the KVStore. - :param key: Key - :param value: Value - """ + Attributes: + key (str): The key of the key-value pair. + value (str): The value associated with the key. + """ + + def __init__(self, key: str, value: str): self.key = key self.value = value class KVStoreUtils: - """ - A utility class that provides additional KVStore-related functionalities. + """Utility class providing KVStore-related query and data retrieval functions. + + This class offers static methods to fetch KVStore data from the HUMAN Protocol + subgraph, including individual key-value pairs, bulk data, and specialized + methods for URLs with hash verification and public keys. """ @staticmethod @@ -59,26 +57,34 @@ def get_kvstore_data( address: str, options: Optional[SubgraphOptions] = None, ) -> Optional[List[KVStoreData]]: - """Returns the KVStore data for a given address. - - :param chain_id: Network in which the KVStore data has been deployed - :param address: Address of the KVStore - :param options: Optional config for subgraph requests - - :return: List of KVStore data - - :example: - .. code-block:: python - - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.kvstore import KVStoreUtils - - print( - KVStoreUtils.get_kvstore_data( - ChainId.POLYGON_AMOY, - "0x15d34aaf54267db7d7c367839aaf71a00a2c6a65" - ) - ) + """Retrieve all KVStore data for a given address. + + Queries the subgraph for all key-value pairs associated with a specific address. + + Args: + chain_id (ChainId): Network where the KVStore data has been stored. + address (str): Address whose KVStore data to retrieve. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests + such as custom endpoints or timeout settings. + + Returns: + List of KVStore data entries if found, empty list otherwise. + + Raises: + KVStoreClientError: If the chain ID is invalid or the address is malformed. + + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.kvstore import KVStoreUtils + + data = KVStoreUtils.get_kvstore_data( + ChainId.POLYGON_AMOY, + "0x15d34aaf54267db7d7c367839aaf71a00a2c6a65", + ) + for item in data: + print(f"{item.key}: {item.value}") + ``` """ from human_protocol_sdk.gql.kvstore import get_kvstore_by_address_query @@ -120,27 +126,35 @@ def get( key: str, options: Optional[SubgraphOptions] = None, ) -> str: - """Gets the value of a key-value pair in the contract. - - :param chain_id: Network in which the KVStore data has been deployed - :param address: The Ethereum address associated with the key-value pair - :param key: The key of the key-value pair to get - :param options: Optional config for subgraph requests - - :return: The value of the key-value pair if it exists - - :example: - .. code-block:: python - - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.kvstore import KVStoreUtils - - chain_id = ChainId.POLYGON_AMOY - address = '0x62dD51230A30401C455c8398d06F85e4EaB6309f' - key = 'role' - - result = KVStoreUtils.get(chain_id, address, key) - print(result) + """Get the value of a specific key for an address. + + Queries the subgraph for a specific key-value pair associated with an address. + + Args: + chain_id (ChainId): Network where the KVStore data has been stored. + address (str): Ethereum address associated with the key-value pair. + key (str): Key to retrieve (cannot be empty). + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. + + Returns: + Value for the key if it exists. + + Raises: + KVStoreClientError: If the key is empty, address is invalid, chain ID is invalid, + or the key is not found for the address. + + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.kvstore import KVStoreUtils + + role = KVStoreUtils.get( + ChainId.POLYGON_AMOY, + "0x62dD51230A30401C455c8398d06F85e4EaB6309f", + "role", + ) + print(role) + ``` """ from human_protocol_sdk.gql.kvstore import get_kvstore_by_address_and_key_query @@ -178,26 +192,40 @@ def get_file_url_and_verify_hash( key: Optional[str] = "url", options: Optional[SubgraphOptions] = None, ) -> str: - """Gets the URL value of the given entity, and verify its hash. - - :param chain_id: Network in which the KVStore data has been deployed - :param address: Address from which to get the URL value. - :param key: Configurable URL key. `url` by default. - :param options: Optional config for subgraph requests - - :return url: The URL value of the given address if exists, and the content is valid - - :example: - .. code-block:: python - - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.kvstore import KVStoreUtils - - chain_id = ChainId.POLYGON_AMOY - address = '0x62dD51230A30401C455c8398d06F85e4EaB6309f' - - url = KVStoreUtils.get_file_url_and_verify_hash(chain_id, address) - linkedin_url = KVStoreUtils.get_file_url_and_verify_hash(chain_id, address, 'linkedin_url') + """Get a stored URL and verify its content hash. + + Retrieves a URL from KVStore, fetches its content, and verifies that the + content hash matches the stored hash value. This ensures the file content + has not been tampered with. + + Args: + chain_id (ChainId): Network where the KVStore data has been stored. + address (str): Address from which to get the URL value. + key (Optional[str]): Configurable URL key. Defaults to ``"url"``. + The hash key is expected to be ``"{key}_hash"``. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. + + Returns: + URL value if it exists and the content hash matches. + Returns empty string if URL is not set. + + Raises: + KVStoreClientError: If the address is invalid, hash verification fails, + or the URL is unreachable. + + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.kvstore import KVStoreUtils + + chain_id = ChainId.POLYGON_AMOY + address = "0x62dD51230A30401C455c8398d06F85e4EaB6309f" + + url = KVStoreUtils.get_file_url_and_verify_hash(chain_id, address) + linkedin_url = KVStoreUtils.get_file_url_and_verify_hash( + chain_id, address, "linkedin_url" + ) + ``` """ if not Web3.is_address(address): @@ -222,23 +250,34 @@ def get_file_url_and_verify_hash( @staticmethod def get_public_key(chain_id: ChainId, address: str) -> str: - """Gets the public key of the given entity, and verify its hash. - - :param chain_id: Network in which the KVStore data has been deployed - :param address: Address from which to get the public key. - - :return public_key: The public key of the given address if exists, and the content is valid - - :example: - .. code-block:: python - - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.kvstore import KVStoreUtils - - chain_id = ChainId.POLYGON_AMOY - address = '0x62dD51230A30401C455c8398d06F85e4EaB6309f' - - public_key = KVStoreUtils.get_public_key(chain_id, address) + """Get the public key of an entity from KVStore. + + Retrieves and validates the public key stored for a given address. + The public key URL is fetched from the ``public_key`` key and verified + against its hash. + + Args: + chain_id (ChainId): Network where the KVStore data has been stored. + address (str): Address from which to get the public key. + + Returns: + Public key content if it exists and is valid. + Returns empty string if no public key is set. + + Raises: + KVStoreClientError: If the address is invalid or hash verification fails. + + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.kvstore import KVStoreUtils + + public_key = KVStoreUtils.get_public_key( + ChainId.POLYGON_AMOY, + "0x62dD51230A30401C455c8398d06F85e4EaB6309f", + ) + print(public_key) + ``` """ public_key_url = KVStoreUtils.get_file_url_and_verify_hash( diff --git a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/legacy_encryption.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/legacy_encryption.py index 5ce0f7c801..134fc19d66 100644 --- a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/legacy_encryption.py +++ b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/legacy_encryption.py @@ -1,12 +1,31 @@ """ -Legacy version of encryption module. -Learn more about [encryption](human_protocol_sdk.encryption.md#human_protocol_sdk.encryption.Encryption). +Legacy encryption utilities for backward compatibility. + +This module provides deprecated encryption functionality maintained for backward +compatibility with older versions of the SDK. For new implementations, use the +``human_protocol_sdk.encryption`` module instead. + +Warning: + This module is deprecated and will be removed in a future version. + Please migrate to ``human_protocol_sdk.encryption.Encryption`` and + ``human_protocol_sdk.encryption.EncryptionUtils``. + +Example: + ```python + # Deprecated - for backward compatibility only + from human_protocol_sdk.legacy_encryption import LegacyEncryption + + # Recommended - use this instead + from human_protocol_sdk.encryption import Encryption + ``` """ +import warnings import hashlib import os import struct import typing as t +from typing import Optional, List, Union from cryptography.hazmat.primitives import hashes, hmac from cryptography.hazmat.primitives.asymmetric import ec @@ -19,65 +38,60 @@ keys as eth_keys, ) from eth_utils import int_to_big_endian +from pgpy import PGPKey, PGPMessage +from pgpy.constants import SymmetricKeyAlgorithm +from pgpy.errors import PGPError class InvalidPublicKey(Exception): - """ - A custom exception raised when trying to convert bytes - into an elliptic curve public key. - """ + """Exception raised when converting bytes into an elliptic curve public key fails.""" pass class DecryptionError(Exception): - """ - Raised when a message could not be decrypted. - """ + """Exception raised when a message could not be decrypted.""" pass class Encryption: - """ - Encryption class specialized in encrypting and decrypting a byte string. + """Encryption class specialized in encrypting and decrypting byte strings using ECIES. + + This class implements Elliptic Curve Integrated Encryption Scheme (ECIES) using + SECP256K1 elliptic curve, AES256 cipher, and HMAC-SHA-256-32. + + Attributes: + ELLIPTIC_CURVE (ec.EllipticCurve): SECP256K1 elliptic curve definition. + KEY_LEN (int): Key length for ECIES (32 bytes for AES256 and HMAC-SHA-256-32). + CIPHER: AES cipher algorithm definition. + MODE: CTR cipher mode definition. + PUBLIC_KEY_LEN (int): Length of public keys in uncompressed form (64 bytes). """ ELLIPTIC_CURVE: ec.EllipticCurve = ec.SECP256K1() - """ Elliptic curve definition. """ - KEY_LEN = 32 - """ ECIES using AES256 and HMAC-SHA-256-32 """ - CIPHER = AES - """ Cipher algorithm definition. """ - MODE = CTR - """ Cipher mode definition. """ - PUBLIC_KEY_LEN: int = 64 - """ - Length of public keys: 512 bit keys in uncompressed form, without - format byte - """ @staticmethod def is_encrypted(data: bytes) -> bool: - """ - Checks whether data is already encrypted by verifying ecies header. - - :param data: Data to be checked. + """Check whether data is already encrypted by verifying ECIES header. - :return: True if data is encrypted, False otherwise. + Args: + data (bytes): Data to be checked for encryption. - :example: - .. code-block:: python + Returns: + ``True`` if data has valid ECIES header (starts with 0x04), ``False`` otherwise. - from human_protocol_sdk.legacy_encryption import Encryption + Example: + ```python + from human_protocol_sdk.legacy_encryption import Encryption - encrypted_message_str = "0402f48d28d29ae3d681e4cbbe499be0803c2a9d94534d0a4501ab79fd531183fbd837a021c1c117f47737e71c430b9d33915615f68c8dcb5e2f4e4dda4c9415d20a8b5fad9770b14067f2dd31a141a8a8da1f56eb2577715409dbf3c39b9bfa7b90c1acd838fe147c95f0e1ca9359a4cfd52367a73a6d6c548b492faa" - - is_encrypted = Encryption.is_encrypted(bytes.fromhex(encrypted_message_str)) + encrypted_hex = "0402f48d28d29ae3d681e4cbbe499be0803c2a9d94534d0a4501ab79fd531183fbd837a021c1c117f47737e71c430b9d33915615f68c8dcb5e2f4e4dda4c9415d20a8b5fad9770b14067f2dd31a141a8a8da1f56eb2577715409dbf3c39b9bfa7b90c1acd838fe147c95f0e1ca9359a4cfd52367a73a6d6c548b492faa" + is_encrypted = Encryption.is_encrypted(bytes.fromhex(encrypted_hex)) + ``` """ return data[:1] == b"\x04" @@ -87,31 +101,39 @@ def encrypt( public_key: eth_datatypes.PublicKey, shared_mac_data: bytes = b"", ) -> bytes: - """ - Encrypt data with ECIES method to the given public key - 1) generate r = random value - 2) generate shared-secret = kdf( ecdhAgree(r, P) ) - 3) generate R = rG [same op as generating a public key] - 4) 0x04 || R || AsymmetricEncrypt(shared-secret, plaintext) || tag - - :param data: Data to be encrypted - :param public_key: Public to be used to encrypt provided data. - :param shared_mac_data: shared mac additional data as suffix. - - :return: Encrypted byte string - - :example: - .. code-block:: python - - from human_protocol_sdk.legacy_encryption import Encryption - from eth_keys import datatypes - - public_key_str = "0a1d228684bc8c8c7611df3264f04ebd823651acc46b28b3574d2e69900d5e34f04a26cf13237fa42ab23245b58060c239b356b0a276f57e8de1234c7100fcf9" - - public_key = datatypes.PublicKey(bytes.fromhex(private_key_str)) - - encryption = Encryption() - encrypted_message = encryption.encrypt(b'your message', public_key) + """Encrypt data using ECIES method with the given public key. + + The encryption process follows these steps: + 1. Generate random ephemeral private key r + 2. Generate shared secret using ECDH key agreement + 3. Derive encryption and MAC keys from shared secret + 4. Generate ephemeral public key R = r*G + 5. Encrypt data using AES256-CTR + 6. Generate authentication tag using HMAC-SHA256 + 7. Return: 0x04 || R || IV || ciphertext || tag + + Args: + data (bytes): Data to be encrypted. + public_key (eth_datatypes.PublicKey): Public key to encrypt data for. + shared_mac_data (bytes): Additional data to include in MAC computation. Defaults to empty bytes. + + Returns: + Encrypted message in ECIES format. + + Raises: + DecryptionError: If key exchange fails or public key is invalid. + + Example: + ```python + from human_protocol_sdk.legacy_encryption import Encryption + from eth_keys import datatypes + + public_key_hex = "0a1d228684bc8c8c7611df3264f04ebd823651acc46b28b3574d2e69900d5e34f04a26cf13237fa42ab23245b58060c239b356b0a276f57e8de1234c7100fcf9" + public_key = datatypes.PublicKey(bytes.fromhex(public_key_hex)) + + encryption = Encryption() + encrypted = encryption.encrypt(b'your message', public_key) + ``` """ # 1) generate r = random value @@ -156,33 +178,39 @@ def decrypt( private_key: eth_datatypes.PrivateKey, shared_mac_data: bytes = b"", ) -> bytes: - """ - Decrypt data with ECIES method using the given private key - 1) generate shared-secret = kdf( ecdhAgree(myPrivKey, msg[1:65]) ) - 2) verify tag - 3) decrypt - ecdhAgree(r, recipientPublic) == ecdhAgree(recipientPrivate, R) - [where R = r*G, and recipientPublic = recipientPrivate*G] - - :param data: Data to be decrypted - :param private_key: Private key to be used in agreement. - :param shared_mac_data: shared mac additional data as suffix. - - :return: Decrypted byte string - - :example: - .. code-block:: python - - from human_protocol_sdk.legacy_encryption import Encryption - from eth_keys import datatypes - - private_key_str = "9822f95dd945e373300f8c8459a831846eda97f314689e01f7cf5b8f1c2298b3" - encrypted_message_str = "0402f48d28d29ae3d681e4cbbe499be0803c2a9d94534d0a4501ab79fd531183fbd837a021c1c117f47737e71c430b9d33915615f68c8dcb5e2f4e4dda4c9415d20a8b5fad9770b14067f2dd31a141a8a8da1f56eb2577715409dbf3c39b9bfa7b90c1acd838fe147c95f0e1ca9359a4cfd52367a73a6d6c548b492faa" - - private_key = datatypes.PrivateKey(bytes.fromhex(private_key_str)) - - encryption = Encryption() - encrypted_message = encryption.decrypt(bytes.fromhex(encrypted_message_str), private_key) + """Decrypt data using ECIES method with the given private key. + + The decryption process follows these steps: + 1. Extract ephemeral public key R from message + 2. Generate shared secret using ECDH: ecdhAgree(privateKey, R) + 3. Derive encryption and MAC keys from shared secret + 4. Verify authentication tag + 5. Decrypt ciphertext using AES256-CTR + + Args: + data (bytes): Encrypted message in ECIES format. + private_key (eth_datatypes.PrivateKey): Private key to decrypt the data. + shared_mac_data (bytes): Additional data used in MAC computation. Defaults to empty bytes. + + Returns: + Decrypted plaintext data. + + Raises: + DecryptionError: If ECIES header is invalid, tag verification fails, + key exchange fails, or decryption fails. + + Example: + ```python + from human_protocol_sdk.legacy_encryption import Encryption + from eth_keys import datatypes + + private_key_hex = "9822f95dd945e373300f8c8459a831846eda97f314689e01f7cf5b8f1c2298b3" + encrypted_hex = "0402f48d28d29ae3d681e4cbbe499be0803c2a9d94534d0a4501ab79fd531183fbd837a021c1c117f47737e71c430b9d33915615f68c8dcb5e2f4e4dda4c9415d20a8b5fad9770b14067f2dd31a141a8a8da1f56eb2577715409dbf3c39b9bfa7b90c1acd838fe147c95f0e1ca9359a4cfd52367a73a6d6c548b492faa" + + private_key = datatypes.PrivateKey(bytes.fromhex(private_key_hex)) + encryption = Encryption() + decrypted = encryption.decrypt(bytes.fromhex(encrypted_hex), private_key) + ``` """ if self.is_encrypted(data) is False: @@ -232,26 +260,20 @@ def decrypt( def _process_key_exchange( self, private_key: eth_datatypes.PrivateKey, public_key: eth_datatypes.PublicKey ) -> bytes: - """ - Performs a key exchange operation using the - ECDH (Elliptic-curve Diffie–Hellman) algorithm. + """Perform ECDH key exchange operation. - NIST SP 800-56a Concatenation Key Derivation Function - (see section 4) - Key agreement. - https://csrc.nist.gov/CSRC/media/Publications/sp/800-56a/archive/2006-05-03/documents/sp800-56-draft-jul2005.pdf + Implements NIST SP 800-56a Concatenation Key Derivation Function (section 4) + for key agreement using ECDH (Elliptic-curve Diffie-Hellman) algorithm. + Args: + private_key (eth_datatypes.PrivateKey): Private key for the initiator. + public_key (eth_datatypes.PublicKey): Public key for the responder. - A key establishment procedure where the resultant secret keying - material is a function of information contributed by two participants, - so that no party can predetermine the value of the secret keying - material independently from the contribut ions of the other parties. - Contrast with key transport. + Returns: + Shared secret key material resulting from the ECDH exchange. - :param private_key: Private key to be used in agreement (the initiator). - :param public_key: Public key to be exchanged (responder). - - :return: Key material resulted of the exchange between two keys, assuming - that they derive the same key material + Raises: + InvalidPublicKey: If the public key cannot be converted to a valid elliptic curve point. """ private_key_int = int(t.cast(int, private_key)) @@ -275,18 +297,18 @@ def _process_key_exchange( raise InvalidPublicKey(str(error)) from error def generate_private_key(self) -> eth_datatypes.PrivateKey: - """ - Generates a new SECP256K1 private key and return it - - :return: New SECP256K1 private key. + """Generate a new SECP256K1 private key. - :example: - .. code-block:: python + Returns: + Newly generated SECP256K1 private key. - from human_protocol_sdk.legacy_encryption import Encryption + Example: + ```python + from human_protocol_sdk.legacy_encryption import Encryption - encryption = Encryption() - private_key = encryption.generate_private_key() + encryption = Encryption() + private_key = encryption.generate_private_key() + ``` """ key = ec.generate_private_key(curve=self.ELLIPTIC_CURVE) @@ -296,41 +318,37 @@ def generate_private_key(self) -> eth_datatypes.PrivateKey: @staticmethod def generate_public_key(private_key: bytes) -> eth_keys.PublicKey: - """ - Generates a public key with combination to private key provided. - - :param private_key: Private to be used to create public key. - - :return: Public key object. + """Generate a public key from the given private key. - :example: - .. code-block:: python + Args: + private_key (bytes): Private key bytes to derive the public key from. - from human_protocol_sdk.legacy_encryption import Encryption + Returns: + Public key object corresponding to the private key. - private_key_str = "9822f95dd945e373300f8c8459a831846eda97f314689e01f7cf5b8f1c2298b3" + Example: + ```python + from human_protocol_sdk.legacy_encryption import Encryption - public_key = Encryption.generate_public_key(bytes.fromhex(private_key_str)) + private_key_hex = "9822f95dd945e373300f8c8459a831846eda97f314689e01f7cf5b8f1c2298b3" + public_key = Encryption.generate_public_key(bytes.fromhex(private_key_hex)) + ``` """ private_key_obj = eth_keys.PrivateKey(private_key) return private_key_obj.public_key def _get_key_derivation(self, key_material: bytes) -> bytes: - """ - NIST SP 800-56a Concatenation Key Derivation Function - (see section 5.8.1) - KDF. - - An Approved key derivation function (KDF) shall be used to derive - secret keying material from a shared secret. + """Derive encryption and MAC keys from shared secret using KDF. - Pretty much copied from geth's implementation: - https://github.com/ethereum/go-ethereum/blob/673007d7aed1d2678ea3277eceb7b55dc29cf092/crypto/ecies/ecies.go#L167 + Implements NIST SP 800-56a Concatenation Key Derivation Function (section 5.8.1). + Uses SHA256 hash to derive secret keying material from ECDH shared secret. - :param key_material: Key material derived from ECDH (shared secret) exchange and - must be processed to deverive a key secret. + Args: + key_material (bytes): Shared secret from ECDH key exchange. - :return: Key secret derived - a called KDF + Returns: + Derived key secret (concatenation of encryption key and MAC key). """ key = b"" @@ -350,7 +368,15 @@ def _get_key_derivation(self, key_material: bytes) -> bytes: @staticmethod def _hmac_sha256(key: bytes, msg: bytes) -> bytes: - """Generates hash MAC using SHA256 Hash Algorithm""" + """Generate HMAC using SHA256 hash algorithm. + + Args: + key (bytes): HMAC key. + msg (bytes): Message to authenticate. + + Returns: + HMAC-SHA256 digest. + """ mac = hmac.HMAC(key, hashes.SHA256()) mac.update(msg) @@ -358,10 +384,11 @@ def _hmac_sha256(key: bytes, msg: bytes) -> bytes: @staticmethod def _pad32(value: bytes) -> bytes: - """ - :param value: Value to be add padding on the data. + """Pad value to 32 bytes with leading zeros. - :return: value with added code added. - """ + Args: + value (bytes): Value to pad. - return value.rjust(32, b"\x00") + Returns: + Value padded to 32 bytes. + """ diff --git a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/operator/operator_utils.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/operator/operator_utils.py index c4332ea4fb..ed467d0389 100644 --- a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/operator/operator_utils.py +++ b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/operator/operator_utils.py @@ -1,11 +1,7 @@ -""" -Utility class for operator-related operations. - -Code Example ------------- - -.. code-block:: python +"""Utility helpers for operator-related queries. +Example: + ```python from human_protocol_sdk.constants import ChainId from human_protocol_sdk.operator import OperatorUtils, OperatorFilter @@ -14,9 +10,7 @@ OperatorFilter(chain_id=ChainId.POLYGON_AMOY, roles=["Job Launcher"]) ) ) - -Module ------- + ``` """ import logging @@ -32,16 +26,22 @@ class OperatorUtilsError(Exception): - """ - Raised when an error occurs while interacting with the operator. - """ + """Exception raised when errors occur during operator operations.""" pass class OperatorFilter: - """ - A class used to filter operators. + """Filter configuration for querying operators from the subgraph. + + Attributes: + chain_id (ChainId): Chain ID to request data from. + roles (List[str]): List of roles to filter by. + min_staked_amount (Optional[int]): Minimum staked amount to include operators. + order_by (Optional[str]): Property to order results by (e.g., "role", "stakedAmount"). + order_direction (OrderDirection): Order direction (ascending or descending). + first (int): Number of items per page (1-1000). + skip (int): Number of items to skip for pagination. """ def __init__( @@ -54,16 +54,19 @@ def __init__( first: int = 10, skip: int = 0, ): - """ - Initializes a OperatorFilter instance. - - :param chain_id: Chain ID to request data - :param roles: Roles to filter by - :param min_staked_amount: Minimum amount staked to filter by - :param order_by: Property to order by, e.g., "role" - :param order_direction: Order direction of results, "asc" or "desc" - :param first: Number of items per page - :param skip: Number of items to skip (for pagination) + """Configure filtering options for operator queries. + + Args: + chain_id: Chain ID to request data. + roles: Roles to filter by. + min_staked_amount: Minimum amount staked to include. + order_by: Property to order by, e.g., "role". + order_direction: Order direction of results. + first: Number of items per page. + skip: Number of items to skip (for pagination). + + Raises: + OperatorUtilsError: If chain ID or order direction is invalid. """ if chain_id not in ChainId: @@ -84,6 +87,32 @@ def __init__( class OperatorData: + """Represents operator information retrieved from the subgraph. + + Attributes: + chain_id (ChainId): Chain where the operator is registered. + id (str): Unique operator identifier. + address (str): Operator's Ethereum address. + staked_amount (Optional[int]): Amount staked by the operator. + locked_amount (Optional[int]): Amount currently locked. + locked_until_timestamp (Optional[int]): Time in milliseconds until locked amount is released. + withdrawn_amount (Optional[int]): Total amount withdrawn. + slashed_amount (Optional[int]): Total amount slashed. + amount_jobs_processed (int): Number of jobs launched/processed by the operator. + role (Optional[str]): Current role of the operator (e.g., "Job Launcher", "Recording Oracle"). + fee (Optional[int]): Operator fee percentage. + public_key (Optional[str]): Operator's public key. + webhook_url (Optional[str]): Webhook URL for notifications. + website (Optional[str]): Operator's website URL. + url (Optional[str]): Operator URL. + job_types (List[str]): List of supported job types. + registration_needed (Optional[bool]): Whether registration is required. + registration_instructions (Optional[str]): Instructions for registration. + reputation_networks (List[str]): List of reputation network addresses. + name (Optional[str]): Operator name. + category (Optional[str]): Operator category. + """ + def __init__( self, chain_id: ChainId, @@ -108,30 +137,30 @@ def __init__( name: Optional[str] = None, category: Optional[str] = None, ): - """ - Initializes a OperatorData instance. - - :param chain_id: Chain Identifier - :param id: Identifier - :param address: Address - :param staked_amount: Amount staked - :param locked_amount: Amount locked - :param locked_until_timestamp: Locked until timestamp - :param withdrawn_amount: Amount withdrawn - :param slashed_amount: Amount slashed - :param amount_jobs_processed: Amount of jobs launched - :param role: Role - :param fee: Fee - :param public_key: Public key - :param webhook_url: Webhook URL - :param website: Website URL - :param url: URL - :param job_types: Job types - :param registration_needed: Whether registration is needed - :param registration_instructions: Registration instructions - :param reputation_networks: List of reputation networks - :param name: Name - :param category: Category + """Represents operator information returned from the subgraph. + + Args: + chain_id: Chain identifier. + id: Operator ID. + address: Operator address. + amount_jobs_processed: Jobs launched by the operator. + reputation_networks: List of reputation networks. + staked_amount: Amount staked. + locked_amount: Amount locked. + locked_until_timestamp: Time (in seconds) until locked amount is released. + withdrawn_amount: Amount withdrawn. + slashed_amount: Amount slashed. + role: Current role of the operator. + fee: Operator fee. + public_key: Public key. + webhook_url: Webhook URL. + website: Website URL. + url: Operator URL. + job_types: Supported job types. + registration_needed: Whether registration is needed. + registration_instructions: Registration instructions. + name: Operator name. + category: Operator category. """ self.chain_id = chain_id @@ -176,25 +205,28 @@ def __init__( class RewardData: + """Represents a reward distributed to a slasher. + + Attributes: + escrow_address (str): Address of the escrow that generated the reward. + amount (int): Reward amount in token's smallest unit. + """ + def __init__( self, escrow_address: str, amount: int, ): - """ - Initializes a RewardData instance. - - :param escrow_address: Escrow address - :param amount: Amount - """ - self.escrow_address = escrow_address self.amount = amount class OperatorUtils: - """ - A utility class that provides additional operator-related functionalities. + """Utility class providing operator-related query and data retrieval functions. + + This class offers static methods to fetch operator data, including filtered + operator lists, individual operator details, reputation network operators, + and reward information from the Human Protocol subgraph. """ @staticmethod @@ -202,24 +234,32 @@ def get_operators( filter: OperatorFilter, options: Optional[SubgraphOptions] = None, ) -> List[OperatorData]: - """Get operators data of the protocol. + """Retrieve a list of operators matching the provided filter criteria. - :param filter: Operator filter - :param options: Optional config for subgraph requests + Queries the subgraph for operators that match the specified parameters + including roles, minimum staked amount, and ordering preferences. - :return: List of operators data + Args: + filter (OperatorFilter): Filter parameters including chain ID, roles, + minimum staked amount, ordering, and pagination options. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests + such as custom endpoints or timeout settings. - :example: - .. code-block:: python + Returns: + A list of operator records matching the filter criteria. + Returns an empty list if no matches are found. - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.operator import OperatorUtils, OperatorFilter + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.operator import OperatorUtils, OperatorFilter - print( - OperatorUtils.get_operators( - OperatorFilter(chain_id=ChainId.POLYGON_AMOY, roles=["Job Launcher"]) - ) - ) + operators = OperatorUtils.get_operators( + OperatorFilter(chain_id=ChainId.POLYGON_AMOY, roles=["Job Launcher"]) + ) + for operator in operators: + print(f"{operator.address}: {operator.role}") + ``` """ from human_protocol_sdk.gql.operator import get_operators_query @@ -290,25 +330,34 @@ def get_operator( operator_address: str, options: Optional[SubgraphOptions] = None, ) -> Optional[OperatorData]: - """Gets the operator details. + """Retrieve a single operator by their address. - :param chain_id: Network in which the operator exists - :param operator_address: Address of the operator - :param options: Optional config for subgraph requests + Fetches detailed information about a specific operator from the subgraph. - :return: Operator data if exists, otherwise None + Args: + chain_id (ChainId): Network where the operator is registered. + operator_address (str): Ethereum address of the operator. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. - :example: - .. code-block:: python + Returns: + Operator data if found, otherwise ``None``. - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.operator import OperatorUtils + Raises: + OperatorUtilsError: If the chain ID is invalid or the operator address is malformed. - chain_id = ChainId.POLYGON_AMOY - operator_address = '0x62dD51230A30401C455c8398d06F85e4EaB6309f' + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.operator import OperatorUtils - operator_data = OperatorUtils.get_operator(chain_id, operator_address) - print(operator_data) + chain_id = ChainId.POLYGON_AMOY + operator_address = "0x62dD51230A30401C455c8398d06F85e4EaB6309f" + + operator_data = OperatorUtils.get_operator(chain_id, operator_address) + if operator_data: + print(f"Role: {operator_data.role}") + print(f"Staked: {operator_data.staked_amount}") + ``` """ from human_protocol_sdk.gql.operator import get_operator_query @@ -369,26 +418,36 @@ def get_reputation_network_operators( role: Optional[str] = None, options: Optional[SubgraphOptions] = None, ) -> List[OperatorData]: - """Get the reputation network operators of the specified address. + """Retrieve operators registered under a specific reputation network. - :param chain_id: Network in which the reputation network exists - :param address: Address of the reputation oracle - :param role: (Optional) Role of the operator - :param options: Optional config for subgraph requests + Fetches all operators associated with a reputation oracle, optionally + filtered by role. - :return: Returns an array of operator details + Args: + chain_id (ChainId): Network where the reputation network exists. + address (str): Ethereum address of the reputation oracle. + role (Optional[str]): Optional role to filter operators (e.g., "Job Launcher"). + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. - :example: - .. code-block:: python + Returns: + A list of operators registered under the reputation network. + Returns an empty list if no operators are found. - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.operator import OperatorUtils + Raises: + OperatorUtilsError: If the chain ID is invalid or the reputation address is malformed. - operators = OperatorUtils.get_reputation_network_operators( - ChainId.POLYGON_AMOY, - '0x62dD51230A30401C455c8398d06F85e4EaB6309f' - ) - print(operators) + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.operator import OperatorUtils + + operators = OperatorUtils.get_reputation_network_operators( + ChainId.POLYGON_AMOY, + "0x62dD51230A30401C455c8398d06F85e4EaB6309f", + role="Recording Oracle", + ) + print(f"Found {len(operators)} operators") + ``` """ from human_protocol_sdk.gql.operator import get_reputation_network_query @@ -454,25 +513,35 @@ def get_rewards_info( slasher: str, options: Optional[SubgraphOptions] = None, ) -> List[RewardData]: - """Get rewards of the given slasher. + """Retrieve rewards collected by a slasher address. - :param chain_id: Network in which the slasher exists - :param slasher: Address of the slasher - :param options: Optional config for subgraph requests + Fetches all reward events where the specified address acted as a slasher + and received rewards for detecting misbehavior. - :return: List of rewards info + Args: + chain_id (ChainId): Network where the slasher operates. + slasher (str): Ethereum address of the slasher. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. - :example: - .. code-block:: python + Returns: + A list of rewards received by the slasher. + Returns an empty list if no rewards are found. - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.operator import OperatorUtils + Raises: + OperatorUtilsError: If the chain ID is invalid or the slasher address is malformed. - rewards_info = OperatorUtils.get_rewards_info( - ChainId.POLYGON_AMOY, - '0x62dD51230A30401C455c8398d06F85e4EaB6309f' - ) - print(rewards_info) + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.operator import OperatorUtils + + rewards_info = OperatorUtils.get_rewards_info( + ChainId.POLYGON_AMOY, + "0x62dD51230A30401C455c8398d06F85e4EaB6309f", + ) + total_rewards = sum(reward.amount for reward in rewards_info) + print(f"Total rewards: {total_rewards}") + ``` """ if chain_id.value not in set(chain_id.value for chain_id in ChainId): diff --git a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/staking/staking_client.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/staking/staking_client.py index 33a9073b53..c467b21ad8 100644 --- a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/staking/staking_client.py +++ b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/staking/staking_client.py @@ -1,54 +1,25 @@ -""" -This client enables performing actions on staking contracts and -obtaining staking information from both the contracts and subgraph. - -Internally, the SDK will use one network or another according to the network ID of the web3. -To use this client, you need to create a Web3 instance and configure the default account, -as well as some middlewares. - -Code Example ------------- +"""Client for staking actions on HUMAN Protocol. -* With Signer - -.. code-block:: python +Internally selects network config based on the Web3 chain id. +Example: + ```python from eth_typing import URI from web3 import Web3 from web3.middleware import SignAndSendRawMiddlewareBuilder from web3.providers.auto import load_provider_from_uri - - from human_protocol_sdk.staking import StakingClient - - def get_w3_with_priv_key(priv_key: str): - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - gas_payer = w3.eth.account.from_key(priv_key) - w3.eth.default_account = gas_payer.address - w3.middleware_onion.inject( - SignAndSendRawMiddlewareBuilder.build(priv_key), - 'SignAndSendRawMiddlewareBuilder', - layer=0, - ) - return (w3, gas_payer) - - (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') - staking_client = StakingClient(w3) - -* Without Signer (For read operations only) - -.. code-block:: python - - from eth_typing import URI - from web3 import Web3 - from web3.providers.auto import load_provider_from_uri - from human_protocol_sdk.staking import StakingClient w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) + gas_payer = w3.eth.account.from_key("YOUR_PRIVATE_KEY") + w3.eth.default_account = gas_payer.address + w3.middleware_onion.inject( + SignAndSendRawMiddlewareBuilder.build("YOUR_PRIVATE_KEY"), + "SignAndSendRawMiddlewareBuilder", + layer=0, + ) staking_client = StakingClient(w3) - -Module ------- + ``` """ import logging @@ -74,23 +45,46 @@ def get_w3_with_priv_key(priv_key: str): class StakingClientError(Exception): - """ - Raises when some error happens when interacting with staking. - """ + """Exception raised when errors occur during staking operations.""" pass class StakingClient: - """ - A class used to manage staking on the HUMAN network. - """ + """Client for interacting with the staking smart contract. - def __init__(self, w3: Web3): - """Initializes a Staking instance + This client provides methods to stake, unstake, withdraw, and slash HMT tokens, + as well as query staker information on the Human Protocol network. - :param w3: Web3 instance + Attributes: + w3 (Web3): Web3 instance configured for the target network. + network (dict): Network configuration for the current chain. + hmtoken_contract (Contract): Contract instance for the HMT token. + factory_contract (Contract): Contract instance for the escrow factory. + staking_contract (Contract): Contract instance for the staking contract. + """ + def __init__(self, w3: Web3): + """Initialize a StakingClient instance. + + Args: + w3 (Web3): Web3 instance configured for the target network. + Must have a valid provider and chain ID. + + Raises: + StakingClientError: If chain ID is invalid, network configuration is missing, + or network configuration is empty. + + Example: + ```python + from eth_typing import URI + from web3 import Web3 + from web3.providers.auto import load_provider_from_uri + from human_protocol_sdk.staking import StakingClient + + w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) + staking_client = StakingClient(w3) + ``` """ # Initialize web3 instance @@ -132,42 +126,29 @@ def __init__(self, w3: Web3): @requires_signer def approve_stake(self, amount: int, tx_options: Optional[TxParams] = None) -> None: - """Approves HMT token for Staking. - - :param amount: Amount to approve - :param tx_options: (Optional) Additional transaction parameters - - :return: None + """Approve HMT tokens for staking. - :validate: - Amount must be greater than 0 + Grants the staking contract permission to transfer HMT tokens from the caller's + account. This must be called before staking. - :example: - .. code-block:: python + Args: + amount (int): Amount of HMT tokens to approve in token's smallest unit + (must be greater than 0). + tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. - from eth_typing import URI - from web3 import Web3 - from web3.middleware import SignAndSendRawMiddlewareBuilder - from web3.providers.auto import load_provider_from_uri + Returns: + None - from human_protocol_sdk.staking import StakingClient + Raises: + StakingClientError: If the amount is not positive or the transaction fails. - def get_w3_with_priv_key(priv_key: str): - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - gas_payer = w3.eth.account.from_key(priv_key) - w3.eth.default_account = gas_payer.address - w3.middleware_onion.inject( - SignAndSendRawMiddlewareBuilder.build(priv_key), - 'SignAndSendRawMiddlewareBuilder', - layer=0, - ) - return (w3, gas_payer) + Example: + ```python + from web3 import Web3 - (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') - staking_client = StakingClient(w3) - - amount = Web3.to_wei(5, 'ether') # convert from ETH to WEI - staking_client.approve_stake(amount) + amount = Web3.to_wei(100, "ether") + staking_client.approve_stake(amount) + ``` """ if amount <= 0: @@ -182,45 +163,44 @@ def get_w3_with_priv_key(priv_key: str): @requires_signer def stake(self, amount: int, tx_options: Optional[TxParams] = None) -> None: - """Stakes HMT token. - - :param amount: Amount to stake - :param tx_options: (Optional) Additional transaction parameters - - :return: None - - :validate: - - Amount must be greater than 0 - - Amount must be less than or equal to the approved amount (on-chain) - - Amount must be less than or equal to the balance of the staker (on-chain) - - :example: - .. code-block:: python - - from eth_typing import URI - from web3 import Web3 - from web3.middleware import SignAndSendRawMiddlewareBuilder - from web3.providers.auto import load_provider_from_uri - - from human_protocol_sdk.staking import StakingClient - - def get_w3_with_priv_key(priv_key: str): - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - gas_payer = w3.eth.account.from_key(priv_key) - w3.eth.default_account = gas_payer.address - w3.middleware_onion.inject( - SignAndSendRawMiddlewareBuilder.build(priv_key), - 'SignAndSendRawMiddlewareBuilder', - layer=0, - ) - return (w3, gas_payer) - - (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') - staking_client = StakingClient(w3) + """Stake HMT tokens. + + Deposits HMT tokens into the staking contract. The tokens must be approved first + using ``approve_stake()``. + + Args: + amount (int): Amount of HMT tokens to stake in token's smallest unit + (must be greater than 0 and within approved/balance limits). + tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. + + Returns: + None + + Raises: + StakingClientError: If the amount is invalid or the transaction fails. + + Example: + ```python + from eth_typing import URI + from web3 import Web3 + from web3.middleware import SignAndSendRawMiddlewareBuilder + from web3.providers.auto import load_provider_from_uri + from human_protocol_sdk.staking import StakingClient + + w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) + gas_payer = w3.eth.account.from_key("YOUR_PRIVATE_KEY") + w3.eth.default_account = gas_payer.address + w3.middleware_onion.inject( + SignAndSendRawMiddlewareBuilder.build("YOUR_PRIVATE_KEY"), + "SignAndSendRawMiddlewareBuilder", + layer=0, + ) - amount = Web3.to_wei(5, 'ether') # convert from ETH to WEI - staking_client.approve_stake(amount) # if it was already approved before, this is not necessary - staking_client.stake(amount) + staking_client = StakingClient(w3) + amount = Web3.to_wei(5, "ether") + staking_client.approve_stake(amount) + staking_client.stake(amount) + ``` """ if amount <= 0: @@ -233,43 +213,27 @@ def get_w3_with_priv_key(priv_key: str): @requires_signer def unstake(self, amount: int, tx_options: Optional[TxParams] = None) -> None: - """Unstakes HMT token. - - :param amount: Amount to unstake - :param tx_options: (Optional) Additional transaction parameters - - :return: None + """Unstake HMT tokens. - :validate: - - Amount must be greater than 0 - - Amount must be less than or equal to the staked amount which is not locked / allocated (on-chain) + Initiates the unstaking process for the specified amount. The tokens will be + locked for a period before they can be withdrawn. - :example: - .. code-block:: python + Args: + amount (int): Amount of HMT tokens to unstake in token's smallest unit + (must be greater than 0 and less than or equal to unlocked staked amount). + tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. - from eth_typing import URI - from web3 import Web3 - from web3.middleware import SignAndSendRawMiddlewareBuilder - from web3.providers.auto import load_provider_from_uri + Returns: + None - from human_protocol_sdk.staking import StakingClient + Raises: + StakingClientError: If the amount is invalid or the transaction fails. - def get_w3_with_priv_key(priv_key: str): - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - gas_payer = w3.eth.account.from_key(priv_key) - w3.eth.default_account = gas_payer.address - w3.middleware_onion.inject( - SignAndSendRawMiddlewareBuilder.build(priv_key), - 'SignAndSendRawMiddlewareBuilder', - layer=0, - ) - return (w3, gas_payer) - - (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') - staking_client = StakingClient(w3) - - amount = Web3.to_wei(5, 'ether') # convert from ETH to WEI - staking_client.unstake(amount) + Example: + ```python + amount = Web3.to_wei(5, "ether") + staking_client.unstake(amount) + ``` """ if amount <= 0: @@ -284,40 +248,24 @@ def get_w3_with_priv_key(priv_key: str): @requires_signer def withdraw(self, tx_options: Optional[TxParams] = None) -> None: - """Withdraws HMT token. - - :param tx_options: (Optional) Additional transaction parameters + """Withdraw unlocked unstaked HMT tokens. - :return: None + Withdraws all available unstaked tokens that have completed the unlocking period + and transfers them back to the caller's account. - :validate: - - There must be unstaked tokens which is unlocked (on-chain) + Args: + tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. - :example: - .. code-block:: python + Returns: + None - from eth_typing import URI - from web3 import Web3 - from web3.middleware import SignAndSendRawMiddlewareBuilder - from web3.providers.auto import load_provider_from_uri + Raises: + StakingClientError: If the transaction fails or no tokens are available to withdraw. - from human_protocol_sdk.staking import StakingClient - - def get_w3_with_priv_key(priv_key: str): - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - gas_payer = w3.eth.account.from_key(priv_key) - w3.eth.default_account = gas_payer.address - w3.middleware_onion.inject( - SignAndSendRawMiddlewareBuilder.build(priv_key), - 'SignAndSendRawMiddlewareBuilder', - layer=0, - ) - return (w3, gas_payer) - - (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') - staking_client = StakingClient(w3) - - staking_client.withdraw() + Example: + ```python + staking_client.withdraw() + ``` """ try: @@ -335,52 +283,35 @@ def slash( amount: int, tx_options: Optional[TxParams] = None, ) -> None: - """Slashes HMT token. - - :param slasher: Address of the slasher - :param staker: Address of the staker - :param escrow_address: Address of the escrow - :param amount: Amount to slash - :param tx_options: (Optional) Additional transaction parameters - - :return: None - - :validate: - - Amount must be greater than 0 - - Amount must be less than or equal to the amount allocated to the escrow (on-chain) - - Escrow address must be valid - - :example: - .. code-block:: python - - from eth_typing import URI - from web3 import Web3 - from web3.middleware import SignAndSendRawMiddlewareBuilder - from web3.providers.auto import load_provider_from_uri - - from human_protocol_sdk.staking import StakingClient - - def get_w3_with_priv_key(priv_key: str): - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - gas_payer = w3.eth.account.from_key(priv_key) - w3.eth.default_account = gas_payer.address - w3.middleware_onion.inject( - SignAndSendRawMiddlewareBuilder.build(priv_key), - 'SignAndSendRawMiddlewareBuilder', - layer=0, - ) - return (w3, gas_payer) - - (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') - staking_client = StakingClient(w3) - - amount = Web3.to_wei(5, 'ether') # convert from ETH to WEI - staking_client.slash( - '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', - '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', - '0x62dD51230A30401C455c8398d06F85e4EaB6309f', - amount - ) + """Slash a staker's stake for a given escrow. + + Penalizes a staker by reducing their staked amount and distributing rewards + to the slasher for detecting misbehavior or violations. + + Args: + slasher (str): Address of the entity performing the slash (receives rewards). + staker (str): Address of the staker to be slashed. + escrow_address (str): Address of the escrow associated with the violation. + amount (int): Amount to slash in token's smallest unit + (must be greater than 0 and within staker's allocation to the escrow). + tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. + + Returns: + None + + Raises: + StakingClientError: If the amount is invalid, escrow address is invalid, + or the transaction fails. + + Example: + ```python + staking_client.slash( + "0xSlasherAddress", + "0xStakerAddress", + "0xEscrowAddress", + Web3.to_wei(10, "ether"), + ) + ``` """ if amount <= 0: @@ -396,28 +327,32 @@ def get_w3_with_priv_key(priv_key: str): handle_error(e, StakingClientError) def get_staker_info(self, staker_address: str) -> dict: - """Retrieves comprehensive staking information for a staker. - - :param staker_address: The address of the staker - :return: A dictionary containing staker information + """Retrieve comprehensive staking information for a staker. - :validate: - - Staker address must be valid + Fetches on-chain staking data including staked amount, locked amount, + lock expiration, and withdrawable amount. - :example: - .. code-block:: python + Args: + staker_address (str): Ethereum address of the staker. - from eth_typing import URI - from web3 import Web3 - from web3.providers.auto import load_provider_from_uri + Returns: + Staker info with keys: - from human_protocol_sdk.staking import StakingClient + - `stakedAmount` (int): Total staked amount. + - `lockedAmount` (int): Currently locked amount. + - `lockedUntil` (int): Block number until tokens are locked (0 if unlocked). + - `withdrawableAmount` (int): Amount available for withdrawal. - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - staking_client = StakingClient(w3) + Raises: + StakingClientError: If the staker address is invalid or the query fails. - staking_info = staking_client.get_staker_info('0xYourStakerAddress') - print(staking_info['stakedAmount']) + Example: + ```python + staking_info = staking_client.get_staker_info("0xYourStakerAddress") + print(f"Staked: {staking_info['stakedAmount']}") + print(f"Locked: {staking_info['lockedAmount']}") + print(f"Withdrawable: {staking_info['withdrawableAmount']}") + ``` """ if not Web3.is_address(staker_address): raise StakingClientError(f"Invalid staker address: {staker_address}") @@ -448,11 +383,16 @@ def get_staker_info(self, staker_address: str) -> dict: raise StakingClientError(f"Failed to get staker info: {str(e)}") def _is_valid_escrow(self, escrow_address: str) -> bool: - """Checks if the escrow address is valid. + """Check if an escrow address exists in the factory registry. + + Internal method to validate that an escrow address is registered with the + escrow factory contract. - :param escrow_address: Address of the escrow + Args: + escrow_address (str): Escrow address to validate. - :return: True if the escrow address is valid, False otherwise + Returns: + ``True`` if the escrow exists in the factory registry, ``False`` otherwise. """ # TODO: Use Escrow/Job Module once implemented diff --git a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/staking/staking_utils.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/staking/staking_utils.py index 74915e278b..64fbbdd9ef 100644 --- a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/staking/staking_utils.py +++ b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/staking/staking_utils.py @@ -1,31 +1,4 @@ -""" -Utility class for staking-related operations. - -Code Example ------------- - -.. code-block:: python - - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.staking.staking_utils import StakingUtils, StakersFilter - - stakers = StakingUtils.get_stakers( - StakersFilter( - chain_id=ChainId.POLYGON_AMOY, - min_staked_amount="1000000000000000000", - max_locked_amount="5000000000000000000", - order_by="withdrawnAmount", - order_direction="asc", - first=5, - skip=0, - ) - ) - print("Filtered stakers:", stakers) - -Module ------- - -""" +"""Utility helpers for staking-related queries.""" from typing import List, Optional from human_protocol_sdk.constants import NETWORKS, ChainId @@ -35,6 +8,19 @@ class StakerData: + """Represents staker information retrieved from the subgraph. + + Attributes: + id (str): Unique staker identifier. + address (str): Staker's Ethereum address. + staked_amount (int): Total amount staked in token's smallest unit. + locked_amount (int): Amount currently locked. + withdrawn_amount (int): Total amount withdrawn. + slashed_amount (int): Total amount slashed. + locked_until_timestamp (int): Time in milliseconds until locked amount is released. + last_deposit_timestamp (int): Last deposit time in milliseconds. + """ + def __init__( self, id: str, @@ -57,16 +43,51 @@ def __init__( class StakingUtilsError(Exception): - pass + """Exception raised when staking utility operations fail.""" class StakingUtils: + """Utility class providing staking-related query and data retrieval functions. + + This class offers static methods to fetch staker data from the Human Protocol + subgraph, including individual staker details and filtered lists. + """ + @staticmethod def get_staker( chain_id: ChainId, address: str, options: Optional[SubgraphOptions] = None, ) -> Optional[StakerData]: + """Retrieve a single staker by their address. + + Fetches detailed staking information for a specific address from the subgraph. + + Args: + chain_id (ChainId): Network where the staker is registered. + address (str): Ethereum address of the staker. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. + + Returns: + Staker data if found, otherwise ``None``. + + Raises: + StakingUtilsError: If the chain ID is not supported. + + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.staking import StakingUtils + + staker = StakingUtils.get_staker( + ChainId.POLYGON_AMOY, + "0x62dD51230A30401C455c8398d06F85e4EaB6309f", + ) + if staker: + print(f"Staked: {staker.staked_amount}") + print(f"Locked: {staker.locked_amount}") + ``` + """ network = NETWORKS.get(chain_id) if not network: raise StakingUtilsError("Unsupported Chain ID") @@ -102,6 +123,40 @@ def get_stakers( filter: StakersFilter, options: Optional[SubgraphOptions] = None, ) -> List[StakerData]: + """Retrieve a list of stakers matching the provided filter criteria. + + Queries the subgraph for stakers that match the specified parameters including + amount ranges, ordering, and pagination. + + Args: + filter (StakersFilter): Filter parameters including chain ID, amount ranges + (staked, locked, withdrawn, slashed), ordering, and pagination options. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. + + Returns: + A list of staker records matching the filter criteria. + Returns an empty list if no matches are found. + + Raises: + StakingUtilsError: If the chain ID is not supported. + + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.staking import StakingUtils + from human_protocol_sdk.filter import StakersFilter + from web3 import Web3 + + stakers = StakingUtils.get_stakers( + StakersFilter( + chain_id=ChainId.POLYGON_AMOY, + min_staked_amount=Web3.to_wei(100, "ether"), + ) + ) + for staker in stakers: + print(f"{staker.address}: {staker.staked_amount}") + ``` + """ network_data = NETWORKS.get(filter.chain_id) if not network_data: raise StakingUtilsError("Unsupported Chain ID") diff --git a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/statistics/statistics_client.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/statistics/statistics_client.py deleted file mode 100644 index b78f927418..0000000000 --- a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/statistics/statistics_client.py +++ /dev/null @@ -1,666 +0,0 @@ -""" -This client enables to obtain statistical information from the subgraph. - -Code Example ------------- - -.. code-block:: python - - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.statistics import StatisticsClient - - statistics_client = StatisticsClient(ChainId.POLYGON_AMOY) - -Module ------- -""" - -from datetime import datetime -import logging - -from typing import List, Optional - -from human_protocol_sdk.constants import ChainId, NETWORKS - -from human_protocol_sdk.utils import SubgraphOptions, custom_gql_fetch -from human_protocol_sdk.filter import StatisticsFilter - -LOG = logging.getLogger("human_protocol_sdk.statistics") - - -class StatisticsClientError(Exception): - """ - Raises when some error happens when getting data from subgraph. - """ - - pass - - -class HMTHoldersParam: - """ - A class used to specify parameters for querying HMT holders. - """ - - def __init__( - self, - address: str = None, - order_direction: str = "asc", - ): - """ - Initializes a HMTHoldersParam instance. - - :param address: Filter by holder's address - :param order_direction: Optional. Direction of sorting ('asc' for ascending, 'desc' for descending) - """ - self.address = address - self.order_direction = order_direction - - -class DailyEscrowData: - """ - A class used to specify daily escrow data. - """ - - def __init__( - self, - timestamp: datetime, - escrows_total: int, - escrows_pending: int, - escrows_solved: int, - escrows_paid: int, - escrows_cancelled: int, - ): - """ - Initializes a DailyEscrowData instance. - - :param timestamp: Timestamp - :param escrows_total: Total escrows - :param escrows_pending: Pending escrows - :param escrows_solved: Solved escrows - :param escrows_paid: Paid escrows - :param escrows_cancelled: Cancelled escrows - """ - - self.timestamp = timestamp - self.escrows_total = escrows_total - self.escrows_pending = escrows_pending - self.escrows_solved = escrows_solved - self.escrows_paid = escrows_paid - self.escrows_cancelled = escrows_cancelled - - -class EscrowStatistics: - """ - A class used to specify escrow statistics. - """ - - def __init__( - self, - total_escrows: int, - daily_escrows_data: List[DailyEscrowData], - ): - """ - Initializes a EscrowStatistics instance. - - :param total_escrows: Total escrows - :param daily_escrows_data: Daily escrows data - """ - - self.total_escrows = total_escrows - self.daily_escrows_data = daily_escrows_data - - -class DailyWorkerData: - """ - A class used to specify daily worker data. - """ - - def __init__( - self, - timestamp: datetime, - active_workers: int, - ): - """ - Initializes a DailyWorkerData instance. - - :param timestamp: Timestamp - :param active_workers: Active workers - """ - - self.timestamp = timestamp - self.active_workers = active_workers - - -class WorkerStatistics: - """ - A class used to specify worker statistics. - """ - - def __init__( - self, - daily_workers_data: List[DailyWorkerData], - ): - """ - Initializes a WorkerStatistics instance. - - :param daily_workers_data: Daily workers data - """ - - self.daily_workers_data = daily_workers_data - - -class DailyPaymentData: - """ - A class used to specify daily payment data. - """ - - def __init__( - self, - timestamp: datetime, - total_amount_paid: int, - total_count: int, - average_amount_per_worker: int, - ): - """ - Initializes a DailyPaymentData instance. - - :param timestamp: Timestamp - :param total_amount_paid: Total amount paid - :param total_count: Total count - :param average_amount_per_worker: Average amount per worker - """ - - self.timestamp = timestamp - self.total_amount_paid = total_amount_paid - self.total_count = total_count - self.average_amount_per_worker = average_amount_per_worker - - -class PaymentStatistics: - """ - A class used to specify payment statistics. - """ - - def __init__( - self, - daily_payments_data: List[DailyPaymentData], - ): - """ - Initializes a PaymentStatistics instance. - - :param daily_payments_data: Daily payments data - """ - - self.daily_payments_data = daily_payments_data - - -class HMTHolder: - """ - A class used to specify HMT holder. - """ - - def __init__( - self, - address: str, - balance: int, - ): - """ - Initializes a HMTHolder instance. - - :param address: Holder address - :param balance: Holder balance - """ - - self.address = address - self.balance = balance - - -class DailyHMTData: - """ - A class used to specify daily HMT data. - """ - - def __init__( - self, - timestamp: datetime, - total_transaction_amount: int, - total_transaction_count: int, - daily_unique_senders: int, - daily_unique_receivers: int, - ): - """ - Initializes a DailyHMTData instance. - - :param timestamp: Timestamp - :param total_transaction_amount: Total transaction amount - :param total_transaction_count: Total transaction count - :param daily_unique_senders: Total unique senders - :param daily_unique_receivers: Total unique receivers - """ - - self.timestamp = timestamp - self.total_transaction_amount = total_transaction_amount - self.total_transaction_count = total_transaction_count - self.daily_unique_senders = daily_unique_senders - self.daily_unique_receivers = daily_unique_receivers - - -class HMTStatistics: - """ - A class used to specify HMT statistics. - """ - - def __init__( - self, - total_transfer_amount: int, - total_transfer_count: int, - total_holders: int, - ): - """ - Initializes a HMTStatistics instance. - - :param total_transfer_amount: Total transfer amount - :param total_transfer_count: Total transfer count - :param total_holders: Total holders - """ - - self.total_transfer_amount = total_transfer_amount - self.total_transfer_count = total_transfer_count - self.total_holders = total_holders - - -class StatisticsClient: - """ - A client used to get statistical data. - """ - - def __init__(self, chain_id: ChainId = ChainId.POLYGON_AMOY): - """Initializes a Statistics instance - - :param chain_id: Chain ID to get statistical data from - - """ - - if chain_id.value not in [chain_id.value for chain_id in ChainId]: - raise StatisticsClientError(f"Invalid ChainId: {chain_id}") - - self.network = NETWORKS[ChainId(chain_id)] - - if not self.network: - raise StatisticsClientError("Empty network configuration") - - def get_escrow_statistics( - self, - filter: StatisticsFilter = StatisticsFilter(), - options: Optional[SubgraphOptions] = None, - ) -> EscrowStatistics: - """Get escrow statistics data for the given date range. - - :param filter: Object containing the date range - :param options: Optional config for subgraph requests - - :return: Escrow statistics data - - :example: - .. code-block:: python - - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.statistics import StatisticsClient - from human_protocol_sdk.filter import StatisticsFilter - - statistics_client = StatisticsClient(ChainId.POLYGON_AMOY) - - print(statistics_client.get_escrow_statistics()) - print( - statistics_client.get_escrow_statistics( - StatisticsFilter( - date_from=datetime.datetime(2023, 5, 8), - date_to=datetime.datetime(2023, 6, 8), - ) - ) - ) - """ - - from human_protocol_sdk.gql.statistics import ( - get_event_day_data_query, - get_escrow_statistics_query, - ) - - escrow_statistics_data = custom_gql_fetch( - self.network, - query=get_escrow_statistics_query, - options=options, - ) - escrow_statistics = escrow_statistics_data["data"]["escrowStatistics"] - - event_day_datas_data = custom_gql_fetch( - self.network, - query=get_event_day_data_query(filter), - params={ - "from": int(filter.date_from.timestamp()) if filter.date_from else None, - "to": int(filter.date_to.timestamp()) if filter.date_to else None, - "first": filter.first, - "skip": filter.skip, - "orderDirection": filter.order_direction.value, - }, - options=options, - ) - event_day_datas = event_day_datas_data["data"]["eventDayDatas"] - - return EscrowStatistics( - total_escrows=int(escrow_statistics.get("totalEscrowCount", 0)), - daily_escrows_data=[ - DailyEscrowData( - timestamp=datetime.fromtimestamp( - int(event_day_data.get("timestamp", 0)) - ), - escrows_total=int(event_day_data.get("dailyEscrowCount", 0)), - escrows_pending=int( - event_day_data.get("dailyPendingStatusEventCount", 0) - ), - escrows_solved=int( - event_day_data.get("dailyCompletedStatusEventCount", 0) - ), - escrows_paid=int( - event_day_data.get("dailyPaidStatusEventCount", 0) - ), - escrows_cancelled=int( - event_day_data.get("dailyCancelledStatusEventCount", 0) - ), - ) - for event_day_data in event_day_datas - ], - ) - - def get_worker_statistics( - self, - filter: StatisticsFilter = StatisticsFilter(), - options: Optional[SubgraphOptions] = None, - ) -> WorkerStatistics: - """Get worker statistics data for the given date range. - - :param filter: Object containing the date range - :param options: Optional config for subgraph requests - - :return: Worker statistics data - - :example: - .. code-block:: python - - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.statistics import StatisticsClient - from human_protocol_sdk.filter import StatisticsFilter - - statistics_client = StatisticsClient(ChainId.POLYGON_AMOY) - - print(statistics_client.get_worker_statistics()) - print( - statistics_client.get_worker_statistics( - StatisticsFilter( - date_from=datetime.datetime(2023, 5, 8), - date_to=datetime.datetime(2023, 6, 8), - ) - ) - ) - """ - from human_protocol_sdk.gql.statistics import ( - get_event_day_data_query, - ) - - event_day_datas_data = custom_gql_fetch( - self.network, - query=get_event_day_data_query(filter), - params={ - "from": int(filter.date_from.timestamp()) if filter.date_from else None, - "to": int(filter.date_to.timestamp()) if filter.date_to else None, - "first": filter.first, - "skip": filter.skip, - "orderDirection": filter.order_direction.value, - }, - options=options, - ) - event_day_datas = event_day_datas_data["data"]["eventDayDatas"] - - return WorkerStatistics( - daily_workers_data=[ - DailyWorkerData( - timestamp=datetime.fromtimestamp( - int(event_day_data.get("timestamp", 0)) - ), - active_workers=int(event_day_data.get("dailyWorkerCount", 0)), - ) - for event_day_data in event_day_datas - ], - ) - - def get_payment_statistics( - self, - filter: StatisticsFilter = StatisticsFilter(), - options: Optional[SubgraphOptions] = None, - ) -> PaymentStatistics: - """Get payment statistics data for the given date range. - - :param filter: Object containing the date range - :param options: Optional config for subgraph requests - - :return: Payment statistics data - - :example: - .. code-block:: python - - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.statistics import StatisticsClient - from human_protocol_sdk.filter import StatisticsFilter - - statistics_client = StatisticsClient(ChainId.POLYGON_AMOY) - - print(statistics_client.get_payment_statistics()) - print( - statistics_client.get_payment_statistics( - StatisticsFilter( - date_from=datetime.datetime(2023, 5, 8), - date_to=datetime.datetime(2023, 6, 8), - ) - ) - ) - """ - - from human_protocol_sdk.gql.statistics import ( - get_event_day_data_query, - ) - - event_day_datas_data = custom_gql_fetch( - self.network, - query=get_event_day_data_query(filter), - params={ - "from": int(filter.date_from.timestamp()) if filter.date_from else None, - "to": int(filter.date_to.timestamp()) if filter.date_to else None, - "first": filter.first, - "skip": filter.skip, - "orderDirection": filter.order_direction.value, - }, - options=options, - ) - event_day_datas = event_day_datas_data["data"]["eventDayDatas"] - - return PaymentStatistics( - daily_payments_data=[ - DailyPaymentData( - timestamp=datetime.fromtimestamp( - int(event_day_data.get("timestamp", 0)) - ), - total_amount_paid=int( - event_day_data.get("dailyHMTPayoutAmount", 0) - ), - total_count=int(event_day_data.get("dailyPayoutCount", 0)), - average_amount_per_worker=( - int(event_day_data.get("dailyHMTPayoutAmount", 0)) - / int(event_day_data.get("dailyWorkerCount")) - if event_day_data.get("dailyWorkerCount", "0") != "0" - else 0 - ), - ) - for event_day_data in event_day_datas - ], - ) - - def get_hmt_statistics( - self, options: Optional[SubgraphOptions] = None - ) -> HMTStatistics: - """Get HMT statistics data. - - :param options: Optional config for subgraph requests - - :return: HMT statistics data - - :example: - .. code-block:: python - - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.statistics import StatisticsClient - - statistics_client = StatisticsClient(ChainId.POLYGON_AMOY) - - print(statistics_client.get_hmt_statistics()) - """ - from human_protocol_sdk.gql.statistics import ( - get_event_day_data_query, - get_hmtoken_statistics_query, - ) - - hmtoken_statistics_data = custom_gql_fetch( - self.network, - query=get_hmtoken_statistics_query, - options=options, - ) - hmtoken_statistics = hmtoken_statistics_data["data"]["hmtokenStatistics"] - - return HMTStatistics( - total_transfer_amount=int( - hmtoken_statistics.get("totalValueTransfered", 0) - ), - total_transfer_count=int( - hmtoken_statistics.get("totalTransferEventCount", 0) - ), - total_holders=int(hmtoken_statistics.get("holders", 0)), - ) - - def get_hmt_holders( - self, - param: HMTHoldersParam = HMTHoldersParam(), - options: Optional[SubgraphOptions] = None, - ) -> List[HMTHolder]: - """Get HMT holders data with optional filters and ordering. - - :param param: Object containing filter and order parameters - :param options: Optional config for subgraph requests - - :return: List of HMT holders - - :example: - .. code-block:: python - - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.statistics import StatisticsClient, HMTHoldersParam - - statistics_client = StatisticsClient(ChainId.POLYGON_AMOY) - - print(statistics_client.get_hmt_holders()) - print( - statistics_client.get_hmt_holders( - HMTHoldersParam( - address="0x123...", - order_direction="asc", - ) - ) - ) - """ - from human_protocol_sdk.gql.hmtoken import get_holders_query - - holders_data = custom_gql_fetch( - self.network, - query=get_holders_query(address=param.address), - params={ - "address": param.address, - "orderBy": "balance", - "orderDirection": param.order_direction, - }, - options=options, - ) - - holders = holders_data["data"]["holders"] - - return [ - HMTHolder( - address=holder.get("address", ""), - balance=int(holder.get("balance", 0)), - ) - for holder in holders - ] - - def get_hmt_daily_data( - self, - filter: StatisticsFilter = StatisticsFilter(), - options: Optional[SubgraphOptions] = None, - ) -> List[DailyHMTData]: - """Get HMT daily statistics data for the given date range. - - :param filter: Object containing the date range - :param options: Optional config for subgraph requests - - :return: HMT statistics data - - :example: - .. code-block:: python - - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.statistics import StatisticsClient, StatisticsFilter - - statistics_client = StatisticsClient(ChainId.POLYGON_AMOY) - - print(statistics_client.get_hmt_daily_data()) - print( - statistics_client.get_hmt_daily_data( - StatisticsFilter( - date_from=datetime.datetime(2023, 5, 8), - date_to=datetime.datetime(2023, 6, 8), - ) - ) - ) - """ - from human_protocol_sdk.gql.statistics import ( - get_event_day_data_query, - ) - - event_day_datas_data = custom_gql_fetch( - self.network, - query=get_event_day_data_query(filter), - params={ - "from": int(filter.date_from.timestamp()) if filter.date_from else None, - "to": int(filter.date_to.timestamp()) if filter.date_to else None, - "first": filter.first, - "skip": filter.skip, - "orderDirection": filter.order_direction.value, - }, - options=options, - ) - event_day_datas = event_day_datas_data["data"]["eventDayDatas"] - - return [ - DailyHMTData( - timestamp=datetime.fromtimestamp( - int(event_day_data.get("timestamp", 0)) - ), - total_transaction_amount=int( - event_day_data.get("dailyHMTTransferAmount", 0) - ), - total_transaction_count=int( - event_day_data.get("dailyHMTTransferCount", 0) - ), - daily_unique_senders=int(event_day_data.get("dailyUniqueSenders", 0)), - daily_unique_receivers=int( - event_day_data.get("dailyUniqueReceivers", 0) - ), - ) - for event_day_data in event_day_datas - ] diff --git a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/statistics/statistics_utils.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/statistics/statistics_utils.py new file mode 100644 index 0000000000..5d79cb567a --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/statistics/statistics_utils.py @@ -0,0 +1,712 @@ +"""Utility helpers for retrieving statistics information. + +Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.statistics import StatisticsUtils + + stats = StatisticsUtils.get_escrow_statistics(ChainId.POLYGON_AMOY) + ``` +""" + +from datetime import datetime +import logging + +from typing import List, Optional + +from human_protocol_sdk.constants import ChainId, NETWORKS + +from human_protocol_sdk.utils import SubgraphOptions, custom_gql_fetch +from human_protocol_sdk.filter import StatisticsFilter + +LOG = logging.getLogger("human_protocol_sdk.statistics") + + +class StatisticsUtilsError(Exception): + """Exception raised when errors occur during statistics operations.""" + + pass + + +class HMTHoldersParam: + """Filter parameters for querying HMT token holders. + + Attributes: + address (Optional[str]): Optional holder address to filter by. + order_direction (str): Sort direction - either "asc" or "desc". + """ + + def __init__( + self, + address: str = None, + order_direction: str = "asc", + ): + self.address = address + self.order_direction = order_direction + + +class DailyEscrowData: + """Represents aggregated escrow metrics for a single day. + + Attributes: + timestamp (datetime): Day boundary timestamp. + escrows_total (int): Total number of escrows created on this day. + escrows_pending (int): Number of escrows in pending status. + escrows_solved (int): Number of escrows that were solved/completed. + escrows_paid (int): Number of escrows that were paid out. + escrows_cancelled (int): Number of escrows that were cancelled. + """ + + def __init__( + self, + timestamp: datetime, + escrows_total: int, + escrows_pending: int, + escrows_solved: int, + escrows_paid: int, + escrows_cancelled: int, + ): + self.timestamp = timestamp + self.escrows_total = escrows_total + self.escrows_pending = escrows_pending + self.escrows_solved = escrows_solved + self.escrows_paid = escrows_paid + self.escrows_cancelled = escrows_cancelled + + +class EscrowStatistics: + """Aggregate escrow statistics data. + + Attributes: + total_escrows (int): Total number of escrows across all time. + daily_escrows_data (List[DailyEscrowData]): Daily breakdown of escrow metrics. + """ + + def __init__( + self, + total_escrows: int, + daily_escrows_data: List[DailyEscrowData], + ): + self.total_escrows = total_escrows + self.daily_escrows_data = daily_escrows_data + + +class DailyWorkerData: + """Represents aggregated worker metrics for a single day. + + Attributes: + timestamp (datetime): Day boundary timestamp. + active_workers (int): Number of active workers on this day. + """ + + def __init__( + self, + timestamp: datetime, + active_workers: int, + ): + self.timestamp = timestamp + self.active_workers = active_workers + + +class WorkerStatistics: + """Aggregate worker statistics data. + + Attributes: + daily_workers_data (List[DailyWorkerData]): Daily breakdown of worker metrics. + """ + + def __init__( + self, + daily_workers_data: List[DailyWorkerData], + ): + self.daily_workers_data = daily_workers_data + + +class DailyPaymentData: + """Represents aggregated payment metrics for a single day. + + Attributes: + timestamp (datetime): Day boundary timestamp. + total_amount_paid (int): Total amount paid out on this day. + total_count (int): Number of payment transactions. + average_amount_per_worker (int): Average payout amount per worker. + """ + + def __init__( + self, + timestamp: datetime, + total_amount_paid: int, + total_count: int, + average_amount_per_worker: int, + ): + self.timestamp = timestamp + self.total_amount_paid = total_amount_paid + self.total_count = total_count + self.average_amount_per_worker = average_amount_per_worker + + +class PaymentStatistics: + """Aggregate payment statistics data. + + Attributes: + daily_payments_data (List[DailyPaymentData]): Daily breakdown of payment metrics. + """ + + def __init__( + self, + daily_payments_data: List[DailyPaymentData], + ): + self.daily_payments_data = daily_payments_data + + +class HMTHolder: + """Represents an HMT token holder. + + Attributes: + address (str): Ethereum address of the holder. + balance (int): Token balance in smallest unit. + """ + + def __init__( + self, + address: str, + balance: int, + ): + self.address = address + self.balance = balance + + +class DailyHMTData: + """Represents aggregated HMT transfer metrics for a single day. + + Attributes: + timestamp (datetime): Day boundary timestamp. + total_transaction_amount (int): Total amount transferred on this day. + total_transaction_count (int): Number of transfer transactions. + daily_unique_senders (int): Number of unique addresses sending tokens. + daily_unique_receivers (int): Number of unique addresses receiving tokens. + """ + + def __init__( + self, + timestamp: datetime, + total_transaction_amount: int, + total_transaction_count: int, + daily_unique_senders: int, + daily_unique_receivers: int, + ): + self.timestamp = timestamp + self.total_transaction_amount = total_transaction_amount + self.total_transaction_count = total_transaction_count + self.daily_unique_senders = daily_unique_senders + self.daily_unique_receivers = daily_unique_receivers + + +class HMTStatistics: + """Aggregate HMT token statistics. + + Attributes: + total_transfer_amount (int): Total amount transferred across all time. + total_transfer_count (int): Total number of transfer transactions. + total_holders (int): Total number of token holders. + """ + + def __init__( + self, + total_transfer_amount: int, + total_transfer_count: int, + total_holders: int, + ): + self.total_transfer_amount = total_transfer_amount + self.total_transfer_count = total_transfer_count + self.total_holders = total_holders + + +class StatisticsUtils: + """Utility class providing statistical data retrieval functions. + + This class offers static methods to fetch various statistics from the Human Protocol + subgraph, including escrow metrics, worker activity, payment data, and HMT token statistics. + """ + + @staticmethod + def get_escrow_statistics( + chain_id: ChainId, + filter: StatisticsFilter = StatisticsFilter(), + options: Optional[SubgraphOptions] = None, + ) -> EscrowStatistics: + """Retrieve escrow statistics for a given date range. + + Fetches aggregate escrow data including total counts and daily breakdowns + of escrow creation and status changes. + + Args: + chain_id (ChainId): Network to retrieve statistics from. + filter (StatisticsFilter): Date range and pagination filter. Defaults to all-time data. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. + + Returns: + Escrow statistics including total count and daily data. + + Raises: + StatisticsUtilsError: If the chain ID is invalid or network configuration is missing. + + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.statistics import StatisticsUtils + from human_protocol_sdk.filter import StatisticsFilter + import datetime + + # Get all-time statistics + stats = StatisticsUtils.get_escrow_statistics(ChainId.POLYGON_AMOY) + print(f"Total escrows: {stats.total_escrows}") + + # Get statistics for specific date range + stats = StatisticsUtils.get_escrow_statistics( + ChainId.POLYGON_AMOY, + StatisticsFilter( + date_from=datetime.datetime(2023, 5, 8), + date_to=datetime.datetime(2023, 6, 8), + ) + ) + for day_data in stats.daily_escrows_data: + print(f"{day_data.timestamp}: {day_data.escrows_total} escrows") + ``` + """ + if chain_id.value not in [cid.value for cid in ChainId]: + raise StatisticsUtilsError(f"Invalid ChainId: {chain_id}") + + network = NETWORKS.get(chain_id) + if not network: + raise StatisticsUtilsError("Empty network configuration") + + from human_protocol_sdk.gql.statistics import ( + get_event_day_data_query, + get_escrow_statistics_query, + ) + + escrow_statistics_data = custom_gql_fetch( + network, + query=get_escrow_statistics_query, + options=options, + ) + escrow_statistics = escrow_statistics_data["data"]["escrowStatistics"] + + event_day_datas_data = custom_gql_fetch( + network, + query=get_event_day_data_query(filter), + params={ + "from": int(filter.date_from.timestamp()) if filter.date_from else None, + "to": int(filter.date_to.timestamp()) if filter.date_to else None, + "first": filter.first, + "skip": filter.skip, + "orderDirection": filter.order_direction.value, + }, + options=options, + ) + event_day_datas = event_day_datas_data["data"]["eventDayDatas"] + + return EscrowStatistics( + total_escrows=int(escrow_statistics.get("totalEscrowCount", 0)), + daily_escrows_data=[ + DailyEscrowData( + timestamp=datetime.fromtimestamp( + int(event_day_data.get("timestamp", 0)) + ), + escrows_total=int(event_day_data.get("dailyEscrowCount", 0)), + escrows_pending=int( + event_day_data.get("dailyPendingStatusEventCount", 0) + ), + escrows_solved=int( + event_day_data.get("dailyCompletedStatusEventCount", 0) + ), + escrows_paid=int( + event_day_data.get("dailyPaidStatusEventCount", 0) + ), + escrows_cancelled=int( + event_day_data.get("dailyCancelledStatusEventCount", 0) + ), + ) + for event_day_data in event_day_datas + ], + ) + + @staticmethod + def get_worker_statistics( + chain_id: ChainId, + filter: StatisticsFilter = StatisticsFilter(), + options: Optional[SubgraphOptions] = None, + ) -> WorkerStatistics: + """Retrieve worker activity statistics for a given date range. + + Fetches daily worker activity metrics showing the number of active workers + participating in escrows. + + Args: + chain_id (ChainId): Network to retrieve statistics from. + filter (StatisticsFilter): Date range and pagination filter. Defaults to all-time data. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. + + Returns: + Worker statistics with daily activity breakdown. + + Raises: + StatisticsUtilsError: If the chain ID is invalid or network configuration is missing. + + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.statistics import StatisticsUtils + from human_protocol_sdk.filter import StatisticsFilter + import datetime + + stats = StatisticsUtils.get_worker_statistics( + ChainId.POLYGON_AMOY, + StatisticsFilter( + date_from=datetime.datetime(2023, 5, 8), + date_to=datetime.datetime(2023, 6, 8), + ) + ) + for day_data in stats.daily_workers_data: + print(f"{day_data.timestamp}: {day_data.active_workers} workers") + ``` + """ + if chain_id.value not in [cid.value for cid in ChainId]: + raise StatisticsUtilsError(f"Invalid ChainId: {chain_id}") + + network = NETWORKS.get(chain_id) + if not network: + raise StatisticsUtilsError("Empty network configuration") + + from human_protocol_sdk.gql.statistics import ( + get_event_day_data_query, + ) + + event_day_datas_data = custom_gql_fetch( + network, + query=get_event_day_data_query(filter), + params={ + "from": int(filter.date_from.timestamp()) if filter.date_from else None, + "to": int(filter.date_to.timestamp()) if filter.date_to else None, + "first": filter.first, + "skip": filter.skip, + "orderDirection": filter.order_direction.value, + }, + options=options, + ) + event_day_datas = event_day_datas_data["data"]["eventDayDatas"] + + return WorkerStatistics( + daily_workers_data=[ + DailyWorkerData( + timestamp=datetime.fromtimestamp( + int(event_day_data.get("timestamp", 0)) + ), + active_workers=int(event_day_data.get("dailyWorkerCount", 0)), + ) + for event_day_data in event_day_datas + ], + ) + + @staticmethod + def get_payment_statistics( + chain_id: ChainId, + filter: StatisticsFilter = StatisticsFilter(), + options: Optional[SubgraphOptions] = None, + ) -> PaymentStatistics: + """Retrieve payment statistics for a given date range. + + Fetches daily payment metrics including total amounts paid, transaction counts, + and average payment per worker. + + Args: + chain_id (ChainId): Network to retrieve statistics from. + filter (StatisticsFilter): Date range and pagination filter. Defaults to all-time data. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. + + Returns: + Payment statistics with daily breakdown. + + Raises: + StatisticsUtilsError: If the chain ID is invalid or network configuration is missing. + + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.statistics import StatisticsUtils + from human_protocol_sdk.filter import StatisticsFilter + import datetime + + stats = StatisticsUtils.get_payment_statistics( + ChainId.POLYGON_AMOY, + StatisticsFilter( + date_from=datetime.datetime(2023, 5, 8), + date_to=datetime.datetime(2023, 6, 8), + ) + ) + for day_data in stats.daily_payments_data: + print(f"{day_data.timestamp}: {day_data.total_amount_paid} paid") + print(f" Average per worker: {day_data.average_amount_per_worker}") + ``` + """ + if chain_id.value not in [cid.value for cid in ChainId]: + raise StatisticsUtilsError(f"Invalid ChainId: {chain_id}") + + network = NETWORKS.get(chain_id) + if not network: + raise StatisticsUtilsError("Empty network configuration") + + from human_protocol_sdk.gql.statistics import ( + get_event_day_data_query, + ) + + event_day_datas_data = custom_gql_fetch( + network, + query=get_event_day_data_query(filter), + params={ + "from": int(filter.date_from.timestamp()) if filter.date_from else None, + "to": int(filter.date_to.timestamp()) if filter.date_to else None, + "first": filter.first, + "skip": filter.skip, + "orderDirection": filter.order_direction.value, + }, + options=options, + ) + event_day_datas = event_day_datas_data["data"]["eventDayDatas"] + + return PaymentStatistics( + daily_payments_data=[ + DailyPaymentData( + timestamp=datetime.fromtimestamp( + int(event_day_data.get("timestamp", 0)) + ), + total_amount_paid=int( + event_day_data.get("dailyHMTPayoutAmount", 0) + ), + total_count=int(event_day_data.get("dailyPayoutCount", 0)), + average_amount_per_worker=( + int(event_day_data.get("dailyHMTPayoutAmount", 0)) + / int(event_day_data.get("dailyWorkerCount")) + if event_day_data.get("dailyWorkerCount", "0") != "0" + else 0 + ), + ) + for event_day_data in event_day_datas + ], + ) + + @staticmethod + def get_hmt_statistics( + chain_id: ChainId, options: Optional[SubgraphOptions] = None + ) -> HMTStatistics: + """Retrieve aggregate HMT token statistics. + + Fetches overall HMT token metrics including total transfers and holder counts. + + Args: + chain_id (ChainId): Network to retrieve statistics from. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. + + Returns: + Aggregate HMT token statistics. + + Raises: + StatisticsUtilsError: If the chain ID is invalid or network configuration is missing. + + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.statistics import StatisticsUtils + + stats = StatisticsUtils.get_hmt_statistics(ChainId.POLYGON_AMOY) + print(f"Total holders: {stats.total_holders}") + print(f"Total transfers: {stats.total_transfer_count}") + print(f"Total amount transferred: {stats.total_transfer_amount}") + ``` + """ + if chain_id.value not in [cid.value for cid in ChainId]: + raise StatisticsUtilsError(f"Invalid ChainId: {chain_id}") + + network = NETWORKS.get(chain_id) + if not network: + raise StatisticsUtilsError("Empty network configuration") + + from human_protocol_sdk.gql.statistics import ( + get_hmtoken_statistics_query, + ) + + hmtoken_statistics_data = custom_gql_fetch( + network, + query=get_hmtoken_statistics_query, + options=options, + ) + hmtoken_statistics = hmtoken_statistics_data["data"]["hmtokenStatistics"] + + return HMTStatistics( + total_transfer_amount=int( + hmtoken_statistics.get("totalValueTransfered", 0) + ), + total_transfer_count=int( + hmtoken_statistics.get("totalTransferEventCount", 0) + ), + total_holders=int(hmtoken_statistics.get("holders", 0)), + ) + + @staticmethod + def get_hmt_holders( + chain_id: ChainId, + param: HMTHoldersParam = HMTHoldersParam(), + options: Optional[SubgraphOptions] = None, + ) -> List[HMTHolder]: + """Retrieve HMT token holders with optional filters and ordering. + + Fetches a list of addresses holding HMT tokens with their balances. + + Args: + chain_id (ChainId): Network to retrieve holder data from. + param (HMTHoldersParam): Filter parameters and sort preferences. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. + + Returns: + List of token holders with addresses and balances. + + Raises: + StatisticsUtilsError: If the chain ID is invalid or network configuration is missing. + + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.statistics import StatisticsUtils, HMTHoldersParam + + # Get all holders sorted by balance ascending + holders = StatisticsUtils.get_hmt_holders(ChainId.POLYGON_AMOY) + for holder in holders: + print(f"{holder.address}: {holder.balance}") + + # Get specific holder + holders = StatisticsUtils.get_hmt_holders( + ChainId.POLYGON_AMOY, + HMTHoldersParam( + address="0x123...", + order_direction="desc", + ) + ) + ``` + """ + if chain_id.value not in [cid.value for cid in ChainId]: + raise StatisticsUtilsError(f"Invalid ChainId: {chain_id}") + + network = NETWORKS.get(chain_id) + if not network: + raise StatisticsUtilsError("Empty network configuration") + + from human_protocol_sdk.gql.hmtoken import get_holders_query + + holders_data = custom_gql_fetch( + network, + query=get_holders_query(address=param.address), + params={ + "address": param.address, + "orderBy": "balance", + "orderDirection": param.order_direction, + }, + options=options, + ) + + holders = holders_data["data"]["holders"] + + return [ + HMTHolder( + address=holder.get("address", ""), + balance=int(holder.get("balance", 0)), + ) + for holder in holders + ] + + @staticmethod + def get_hmt_daily_data( + chain_id: ChainId, + filter: StatisticsFilter = StatisticsFilter(), + options: Optional[SubgraphOptions] = None, + ) -> List[DailyHMTData]: + """Retrieve daily HMT token transfer statistics for a given date range. + + Fetches daily metrics about HMT token transfers including amounts, counts, + and unique participants. + + Args: + chain_id (ChainId): Network to retrieve statistics from. + filter (StatisticsFilter): Date range and pagination filter. Defaults to all-time data. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. + + Returns: + List of daily HMT transfer statistics. + + Raises: + StatisticsUtilsError: If the chain ID is invalid or network configuration is missing. + + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.statistics import StatisticsUtils + from human_protocol_sdk.filter import StatisticsFilter + import datetime + + daily_data = StatisticsUtils.get_hmt_daily_data( + ChainId.POLYGON_AMOY, + StatisticsFilter( + date_from=datetime.datetime(2023, 5, 8), + date_to=datetime.datetime(2023, 6, 8), + ) + ) + for day in daily_data: + print(f"{day.timestamp}:") + print(f" Transfers: {day.total_transaction_count}") + print(f" Amount: {day.total_transaction_amount}") + print(f" Unique senders: {day.daily_unique_senders}") + ``` + """ + if chain_id.value not in [cid.value for cid in ChainId]: + raise StatisticsUtilsError(f"Invalid ChainId: {chain_id}") + + network = NETWORKS.get(chain_id) + if not network: + raise StatisticsUtilsError("Empty network configuration") + + from human_protocol_sdk.gql.statistics import ( + get_event_day_data_query, + ) + + event_day_datas_data = custom_gql_fetch( + network, + query=get_event_day_data_query(filter), + params={ + "from": int(filter.date_from.timestamp()) if filter.date_from else None, + "to": int(filter.date_to.timestamp()) if filter.date_to else None, + "first": filter.first, + "skip": filter.skip, + "orderDirection": filter.order_direction.value, + }, + options=options, + ) + event_day_datas = event_day_datas_data["data"]["eventDayDatas"] + + return [ + DailyHMTData( + timestamp=datetime.fromtimestamp( + int(event_day_data.get("timestamp", 0)) + ), + total_transaction_amount=int( + event_day_data.get("dailyHMTTransferAmount", 0) + ), + total_transaction_count=int( + event_day_data.get("dailyHMTTransferCount", 0) + ), + daily_unique_senders=int(event_day_data.get("dailyUniqueSenders", 0)), + daily_unique_receivers=int( + event_day_data.get("dailyUniqueReceivers", 0) + ), + ) + for event_day_data in event_day_datas + ] diff --git a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/transaction/transaction_utils.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/transaction/transaction_utils.py index ee725ff1b0..e3ac51f7ae 100644 --- a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/transaction/transaction_utils.py +++ b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/transaction/transaction_utils.py @@ -1,28 +1,20 @@ -""" -Utility class for transaction-related operations. - -Code Example ------------- - -.. code-block:: python +"""Utility helpers for transaction-related queries. +Example: + ```python from human_protocol_sdk.constants import ChainId from human_protocol_sdk.transaction import TransactionUtils, TransactionFilter - print( - TransactionUtils.get_transactions( - TransactionFilter( - chain_id=ChainId.POLYGON_AMOY, - from_address="0x1234567890123456789012345678901234567890", - to_address="0x0987654321098765432109876543210987654321", - start_date=datetime.datetime(2023, 5, 8), - end_date=datetime.datetime(2023, 6, 8), - ) + TransactionUtils.get_transactions( + TransactionFilter( + chain_id=ChainId.POLYGON_AMOY, + from_address="0x1234567890123456789012345678901234567890", + to_address="0x0987654321098765432109876543210987654321", + start_date=datetime.datetime(2023, 5, 8), + end_date=datetime.datetime(2023, 6, 8), ) ) - -Module ------- + ``` """ from typing import List, Optional @@ -34,6 +26,21 @@ class InternalTransaction: + """Represents an internal transaction within a parent transaction. + + Internal transactions are contract-to-contract calls that occur within + the execution of a main transaction. + + Attributes: + from_address (str): Source address of the internal transaction. + to_address (str): Destination address of the internal transaction. + value (int): Value transferred in token's smallest unit. + method (str): Method signature called in the internal transaction. + receiver (Optional[str]): Receiver address if applicable. + escrow (Optional[str]): Escrow address if the transaction involves an escrow. + token (Optional[str]): Token address if the transaction involves a token transfer. + """ + def __init__( self, from_address: str, @@ -54,6 +61,23 @@ def __init__( class TransactionData: + """Represents on-chain transaction data retrieved from the subgraph. + + Attributes: + chain_id (ChainId): Chain where the transaction was executed. + block (int): Block number containing the transaction. + tx_hash (str): Transaction hash. + from_address (str): Sender address. + to_address (str): Recipient address (contract or EOA). + timestamp (int): Transaction timestamp in milliseconds. + value (int): Value transferred in the main transaction. + method (str): Method signature of the transaction. + receiver (Optional[str]): Receiver address if applicable. + escrow (Optional[str]): Escrow address if the transaction involves an escrow. + token (Optional[str]): Token address if the transaction involves a token transfer. + internal_transactions (List[InternalTransaction]): List of internal transactions. + """ + def __init__( self, chain_id: ChainId, @@ -84,42 +108,55 @@ def __init__( class TransactionUtilsError(Exception): - """ - Raises when some error happens when getting data from subgraph. - """ + """Exception raised when transaction lookup or query operations fail.""" pass class TransactionUtils: - """ - A utility class that provides additional transaction-related functionalities. + """Utility class providing transaction query functions from the subgraph. + + This class offers static methods to fetch on-chain transaction data including + individual transactions by hash and filtered transaction lists with support for + internal transactions. """ @staticmethod def get_transaction( chain_id: ChainId, hash: str, options: Optional[SubgraphOptions] = None ) -> Optional[TransactionData]: - """Returns the transaction for a given hash. + """Retrieve a single transaction by its hash. - :param chain_id: Network in which the transaction was executed - :param hash: Hash of the transaction - :param options: Optional config for subgraph requests + Fetches detailed transaction information including internal transactions + from the subgraph. - :return: Transaction data + Args: + chain_id (ChainId): Network where the transaction was executed. + hash (str): Transaction hash to look up. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. - :example: - .. code-block:: python + Returns: + Transaction data if found, otherwise ``None``. - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.transaction import TransactionUtils + Raises: + TransactionUtilsError: If the chain ID is not supported. - print( - TransactionUtils.get_transaction( - ChainId.POLYGON_AMOY, - "0x1234567890123456789012345678901234567891" - ) - ) + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.transaction import TransactionUtils + + tx = TransactionUtils.get_transaction( + ChainId.POLYGON_AMOY, + "0x1234567890123456789012345678901234567890abcdef1234567890abcdef12", + ) + if tx: + print(f"Block: {tx.block}") + print(f"From: {tx.from_address}") + print(f"To: {tx.to_address}") + print(f"Value: {tx.value}") + print(f"Internal txs: {len(tx.internal_transactions)}") + ``` """ network = NETWORKS.get(chain_id) if not network: @@ -173,33 +210,63 @@ def get_transaction( def get_transactions( filter: TransactionFilter, options: Optional[SubgraphOptions] = None ) -> List[TransactionData]: - """Get an array of transactions based on the specified filter parameters. - - :param filter: Object containing all the necessary parameters to filter - (chain_id, from_address, to_address, start_date, end_date, start_block, end_block, method, escrow, token, first, skip, order_direction) - :param options: Optional config for subgraph requests - - :return: List of transactions - - :example: - .. code-block:: python - - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.transaction import TransactionUtils, TransactionFilter - - print( - TransactionUtils.get_transactions( - TransactionFilter( - chain_id=ChainId.POLYGON_AMOY, - from_address="0x1234567890123456789012345678901234567890", - to_address="0x0987654321098765432109876543210987654321", - method="transfer", - escrow="0x0987654321098765432109876543210987654321", - start_date=datetime.datetime(2023, 5, 8), - end_date=datetime.datetime(2023, 6, 8), - ) - ) + """Retrieve a list of transactions matching the provided filter criteria. + + Queries the subgraph for transactions that match the specified parameters + including addresses, date/block ranges, method signatures, and related contracts. + + Args: + filter (TransactionFilter): Filter parameters including chain ID, sender/recipient + addresses, date/block ranges, method signature, escrow address, token address, + pagination, and sorting options. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. + + Returns: + A list of transactions matching the filter criteria. + Returns an empty list if no matches are found. + + Raises: + TransactionUtilsError: If the chain ID is not supported. + + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.transaction import TransactionUtils, TransactionFilter + import datetime + + # Get all transactions from a specific address + txs = TransactionUtils.get_transactions( + TransactionFilter( + chain_id=ChainId.POLYGON_AMOY, + from_address="0x1234567890123456789012345678901234567890", + ) + ) + + # Get transactions within a date range with method filter + txs = TransactionUtils.get_transactions( + TransactionFilter( + chain_id=ChainId.POLYGON_AMOY, + from_address="0x1234567890123456789012345678901234567890", + to_address="0x0987654321098765432109876543210987654321", + method="transfer", + start_date=datetime.datetime(2023, 5, 8), + end_date=datetime.datetime(2023, 6, 8), + ) + ) + + # Get transactions involving specific escrow + txs = TransactionUtils.get_transactions( + TransactionFilter( + chain_id=ChainId.POLYGON_AMOY, + escrow="0x0987654321098765432109876543210987654321", + start_block=1000000, + end_block=2000000, ) + ) + + for tx in txs: + print(f"{tx.tx_hash}: {tx.method} - {tx.value}") + ``` """ from human_protocol_sdk.gql.transaction import get_transactions_query diff --git a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/utils.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/utils.py index c9c5b9034e..168d17ebb0 100644 --- a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/utils.py +++ b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/utils.py @@ -3,7 +3,7 @@ import os import time import re -from typing import Tuple, Optional +from typing import Tuple, Optional, Any, Dict, Type from dataclasses import dataclass import requests @@ -34,20 +34,40 @@ @dataclass class SubgraphOptions: - """Configuration for subgraph logic.""" + """Configuration options for subgraph queries with retry logic and indexer routing. + + Attributes: + max_retries (Optional[int]): Maximum number of retry attempts for failed queries. Must be paired with base_delay. + base_delay (Optional[int]): Base delay in milliseconds between retry attempts. Must be paired with max_retries. + indexer_id (Optional[str]): Specific indexer ID to route requests to (requires SUBGRAPH_API_KEY environment variable). + """ max_retries: Optional[int] = None - base_delay: Optional[int] = None # milliseconds + base_delay: Optional[int] = None indexer_id: Optional[str] = None def is_indexer_error(error: Exception) -> bool: - """ - Check if an error indicates that the indexer is down or not synced. - This function specifically checks for "bad indexers" errors from The Graph. + """Check if an error indicates that The Graph indexer is down or not synced. + + This function inspects error responses from The Graph API to detect "bad indexers" + messages that indicate infrastructure issues rather than query problems. + + Args: + error (Exception): The exception to check. - :param error: The error to check - :return: True if the error indicates indexer issues + Returns: + True if the error indicates indexer issues, False otherwise. + + Example: + ```python + try: + data = custom_gql_fetch(network, query) + except Exception as e: + if is_indexer_error(e): + # Retry with different indexer + pass + ``` """ if not error: return False @@ -75,21 +95,44 @@ def is_indexer_error(error: Exception) -> bool: def custom_gql_fetch( - network: dict, + network: Dict[str, Any], query: str, - params: dict = None, + params: Optional[Dict[str, Any]] = None, options: Optional[SubgraphOptions] = None, -): - """Fetch data from the subgraph with optional logic. - - :param network: Network configuration dictionary - :param query: GraphQL query string - :param params: Query parameters - :param options: Optional subgraph configuration - - :return: JSON response from the subgraph - - :raise Exception: If the subgraph query fails +) -> Dict[str, Any]: + """Fetch data from the subgraph with optional retry logic and indexer routing. + + Args: + network (Dict[str, Any]): Network configuration dictionary containing subgraph URLs. + query (str): GraphQL query string to execute. + params (Optional[Dict[str, Any]]): Optional query parameters/variables dictionary. + options (Optional[SubgraphOptions]): Optional subgraph configuration for retries and indexer selection. + + Returns: + JSON response from the subgraph containing the query results. + + Raises: + ValueError: If retry configuration is incomplete or indexer routing requires missing API key. + Exception: If the subgraph query fails after all retry attempts. + + Example: + ```python + from human_protocol_sdk.constants import NETWORKS, ChainId + from human_protocol_sdk.utils import SubgraphOptions, custom_gql_fetch + + network = NETWORKS[ChainId.POLYGON_AMOY] + query = "{ escrows(first: 10) { id address } }" + + # Simple query + data = custom_gql_fetch(network, query) + + # With retry logic + data = custom_gql_fetch( + network, + query, + options=SubgraphOptions(max_retries=3, base_delay=1000) + ) + ``` """ subgraph_api_key = os.getenv("SUBGRAPH_API_KEY", "") @@ -130,11 +173,25 @@ def custom_gql_fetch( def _fetch_subgraph_data( - network: dict, + network: Dict[str, Any], query: str, - params: dict = None, + params: Optional[Dict[str, Any]] = None, indexer_id: Optional[str] = None, -): +) -> Dict[str, Any]: + """Internal function to fetch data from the subgraph API. + + Args: + network (Dict[str, Any]): Network configuration dictionary containing subgraph URLs. + query (str): GraphQL query string to execute. + params (Optional[Dict[str, Any]]): Optional query parameters/variables dictionary. + indexer_id (Optional[str]): Optional indexer ID to route the request to. + + Returns: + JSON response from the subgraph. + + Raises: + Exception: If the HTTP request fails or returns a non-200 status code. + """ subgraph_api_key = os.getenv("SUBGRAPH_API_KEY", "") if subgraph_api_key: subgraph_url = network["subgraph_url_api_key"].replace( @@ -166,21 +223,43 @@ def _fetch_subgraph_data( def _attach_indexer_id(url: str, indexer_id: Optional[str]) -> str: + """Append indexer ID to the subgraph URL for routing. + + Args: + url: Base subgraph URL. + indexer_id: Optional indexer ID to append. + + Returns: + Modified URL with indexer routing path if indexer_id is provided, otherwise the original URL. + """ if not indexer_id: return url return f"{url}/indexers/id/{indexer_id}" -def get_hmt_balance(wallet_addr, token_addr, w3): - """Get HMT balance +def get_hmt_balance(wallet_addr: str, token_addr: str, w3: Web3) -> int: + """Get the HMT token balance for a wallet address. - :param wallet_addr: wallet address - :param token_addr: ERC-20 contract - :param w3: Web3 instance + Args: + wallet_addr (str): Wallet address to check balance for. + token_addr (str): ERC-20 token contract address. + w3 (Web3): Web3 instance connected to the network. - :return: HMT balance (wei) - """ + Returns: + HMT token balance in wei. + + Example: + ```python + from web3 import Web3 + w3 = Web3(Web3.HTTPProvider("https://polygon-rpc.com")) + balance = get_hmt_balance( + "0x1234567890123456789012345678901234567890", + "0xc748B2A084F8eFc47E086ccdDD9b7e67aEb571BF", + w3 + ) + ``` + """ abi = [ { "constant": True, @@ -197,12 +276,27 @@ def get_hmt_balance(wallet_addr, token_addr, w3): def parse_transfer_transaction( hmtoken_contract: Contract, tx_receipt: Optional[TxReceipt] ) -> Tuple[bool, Optional[int]]: - """Parse a transfer transaction receipt. + """Parse a transaction receipt to extract HMT transfer information. + + Args: + hmtoken_contract: The HMT token contract instance. + tx_receipt: Transaction receipt to parse, or None. - :param hmtoken_contract: The HMT token contract - :param tx_receipt: The transaction receipt + Returns: + A tuple containing: - :return: A tuple indicating if HMT was transferred and the transaction balance + - bool: True if HMT was successfully transferred, False otherwise. + - Optional[int]: The transfer amount in wei if successful, None otherwise. + + Example: + ```python + from web3 import Web3 + + tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash) + transferred, amount = parse_transfer_transaction(hmt_contract, tx_receipt) + if transferred: + print(f"Transferred {amount} wei") + ``` """ hmt_transferred = False tx_balance = None @@ -220,23 +314,37 @@ def parse_transfer_transaction( return hmt_transferred and tx_balance is not None, tx_balance -def get_contract_interface(contract_entrypoint): - """Retrieve the contract interface of a given contract. +def get_contract_interface(contract_entrypoint: str) -> Dict[str, Any]: + """Retrieve the contract ABI and interface from a compiled artifact file. - :param contract_entrypoint: the entrypoint of the JSON. + Args: + contract_entrypoint (str): File path to the contract JSON artifact. - :return: The contract interface containing the contract abi. - """ + Returns: + Contract interface dictionary containing the ABI and other metadata. + Example: + ```python + interface = get_contract_interface("artifacts/contracts/MyContract.sol/MyContract.json") + abi = interface["abi"] + ``` + """ with open(contract_entrypoint) as f: contract_interface = json.load(f) return contract_interface -def get_erc20_interface(): - """Retrieve the ERC20 interface. +def get_erc20_interface() -> Dict[str, Any]: + """Retrieve the standard ERC20 token contract interface. + + Returns: + The ERC20 contract interface containing the ABI. - :return: The ERC20 interface of smart contract. + Example: + ```python + erc20_interface = get_erc20_interface() + token_contract = w3.eth.contract(address=token_address, abi=erc20_interface["abi"]) + ``` """ return get_contract_interface( @@ -246,11 +354,17 @@ def get_erc20_interface(): ) -def get_factory_interface(): - """Retrieve the EscrowFactory interface. +def get_factory_interface() -> Dict[str, Any]: + """Retrieve the EscrowFactory contract interface. - :return: The EscrowFactory interface of smart contract. + Returns: + The EscrowFactory contract interface containing the ABI. + Example: + ```python + factory_interface = get_factory_interface() + factory_contract = w3.eth.contract(address=factory_address, abi=factory_interface["abi"]) + ``` """ return get_contract_interface( @@ -258,11 +372,17 @@ def get_factory_interface(): ) -def get_staking_interface(): - """Retrieve the Staking interface. +def get_staking_interface() -> Dict[str, Any]: + """Retrieve the Staking contract interface. - :return: The Staking interface of smart contract. + Returns: + The Staking contract interface containing the ABI. + Example: + ```python + staking_interface = get_staking_interface() + staking_contract = w3.eth.contract(address=staking_address, abi=staking_interface["abi"]) + ``` """ return get_contract_interface( @@ -270,11 +390,17 @@ def get_staking_interface(): ) -def get_escrow_interface(): - """Retrieve the RewardPool interface. +def get_escrow_interface() -> Dict[str, Any]: + """Retrieve the Escrow contract interface. - :return: The RewardPool interface of smart contract. + Returns: + The Escrow contract interface containing the ABI. + Example: + ```python + escrow_interface = get_escrow_interface() + escrow_contract = w3.eth.contract(address=escrow_address, abi=escrow_interface["abi"]) + ``` """ return get_contract_interface( @@ -282,11 +408,17 @@ def get_escrow_interface(): ) -def get_kvstore_interface(): - """Retrieve the KVStore interface. +def get_kvstore_interface() -> Dict[str, Any]: + """Retrieve the KVStore contract interface. - :return: The KVStore interface of smart contract. + Returns: + The KVStore contract interface containing the ABI. + Example: + ```python + kvstore_interface = get_kvstore_interface() + kvstore_contract = w3.eth.contract(address=kvstore_address, abi=kvstore_interface["abi"]) + ``` """ return get_contract_interface( @@ -294,25 +426,30 @@ def get_kvstore_interface(): ) -def handle_error(e, exception_class): - """ - Handles and translates errors raised during contract transactions. +def handle_error(e: Exception, exception_class: Type[Exception]) -> None: + """Handle and translate errors raised during contract transactions. This function captures exceptions (especially ContractLogicError from web3.py), - extracts meaningful revert reasons if present, logs unexpected errors, and raises + extracts meaningful revert reasons when present, logs unexpected errors, and raises a custom exception with a clear message for SDK users. - :param e: The exception object raised during a transaction. - :param exception_class: The custom exception class to raise (e.g., EscrowClientError). + Args: + e (Exception): The exception object raised during a transaction. + exception_class (Type[Exception]): The custom exception class to raise (e.g., EscrowClientError). + + Raises: + exception_class: Always raises the provided exception class with a formatted error message. - :raises exception_class: With a detailed error message, including contract revert reasons if available. + Example: + ```python + from human_protocol_sdk.escrow import EscrowClientError - :example: try: tx_hash = contract.functions.someMethod(...).transact() w3.eth.wait_for_transaction_receipt(tx_hash) except Exception as e: handle_error(e, EscrowClientError) + ``` """ def extract_reason(msg): @@ -349,13 +486,27 @@ def extract_reason(msg): def validate_url(url: str) -> bool: - """Validates the given URL. + """Validate whether a string is a properly formatted URL. + + This function supports both standard URLs and Docker network URLs that may + not be recognized by strict validators. + + Args: + url: URL string to validate (e.g., "https://example.com" or "http://localhost:8080"). + + Returns: + True if the URL is valid, False otherwise. - :param url: Public or private URL address + Raises: + ValidationFailure: If the URL format is invalid according to the validators library. - :return: True if URL is valid, False otherwise + Example: + ```python + from human_protocol_sdk.utils import validate_url - :raise ValidationFailure: If the URL is invalid + if validate_url("https://example.com"): + print("Valid URL") + ``` """ # validators.url tracks docker network URL as invalid @@ -384,9 +535,21 @@ def validate_url(url: str) -> bool: def validate_json(data: str) -> bool: - """Validates if the given string is a valid JSON. - :param data: String to validate - :return: True if the string is a valid JSON, False otherwise + """Validate whether a string contains valid JSON data. + + Args: + data: String to validate as JSON. + + Returns: + True if the string is valid JSON, False otherwise. + + Example: + ```python + from human_protocol_sdk.utils import validate_json + + if validate_json('{"key": "value"}'): + print("Valid JSON") + ``` """ try: json.loads(data) diff --git a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/worker/worker_utils.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/worker/worker_utils.py index 1bdab5ca14..27de33976a 100644 --- a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/worker/worker_utils.py +++ b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/worker/worker_utils.py @@ -1,3 +1,18 @@ +"""Utility helpers for worker-related queries. + +Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.worker import WorkerUtils, WorkerFilter + + workers = WorkerUtils.get_workers( + WorkerFilter(chain_id=ChainId.POLYGON_AMOY) + ) + for worker in workers: + print(f"{worker.address}: {worker.total_amount_received}") + ``` +""" + import logging from typing import List, Optional @@ -11,14 +26,21 @@ class WorkerUtilsError(Exception): - """ - Raised when an error occurs when getting data from subgraph. - """ + """Exception raised when errors occur during worker data retrieval operations.""" pass class WorkerData: + """Represents worker information retrieved from the subgraph. + + Attributes: + id (str): Unique worker identifier. + address (str): Worker's Ethereum address. + total_amount_received (int): Total amount of HMT tokens received by the worker. + payout_count (int): Number of payouts the worker has received. + """ + def __init__( self, id: str, @@ -26,15 +48,6 @@ def __init__( total_amount_received: str, payout_count: str, ): - """ - Initializes a WorkerData instance. - - :param id: Worker ID - :param address: Worker address - :param total_amount_received: Total amount received by the worker - :param payout_count: Number of payouts received by the worker - """ - self.id = id self.address = address self.total_amount_received = int(total_amount_received) @@ -42,8 +55,10 @@ def __init__( class WorkerUtils: - """ - A utility class that provides additional worker-related functionalities. + """Utility class providing worker-related query and data retrieval functions. + + This class offers static methods to fetch worker data from the Human Protocol + subgraph, including filtered worker lists and individual worker details. """ @staticmethod @@ -51,12 +66,44 @@ def get_workers( filter: WorkerFilter, options: Optional[SubgraphOptions] = None, ) -> List[WorkerData]: - """Get workers data of the protocol. + """Retrieve a list of workers matching the provided filter criteria. + + Queries the subgraph for workers based on the specified parameters including + address filters, ordering preferences, and pagination. + + Args: + filter (WorkerFilter): Filter parameters including chain ID, worker address, + ordering, and pagination options. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests + such as custom endpoints or timeout settings. + + Returns: + A list of worker records matching the filter criteria. + Returns an empty list if no matches are found. - :param filter: Worker filter - :param options: Optional config for subgraph requests + Raises: + WorkerUtilsError: If the chain ID is not supported. - :return: List of workers data + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.worker import WorkerUtils, WorkerFilter + + # Get all workers + workers = WorkerUtils.get_workers( + WorkerFilter(chain_id=ChainId.POLYGON_AMOY) + ) + for worker in workers: + print(f"{worker.address}: {worker.total_amount_received} HMT") + + # Get specific worker + workers = WorkerUtils.get_workers( + WorkerFilter( + chain_id=ChainId.POLYGON_AMOY, + worker_address="0x1234567890123456789012345678901234567890", + ) + ) + ``` """ from human_protocol_sdk.gql.worker import get_workers_query @@ -107,13 +154,35 @@ def get_worker( worker_address: str, options: Optional[SubgraphOptions] = None, ) -> Optional[WorkerData]: - """Gets the worker details. + """Retrieve a single worker by their address. + + Fetches detailed information about a specific worker from the subgraph, + including their total earnings and payout history. + + Args: + chain_id (ChainId): Network where the worker has participated. + worker_address (str): Ethereum address of the worker. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. - :param chain_id: Network in which the worker exists - :param worker_address: Address of the worker - :param options: Optional config for subgraph requests + Returns: + Worker data if found, otherwise ``None``. - :return: Worker data if exists, otherwise None + Raises: + WorkerUtilsError: If the chain ID is not supported or the worker address is invalid. + + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.worker import WorkerUtils + + worker = WorkerUtils.get_worker( + ChainId.POLYGON_AMOY, + "0x1234567890123456789012345678901234567890", + ) + if worker: + print(f"Total received: {worker.total_amount_received} HMT") + print(f"Payout count: {worker.payout_count}") + ``` """ from human_protocol_sdk.gql.worker import get_worker_query @@ -123,7 +192,7 @@ def get_worker( raise WorkerUtilsError("Unsupported Chain ID") if not Web3.is_address(worker_address): - raise WorkerUtilsError(f"Invalid operator address: {worker_address}") + raise WorkerUtilsError(f"Invalid worker address: {worker_address}") network = NETWORKS[chain_id] worker_data = custom_gql_fetch( diff --git a/packages/sdk/typescript/human-protocol-sdk/.gitignore b/packages/sdk/typescript/human-protocol-sdk/.gitignore index f87fcba870..4d3fb3fcc4 100644 --- a/packages/sdk/typescript/human-protocol-sdk/.gitignore +++ b/packages/sdk/typescript/human-protocol-sdk/.gitignore @@ -7,5 +7,5 @@ dist # Logs logs -#Docs -docs \ No newline at end of file +docs +!docs/index.md \ No newline at end of file diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/index.md b/packages/sdk/typescript/human-protocol-sdk/docs/index.md new file mode 100644 index 0000000000..2fbde867d1 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/docs/index.md @@ -0,0 +1,294 @@ +# HUMAN Protocol TypeScript SDK + +The **HUMAN Protocol TypeScript SDK** provides a comprehensive, type-safe interface for interacting with HUMAN Protocol smart contracts and off-chain services. It enables developers to build decentralized job marketplaces, data labeling platforms, and other human-in-the-loop applications on blockchain networks. + +## Overview + +HUMAN Protocol is a decentralized infrastructure for coordinating human work at scale. The TypeScript SDK simplifies integration by providing high-level abstractions for: + +- **Escrow Management**: Create, fund, and manage escrow contracts for job distribution +- **Staking Operations**: Stake HMT tokens and manage operator allocations +- **On-chain Storage**: Store and retrieve configuration data using KVStore +- **Operator Discovery**: Query and filter operators by role, reputation, and capabilities +- **Worker Analytics**: Track worker performance and payout history +- **Statistics**: Access protocol-wide metrics and analytics +- **Encryption**: Secure message encryption using PGP for private communications + +!!! info "Subgraph access and rate limits" + The SDK calls public subgraph endpoints by default. Unauthenticated requests are rate-limited and may return errors. For higher limits, use your own [API key](https://thegraph.com/docs/it/subgraphs/querying/managing-api-keys/). + +## Key Features + +### Smart Contract Clients + +- **EscrowClient**: Full lifecycle management of escrow contracts + - Create, fund, and configure escrows + - Bulk payout distribution with string-based IDs + - Store and verify results with hash validation + - Cancel, request cancellation, and refund mechanisms + - Withdraw additional tokens +- **StakingClient**: Manage HMT token staking + - Stake, unstake, and withdraw operations + - Slash malicious operators + - Query staking information +- **KVStoreClient**: On-chain key-value storage + - Store operator configuration + - Manage URLs with automatic hash verification + - Retrieve public keys and metadata + +### Subgraph Utilities + +- **EscrowUtils**: Query escrow data, status events, payouts, and cancellation refunds +- **OperatorUtils**: Discover operators by role, reputation network, and rewards +- **StakingUtils**: Access staker information and statistics +- **WorkerUtils**: Query worker statistics and payout history +- **StatisticsUtils**: Retrieve protocol statistics and HMT token metrics +- **TransactionUtils**: Query on-chain transactions with advanced filters + +### Developer Tools + +- **EncryptionUtils**: PGP-based message encryption, signing, and key generation +- **Type Safety**: Full TypeScript support with comprehensive type definitions +- **Error Handling**: Descriptive exceptions with clear error messages +- **Flexible Filters**: Query builders for subgraph data with pagination and ordering +- **Multi-network Support**: Built-in configurations for multiple chains + +## Installation + +### npm + +```bash +npm install @human-protocol/sdk +``` + +### yarn + +```bash +yarn add @human-protocol/sdk +``` + +!!! warning "Keep ethers in sync" + The SDK is built against a specific `ethers` major/minor (currently `6.15.x`). Pin the same major/minor in your app. Mixing different minors (e.g., `6.16.x` with the SDK) can trigger errors. + +## Quick Start + +### Read-Only Operations + +Query escrow data without a signer: + +```typescript +import { EscrowUtils, ChainId, EscrowStatus } from '@human-protocol/sdk'; + +// Get escrows from the subgraph +const escrows = await EscrowUtils.getEscrows({ + chainId: ChainId.POLYGON_AMOY, + status: EscrowStatus.Pending, + first: 10, +}); + +for (const escrow of escrows) { + console.log(`Escrow: ${escrow.address}`); + console.log(`Balance: ${escrow.balance}`); + console.log(`Status: ${escrow.status}`); +} +``` + +### Write Operations + +Create and fund an escrow with a signer: + +```typescript +import { EscrowClient } from '@human-protocol/sdk'; +import { Wallet, JsonRpcProvider, parseUnits } from 'ethers'; + +// Initialize provider and signer +const provider = new JsonRpcProvider('https://polygon-amoy-rpc.com'); +const signer = new Wallet('YOUR_PRIVATE_KEY', provider); + +// Create escrow client +const escrowClient = await EscrowClient.build(signer); + +// Create escrow configuration +const escrowConfig = { + recordingOracle: '0x...', + reputationOracle: '0x...', + exchangeOracle: '0x...', + recordingOracleFee: 10n, + reputationOracleFee: 10n, + exchangeOracleFee: 10n, + manifest: 'https://example.com/manifest.json', + manifestHash: 'manifest_hash', +}; + +// Create and setup escrow +const escrowAddress = await escrowClient.createFundAndSetupEscrow( + '0x...', // token address + parseUnits('100', 18), + 'job-requester-123', + escrowConfig +); + +console.log(`Created escrow: ${escrowAddress}`); +``` + +### Query Statistics + +Access protocol-wide statistics: + +```typescript +import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; + +// Get network data +const networkData = NETWORKS[ChainId.POLYGON_AMOY]; + +// Get escrow statistics +const stats = await StatisticsUtils.getEscrowStatistics(networkData); +console.log(`Total escrows: ${stats.totalEscrows}`); + +// Get HMT token statistics +const hmtStats = await StatisticsUtils.getHMTStatistics(networkData); +console.log(`Total holders: ${hmtStats.totalHolders}`); +console.log(`Total transfers: ${hmtStats.totalTransferCount}`); +``` + +### Operator Discovery + +Find operators by role and reputation: + +```typescript +import { OperatorUtils, ChainId } from '@human-protocol/sdk'; + +// Find recording oracles +const operators = await OperatorUtils.getOperators({ + chainId: ChainId.POLYGON_AMOY, + roles: ['Recording Oracle'], + first: 10, +}); + +for (const operator of operators) { + console.log(`Operator: ${operator.address}`); + console.log(`Role: ${operator.role}`); + console.log(`Staked: ${operator.stakedAmount}`); +} +``` + +### Encryption + +Encrypt and decrypt messages using PGP: + +```typescript +import { Encryption, EncryptionUtils } from '@human-protocol/sdk'; + +// Generate key pair +const keyPair = await EncryptionUtils.generateKeyPair( + 'Alice', + 'alice@example.com', + 'passphrase123' +); + +// Initialize encryption with private key +const encryption = await Encryption.build( + keyPair.privateKey, + 'passphrase123' +); + +// Sign and encrypt a message +const publicKeys = [keyPair.publicKey, 'OTHER_PUBLIC_KEY']; +const encrypted = await encryption.signAndEncrypt('Hello, HUMAN!', publicKeys); + +// Decrypt and verify +const decrypted = await encryption.decrypt(encrypted, keyPair.publicKey); +console.log(new TextDecoder().decode(decrypted)); +``` + +## Supported Networks + +The SDK supports multiple blockchain networks: + +- **Mainnet**: Ethereum, Polygon, BSC +- **Testnets**: Sepolia, Polygon Amoy, BSC Testnet +- **Local Development**: Localhost (Hardhat/Ganache) + +Network configurations are automatically loaded based on the provider's chain ID. + +## Architecture + +The SDK is organized into several modules: + +- **`escrow`**: Escrow contract client and utilities +- **`staking`**: Staking contract client and utilities +- **`kvstore`**: Key-value store client and utilities +- **`operator`**: Operator discovery and management utilities +- **`worker`**: Worker statistics utilities +- **`statistics`**: Protocol statistics utilities (instance-based and static methods) +- **`transaction`**: Transaction query utilities +- **`encryption`**: PGP encryption helpers (instance-based and static methods) +- **`constants`**: Network configurations and enums +- **`types`**: TypeScript type definitions +- **`interfaces`**: Interface definitions for data structures + +## Usage Patterns + +### Client Classes vs Utility Classes + +The SDK provides two patterns for interacting with the protocol: + +**Client Classes** (require Signer/Provider): +- `EscrowClient` +- `StakingClient` +- `KVStoreClient` + +```typescript +const client = await EscrowClient.build(signerOrProvider); +const balance = await client.getBalance(escrowAddress); +``` + +**Utility Classes** (static methods, no initialization): +- `EscrowUtils` +- `StakingUtils` +- `KVStoreUtils` +- `OperatorUtils` +- `WorkerUtils` +- `StatisticsUtils` +- `TransactionUtils` + +```typescript +const escrows = await EscrowUtils.getEscrows(filter); +const operators = await OperatorUtils.getOperators(filter); +``` + +### Subgraph Configuration + +Control subgraph requests with optional parameters: + +```typescript +const escrows = await EscrowUtils.getEscrows( + filter, + { + maxRetries: 3, + baseDelay: 1000, + indexerId: 'specific-indexer-id' + } +); +``` + +Environment variable for API key: + +```bash +export SUBGRAPH_API_KEY="your-api-key" +``` + +## Requirements + +- Node.js 16.0 or higher +- TypeScript 4.7+ (for development) +- ethers.js 6.0+ +- Access to an Ethereum-compatible RPC endpoint +- (Optional) Private key for transaction signing + +## Resources + +- [GitHub Repository](https://github.com/humanprotocol/human-protocol) +- [HUMAN Protocol Documentation](https://docs.humanprotocol.org/) +- [Discord Community](https://discord.gg/humanprotocol) +- [Website](https://www.humanprotocol.org/) diff --git a/packages/sdk/typescript/human-protocol-sdk/package.json b/packages/sdk/typescript/human-protocol-sdk/package.json index 67a4a66f3c..064997acae 100644 --- a/packages/sdk/typescript/human-protocol-sdk/package.json +++ b/packages/sdk/typescript/human-protocol-sdk/package.json @@ -10,9 +10,9 @@ "types": "dist/index.d.ts", "scripts": { "clean": "tsc --build --clean && rm -rf ./dist", - "clean:doc": "rm -rf ../../../../docs/sdk/typescript/", "build": "yarn clean && tsc --build", - "build:doc": "yarn clean:doc && typedoc --plugin typedoc-plugin-markdown --out ../../../../docs/sdk/typescript/", + "docs:post": "ts-node scripts/postprocess-docs.ts", + "build:doc": "typedoc && yarn docs:post", "test": "vitest -u", "lint": "eslint .", "lint:fix": "eslint . --fix", @@ -54,27 +54,11 @@ "eslint": "^9.39.1", "eslint-plugin-jest": "^28.9.0", "eslint-plugin-prettier": "^5.2.1", + "glob": "^13.0.0", "prettier": "^3.7.4", "ts-node": "^10.9.2", - "typedoc": "^0.28.7", - "typedoc-plugin-markdown": "^4.2.3", + "typedoc": "^0.28.15", + "typedoc-plugin-markdown": "^4.9.0", "typescript": "^5.8.3" - }, - "typedocOptions": { - "entryPoints": [ - "./src/base.ts", - "./src/encryption.ts", - "./src/escrow.ts", - "./src/kvstore.ts", - "./src/operator.ts", - "./src/staking.ts", - "./src/storage.ts", - "./src/statistics.ts", - "./src/transaction.ts", - "./src/enums.ts", - "./src/graphql/types.ts", - "./src/interfaces.ts", - "./src/types.ts" - ] } } diff --git a/packages/sdk/typescript/human-protocol-sdk/scripts/postprocess-docs.ts b/packages/sdk/typescript/human-protocol-sdk/scripts/postprocess-docs.ts new file mode 100644 index 0000000000..daeb65972e --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/scripts/postprocess-docs.ts @@ -0,0 +1,457 @@ +import { readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { globSync } from 'glob'; +import { PathOrFileDescriptor } from 'fs'; + +const ROOT = 'docs'; // adjust if needed + +function processFile(path: PathOrFileDescriptor) { + const original = readFileSync(path, 'utf8'); + let text = original; + + // First pass: keep original overload structure + text = collapseOverloadedMethods(text); + + const lines = text.split('\n'); + const out: string[] = []; + + let i = 0; + + while (i < lines.length) { + let line = lines[i]; + + // ---------- Handle a single Call Signature block as a unit ---------- + if (/^####\s+Call Signature/i.test(line)) { + const section: string[] = []; + // capture this call signature block until next call signature or next method heading + while (i < lines.length) { + const cur = lines[i]; + if (section.length > 0 && /^####\s+Call Signature/i.test(cur.trim())) { + break; + } + if (section.length > 0 && /^###\s+/.test(cur)) { + break; + } + section.push(cur); + i++; + } + out.push(...processCallSignatureSection(section)); + continue; + } + + // ---------- Normalize 5# headings to 4# for consistency ---------- + if ( + /^#####\s+(Parameters|Returns|Throws|Example|Examples|Remarks)\b/.test( + line + ) + ) { + // rewrite in-place and re-process this line + lines[i] = line = line.replace(/^#####/, '####'); + } + + // ---------- Convert parameter tables to have #### Parameters heading and capture full table ---------- + if (line.trim().match(/^\|\s*Parameter\s*\|\s*Type/i)) { + // Check if previous non-empty line is already "#### Parameters" + let lookBack = out.length - 1; + while (lookBack >= 0 && out[lookBack].trim() === '') lookBack--; + + if (lookBack < 0 || !out[lookBack].startsWith('#### Parameters')) { + // Remove trailing blanks then add heading + while (out.length > 0 && out[out.length - 1].trim() === '') out.pop(); + out.push(''); + out.push('#### Parameters'); + out.push(''); + } + + // Emit the whole table block: header + following rows + while (i < lines.length && lines[i].trim().startsWith('|')) { + out.push(lines[i]); + i++; + } + out.push(''); + continue; + } + + // ---------- THROWS: normalize into a single table and merge consecutive headings (non-overload context) ---------- + if (line.startsWith('#### Throws')) { + type Row = { type: string; desc: string }; + const rows: Row[] = []; + + const pushLineAsRow = (raw: string) => { + const cleaned = raw.trim().replace(/^-\s*/, ''); + const m = cleaned.match(/^`?([^`\s|]+)`?\s*(.*)$/); + if (m) { + rows.push({ type: m[1].trim(), desc: (m[2] || '').trim() }); + } else if (cleaned) { + rows.push({ type: '-', desc: cleaned }); + } + }; + + // consume one or more consecutive "#### Throws" sections + while (i < lines.length && lines[i].startsWith('#### Throws')) { + i++; // skip heading + + // skip blank lines + while (i < lines.length && lines[i].trim() === '') i++; + + if (i >= lines.length) break; + + // if table-form throws, parse all rows + if (lines[i].trim().startsWith('|')) { + const table: string[] = []; + while (i < lines.length && lines[i].trim().startsWith('|')) { + const l = lines[i].trim(); + table.push(l); + i++; + } + for (const r of table) { + const cells = r.split('|').map((c) => c.trim()); + if ( + cells.length >= 4 && + cells[1] && + cells[2] && + !/^(-{2,}|Type)$/i.test(cells[1]) && + !/^(-{2,}|Description)$/i.test(cells[2]) + ) { + const typeCell = cells[1].replace(/`/g, '').trim(); + const descCell = cells[2].trim(); + rows.push({ type: typeCell || '-', desc: descCell || '-' }); + } + } + } else { + // freeform lines until next heading or blank line + while ( + i < lines.length && + lines[i].trim() !== '' && + !/^### /.test(lines[i]) && + !/^#### /.test(lines[i]) && + !/^##### /.test(lines[i]) + ) { + pushLineAsRow(lines[i]); + i++; + } + } + + // skip blank lines between throws blocks + while (i < lines.length && lines[i].trim() === '') i++; + } + + // emit one normalized table + out.push('#### Throws', ''); + out.push('| Type | Description |'); + out.push('|------|-------------|'); + for (const r of rows) { + out.push(`| \`${r.type || '-'}\` | ${r.desc || '-'} |`); + } + out.push(''); + continue; + } + + // ---------- RETURNS: normalize into a table (after heading normalization) ---------- + if (line.startsWith('#### Returns')) { + i++; // skip heading + + // skip blank lines + while (i < lines.length && lines[i].trim() === '') i++; + + if (i >= lines.length) { + out.push('#### Returns'); + break; + } + + // type line (e.g. `Promise`\<`void`\> or `Promise`) + const typeLine = lines[i].trim(); + i++; + + // skip blank lines + while (i < lines.length && lines[i].trim() === '') i++; + + // description lines until blank or next heading + const descParts: string[] = []; + while ( + i < lines.length && + lines[i].trim() !== '' && + !/^###? /.test(lines[i]) && + !/^#### /.test(lines[i]) && + !/^##### /.test(lines[i]) + ) { + descParts.push(lines[i].trim()); + i++; + } + + // clean type: remove backticks and backslash escapes + let rawType = typeLine + .replace(/`/g, '') + .replace(/\\/g, '>'); + rawType = rawType.trim(); + + // strip Promise<...> wrapper + const type = rawType.replace(/^Promise\s*<\s*([^>]+)\s*>$/i, '$1').trim(); + + const desc = descParts.join(' '); + + out.push('#### Returns', ''); + out.push('| Type | Description |'); + out.push('|------|-------------|'); + out.push(`| \`${type}\` | ${desc || '-'} |`); + out.push(''); + + // skip any trailing blank lines we already consumed + while (i < lines.length && lines[i].trim() === '') i++; + + continue; + } + + // ---------- Handle orphan Param sections (from overloads) ---------- + if (line.startsWith('#### Param')) { + // Skip orphan param lines that appear before method signatures + i++; + while (i < lines.length && lines[i].trim() === '') i++; + continue; + } + + // default: copy line + out.push(line); + i++; + } + + // second pass: transform Examples into admonitions + text = out.join('\n'); + text = transformExamples(text); + + writeFileSync(path, text); +} + +// ---------- Process a single Call Signature block ---------- +function processCallSignatureSection(section: string[]): string[] { + const t = (s: string) => s.trim(); + // normalize 5# to 4# inside the section + section = section.map((l) => + l.replace( + /^#####\s+(Parameters|Returns|Throws|Example|Examples|Remarks)\b/, + '#### $1' + ) + ); + + const out: string[] = []; + const throwRows: { type: string; desc: string }[] = []; + let firstThrowsOutIdx: number | null = null; + + const pushLineAsThrowRow = (raw: string) => { + const cleaned = raw.trim().replace(/^-\s*/, ''); + const m = cleaned.match(/^`?([^`\s|]+)`?\s*(.*)$/); + if (m) { + throwRows.push({ type: m[1].trim(), desc: (m[2] || '').trim() }); + } else if (cleaned) { + throwRows.push({ type: '-', desc: cleaned }); + } + }; + + let i = 0; + while (i < section.length) { + const line = section[i]; + + // Parameter table without heading: add heading, then copy table + if (t(line).match(/^\|\s*Parameter\s*\|\s*Type/i)) { + // ensure "#### Parameters" before + let lookBack = out.length - 1; + while (lookBack >= 0 && out[lookBack].trim() === '') lookBack--; + if (lookBack < 0 || !out[lookBack].startsWith('#### Parameters')) { + while (out.length > 0 && out[out.length - 1].trim() === '') out.pop(); + out.push(''); + out.push('#### Parameters'); + out.push(''); + } + // emit full table + while (i < section.length && t(section[i]).startsWith('|')) { + out.push(section[i]); + i++; + } + out.push(''); + continue; + } + + // Returns: normalize into a table + if (t(line).startsWith('#### Returns')) { + i++; // skip heading + while (i < section.length && t(section[i]) === '') i++; + if (i >= section.length) { + out.push('#### Returns'); + break; + } + const typeLine = t(section[i] || ''); + i++; + while (i < section.length && t(section[i]) === '') i++; + + const descParts: string[] = []; + while ( + i < section.length && + t(section[i]) !== '' && + !/^#### /.test(t(section[i])) && + !/^### /.test(t(section[i])) + ) { + descParts.push(t(section[i])); + i++; + } + + let rawType = typeLine + .replace(/`/g, '') + .replace(/\\/g, '>'); + rawType = rawType.trim(); + const type = rawType.replace(/^Promise\s*<\s*([^>]+)\s*>$/i, '$1').trim(); + const desc = descParts.join(' '); + + out.push('#### Returns', ''); + out.push('| Type | Description |'); + out.push('|------|-------------|'); + out.push(`| \`${type}\` | ${desc || '-'} |`); + out.push(''); + while (i < section.length && t(section[i]) === '') i++; + continue; + } + + // Throws: collect rows, defer emission; skip original throws blocks + if (t(line).startsWith('#### Throws')) { + if (firstThrowsOutIdx === null) firstThrowsOutIdx = out.length; + i++; // skip heading + while (i < section.length && t(section[i]) === '') i++; + if (i >= section.length) break; + + if (t(section[i]).startsWith('|')) { + // table form + const table: string[] = []; + while (i < section.length && t(section[i]).startsWith('|')) { + table.push(section[i].trim()); + i++; + } + for (const r of table) { + const cells = r.split('|').map((c) => c.trim()); + if ( + cells.length >= 4 && + cells[1] && + cells[2] && + !/^(-{2,}|Type)$/i.test(cells[1]) && + !/^(-{2,}|Description)$/i.test(cells[2]) + ) { + const typeCell = cells[1].replace(/`/g, '').trim(); + const descCell = cells[2].trim(); + throwRows.push({ type: typeCell || '-', desc: descCell || '-' }); + } + } + } else { + // freeform + while ( + i < section.length && + t(section[i]) !== '' && + !/^#### /.test(t(section[i])) && + !/^### /.test(t(section[i])) + ) { + pushLineAsThrowRow(section[i]); + i++; + } + } + // skip blank lines after each throws block + while (i < section.length && t(section[i]) === '') i++; + continue; + } + + // Default: copy line + out.push(line); + i++; + } + + // Insert merged Throws table at the first encountered position (or append at end if not found) + if (throwRows.length > 0) { + const block: string[] = []; + block.push('#### Throws', ''); + block.push('| Type | Description |'); + block.push('|------|-------------|'); + for (const r of throwRows) { + block.push(`| \`${r.type || '-'}\` | ${r.desc || '-'} |`); + } + block.push(''); + + const insertAt = firstThrowsOutIdx ?? out.length; + out.splice(insertAt, 0, ...block); + } + + return out; +} + +// ---------- EXAMPLES -> admonition ---------- +function transformExamples(text: string): string { + const lines = text.split('\n'); + const out: string[] = []; + let i = 0; + + while (i < lines.length) { + const line = lines[i]; + + // Match "#### Example" or "#### Examples" + if (/^####\s+Examples?/.test(line)) { + i++; // skip heading + + // Skip blank lines + while (i < lines.length && lines[i].trim() === '') i++; + + // If next line is not a code fence, leave it alone + if (i >= lines.length || !lines[i].trim().startsWith('```')) { + out.push('#### Example'); + continue; + } + + // Capture exactly one fenced code block + const code: string[] = []; + code.push(lines[i]); // opening ``` + i++; + + // Capture lines until closing ``` + while (i < lines.length && !lines[i].trim().startsWith('```')) { + code.push(lines[i]); + i++; + } + + // Capture final ``` + if (i < lines.length) { + code.push(lines[i]); + i++; + } + + // Emit MkDocs Material example block + out.push('???+ example "Example"', ''); + for (const l of code) out.push(' ' + l); // indent + out.push(''); + + continue; + } + + // Normalize 5# "##### Examples" to 4# earlier in processFile; also handle here just in case + if (/^#####\s+Examples?/.test(line)) { + out.push(line.replace(/^#####/, '####')); + i++; + continue; + } + + out.push(line); + i++; + } + + return out.join('\n'); +} + +// ---------- Collapse overloaded methods: no-op to keep Call Signature blocks ---------- +function collapseOverloadedMethods(text: string): string { + return text; +} + +// add runner to process all docs +function main() { + const files = globSync(join(ROOT, '**/*.md')); + for (const file of files) { + processFile(file); + } +} + +main(); diff --git a/packages/sdk/typescript/human-protocol-sdk/src/base.ts b/packages/sdk/typescript/human-protocol-sdk/src/base.ts index a0f3083da7..b9be0c077d 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/base.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/base.ts @@ -2,10 +2,9 @@ import { ContractRunner } from 'ethers'; import { NetworkData } from './types'; /** - * ## Introduction - * - * This class is used as a base class for other clients making on-chain calls. + * Base class for clients making on-chain calls. * + * This class provides common functionality for interacting with Ethereum contracts. */ export abstract class BaseEthersClient { protected runner: ContractRunner; @@ -14,8 +13,8 @@ export abstract class BaseEthersClient { /** * **BaseClient constructor** * - * @param {ContractRunner} runner The Signer or Provider object to interact with the Ethereum network - * @param {NetworkData} networkData The network information required to connect to the contracts + * @param runner - The Signer or Provider object to interact with the Ethereum network + * @param networkData - The network information required to connect to the contracts */ constructor(runner: ContractRunner, networkData: NetworkData) { this.networkData = networkData; diff --git a/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts b/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts index 38d1921f93..208f3b9513 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts @@ -4,8 +4,10 @@ import { IKeyPair } from './interfaces'; /** * Type representing the data type of a message. * It can be either a string or a Uint8Array. + * + * @public */ -type MessageDataType = string | Uint8Array; +export type MessageDataType = string | Uint8Array; function makeMessageDataBinary(message: MessageDataType): Uint8Array { if (typeof message === 'string') { @@ -16,44 +18,11 @@ function makeMessageDataBinary(message: MessageDataType): Uint8Array { } /** - * ## Introduction - * * Class for signing and decrypting messages. * * The algorithm includes the implementation of the [PGP encryption algorithm](https://github.com/openpgpjs/openpgpjs) multi-public key encryption on typescript, and uses the vanilla [ed25519](https://en.wikipedia.org/wiki/EdDSA#Ed25519) implementation Schnorr signature for signatures and [curve25519](https://en.wikipedia.org/wiki/Curve25519) for encryption. [Learn more](https://wiki.polkadot.network/docs/learn-cryptography). * - * To get an instance of this class, initialization is recommended using the static `build` method. - * - * ```ts - * static async build(privateKeyArmored: string, passphrase?: string): Promise - * ``` - * - * ## Installation - * - * ### npm - * ```bash - * npm install @human-protocol/sdk - * ``` - * - * ### yarn - * ```bash - * yarn install @human-protocol/sdk - * ``` - * - * ## Input parameters - * - * - `privateKeyArmored` - The encrypted private key in armored format. - * - `passphrase` - The passphrase for the private key. - * - * ## Code example - * - * ```ts - * import { Encryption } from '@human-protocol/sdk'; - * - * const privateKey = 'Armored_priv_key'; - * const passphrase = 'example_passphrase'; - * const encryption = await Encryption.build(privateKey, passphrase); - * ``` + * To get an instance of this class, initialization is recommended using the static [`build`](/ts/classes/Encryption/#build) method. */ export class Encryption { private privateKey: openpgp.PrivateKey; @@ -61,7 +30,7 @@ export class Encryption { /** * Constructor for the Encryption class. * - * @param {PrivateKey} privateKey - The private key. + * @param privateKey - The private key. */ constructor(privateKey: openpgp.PrivateKey) { this.privateKey = privateKey; @@ -70,9 +39,18 @@ export class Encryption { /** * Builds an Encryption instance by decrypting the private key from an encrypted private key and passphrase. * - * @param {string} privateKeyArmored - The encrypted private key in armored format. - * @param {string} passphrase - Optional: The passphrase for the private key. - * @returns {Promise} - The Encryption instance. + * @param privateKeyArmored - The encrypted private key in armored format. + * @param passphrase - The passphrase for the private key (optional). + * @returns The Encryption instance. + * + * @example + * ```ts + * import { Encryption } from '@human-protocol/sdk'; + * + * const privateKey = 'Armored_priv_key'; + * const passphrase = 'example_passphrase'; + * const encryption = await Encryption.build(privateKey, passphrase); + * ``` */ public static async build( privateKeyArmored: string, @@ -98,45 +76,18 @@ export class Encryption { /** * This function signs and encrypts a message using the private key used to initialize the client and the specified public keys. * - * @param {MessageDataType} message Message to sign and encrypt. - * @param {string[]} publicKeys Array of public keys to use for encryption. - * @returns {Promise} Message signed and encrypted. - * - * **Code example** + * @param message - Message to sign and encrypt. + * @param publicKeys - Array of public keys to use for encryption. + * @returns Message signed and encrypted. * + * @example * ```ts - * import { Encryption } from '@human-protocol/sdk'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const privateKey = 'Armored_priv_key'; - * const passphrase = 'example_passphrase'; - * const encryption = await Encryption.build(privateKey, passphrase); - * const publicKey1 = `-----BEGIN PGP PUBLIC KEY BLOCK----- - * xjMEZKQEMxYJKwYBBAHaRw8BAQdA5oZTq4UPlS0IXn4kEaSqQdAa9+Cq522v - * WYxJQn3vo1/NFEh1bWFuIDxodW1hbkBobXQuYWk+wowEEBYKAD4FAmSkBDME - * CwkHCAkQJBFPuuhtQo4DFQgKBBYAAgECGQECGwMCHgEWIQTQ5fbVPB9CWIdf - * XdYkEU+66G1CjgAAKYYA/jMyDCtJtqu6hj22kq9SW6fuV1FCT2ySJ9vBhumF - * X8wWAP433zVFl4VECOkgGk8qFr8BgkYxaz16GOFAqYbfO6oMBc44BGSkBDMS - * CisGAQQBl1UBBQEBB0AKR+A48zVVYZWQvgu7Opn2IGvzI9jePB/J8pzqRhg2 - * YAMBCAfCeAQYFggAKgUCZKQEMwkQJBFPuuhtQo4CGwwWIQTQ5fbVPB9CWIdf - * XdYkEU+66G1CjgAA0xgBAK4AIahFFnmWR2Mp6A3q021cZXpGklc0Xw1Hfswc - * UYLqAQDfdym4kiUvKO1+REKASt0Gwykndl7hra9txqlUL5DXBQ===Vwgv - * -----END PGP PUBLIC KEY BLOCK-----`; - * - * const publicKey2 = `-----BEGIN PGP PUBLIC KEY BLOCK----- - * xjMEZKQEMxYJKwYBBAHaRw8BAQdAG6h+E+6T/RV2tIHer3FP/jKThAyGcoVx - * FzhnP0hncPzNFEh1bWFuIDxodW1hbkBobXQuYWk+wowEEBYKAD4FAmSkBDME - * CwkHCAkQPIq5xLhlTYkDFQgKBBYAAgECGQECGwMCHgEWIQTcxtMgul/AeUvH - * bio8irnEuGVNiQAA/HsBANpfFkxNYixpsBk8LlaaCaPy5f1/cWNPgODM9uzo - * ciSTAQDtAYynu4dSJO9GbMuDuc0FaUHRWJK3mS6JkvedYL4oBM44BGSkBDMS - * CisGAQQBl1UBBQEBB0DWbEG7DMhkeSc8ZPzrH8XNSCqS3t9y/oQidFR+xN3Z - * bAMBCAfCeAQYFggAKgUCZKQEMwkQPIq5xLhlTYkCGwwWIQTcxtMgul/AeUvH - * bio8irnEuGVNiQAAqt8BAM/4Lw0RVOb0L5Ki9CyxO/6AKvRg4ra3Q3WR+duP - * s/88AQCDErzvn+SOX4s3gvZcM3Vr4wh4Q2syHV8Okgx8STYPDg===DsVk - * -----END PGP PUBLIC KEY BLOCK-----`; + * const publicKey1 = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; + * const publicKey2 = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; * * const publicKeys = [publicKey1, publicKey2]; * const resultMessage = await encryption.signAndEncrypt('message', publicKeys); + * console.log('Encrypted message:', resultMessage); * ``` */ public async signAndEncrypt( @@ -163,32 +114,17 @@ export class Encryption { /** * This function decrypts messages using the private key. In addition, the public key can be added for signature verification. * - * @param {string} message Message to decrypt. - * @param {string} publicKey Public key used to verify signature if needed. This is optional. - * @returns {Promise} Message decrypted. - * - * **Code example** + * @param message - Message to decrypt. + * @param publicKey - Public key used to verify signature if needed (optional). + * @returns Message decrypted. + * @throws Error If signature could not be verified when public key is provided * + * @example * ```ts - * import { Encryption } from '@human-protocol/sdk'; - * - * const privateKey = 'Armored_priv_key'; - * const passphrase = 'example_passphrase'; - * const encryption = await Encryption.build(privateKey, passphrase); - * - * const publicKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- - * xjMEZKQEMxYJKwYBBAHaRw8BAQdA5oZTq4UPlS0IXn4kEaSqQdAa9+Cq522v - * WYxJQn3vo1/NFEh1bWFuIDxodW1hbkBobXQuYWk+wowEEBYKAD4FAmSkBDME - * CwkHCAkQJBFPuuhtQo4DFQgKBBYAAgECGQECGwMCHgEWIQTQ5fbVPB9CWIdf - * XdYkEU+66G1CjgAAKYYA/jMyDCtJtqu6hj22kq9SW6fuV1FCT2ySJ9vBhumF - * X8wWAP433zVFl4VECOkgGk8qFr8BgkYxaz16GOFAqYbfO6oMBc44BGSkBDMS - * CisGAQQBl1UBBQEBB0AKR+A48zVVYZWQvgu7Opn2IGvzI9jePB/J8pzqRhg2 - * YAMBCAfCeAQYFggAKgUCZKQEMwkQJBFPuuhtQo4CGwwWIQTQ5fbVPB9CWIdf - * XdYkEU+66G1CjgAA0xgBAK4AIahFFnmWR2Mp6A3q021cZXpGklc0Xw1Hfswc - * UYLqAQDfdym4kiUvKO1+REKASt0Gwykndl7hra9txqlUL5DXBQ===Vwgv - * -----END PGP PUBLIC KEY BLOCK-----`; + * const publicKey = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; * - * const resultMessage = await encryption.decrypt('message'); + * const resultMessage = await encryption.decrypt('message', publicKey); + * console.log('Decrypted message:', resultMessage); * ``` */ public async decrypt( @@ -233,19 +169,13 @@ export class Encryption { /** * This function signs a message using the private key used to initialize the client. * - * @param {string} message Message to sign. - * @returns {Promise} Message signed. - * - * **Code example** + * @param message - Message to sign. + * @returns Message signed. * + * @example * ```ts - * import { Encryption } from '@human-protocol/sdk'; - * - * const privateKey = 'Armored_priv_key'; - * const passphrase = 'example_passphrase'; - * const encryption = await Encryption.build(privateKey, passphrase); - * * const resultMessage = await encryption.sign('message'); + * console.log('Signed message:', resultMessage); * ``` */ public async sign(message: string): Promise { @@ -263,56 +193,23 @@ export class Encryption { } /** - * ## Introduction - * * Utility class for encryption-related operations. - * - * ## Installation - * - * ### npm - * ```bash - * npm install @human-protocol/sdk - * ``` - * - * ### yarn - * ```bash - * yarn install @human-protocol/sdk - * ``` - * - * ## Code example - * - * ```ts - * import { EncryptionUtils } from '@human-protocol/sdk'; - * - * const keyPair = await EncryptionUtils.generateKeyPair('Human', 'human@hmt.ai'); - * ``` */ export class EncryptionUtils { /** * This function verifies the signature of a signed message using the public key. * - * @param {string} message Message to verify. - * @param {string} publicKey Public key to verify that the message was signed by a specific source. - * @returns {Promise} True if verified. False if not verified. - * - * **Code example** + * @param message - Message to verify. + * @param publicKey - Public key to verify that the message was signed by a specific source. + * @returns True if verified. False if not verified. * + * @example * ```ts * import { EncryptionUtils } from '@human-protocol/sdk'; * - * const publicKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- - * xjMEZKQEMxYJKwYBBAHaRw8BAQdA5oZTq4UPlS0IXn4kEaSqQdAa9+Cq522v - * WYxJQn3vo1/NFEh1bWFuIDxodW1hbkBobXQuYWk+wowEEBYKAD4FAmSkBDME - * CwkHCAkQJBFPuuhtQo4DFQgKBBYAAgECGQECGwMCHgEWIQTQ5fbVPB9CWIdf - * XdYkEU+66G1CjgAAKYYA/jMyDCtJtqu6hj22kq9SW6fuV1FCT2ySJ9vBhumF - * X8wWAP433zVFl4VECOkgGk8qFr8BgkYxaz16GOFAqYbfO6oMBc44BGSkBDMS - * CisGAQQBl1UBBQEBB0AKR+A48zVVYZWQvgu7Opn2IGvzI9jePB/J8pzqRhg2 - * YAMBCAfCeAQYFggAKgUCZKQEMwkQJBFPuuhtQo4CGwwWIQTQ5fbVPB9CWIdf - * XdYkEU+66G1CjgAA0xgBAK4AIahFFnmWR2Mp6A3q021cZXpGklc0Xw1Hfswc - * UYLqAQDfdym4kiUvKO1+REKASt0Gwykndl7hra9txqlUL5DXBQ===Vwgv - * -----END PGP PUBLIC KEY BLOCK-----`; - * + * const publicKey = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; * const result = await EncryptionUtils.verify('message', publicKey); + * console.log('Verification result:', result); * ``` */ public static async verify( @@ -337,15 +234,16 @@ export class EncryptionUtils { /** * This function gets signed data from a signed message. * - * @param {string} message Message. - * @returns {Promise} Signed data. - * - * **Code example** + * @param message - Message. + * @returns Signed data. + * @throws Error If data could not be extracted from the message * + * @example * ```ts * import { EncryptionUtils } from '@human-protocol/sdk'; * * const signedData = await EncryptionUtils.getSignedData('message'); + * console.log('Signed data:', signedData); * ``` */ public static async getSignedData(message: string): Promise { @@ -363,20 +261,20 @@ export class EncryptionUtils { /** * This function generates a key pair for encryption and decryption. * - * @param {string} name Name for the key pair. - * @param {string} email Email for the key pair. - * @param {string} passphrase Passphrase to encrypt the private key. Optional. - * @returns {Promise} Key pair generated. - * - * **Code example** + * @param name - Name for the key pair. + * @param email - Email for the key pair. + * @param passphrase - Passphrase to encrypt the private key (optional, defaults to empty string). + * @returns Key pair generated. * + * @example * ```ts * import { EncryptionUtils } from '@human-protocol/sdk'; * * const name = 'YOUR_NAME'; * const email = 'YOUR_EMAIL'; * const passphrase = 'YOUR_PASSPHRASE'; - * const result = await EncryptionUtils.generateKeyPair(name, email, passphrase); + * const keyPair = await EncryptionUtils.generateKeyPair(name, email, passphrase); + * console.log('Public key:', keyPair.publicKey); * ``` */ public static async generateKeyPair( @@ -404,41 +302,19 @@ export class EncryptionUtils { /** * This function encrypts a message using the specified public keys. * - * @param {MessageDataType} message Message to encrypt. - * @param {string[]} publicKeys Array of public keys to use for encryption. - * @returns {Promise} Message encrypted. - * - * **Code example** + * @param message - Message to encrypt. + * @param publicKeys - Array of public keys to use for encryption. + * @returns Message encrypted. * + * @example * ```ts * import { EncryptionUtils } from '@human-protocol/sdk'; * - * const publicKey1 = `-----BEGIN PGP PUBLIC KEY BLOCK----- - * xjMEZKQEMxYJKwYBBAHaRw8BAQdA5oZTq4UPlS0IXn4kEaSqQdAa9+Cq522v - * WYxJQn3vo1/NFEh1bWFuIDxodW1hbkBobXQuYWk+wowEEBYKAD4FAmSkBDME - * CwkHCAkQJBFPuuhtQo4DFQgKBBYAAgECGQECGwMCHgEWIQTQ5fbVPB9CWIdf - * XdYkEU+66G1CjgAAKYYA/jMyDCtJtqu6hj22kq9SW6fuV1FCT2ySJ9vBhumF - * X8wWAP433zVFl4VECOkgGk8qFr8BgkYxaz16GOFAqYbfO6oMBc44BGSkBDMS - * CisGAQQBl1UBBQEBB0AKR+A48zVVYZWQvgu7Opn2IGvzI9jePB/J8pzqRhg2 - * YAMBCAfCeAQYFggAKgUCZKQEMwkQJBFPuuhtQo4CGwwWIQTQ5fbVPB9CWIdf - * XdYkEU+66G1CjgAA0xgBAK4AIahFFnmWR2Mp6A3q021cZXpGklc0Xw1Hfswc - * UYLqAQDfdym4kiUvKO1+REKASt0Gwykndl7hra9txqlUL5DXBQ===Vwgv - * -----END PGP PUBLIC KEY BLOCK-----`; - * - * const publicKey2 = `-----BEGIN PGP PUBLIC KEY BLOCK----- - * xjMEZKQEMxYJKwYBBAHaRw8BAQdAG6h+E+6T/RV2tIHer3FP/jKThAyGcoVx - * FzhnP0hncPzNFEh1bWFuIDxodW1hbkBobXQuYWk+wowEEBYKAD4FAmSkBDME - * CwkHCAkQPIq5xLhlTYkDFQgKBBYAAgECGQECGwMCHgEWIQTcxtMgul/AeUvH - * bio8irnEuGVNiQAA/HsBANpfFkxNYixpsBk8LlaaCaPy5f1/cWNPgODM9uzo - * ciSTAQDtAYynu4dSJO9GbMuDuc0FaUHRWJK3mS6JkvedYL4oBM44BGSkBDMS - * CisGAQQBl1UBBQEBB0DWbEG7DMhkeSc8ZPzrH8XNSCqS3t9y/oQidFR+xN3Z - * bAMBCAfCeAQYFggAKgUCZKQEMwkQPIq5xLhlTYkCGwwWIQTcxtMgul/AeUvH - * bio8irnEuGVNiQAAqt8BAM/4Lw0RVOb0L5Ki9CyxO/6AKvRg4ra3Q3WR+duP - * s/88AQCDErzvn+SOX4s3gvZcM3Vr4wh4Q2syHV8Okgx8STYPDg===DsVk - * -----END PGP PUBLIC KEY BLOCK-----`; - * - * const publicKeys = [publicKey1, publicKey2] - * const result = await EncryptionUtils.encrypt('message', publicKeys); + * const publicKey1 = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; + * const publicKey2 = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; + * const publicKeys = [publicKey1, publicKey2]; + * const encryptedMessage = await EncryptionUtils.encrypt('message', publicKeys); + * console.log('Encrypted message:', encryptedMessage); * ``` */ public static async encrypt( @@ -464,25 +340,15 @@ export class EncryptionUtils { /** * Verifies if a message appears to be encrypted with OpenPGP. * - * @param {string} message Message to verify. - * @returns {Promise} `true` if the message appears to be encrypted, `false` if not. - * - * **Code example:** + * @param message - Message to verify. + * @returns `true` if the message appears to be encrypted, `false` if not. * + * @example * ```ts - * const message = `-----BEGIN PGP MESSAGE----- - * - * wV4DqdeRpqH+jaISAQdAsvBFxikvjxRqC7ZlDe98cLd7/aeCEI/AcL8PpVKK - * mC0wKlwxNg/ADi55z9jcYFuMC4kKE+C/teM+JqiI8DO9AwassQUvKFtULnpx - * h2jaOjC/0sAQASjUsIFK8zbuDgk/P8T9Npn6px+GlJPg9K90iwtPWiIp0eyW - * 4zXamJZT51k2DyaUX/Rsc6P4PYhQRKjt0yxtH0jHPmKkLC/9eBeFf4GP0zlZ - * 18xMZ8uCpQCma708Gz0sJYxEz3u/eZdHD7Mc7tWQKyJG8MsTwM1P+fdK1X75 - * L9UryJG2AY+6kKZhG4dqjNxiO4fWluiB2u7iMF+iLEyE3SQCEYorWMC+NDWi - * QIJZ7oQ2w7BaPo1a991gvTOSNm5v2x44KfqPI1uj859BjsQTCA== - * =tsmI - * -----END PGP MESSAGE-----`; + * import { EncryptionUtils } from '@human-protocol/sdk'; * - * const isEncrypted = await EncryptionUtils.isEncrypted(message); + * const message = '-----BEGIN PGP MESSAGE-----...'; + * const isEncrypted = EncryptionUtils.isEncrypted(message); * * if (isEncrypted) { * console.log('The message is encrypted with OpenPGP.'); diff --git a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts b/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts index 6ade2c66e6..065bd369fb 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts @@ -77,71 +77,52 @@ import { } from './utils'; /** - * ## Introduction - * - * This client enables performing actions on Escrow contracts and obtaining information from both the contracts and subgraph. + * Client to perform actions on Escrow contracts and obtain information from the contracts. * * Internally, the SDK will use one network or another according to the network ID of the `runner`. - * To use this client, it is recommended to initialize it using the static `build` method. - * - * ```ts - * static async build(runner: ContractRunner): Promise; - * ``` + * To use this client, it is recommended to initialize it using the static [`build`](/ts/classes/EscrowClient/#build) method. * * A `Signer` or a `Provider` should be passed depending on the use case of this module: * * - **Signer**: when the user wants to use this model to send transactions calling the contract functions. * - **Provider**: when the user wants to use this model to get information from the contracts or subgraph. * - * ## Installation - * - * ### npm - * ```bash - * npm install @human-protocol/sdk - * ``` - * - * ### yarn - * ```bash - * yarn install @human-protocol/sdk - * ``` - * - * ## Code example + * @example * - * ### Signer + * ###Using Signer * - * **Using private key (backend)** + * ####Using private key (backend) * * ```ts * import { EscrowClient } from '@human-protocol/sdk'; - * import { Wallet, providers } from 'ethers'; + * import { Wallet, JsonRpcProvider } from 'ethers'; * * const rpcUrl = 'YOUR_RPC_URL'; * const privateKey = 'YOUR_PRIVATE_KEY'; * - * const provider = new providers.JsonRpcProvider(rpcUrl); + * const provider = new JsonRpcProvider(rpcUrl); * const signer = new Wallet(privateKey, provider); * const escrowClient = await EscrowClient.build(signer); * ``` * - * **Using Wagmi (frontend)** + * ####Using Wagmi (frontend) * * ```ts - * import { useSigner, useChainId } from 'wagmi'; + * import { useSigner } from 'wagmi'; * import { EscrowClient } from '@human-protocol/sdk'; * * const { data: signer } = useSigner(); * const escrowClient = await EscrowClient.build(signer); * ``` * - * ### Provider + * ###Using Provider * * ```ts * import { EscrowClient } from '@human-protocol/sdk'; - * import { providers } from 'ethers'; + * import { JsonRpcProvider } from 'ethers'; * * const rpcUrl = 'YOUR_RPC_URL'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); + * const provider = new JsonRpcProvider(rpcUrl); * const escrowClient = await EscrowClient.build(provider); * ``` */ @@ -151,8 +132,9 @@ export class EscrowClient extends BaseEthersClient { /** * **EscrowClient constructor** * - * @param {ContractRunner} runner The Runner object to interact with the Ethereum network - * @param {NetworkData} networkData The network information required to connect to the Escrow contract + * @param runner - The Runner object to interact with the Ethereum network + * @param networkData - The network information required to connect to the Escrow contract + * @returns An instance of EscrowClient */ constructor(runner: ContractRunner, networkData: NetworkData) { super(runner, networkData); @@ -166,11 +148,10 @@ export class EscrowClient extends BaseEthersClient { /** * Creates an instance of EscrowClient from a Runner. * - * @param {ContractRunner} runner The Runner object to interact with the Ethereum network - * - * @returns {Promise} An instance of EscrowClient - * @throws {ErrorProviderDoesNotExist} Thrown if the provider does not exist for the provided Signer - * @throws {ErrorUnsupportedChainID} Thrown if the network's chainId is not supported + * @param runner - The Runner object to interact with the Ethereum network + * @returns An instance of EscrowClient + * @throws ErrorProviderDoesNotExist If the provider does not exist for the provided Signer + * @throws ErrorUnsupportedChainID If the network's chainId is not supported */ public static async build(runner: ContractRunner): Promise { if (!runner.provider) { @@ -204,28 +185,17 @@ export class EscrowClient extends BaseEthersClient { /** * This function creates an escrow contract that uses the token passed to pay oracle fees and reward workers. + * @remarks Need to have available stake. + * @param tokenAddress - The address of the token to use for escrow funding. + * @param jobRequesterId - Identifier for the job requester. + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @returns Returns the address of the escrow created. + * @throws ErrorInvalidTokenAddress If the token address is invalid + * @throws ErrorLaunchedEventIsNotEmitted If the LaunchedV2 event is not emitted * - * @param {string} tokenAddress - The address of the token to use for escrow funding. - * @param {string} jobRequesterId - Identifier for the job requester. - * @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object). - * @returns {Promise} Returns the address of the escrow created. - * - * - * **Code example** - * - * > Need to have available stake. + * @example * * ```ts - * import { Wallet, providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * const privateKey = 'YOUR_PRIVATE_KEY'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const signer = new Wallet(privateKey, provider); - * const escrowClient = await EscrowClient.build(signer); - * * const tokenAddress = '0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4'; * const jobRequesterId = "job-requester-id"; * const escrowAddress = await escrowClient.createEscrow(tokenAddress, jobRequesterId); @@ -315,50 +285,45 @@ export class EscrowClient extends BaseEthersClient { /** * Creates, funds, and sets up a new escrow contract in a single transaction. * - * @param {string} tokenAddress - The ERC-20 token address used to fund the escrow. - * @param {bigint} amount - The token amount to fund the escrow with. - * @param {string} jobRequesterId - An off-chain identifier for the job requester. - * @param {IEscrowConfig} escrowConfig - Configuration parameters for escrow setup: - * - `recordingOracle`: Address of the recording oracle. - * - `reputationOracle`: Address of the reputation oracle. - * - `exchangeOracle`: Address of the exchange oracle. - * - `recordingOracleFee`: Fee (in basis points or percentage * 100) for the recording oracle. - * - `reputationOracleFee`: Fee for the reputation oracle. - * - `exchangeOracleFee`: Fee for the exchange oracle. - * - `manifest`: URL to the manifest file. - * - `manifestHash`: Hash of the manifest content. - * @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object). - * - * @returns {Promise} Returns the address of the escrow created. + * @remarks Need to have available stake and approve allowance in the token contract before calling this method. + * @param tokenAddress - The ERC-20 token address used to fund the escrow. + * @param amount - The token amount to fund the escrow with. + * @param jobRequesterId - An off-chain identifier for the job requester. + * @param escrowConfig - Configuration parameters for escrow setup. + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @returns Returns the address of the escrow created. + * @throws ErrorInvalidTokenAddress If the token address is invalid + * @throws ErrorInvalidRecordingOracleAddressProvided If the recording oracle address is invalid + * @throws ErrorInvalidReputationOracleAddressProvided If the reputation oracle address is invalid + * @throws ErrorInvalidExchangeOracleAddressProvided If the exchange oracle address is invalid + * @throws ErrorAmountMustBeGreaterThanZero If any oracle fee is less than or equal to zero + * @throws ErrorTotalFeeMustBeLessThanHundred If the total oracle fees exceed 100 + * @throws ErrorInvalidManifest If the manifest is not a valid URL or JSON string + * @throws ErrorHashIsEmptyString If the manifest hash is empty + * @throws ErrorLaunchedEventIsNotEmitted If the LaunchedV2 event is not emitted * * @example - * import { Wallet, ethers } from 'ethers'; - * import { EscrowClient, IERC20__factory } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * const privateKey = 'YOUR_PRIVATE_KEY'; - * const provider = new ethers.JsonRpcProvider(rpcUrl); - * const signer = new Wallet(privateKey, provider); - * - * const escrowClient = await EscrowClient.build(signer); + * ```ts + * import { ethers } from 'ethers'; + * import { ERC20__factory } from '@human-protocol/sdk'; * - * const tokenAddress = '0xTokenAddress'; + * const tokenAddress = '0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4'; * const amount = ethers.parseUnits('1000', 18); * const jobRequesterId = 'requester-123'; * - * const token = IERC20__factory.connect(tokenAddress, signer); + * const token = ERC20__factory.connect(tokenAddress, signer); * await token.approve(escrowClient.escrowFactoryContract.target, amount); * * const escrowConfig = { - * recordingOracle: '0xRecordingOracle', - * reputationOracle: '0xReputationOracle', - * exchangeOracle: '0xExchangeOracle', + * recordingOracle: '0xRecordingOracleAddress', + * reputationOracle: '0xReputationOracleAddress', + * exchangeOracle: '0xExchangeOracleAddress', * recordingOracleFee: 5n, * reputationOracleFee: 5n, * exchangeOracleFee: 5n, * manifest: 'https://example.com/manifest.json', * manifestHash: 'manifestHash-123', - * } satisfies IEscrowConfig; + * }; * * const escrowAddress = await escrowClient.createFundAndSetupEscrow( * tokenAddress, @@ -366,8 +331,8 @@ export class EscrowClient extends BaseEthersClient { * jobRequesterId, * escrowConfig * ); - * * console.log('Escrow created at:', escrowAddress); + * ``` */ @requiresSigner public async createFundAndSetupEscrow( @@ -431,35 +396,33 @@ export class EscrowClient extends BaseEthersClient { /** * This function sets up the parameters of the escrow. * - * @param {string} escrowAddress Address of the escrow to set up. - * @param {IEscrowConfig} escrowConfig Escrow configuration parameters. - * @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object). - * @returns Returns void if successful. Throws error if any. + * @remarks Only Job Launcher or admin can call it. + * + * @param escrowAddress - Address of the escrow to set up. + * @param escrowConfig - Escrow configuration parameters. + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @returns - + * @throws ErrorInvalidRecordingOracleAddressProvided If the recording oracle address is invalid + * @throws ErrorInvalidReputationOracleAddressProvided If the reputation oracle address is invalid + * @throws ErrorInvalidExchangeOracleAddressProvided If the exchange oracle address is invalid + * @throws ErrorAmountMustBeGreaterThanZero If any oracle fee is less than or equal to zero + * @throws ErrorTotalFeeMustBeLessThanHundred If the total oracle fees exceed 100 + * @throws ErrorInvalidManifest If the manifest is not a valid URL or JSON string + * @throws ErrorHashIsEmptyString If the manifest hash is empty + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory * - * - * **Code example** - * - * > Only Job Launcher or admin can call it. + * @example * * ```ts - * import { Wallet, providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * const privateKey = 'YOUR_PRIVATE_KEY'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const signer = new Wallet(privateKey, provider); - * const escrowClient = await EscrowClient.build(signer); - * * const escrowAddress = '0x62dD51230A30401C455c8398d06F85e4EaB6309f'; * const escrowConfig = { * recordingOracle: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', * reputationOracle: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', * exchangeOracle: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', - * recordingOracleFee: BigInt('10'), - * reputationOracleFee: BigInt('10'), - * exchangeOracleFee: BigInt('10'), + * recordingOracleFee: 10n, + * reputationOracleFee: 10n, + * exchangeOracleFee: 10n, * manifest: 'http://localhost/manifest.json', * manifestHash: 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079', * }; @@ -519,26 +482,19 @@ export class EscrowClient extends BaseEthersClient { /** * This function adds funds of the chosen token to the escrow. * - * @param {string} escrowAddress Address of the escrow to fund. - * @param {bigint} amount Amount to be added as funds. - * @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object). - * @returns Returns void if successful. Throws error if any. - * - * - * **Code example** + * @param escrowAddress - Address of the escrow to fund. + * @param amount - Amount to be added as funds. + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @returns - + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorAmountMustBeGreaterThanZero If the amount is less than or equal to zero + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory * + * @example * ```ts - * import { ethers, Wallet, providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * const privateKey = 'YOUR_PRIVATE_KEY'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const signer = new Wallet(privateKey, provider); - * const escrowClient = await EscrowClient.build(signer); + * import { ethers } from 'ethers'; * - * const amount = ethers.parseUnits(5, 'ether'); //convert from ETH to WEI + * const amount = ethers.parseUnits('5', 'ether'); * await escrowClient.fund('0x62dD51230A30401C455c8398d06F85e4EaB6309f', amount); * ``` */ @@ -580,75 +536,74 @@ export class EscrowClient extends BaseEthersClient { } /** - * This function stores the results URL and hash. - * - * @param {string} escrowAddress Address of the escrow. - * @param {string} url Results file URL. - * @param {string} hash Results file hash. - * @param {bigint} fundsToReserve Funds to reserve for payouts - * @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object). - * @returns Returns void if successful. Throws error if any. - * + * Stores the result URL and result hash for an escrow. * - * **Code example** + * @remarks Only Recording Oracle or admin can call it. * - * > Only Recording Oracle or admin can call it. + * @param escrowAddress - The escrow address. + * @param url - The URL containing the final results. May be empty only when `fundsToReserve` is `0n`. + * @param hash - The hash of the results payload. + * @param txOptions - Optional transaction overrides. + * @returns - + * @throws ErrorInvalidEscrowAddressProvided If the provided escrow address is invalid. + * @throws ErrorInvalidUrl If the URL format is invalid. + * @throws ErrorHashIsEmptyString If the hash is empty and empty values are not allowed. + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow does not exist in the factory. + * @throws ErrorStoreResultsVersion If the contract supports only the deprecated signature. * + * @example * ```ts - * import { ethers, Wallet, providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * const privateKey = 'YOUR_PRIVATE_KEY'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const signer = new Wallet(privateKey, provider); - * const escrowClient = await EscrowClient.build(signer); - * - * await escrowClient.storeResults('0x62dD51230A30401C455c8398d06F85e4EaB6309f', 'http://localhost/results.json', 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079', ethers.parseEther('10')); + * await escrowClient.storeResults( + * '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + * 'https://example.com/results.json', + * '0xHASH123' + * ); * ``` */ - async storeResults( escrowAddress: string, url: string, hash: string, - fundsToReserve: bigint, txOptions?: Overrides ): Promise; /** - * This function stores the results URL and hash. - * - * @param {string} escrowAddress Address of the escrow. - * @param {string} url Results file URL. - * @param {string} hash Results file hash. - * @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object). - * @returns Returns void if successful. Throws error if any. + * Stores the result URL and result hash for an escrow. * + * @remarks Only Recording Oracle or admin can call it. * - * **Code example** + * If `fundsToReserve` is provided, the escrow reserves the specified funds. + * When `fundsToReserve` is `0n`, an empty URL is allowed (for cases where no solutions were provided). * - * > Only Recording Oracle or admin can call it. + * @param escrowAddress - The escrow address. + * @param url - The URL containing the final results. May be empty only when `fundsToReserve` is `0n`. + * @param hash - The hash of the results payload. + * @param fundsToReserve - Optional amount of funds to reserve (when using second overload). + * @param txOptions - Optional transaction overrides. + * @returns - + * @throws ErrorInvalidEscrowAddressProvided If the provided escrow address is invalid. + * @throws ErrorInvalidUrl If the URL format is invalid. + * @throws ErrorHashIsEmptyString If the hash is empty and empty values are not allowed. + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow does not exist in the factory. + * @throws ErrorStoreResultsVersion If the contract supports only the deprecated signature. * + * @example * ```ts - * import { ethers, Wallet, providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * const privateKey = 'YOUR_PRIVATE_KEY'; + * import { ethers } from 'ethers'; * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const signer = new Wallet(privateKey, provider); - * const escrowClient = await EscrowClient.build(signer); - * - * await escrowClient.storeResults('0x62dD51230A30401C455c8398d06F85e4EaB6309f', 'http://localhost/results.json', 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079'); + * await escrowClient.storeResults( + * '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + * 'https://example.com/results.json', + * '0xHASH123', + * ethers.parseEther('5') + * ); * ``` */ async storeResults( escrowAddress: string, url: string, hash: string, + fundsToReserve: bigint, txOptions?: Overrides ): Promise; @@ -715,27 +670,15 @@ export class EscrowClient extends BaseEthersClient { /** * This function sets the status of an escrow to completed. + * @remarks Only Recording Oracle or admin can call it. + * @param escrowAddress - Address of the escrow. + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @returns - + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid. + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory. * - * @param {string} escrowAddress Address of the escrow. - * @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object). - * @returns Returns void if successful. Throws error if any. - * - * - * **Code example** - * - * > Only Recording Oracle or admin can call it. - * + * @example * ```ts - * import { Wallet, providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * const privateKey = 'YOUR_PRIVATE_KEY'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const signer = new Wallet(privateKey, provider); - * const escrowClient = await EscrowClient.build(signer); - * * await escrowClient.complete('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); * ``` */ @@ -764,40 +707,48 @@ export class EscrowClient extends BaseEthersClient { /** * This function pays out the amounts specified to the workers and sets the URL of the final results file. + * @remarks Only Reputation Oracle or admin can call it. + * + * @param escrowAddress - Escrow address to payout. + * @param recipients - Array of recipient addresses. + * @param amounts - Array of amounts the recipients will receive. + * @param finalResultsUrl - Final results file URL. + * @param finalResultsHash - Final results file hash. + * @param txId - Transaction ID. + * @param forceComplete - Indicates if remaining balance should be transferred to the escrow creator (optional, defaults to false). + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @returns - + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorRecipientCannotBeEmptyArray If the recipients array is empty + * @throws ErrorTooManyRecipients If there are too many recipients + * @throws ErrorAmountsCannotBeEmptyArray If the amounts array is empty + * @throws ErrorRecipientAndAmountsMustBeSameLength If recipients and amounts arrays have different lengths + * @throws InvalidEthereumAddressError If any recipient address is invalid + * @throws ErrorInvalidUrl If the final results URL is invalid + * @throws ErrorHashIsEmptyString If the final results hash is empty + * @throws ErrorEscrowDoesNotHaveEnoughBalance If the escrow doesn't have enough balance + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + * @throws ErrorBulkPayOutVersion If using deprecated signature * - * @param {string} escrowAddress Escrow address to payout. - * @param {string[]} recipients Array of recipient addresses. - * @param {bigint[]} amounts Array of amounts the recipients will receive. - * @param {string} finalResultsUrl Final results file URL. - * @param {string} finalResultsHash Final results file hash. - * @param {number} txId Transaction ID. - * @param {boolean} forceComplete Indicates if remaining balance should be transferred to the escrow creator (optional, defaults to false). - * @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object). - * @returns Returns void if successful. Throws error if any. - * - * - * **Code example** - * - * > Only Reputation Oracle or admin can call it. - * + * @example * ```ts - * import { ethers, Wallet, providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * const privateKey = 'YOUR_PRIVATE_KEY'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const signer = new Wallet(privateKey, provider); - * const escrowClient = await EscrowClient.build(signer); + * import { ethers } from 'ethers'; * - * const recipients = ['0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266']; - * const amounts = [ethers.parseUnits(5, 'ether'), ethers.parseUnits(10, 'ether')]; + * const recipients = ['0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', '0x70997970C51812dc3A010C7d01b50e0d17dc79C8']; + * const amounts = [ethers.parseUnits('5', 'ether'), ethers.parseUnits('10', 'ether')]; * const resultsUrl = 'http://localhost/results.json'; * const resultsHash = 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079'; * const txId = 1; * - * await escrowClient.bulkPayOut('0x62dD51230A30401C455c8398d06F85e4EaB6309f', recipients, amounts, resultsUrl, resultsHash, txId, true); + * await escrowClient.bulkPayOut( + * '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + * recipients, + * amounts, + * resultsUrl, + * resultsHash, + * txId, + * true + * ); * ``` */ async bulkPayOut( @@ -813,41 +764,49 @@ export class EscrowClient extends BaseEthersClient { /** * This function pays out the amounts specified to the workers and sets the URL of the final results file. + * @remarks Only Reputation Oracle or admin can call it. + * @param escrowAddress - Escrow address to payout. + * @param recipients - Array of recipient addresses. + * @param amounts - Array of amounts the recipients will receive. + * @param finalResultsUrl - Final results file URL. + * @param finalResultsHash - Final results file hash. + * @param payoutId - Payout ID. + * @param forceComplete - Indicates if remaining balance should be transferred to the escrow creator (optional, defaults to false). + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @returns - + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorRecipientCannotBeEmptyArray If the recipients array is empty + * @throws ErrorTooManyRecipients If there are too many recipients + * @throws ErrorAmountsCannotBeEmptyArray If the amounts array is empty + * @throws ErrorRecipientAndAmountsMustBeSameLength If recipients and amounts arrays have different lengths + * @throws InvalidEthereumAddressError If any recipient address is invalid + * @throws ErrorInvalidUrl If the final results URL is invalid + * @throws ErrorHashIsEmptyString If the final results hash is empty + * @throws ErrorEscrowDoesNotHaveEnoughBalance If the escrow doesn't have enough balance + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + * @throws ErrorBulkPayOutVersion If using deprecated signature * - * @param {string} escrowAddress Escrow address to payout. - * @param {string[]} recipients Array of recipient addresses. - * @param {bigint[]} amounts Array of amounts the recipients will receive. - * @param {string} finalResultsUrl Final results file URL. - * @param {string} finalResultsHash Final results file hash. - * @param {string} payoutId Payout ID. - * @param {boolean} forceComplete Indicates if remaining balance should be transferred to the escrow creator (optional, defaults to false). - * @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object). - * @returns Returns void if successful. Throws error if any. - * - * - * **Code example** - * - * > Only Reputation Oracle or admin can call it. + * @example * * ```ts - * import { ethers, Wallet, providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; + * import { ethers } from 'ethers'; * import { v4 as uuidV4 } from 'uuid'; * - * const rpcUrl = 'YOUR_RPC_URL'; - * const privateKey = 'YOUR_PRIVATE_KEY'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const signer = new Wallet(privateKey, provider); - * const escrowClient = await EscrowClient.build(signer); - * - * const recipients = ['0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266']; - * const amounts = [ethers.parseUnits(5, 'ether'), ethers.parseUnits(10, 'ether')]; + * const recipients = ['0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', '0x70997970C51812dc3A010C7d01b50e0d17dc79C8']; + * const amounts = [ethers.parseUnits('5', 'ether'), ethers.parseUnits('10', 'ether')]; * const resultsUrl = 'http://localhost/results.json'; * const resultsHash = 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079'; * const payoutId = uuidV4(); * - * await escrowClient.bulkPayOut('0x62dD51230A30401C455c8398d06F85e4EaB6309f', recipients, amounts, resultsUrl, resultsHash, payoutId, true); + * await escrowClient.bulkPayOut( + * '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + * recipients, + * amounts, + * resultsUrl, + * resultsHash, + * payoutId, + * true + * ); * ``` */ async bulkPayOut( @@ -925,26 +884,16 @@ export class EscrowClient extends BaseEthersClient { /** * This function cancels the specified escrow and sends the balance to the canceler. + * @remarks Only Job Launcher or admin can call it. + * @param escrowAddress - Address of the escrow to cancel. + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @returns - + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory * - * @param {string} escrowAddress Address of the escrow to cancel. - * @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object). - * - * - * **Code example** - * - * > Only Job Launcher or admin can call it. + * @example * * ```ts - * import { ethers, Wallet, providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * const privateKey = 'YOUR_PRIVATE_KEY'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const signer = new Wallet(privateKey, provider); - * const escrowClient = await EscrowClient.build(signer); - * * await escrowClient.cancel('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); * ``` */ @@ -971,26 +920,16 @@ export class EscrowClient extends BaseEthersClient { /** * This function requests the cancellation of the specified escrow (moves status to ToCancel or finalizes if expired). + * @remarks Only Job Launcher or admin can call it. + * @param escrowAddress - Address of the escrow to request cancellation. + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @returns - + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory * - * @param {string} escrowAddress Address of the escrow to request cancellation. - * @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object). - * @returns Returns void if successful. Throws error if any. - * - * **Code example** - * - * > Only Job Launcher or admin can call it. + * @example * * ```ts - * import { Wallet, providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * const privateKey = 'YOUR_PRIVATE_KEY'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const signer = new Wallet(privateKey, provider); - * const escrowClient = await EscrowClient.build(signer); - * * await escrowClient.requestCancellation('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); * ``` */ @@ -1017,32 +956,25 @@ export class EscrowClient extends BaseEthersClient { /** * This function withdraws additional tokens in the escrow to the canceler. + * @remarks Only Job Launcher or admin can call it. * - * @param {string} escrowAddress Address of the escrow to withdraw. - * @param {string} tokenAddress Address of the token to withdraw. - * @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object). - * @returns {IEscrowWithdraw} Returns the escrow withdrawal data including transaction hash and withdrawal amount. Throws error if any. + * @param escrowAddress - Address of the escrow to withdraw. + * @param tokenAddress - Address of the token to withdraw. + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @returns Returns the escrow withdrawal data including transaction hash and withdrawal amount. + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorInvalidTokenAddress If the token address is invalid + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + * @throws ErrorTransferEventNotFoundInTransactionLogs If the Transfer event is not found in transaction logs * - * - * **Code example** - * - * > Only Job Launcher or admin can call it. + * @example * * ```ts - * import { ethers, Wallet, providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * const privateKey = 'YOUR_PRIVATE_KEY'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const signer = new Wallet(privateKey, provider); - * const escrowClient = await EscrowClient.build(signer); - * - * await escrowClient.withdraw( + * const withdrawData = await escrowClient.withdraw( * '0x62dD51230A30401C455c8398d06F85e4EaB6309f', * '0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4' * ); + * console.log('Withdrawn amount:', withdrawData.withdrawnAmount); * ``` */ @requiresSigner @@ -1108,43 +1040,54 @@ export class EscrowClient extends BaseEthersClient { /** * Creates a prepared transaction for bulk payout without immediately sending it. - * @param {string} escrowAddress Escrow address to payout. - * @param {string[]} recipients Array of recipient addresses. - * @param {bigint[]} amounts Array of amounts the recipients will receive. - * @param {string} finalResultsUrl Final results file URL. - * @param {string} finalResultsHash Final results file hash. - * @param {string} payoutId Payout ID to identify the payout. - * @param {boolean} forceComplete Indicates if remaining balance should be transferred to the escrow creator (optional, defaults to false). - * @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object). - * @returns Returns object with raw transaction and signed transaction hash + * @remarks Only Reputation Oracle or admin can call it. + * + * @param escrowAddress - Escrow address to payout. + * @param recipients - Array of recipient addresses. + * @param amounts - Array of amounts the recipients will receive. + * @param finalResultsUrl - Final results file URL. + * @param finalResultsHash - Final results file hash. + * @param payoutId - Payout ID to identify the payout. + * @param forceComplete - Indicates if remaining balance should be transferred to the escrow creator (optional, defaults to false). + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @returns Returns object with raw transaction and nonce + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorRecipientCannotBeEmptyArray If the recipients array is empty + * @throws ErrorTooManyRecipients If there are too many recipients + * @throws ErrorAmountsCannotBeEmptyArray If the amounts array is empty + * @throws ErrorRecipientAndAmountsMustBeSameLength If recipients and amounts arrays have different lengths + * @throws InvalidEthereumAddressError If any recipient address is invalid + * @throws ErrorInvalidUrl If the final results URL is invalid + * @throws ErrorHashIsEmptyString If the final results hash is empty + * @throws ErrorEscrowDoesNotHaveEnoughBalance If the escrow doesn't have enough balance + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory * - * **Code example** - * - * > Only Reputation Oracle or admin can call it. + * @example * * ```ts - * import { ethers, Wallet, providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * const privateKey = 'YOUR_PRIVATE_KEY' - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const signer = new Wallet(privateKey, provider); - * const escrowClient = await EscrowClient.build(signer); + * import { ethers } from 'ethers'; + * import { v4 as uuidV4 } from 'uuid'; * - * const recipients = ['0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266']; - * const amounts = [ethers.parseUnits(5, 'ether'), ethers.parseUnits(10, 'ether')]; + * const recipients = ['0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', '0x70997970C51812dc3A010C7d01b50e0d17dc79C8']; + * const amounts = [ethers.parseUnits('5', 'ether'), ethers.parseUnits('10', 'ether')]; * const resultsUrl = 'http://localhost/results.json'; * const resultsHash = 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079'; - * const payoutId = '372f6916-fe34-4711-b6e3-274f682047de'; + * const payoutId = uuidV4(); * - * const rawTransaction = await escrowClient.createBulkPayoutTransaction('0x62dD51230A30401C455c8398d06F85e4EaB6309f', recipients, amounts, resultsUrl, resultsHash, txId); + * const rawTransaction = await escrowClient.createBulkPayoutTransaction( + * '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + * recipients, + * amounts, + * resultsUrl, + * resultsHash, + * payoutId + * ); * console.log('Raw transaction:', rawTransaction); * * const signedTransaction = await signer.signTransaction(rawTransaction); * console.log('Tx hash:', ethers.keccak256(signedTransaction)); - * (await signer.sendTransaction(rawTransaction)).wait(); + * await signer.sendTransaction(rawTransaction); + * ``` */ @requiresSigner async createBulkPayoutTransaction( @@ -1275,21 +1218,15 @@ export class EscrowClient extends BaseEthersClient { /** * This function returns the balance for a specified escrow address. * - * @param {string} escrowAddress Address of the escrow. - * @returns {Promise} Balance of the escrow in the token used to fund it. - * - * **Code example** + * @param escrowAddress - Address of the escrow. + * @returns Balance of the escrow in the token used to fund it. + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory * + * @example * ```ts - * import { providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const escrowClient = await EscrowClient.build(provider); - * * const balance = await escrowClient.getBalance('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + * console.log('Balance:', balance); * ``` */ async getBalance(escrowAddress: string): Promise { @@ -1319,21 +1256,15 @@ export class EscrowClient extends BaseEthersClient { /** * This function returns the reserved funds for a specified escrow address. * - * @param {string} escrowAddress Address of the escrow. - * @returns {Promise} Reserved funds of the escrow in the token used to fund it. - * - * **Code example** + * @param escrowAddress - Address of the escrow. + * @returns Reserved funds of the escrow in the token used to fund it. + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory * + * @example * ```ts - * import { providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const escrowClient = await EscrowClient.build(provider); - * * const reservedFunds = await escrowClient.getReservedFunds('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + * console.log('Reserved funds:', reservedFunds); * ``` */ async getReservedFunds(escrowAddress: string): Promise { @@ -1356,21 +1287,15 @@ export class EscrowClient extends BaseEthersClient { /** * This function returns the manifest file hash. * - * @param {string} escrowAddress Address of the escrow. - * @returns {Promise} Hash of the manifest file content. - * - * **Code example** + * @param escrowAddress - Address of the escrow. + * @returns Hash of the manifest file content. + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory * + * @example * ```ts - * import { providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const escrowClient = await EscrowClient.build(provider); - * * const manifestHash = await escrowClient.getManifestHash('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + * console.log('Manifest hash:', manifestHash); * ``` */ async getManifestHash(escrowAddress: string): Promise { @@ -1394,21 +1319,15 @@ export class EscrowClient extends BaseEthersClient { /** * This function returns the manifest. Could be a URL or a JSON string. * - * @param {string} escrowAddress Address of the escrow. - * @returns {Promise} Url of the manifest. - * - * **Code example** + * @param escrowAddress - Address of the escrow. + * @returns Manifest URL or JSON string. + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory * + * @example * ```ts - * import { providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const escrowClient = await EscrowClient.build(provider); - * * const manifest = await escrowClient.getManifest('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + * console.log('Manifest:', manifest); * ``` */ async getManifest(escrowAddress: string): Promise { @@ -1432,21 +1351,15 @@ export class EscrowClient extends BaseEthersClient { /** * This function returns the results file URL. * - * @param {string} escrowAddress Address of the escrow. - * @returns {Promise} Results file url. - * - * **Code example** + * @param escrowAddress - Address of the escrow. + * @returns Results file URL. + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory * + * @example * ```ts - * import { providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const escrowClient = await EscrowClient.build(provider); - * * const resultsUrl = await escrowClient.getResultsUrl('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + * console.log('Results URL:', resultsUrl); * ``` */ async getResultsUrl(escrowAddress: string): Promise { @@ -1470,21 +1383,15 @@ export class EscrowClient extends BaseEthersClient { /** * This function returns the intermediate results file URL. * - * @param {string} escrowAddress Address of the escrow. - * @returns {Promise} Url of the file that store results from Recording Oracle. - * - * **Code example** + * @param escrowAddress - Address of the escrow. + * @returns URL of the file that stores results from Recording Oracle. + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory * + * @example * ```ts - * import { providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const escrowClient = await EscrowClient.build(provider); - * * const intermediateResultsUrl = await escrowClient.getIntermediateResultsUrl('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + * console.log('Intermediate results URL:', intermediateResultsUrl); * ``` */ async getIntermediateResultsUrl(escrowAddress: string): Promise { @@ -1508,21 +1415,15 @@ export class EscrowClient extends BaseEthersClient { /** * This function returns the intermediate results hash. * - * @param {string} escrowAddress Address of the escrow. - * @returns {Promise} Hash of the intermediate results file content. - * - * **Code example** + * @param escrowAddress - Address of the escrow. + * @returns Hash of the intermediate results file content. + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory * + * @example * ```ts - * import { providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const escrowClient = await EscrowClient.build(provider); - * * const intermediateResultsHash = await escrowClient.getIntermediateResultsHash('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + * console.log('Intermediate results hash:', intermediateResultsHash); * ``` */ async getIntermediateResultsHash(escrowAddress: string): Promise { @@ -1546,21 +1447,15 @@ export class EscrowClient extends BaseEthersClient { /** * This function returns the token address used for funding the escrow. * - * @param {string} escrowAddress Address of the escrow. - * @returns {Promise} Address of the token used to fund the escrow. - * - * **Code example** + * @param escrowAddress - Address of the escrow. + * @returns Address of the token used to fund the escrow. + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory * + * @example * ```ts - * import { providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const escrowClient = await EscrowClient.build(provider); - * * const tokenAddress = await escrowClient.getTokenAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + * console.log('Token address:', tokenAddress); * ``` */ async getTokenAddress(escrowAddress: string): Promise { @@ -1584,21 +1479,17 @@ export class EscrowClient extends BaseEthersClient { /** * This function returns the current status of the escrow. * - * @param {string} escrowAddress Address of the escrow. - * @returns {Promise} Current status of the escrow. - * - * **Code example** + * @param escrowAddress - Address of the escrow. + * @returns Current status of the escrow. + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory * + * @example * ```ts - * import { providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const escrowClient = await EscrowClient.build(provider); + * import { EscrowStatus } from '@human-protocol/sdk'; * * const status = await escrowClient.getStatus('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + * console.log('Status:', EscrowStatus[status]); * ``` */ async getStatus(escrowAddress: string): Promise { @@ -1622,21 +1513,15 @@ export class EscrowClient extends BaseEthersClient { /** * This function returns the recording oracle address for a given escrow. * - * @param {string} escrowAddress Address of the escrow. - * @returns {Promise} Address of the Recording Oracle. - * - * **Code example** + * @param escrowAddress - Address of the escrow. + * @returns Address of the Recording Oracle. + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory * + * @example * ```ts - * import { providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const escrowClient = await EscrowClient.build(provider); - * * const oracleAddress = await escrowClient.getRecordingOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + * console.log('Recording Oracle address:', oracleAddress); * ``` */ async getRecordingOracleAddress(escrowAddress: string): Promise { @@ -1660,21 +1545,15 @@ export class EscrowClient extends BaseEthersClient { /** * This function returns the job launcher address for a given escrow. * - * @param {string} escrowAddress Address of the escrow. - * @returns {Promise} Address of the Job Launcher. - * - * **Code example** + * @param escrowAddress - Address of the escrow. + * @returns Address of the Job Launcher. + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory * + * @example * ```ts - * import { providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const escrowClient = await EscrowClient.build(provider); - * * const jobLauncherAddress = await escrowClient.getJobLauncherAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + * console.log('Job Launcher address:', jobLauncherAddress); * ``` */ async getJobLauncherAddress(escrowAddress: string): Promise { @@ -1698,21 +1577,15 @@ export class EscrowClient extends BaseEthersClient { /** * This function returns the reputation oracle address for a given escrow. * - * @param {string} escrowAddress Address of the escrow. - * @returns {Promise} Address of the Reputation Oracle. - * - * **Code example** + * @param escrowAddress - Address of the escrow. + * @returns Address of the Reputation Oracle. + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory * + * @example * ```ts - * import { providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const escrowClient = await EscrowClient.build(provider); - * * const oracleAddress = await escrowClient.getReputationOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + * console.log('Reputation Oracle address:', oracleAddress); * ``` */ async getReputationOracleAddress(escrowAddress: string): Promise { @@ -1736,21 +1609,15 @@ export class EscrowClient extends BaseEthersClient { /** * This function returns the exchange oracle address for a given escrow. * - * @param {string} escrowAddress Address of the escrow. - * @returns {Promise} Address of the Exchange Oracle. - * - * **Code example** + * @param escrowAddress - Address of the escrow. + * @returns Address of the Exchange Oracle. + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory * + * @example * ```ts - * import { providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const escrowClient = await EscrowClient.build(provider); - * * const oracleAddress = await escrowClient.getExchangeOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + * console.log('Exchange Oracle address:', oracleAddress); * ``` */ async getExchangeOracleAddress(escrowAddress: string): Promise { @@ -1774,21 +1641,15 @@ export class EscrowClient extends BaseEthersClient { /** * This function returns the escrow factory address for a given escrow. * - * @param {string} escrowAddress Address of the escrow. - * @returns {Promise} Address of the escrow factory. - * - * **Code example** + * @param escrowAddress - Address of the escrow. + * @returns Address of the escrow factory. + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory * + * @example * ```ts - * import { providers } from 'ethers'; - * import { EscrowClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const escrowClient = await EscrowClient.build(provider); - * * const factoryAddress = await escrowClient.getFactoryAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + * console.log('Factory address:', factoryAddress); * ``` */ async getFactoryAddress(escrowAddress: string): Promise { @@ -1810,138 +1671,40 @@ export class EscrowClient extends BaseEthersClient { } } /** - * ## Introduction - * - * Utility class for escrow-related operations. - * - * ## Installation - * - * ### npm - * ```bash - * npm install @human-protocol/sdk - * ``` - * - * ### yarn - * ```bash - * yarn install @human-protocol/sdk - * ``` - * - * ## Code example - * - * ### Signer - * - * **Using private key(backend)** + * Utility helpers for escrow-related queries. * + * @example * ```ts * import { ChainId, EscrowUtils } from '@human-protocol/sdk'; * - * const escrowAddresses = new EscrowUtils.getEscrows({ + * const escrows = await EscrowUtils.getEscrows({ * chainId: ChainId.POLYGON_AMOY * }); + * console.log('Escrows:', escrows); * ``` */ export class EscrowUtils { /** * This function returns an array of escrows based on the specified filter parameters. * + * @param filter - Filter parameters. + * @param options - Optional configuration for subgraph requests. + * @returns List of escrows that match the filter. + * @throws ErrorInvalidAddress If any filter address is invalid + * @throws ErrorUnsupportedChainID If the chain ID is not supported * - * **Input parameters** - * - * ```ts - * interface IEscrowsFilter { - * chainId: ChainId; - * launcher?: string; - * reputationOracle?: string; - * recordingOracle?: string; - * exchangeOracle?: string; - * jobRequesterId?: string; - * status?: EscrowStatus; - * from?: Date; - * to?: Date; - * first?: number; - * skip?: number; - * orderDirection?: OrderDirection; - * } - * ``` - * - * ```ts - * enum ChainId { - * ALL = -1, - * MAINNET = 1, - * SEPOLIA = 11155111, - * BSC_MAINNET = 56, - * BSC_TESTNET = 97, - * POLYGON = 137, - * POLYGON_AMOY=80002, - * LOCALHOST = 1338, - * } - * ``` - * - * ```ts - * enum OrderDirection { - * ASC = 'asc', - * DESC = 'desc', - * } - * ``` - * - * ```ts - * enum EscrowStatus { - * Launched, - * Pending, - * Partial, - * Paid, - * Complete, - * Cancelled, - * } - * ``` - * - * ```ts - * interface IEscrow { - * id: string; - * address: string; - * amountPaid: bigint; - * balance: bigint; - * count: bigint; - * factoryAddress: string; - * finalResultsUrl: string | null; - * finalResultsHash: string | null; - * intermediateResultsUrl: string | null; - * intermediateResultsHash: string | null; - * launcher: string; - * jobRequesterId: string | null; - * manifestHash: string | null; - * manifest: string | null; - * recordingOracle: string | null; - * reputationOracle: string | null; - * exchangeOracle: string | null; - * recordingOracleFee: number | null; - * reputationOracleFee: number | null; - * exchangeOracleFee: number | null; - * status: string; - * token: string; - * totalFundedAmount: bigint; - * createdAt: number; - * chainId: number; - * }; - * ``` - * - * - * @param {IEscrowsFilter} filter Filter parameters. - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {IEscrow[]} List of escrows that match the filter. - * - * **Code example** - * + * @example * ```ts - * import { ChainId, EscrowUtils, EscrowStatus } from '@human-protocol/sdk'; + * import { ChainId, EscrowStatus } from '@human-protocol/sdk'; * - * const filters: IEscrowsFilter = { + * const filters = { * status: EscrowStatus.Pending, * from: new Date(2023, 4, 8), * to: new Date(2023, 5, 8), * chainId: ChainId.POLYGON_AMOY * }; * const escrows = await EscrowUtils.getEscrows(filters); + * console.log('Found escrows:', escrows.length); * ``` */ public static async getEscrows( @@ -2006,63 +1769,24 @@ export class EscrowUtils { * * > This uses Subgraph * - * **Input parameters** - * - * ```ts - * enum ChainId { - * ALL = -1, - * MAINNET = 1, - * SEPOLIA = 11155111, - * BSC_MAINNET = 56, - * BSC_TESTNET = 97, - * POLYGON = 137, - * POLYGON_AMOY = 80002, - * LOCALHOST = 1338, - * } - * ``` - * - * ```ts - * interface IEscrow { - * id: string; - * address: string; - * amountPaid: bigint; - * balance: bigint; - * count: bigint; - * factoryAddress: string; - * finalResultsUrl: string | null; - * finalResultsHash: string | null; - * intermediateResultsUrl: string | null; - * intermediateResultsHash: string | null; - * launcher: string; - * jobRequesterId: string | null; - * manifestHash: string | null; - * manifest: string | null; - * recordingOracle: string | null; - * reputationOracle: string | null; - * exchangeOracle: string | null; - * recordingOracleFee: number | null; - * reputationOracleFee: number | null; - * exchangeOracleFee: number | null; - * status: string; - * token: string; - * totalFundedAmount: bigint; - * createdAt: number; - * chainId: number; - * }; - * ``` - * - * - * @param {ChainId} chainId Network in which the escrow has been deployed - * @param {string} escrowAddress Address of the escrow - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {Promise} - Escrow data or null if not found. - * - * **Code example** + * @param chainId - Network in which the escrow has been deployed + * @param escrowAddress - Address of the escrow + * @param options - Optional configuration for subgraph requests. + * @returns Escrow data or null if not found. + * @throws ErrorUnsupportedChainID If the chain ID is not supported + * @throws ErrorInvalidAddress If the escrow address is invalid * + * @example * ```ts - * import { ChainId, EscrowUtils } from '@human-protocol/sdk'; + * import { ChainId } from '@human-protocol/sdk'; * - * const escrow = new EscrowUtils.getEscrow(ChainId.POLYGON_AMOY, "0x1234567890123456789012345678901234567890"); + * const escrow = await EscrowUtils.getEscrow( + * ChainId.POLYGON_AMOY, + * "0x1234567890123456789012345678901234567890" + * ); + * if (escrow) { + * console.log('Escrow status:', escrow.status); + * } * ``` */ public static async getEscrow( @@ -2096,56 +1820,25 @@ export class EscrowUtils { * * > This uses Subgraph * - * **Input parameters** - * - * ```ts - * enum ChainId { - * ALL = -1, - * MAINNET = 1, - * SEPOLIA = 11155111, - * BSC_MAINNET = 56, - * BSC_TESTNET = 97, - * POLYGON = 137, - * POLYGON_AMOY = 80002, - * LOCALHOST = 1338, - * } - * ``` - * - * ```ts - * enum OrderDirection { - * ASC = 'asc', - * DESC = 'desc', - * } - * ``` + * @param filter - Filter parameters. + * @param options - Optional configuration for subgraph requests. + * @returns Array of status events with their corresponding statuses. + * @throws ErrorInvalidAddress If the launcher address is invalid + * @throws ErrorUnsupportedChainID If the chain ID is not supported * + * @example * ```ts - * type Status = { - * escrowAddress: string; - * timestamp: string; - * status: string; - * }; - * ``` - * - * @param {IStatusEventFilter} filter Filter parameters. - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {Promise} - Array of status events with their corresponding statuses. + * import { ChainId, EscrowStatus } from '@human-protocol/sdk'; * - * **Code example** - * - * ```ts - * import { ChainId, EscrowUtils, EscrowStatus } from '@human-protocol/sdk'; - * - * (async () => { - * const fromDate = new Date('2023-01-01'); - * const toDate = new Date('2023-12-31'); - * const statusEvents = await EscrowUtils.getStatusEvents({ - * chainId: ChainId.POLYGON, - * statuses: [EscrowStatus.Pending, EscrowStatus.Complete], - * from: fromDate, - * to: toDate - * }); - * console.log(statusEvents); - * })(); + * const fromDate = new Date('2023-01-01'); + * const toDate = new Date('2023-12-31'); + * const statusEvents = await EscrowUtils.getStatusEvents({ + * chainId: ChainId.POLYGON, + * statuses: [EscrowStatus.Pending, EscrowStatus.Complete], + * from: fromDate, + * to: toDate + * }); + * console.log('Status events:', statusEvents.length); * ``` */ public static async getStatusEvents( @@ -2218,17 +1911,15 @@ export class EscrowUtils { * * > This uses Subgraph * - * **Input parameters** - * Fetch payouts from the subgraph. - * - * @param {IPayoutFilter} filter Filter parameters. - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {Promise} List of payouts matching the filters. - * - * **Code example** + * @param filter - Filter parameters. + * @param options - Optional configuration for subgraph requests. + * @returns List of payouts matching the filters. + * @throws ErrorUnsupportedChainID If the chain ID is not supported + * @throws ErrorInvalidAddress If any filter address is invalid * + * @example * ```ts - * import { ChainId, EscrowUtils } from '@human-protocol/sdk'; + * import { ChainId } from '@human-protocol/sdk'; * * const payouts = await EscrowUtils.getPayouts({ * chainId: ChainId.POLYGON, @@ -2237,7 +1928,7 @@ export class EscrowUtils { * from: new Date('2023-01-01'), * to: new Date('2023-12-31') * }); - * console.log(payouts); + * console.log('Payouts:', payouts.length); * ``` */ public static async getPayouts( @@ -2292,48 +1983,22 @@ export class EscrowUtils { * * > This uses Subgraph * - * **Input parameters** - * - * ```ts - * enum ChainId { - * ALL = -1, - * MAINNET = 1, - * SEPOLIA = 11155111, - * BSC_MAINNET = 56, - * BSC_TESTNET = 97, - * POLYGON = 137, - * POLYGON_AMOY = 80002, - * LOCALHOST = 1338, - * } - * ``` - * - * ```ts - * interface ICancellationRefund { - * id: string; - * escrowAddress: string; - * receiver: string; - * amount: bigint; - * block: number; - * timestamp: number; - * txHash: string; - * }; - * ``` - * - * - * @param {Object} filter Filter parameters. - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {Promise} List of cancellation refunds matching the filters. - * - * **Code example** + * @param filter - Filter parameters. + * @param options - Optional configuration for subgraph requests. + * @returns List of cancellation refunds matching the filters. + * @throws ErrorUnsupportedChainID If the chain ID is not supported + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorInvalidAddress If the receiver address is invalid * + * @example * ```ts - * import { ChainId, EscrowUtils } from '@human-protocol/sdk'; + * import { ChainId } from '@human-protocol/sdk'; * * const cancellationRefunds = await EscrowUtils.getCancellationRefunds({ * chainId: ChainId.POLYGON_AMOY, * escrowAddress: '0x1234567890123456789012345678901234567890', * }); - * console.log(cancellationRefunds); + * console.log('Cancellation refunds:', cancellationRefunds.length); * ``` */ public static async getCancellationRefunds( @@ -2391,45 +2056,25 @@ export class EscrowUtils { * * > This uses Subgraph * - * **Input parameters** - * - * ```ts - * enum ChainId { - * ALL = -1, - * MAINNET = 1, - * SEPOLIA = 11155111, - * BSC_MAINNET = 56, - * BSC_TESTNET = 97, - * POLYGON = 137, - * POLYGON_AMOY = 80002, - * LOCALHOST = 1338, - * } - * ``` + * @param chainId - Network in which the escrow has been deployed + * @param escrowAddress - Address of the escrow + * @param options - Optional configuration for subgraph requests. + * @returns Cancellation refund data or null if not found. + * @throws ErrorUnsupportedChainID If the chain ID is not supported + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid * + * @example * ```ts - * interface ICancellationRefund { - * id: string; - * escrowAddress: string; - * receiver: string; - * amount: bigint; - * block: number; - * timestamp: number; - * txHash: string; - * }; - * ``` - * - * - * @param {ChainId} chainId Network in which the escrow has been deployed - * @param {string} escrowAddress Address of the escrow - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {Promise} Cancellation refund data + * import { ChainId } from '@human-protocol/sdk'; * - * **Code example** * - * ```ts - * import { ChainId, EscrowUtils } from '@human-protocol/sdk'; - * - * const cancellationRefund = await EscrowUtils.getCancellationRefund(ChainId.POLYGON_AMOY, "0x1234567890123456789012345678901234567890"); + * const cancellationRefund = await EscrowUtils.getCancellationRefund( + * ChainId.POLYGON_AMOY, + * "0x1234567890123456789012345678901234567890" + * ); + * if (cancellationRefund) { + * console.log('Refund amount:', cancellationRefund.amount); + * } * ``` */ public static async getCancellationRefund( diff --git a/packages/sdk/typescript/human-protocol-sdk/src/index.ts b/packages/sdk/typescript/human-protocol-sdk/src/index.ts index 15a363bae2..0e07f51949 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/index.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/index.ts @@ -1,8 +1,8 @@ import { StakingClient, StakingUtils } from './staking'; import { KVStoreClient, KVStoreUtils } from './kvstore'; import { EscrowClient, EscrowUtils } from './escrow'; -import { StatisticsClient } from './statistics'; -import { Encryption, EncryptionUtils } from './encryption'; +import { StatisticsUtils } from './statistics'; +import { Encryption, EncryptionUtils, MessageDataType } from './encryption'; import { OperatorUtils } from './operator'; import { TransactionUtils } from './transaction'; import { WorkerUtils } from './worker'; @@ -30,11 +30,12 @@ export { KVStoreUtils, EscrowClient, EscrowUtils, - StatisticsClient, + StatisticsUtils, Encryption, EncryptionUtils, OperatorUtils, TransactionUtils, WorkerUtils, StakingUtils, + MessageDataType, }; diff --git a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts b/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts index 518217ee01..de4a03457e 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts @@ -26,12 +26,10 @@ import { import { KVStoreData } from './graphql'; import { IKVStore, SubgraphOptions } from './interfaces'; /** - * ## Introduction - * - * This client enables performing actions on KVStore contract and obtaining information from both the contracts and subgraph. + * Client for interacting with the KVStore contract. * * Internally, the SDK will use one network or another according to the network ID of the `runner`. - * To use this client, it is recommended to initialize it using the static `build` method. + * To use this client, it is recommended to initialize it using the static [`build`](/ts/classes/KVStoreClient/#build) method. * * ```ts * static async build(runner: ContractRunner): Promise; @@ -42,37 +40,25 @@ import { IKVStore, SubgraphOptions } from './interfaces'; * - **Signer**: when the user wants to use this model to send transactions calling the contract functions. * - **Provider**: when the user wants to use this model to get information from the contracts or subgraph. * - * ## Installation - * - * ### npm - * ```bash - * npm install @human-protocol/sdk - * ``` - * - * ### yarn - * ```bash - * yarn install @human-protocol/sdk - * ``` - * - * ## Code example + * @example * - * ### Signer + * ###Using Signer * - * **Using private key (backend)** + * ####Using private key (backend) * * ```ts * import { KVStoreClient } from '@human-protocol/sdk'; - * import { Wallet, providers } from 'ethers'; + * import { Wallet, JsonRpcProvider } from 'ethers'; * * const rpcUrl = 'YOUR_RPC_URL'; * const privateKey = 'YOUR_PRIVATE_KEY'; * - * const provider = new providers.JsonRpcProvider(rpcUrl); + * const provider = new JsonRpcProvider(rpcUrl); * const signer = new Wallet(privateKey, provider); * const kvstoreClient = await KVStoreClient.build(signer); * ``` * - * **Using Wagmi (frontend)** + * ####Using Wagmi (frontend) * * ```ts * import { useSigner, useChainId } from 'wagmi'; @@ -82,15 +68,15 @@ import { IKVStore, SubgraphOptions } from './interfaces'; * const kvstoreClient = await KVStoreClient.build(signer); * ``` * - * ### Provider + * ###Using Provider * * ```ts * import { KVStoreClient } from '@human-protocol/sdk'; - * import { providers } from 'ethers'; + * import { JsonRpcProvider } from 'ethers'; * * const rpcUrl = 'YOUR_RPC_URL'; * - * const provider = new providers.JsonRpcProvider(rpcUrl); + * const provider = new JsonRpcProvider(rpcUrl); * const kvstoreClient = await KVStoreClient.build(provider); * ``` */ @@ -101,8 +87,8 @@ export class KVStoreClient extends BaseEthersClient { /** * **KVStoreClient constructor** * - * @param {ContractRunner} runner - The Runner object to interact with the Ethereum network - * @param {NetworkData} networkData - The network information required to connect to the KVStore contract + * @param runner - The Runner object to interact with the Ethereum network + * @param networkData - The network information required to connect to the KVStore contract */ constructor(runner: ContractRunner, networkData: NetworkData) { super(runner, networkData); @@ -116,11 +102,23 @@ export class KVStoreClient extends BaseEthersClient { /** * Creates an instance of KVStoreClient from a runner. * - * @param {ContractRunner} runner - The Runner object to interact with the Ethereum network + * @param runner - The Runner object to interact with the Ethereum network + * @returns An instance of KVStoreClient + * @throws ErrorProviderDoesNotExist If the provider does not exist for the provided Signer + * @throws ErrorUnsupportedChainID If the network's chainId is not supported * - * @returns {Promise} - An instance of KVStoreClient - * @throws {ErrorProviderDoesNotExist} - Thrown if the provider does not exist for the provided Signer - * @throws {ErrorUnsupportedChainID} - Thrown if the network's chainId is not supported + * @example + * ```ts + * import { KVStoreClient } from '@human-protocol/sdk'; + * import { Wallet, JsonRpcProvider } from 'ethers'; + * + * const rpcUrl = 'YOUR_RPC_URL'; + * const privateKey = 'YOUR_PRIVATE_KEY'; + * + * const provider = new JsonRpcProvider(rpcUrl); + * const signer = new Wallet(privateKey, provider); + * const kvstoreClient = await KVStoreClient.build(signer); + * ``` */ public static async build(runner: ContractRunner): Promise { if (!runner.provider) { @@ -142,27 +140,15 @@ export class KVStoreClient extends BaseEthersClient { /** * This function sets a key-value pair associated with the address that submits the transaction. * - * @param {string} key Key of the key-value pair - * @param {string} value Value of the key-value pair - * @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object). - * @returns Returns void if successful. Throws error if any. - * - * - * **Code example** - * - * > Need to have available stake. + * @param key - Key of the key-value pair + * @param value - Value of the key-value pair + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @returns - + * @throws ErrorKVStoreEmptyKey If the key is empty + * @throws Error If the transaction fails * + * @example * ```ts - * import { Wallet, providers } from 'ethers'; - * import { KVStoreClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * const privateKey = 'YOUR_PRIVATE_KEY'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const signer = new Wallet(privateKey, provider); - * const kvstoreClient = await KVStoreClient.build(signer); - * * await kvstoreClient.set('Role', 'RecordingOracle'); * ``` */ @@ -183,27 +169,16 @@ export class KVStoreClient extends BaseEthersClient { /** * This function sets key-value pairs in bulk associated with the address that submits the transaction. * - * @param {string[]} keys Array of keys (keys and value must have the same order) - * @param {string[]} values Array of values - * @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object). - * @returns Returns void if successful. Throws error if any. - * - * - * **Code example** - * - * > Need to have available stake. + * @param keys - Array of keys (keys and value must have the same order) + * @param values - Array of values + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @returns - + * @throws ErrorKVStoreArrayLength If keys and values arrays have different lengths + * @throws ErrorKVStoreEmptyKey If any key is empty + * @throws Error If the transaction fails * + * @example * ```ts - * import { Wallet, providers } from 'ethers'; - * import { KVStoreClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * const privateKey = 'YOUR_PRIVATE_KEY'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const signer = new Wallet(privateKey, provider); - * const kvstoreClient = await KVStoreClient.build(signer); - * * const keys = ['role', 'webhook_url']; * const values = ['RecordingOracle', 'http://localhost']; * await kvstoreClient.setBulk(keys, values); @@ -229,25 +204,15 @@ export class KVStoreClient extends BaseEthersClient { /** * Sets a URL value for the address that submits the transaction, and its hash. * - * @param {string} url URL to set - * @param {string | undefined} urlKey Configurable URL key. `url` by default. - * @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object). - * @returns Returns void if successful. Throws error if any. - * - * - * **Code example** + * @param url - URL to set + * @param urlKey - Configurable URL key. `url` by default. + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @returns - + * @throws ErrorInvalidUrl If the URL is invalid + * @throws Error If the transaction fails * + * @example * ```ts - * import { Wallet, providers } from 'ethers'; - * import { KVStoreClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * const privateKey = 'YOUR_PRIVATE_KEY'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const signer = new Wallet(privateKey, provider); - * const kvstoreClient = await KVStoreClient.build(signer); - * * await kvstoreClient.setFileUrlAndHash('example.com'); * await kvstoreClient.setFileUrlAndHash('linkedin.com/example', 'linkedin_url'); * ``` @@ -283,26 +248,17 @@ export class KVStoreClient extends BaseEthersClient { /** * Gets the value of a key-value pair in the contract. * - * @param {string} address Address from which to get the key value. - * @param {string} key Key to obtain the value. - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {string} Value of the key. - * - * - * **Code example** - * - * > Need to have available stake. + * @param address - Address from which to get the key value. + * @param key - Key to obtain the value. + * @returns Value of the key. + * @throws ErrorKVStoreEmptyKey If the key is empty + * @throws ErrorInvalidAddress If the address is invalid + * @throws Error If the contract call fails * + * @example * ```ts - * import { providers } from 'ethers'; - * import { KVStoreClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const kvstoreClient = await KVStoreClient.build(provider); - * * const value = await kvstoreClient.get('0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', 'Role'); + * console.log('Value:', value); * ``` */ public async get(address: string, key: string): Promise { @@ -320,55 +276,37 @@ export class KVStoreClient extends BaseEthersClient { } /** - * ## Introduction - * - * Utility class for KVStore-related operations. - * - * ## Installation - * - * ### npm - * ```bash - * npm install @human-protocol/sdk - * ``` - * - * ### yarn - * ```bash - * yarn install @human-protocol/sdk - * ``` - * - * ## Code example - * - * ### Signer - * - * **Using private key (backend)** + * Utility helpers for KVStore-related queries. * + * @example * ```ts * import { ChainId, KVStoreUtils } from '@human-protocol/sdk'; * - * const KVStoreAddresses = await KVStoreUtils.getKVStoreData( + * const kvStoreData = await KVStoreUtils.getKVStoreData( * ChainId.POLYGON_AMOY, * "0x1234567890123456789012345678901234567890" * ); + * console.log('KVStore data:', kvStoreData); * ``` */ export class KVStoreUtils { /** * This function returns the KVStore data for a given address. * - * @param {ChainId} chainId Network in which the KVStore is deployed - * @param {string} address Address of the KVStore - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {Promise} KVStore data - * @throws {ErrorUnsupportedChainID} - Thrown if the network's chainId is not supported - * @throws {ErrorInvalidAddress} - Thrown if the Address sent is invalid - * - * **Code example** + * @param chainId - Network in which the KVStore is deployed + * @param address - Address of the KVStore + * @param options - Optional configuration for subgraph requests. + * @returns KVStore data + * @throws ErrorUnsupportedChainID If the network's chainId is not supported + * @throws ErrorInvalidAddress If the address is invalid * + * @example * ```ts - * import { ChainId, KVStoreUtils } from '@human-protocol/sdk'; - * - * const kvStoreData = await KVStoreUtils.getKVStoreData(ChainId.POLYGON_AMOY, "0x1234567890123456789012345678901234567890"); - * console.log(kvStoreData); + * const kvStoreData = await KVStoreUtils.getKVStoreData( + * ChainId.POLYGON_AMOY, + * "0x1234567890123456789012345678901234567890" + * ); + * console.log('KVStore data:', kvStoreData); * ``` */ public static async getKVStoreData( @@ -404,26 +342,24 @@ export class KVStoreUtils { /** * Gets the value of a key-value pair in the KVStore using the subgraph. * - * @param {ChainId} chainId Network in which the KVStore is deployed - * @param {string} address Address from which to get the key value. - * @param {string} key Key to obtain the value. - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {Promise} Value of the key. - * @throws {ErrorUnsupportedChainID} - Thrown if the network's chainId is not supported - * @throws {ErrorInvalidAddress} - Thrown if the Address sent is invalid - * @throws {ErrorKVStoreEmptyKey} - Thrown if the key is empty - * - * **Code example** - * + * @param chainId - Network in which the KVStore is deployed + * @param address - Address from which to get the key value. + * @param key - Key to obtain the value. + * @param options - Optional configuration for subgraph requests. + * @returns Value of the key. + * @throws ErrorUnsupportedChainID If the network's chainId is not supported + * @throws ErrorInvalidAddress If the address is invalid + * @throws ErrorKVStoreEmptyKey If the key is empty + * @throws InvalidKeyError If the key is not found + * + * @example * ```ts - * import { ChainId, KVStoreUtils } from '@human-protocol/sdk'; - * - * const chainId = ChainId.POLYGON_AMOY; - * const address = '0x1234567890123456789012345678901234567890'; - * const key = 'role'; - * - * const value = await KVStoreUtils.get(chainId, address, key); - * console.log(value); + * const value = await KVStoreUtils.get( + * ChainId.POLYGON_AMOY, + * '0x1234567890123456789012345678901234567890', + * 'role' + * ); + * console.log('Value:', value); * ``` */ public static async get( @@ -458,22 +394,22 @@ export class KVStoreUtils { /** * Gets the URL value of the given entity, and verifies its hash. * - * @param {ChainId} chainId Network in which the KVStore is deployed - * @param {string} address Address from which to get the URL value. - * @param {string} urlKey Configurable URL key. `url` by default. - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {Promise} URL value for the given address if it exists, and the content is valid - * - * **Code example** + * @param chainId - Network in which the KVStore is deployed + * @param address - Address from which to get the URL value. + * @param urlKey - Configurable URL key. `url` by default. + * @param options - Optional configuration for subgraph requests. + * @returns URL value for the given address if it exists, and the content is valid + * @throws ErrorInvalidAddress If the address is invalid + * @throws ErrorInvalidHash If the hash verification fails + * @throws Error If fetching URL or hash fails * + * @example * ```ts - * import { ChainId, KVStoreUtils } from '@human-protocol/sdk'; - * - * const chainId = ChainId.POLYGON_AMOY; - * const address = '0x1234567890123456789012345678901234567890'; - * - * const url = await KVStoreUtils.getFileUrlAndVerifyHash(chainId, address); - * console.log(url); + * const url = await KVStoreUtils.getFileUrlAndVerifyHash( + * ChainId.POLYGON_AMOY, + * '0x1234567890123456789012345678901234567890' + * ); + * console.log('Verified URL:', url); * ``` */ public static async getFileUrlAndVerifyHash( @@ -521,20 +457,21 @@ export class KVStoreUtils { /** * Gets the public key of the given entity, and verifies its hash. * - * @param {ChainId} chainId Network in which the KVStore is deployed - * @param {string} address Address from which to get the public key. - * @returns {Promise} Public key for the given address if it exists, and the content is valid - * - * **Code example** + * @param chainId - Network in which the KVStore is deployed + * @param address - Address from which to get the public key. + * @param options - Optional configuration for subgraph requests. + * @returns Public key for the given address if it exists, and the content is valid + * @throws ErrorInvalidAddress If the address is invalid + * @throws ErrorInvalidHash If the hash verification fails + * @throws Error If fetching the public key fails * + * @example * ```ts - * import { ChainId, KVStoreUtils } from '@human-protocol/sdk'; - * - * const chainId = ChainId.POLYGON_AMOY; - * const address = '0x1234567890123456789012345678901234567890'; - * - * const publicKey = await KVStoreUtils.getPublicKey(chainId, address); - * console.log(publicKey); + * const publicKey = await KVStoreUtils.getPublicKey( + * ChainId.POLYGON_AMOY, + * '0x1234567890123456789012345678901234567890' + * ); + * console.log('Public key:', publicKey); * ``` */ public static async getPublicKey( diff --git a/packages/sdk/typescript/human-protocol-sdk/src/operator.ts b/packages/sdk/typescript/human-protocol-sdk/src/operator.ts index 2428c9d24e..ad0dd150d7 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/operator.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/operator.ts @@ -26,21 +26,40 @@ import { getSubgraphUrl, customGqlFetch } from './utils'; import { ChainId, OrderDirection } from './enums'; import { NETWORKS } from './constants'; +/** + * Utility helpers for operator-related queries. + * + * @example + * ```ts + * import { OperatorUtils, ChainId } from '@human-protocol/sdk'; + * + * const operator = await OperatorUtils.getOperator( + * ChainId.POLYGON_AMOY, + * '0x62dD51230A30401C455c8398d06F85e4EaB6309f' + * ); + * console.log('Operator:', operator); + * ``` + */ export class OperatorUtils { /** * This function returns the operator data for the given address. * - * @param {ChainId} chainId Network in which the operator is deployed - * @param {string} address Operator address. - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {Promise} - Returns the operator details or null if not found. - * - * **Code example** + * @param chainId - Network in which the operator is deployed + * @param address - Operator address. + * @param options - Optional configuration for subgraph requests. + * @returns Returns the operator details or null if not found. + * @throws ErrorInvalidStakerAddressProvided If the address is invalid + * @throws ErrorUnsupportedChainID If the chain ID is not supported * + * @example * ```ts * import { OperatorUtils, ChainId } from '@human-protocol/sdk'; * - * const operator = await OperatorUtils.getOperator(ChainId.POLYGON_AMOY, '0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + * const operator = await OperatorUtils.getOperator( + * ChainId.POLYGON_AMOY, + * '0x62dD51230A30401C455c8398d06F85e4EaB6309f' + * ); + * console.log('Operator:', operator); * ``` */ public static async getOperator( @@ -74,19 +93,20 @@ export class OperatorUtils { /** * This function returns all the operator details of the protocol. * - * @param {IOperatorsFilter} filter Filter for the operators. - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {Promise} Returns an array with all the operator details. - * - * **Code example** + * @param filter - Filter for the operators. + * @param options - Optional configuration for subgraph requests. + * @returns Returns an array with all the operator details. + * @throws ErrorUnsupportedChainID If the chain ID is not supported * + * @example * ```ts - * import { OperatorUtils, ChainId } from '@human-protocol/sdk'; + * import { ChainId } from '@human-protocol/sdk'; * - * const filter: IOperatorsFilter = { - * chainId: ChainId.POLYGON + * const filter = { + * chainId: ChainId.POLYGON_AMOY * }; * const operators = await OperatorUtils.getOperators(filter); + * console.log('Operators:', operators.length); * ``` */ public static async getOperators( @@ -142,18 +162,22 @@ export class OperatorUtils { /** * Retrieves the reputation network operators of the specified address. * - * @param {ChainId} chainId Network in which the reputation network is deployed - * @param {string} address Address of the reputation oracle. - * @param {string} [role] - (Optional) Role of the operator. - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {Promise} - Returns an array of operator details. - * - * **Code example** + * @param chainId - Network in which the reputation network is deployed + * @param address - Address of the reputation oracle. + * @param role - Role of the operator (optional). + * @param options - Optional configuration for subgraph requests. + * @returns Returns an array of operator details. + * @throws ErrorUnsupportedChainID If the chain ID is not supported * + * @example * ```ts * import { OperatorUtils, ChainId } from '@human-protocol/sdk'; * - * const operators = await OperatorUtils.getReputationNetworkOperators(ChainId.POLYGON_AMOY, '0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + * const operators = await OperatorUtils.getReputationNetworkOperators( + * ChainId.POLYGON_AMOY, + * '0x62dD51230A30401C455c8398d06F85e4EaB6309f' + * ); + * console.log('Operators:', operators.length); * ``` */ public static async getReputationNetworkOperators( @@ -189,17 +213,22 @@ export class OperatorUtils { /** * This function returns information about the rewards for a given slasher address. * - * @param {ChainId} chainId Network in which the rewards are deployed - * @param {string} slasherAddress Slasher address. - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {Promise} Returns an array of Reward objects that contain the rewards earned by the user through slashing other users. - * - * **Code example** + * @param chainId - Network in which the rewards are deployed + * @param slasherAddress - Slasher address. + * @param options - Optional configuration for subgraph requests. + * @returns Returns an array of Reward objects that contain the rewards earned by the user through slashing other users. + * @throws ErrorInvalidSlasherAddressProvided If the slasher address is invalid + * @throws ErrorUnsupportedChainID If the chain ID is not supported * + * @example * ```ts * import { OperatorUtils, ChainId } from '@human-protocol/sdk'; * - * const rewards = await OperatorUtils.getRewards(ChainId.POLYGON_AMOY, '0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + * const rewards = await OperatorUtils.getRewards( + * ChainId.POLYGON_AMOY, + * '0x62dD51230A30401C455c8398d06F85e4EaB6309f' + * ); + * console.log('Rewards:', rewards.length); * ``` */ public static async getRewards( diff --git a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts b/packages/sdk/typescript/human-protocol-sdk/src/staking.ts index eac6ffb8d3..c39669db25 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/staking.ts @@ -37,9 +37,7 @@ import { } from './graphql/queries/staking'; /** - * ## Introduction - * - * This client enables performing actions on staking contracts and obtaining staking information from both the contracts and subgraph. + * Client for staking actions on HUMAN Protocol. * * Internally, the SDK will use one network or another according to the network ID of the `runner`. * To use this client, it is recommended to initialize it using the static `build` method. @@ -53,37 +51,25 @@ import { * - **Signer**: when the user wants to use this model to send transactions calling the contract functions. * - **Provider**: when the user wants to use this model to get information from the contracts or subgraph. * - * ## Installation - * - * ### npm - * ```bash - * npm install @human-protocol/sdk - * ``` - * - * ### yarn - * ```bash - * yarn install @human-protocol/sdk - * ``` - * - * ## Code example + * @example * - * ### Signer + * ###Using Signer * - * **Using private key (backend)** + * ####Using private key (backend) * * ```ts * import { StakingClient } from '@human-protocol/sdk'; - * import { Wallet, providers } from 'ethers'; + * import { Wallet, JsonRpcProvider } from 'ethers'; * * const rpcUrl = 'YOUR_RPC_URL'; * const privateKey = 'YOUR_PRIVATE_KEY'; * - * const provider = new providers.JsonRpcProvider(rpcUrl); + * const provider = new JsonRpcProvider(rpcUrl); * const signer = new Wallet(privateKey, provider); * const stakingClient = await StakingClient.build(signer); * ``` * - * **Using Wagmi (frontend)** + * ####Using Wagmi (frontend) * * ```ts * import { useSigner, useChainId } from 'wagmi'; @@ -93,15 +79,15 @@ import { * const stakingClient = await StakingClient.build(signer); * ``` * - * ### Provider + * ###Using Provider * * ```ts * import { StakingClient } from '@human-protocol/sdk'; - * import { providers } from 'ethers'; + * import { JsonRpcProvider } from 'ethers'; * * const rpcUrl = 'YOUR_RPC_URL'; * - * const provider = new providers.JsonRpcProvider(rpcUrl); + * const provider = new JsonRpcProvider(rpcUrl); * const stakingClient = await StakingClient.build(provider); * ``` */ @@ -113,8 +99,8 @@ export class StakingClient extends BaseEthersClient { /** * **StakingClient constructor** * - * @param {ContractRunner} runner - The Runner object to interact with the Ethereum network - * @param {NetworkData} networkData - The network information required to connect to the Staking contract + * @param runner - The Runner object to interact with the Ethereum network + * @param networkData - The network information required to connect to the Staking contract */ constructor(runner: ContractRunner, networkData: NetworkData) { super(runner, networkData); @@ -138,11 +124,23 @@ export class StakingClient extends BaseEthersClient { /** * Creates an instance of StakingClient from a Runner. * - * @param {ContractRunner} runner - The Runner object to interact with the Ethereum network + * @param runner - The Runner object to interact with the Ethereum network + * @returns An instance of StakingClient + * @throws ErrorProviderDoesNotExist If the provider does not exist for the provided Signer + * @throws ErrorUnsupportedChainID If the network's chainId is not supported * - * @returns {Promise} - An instance of StakingClient - * @throws {ErrorProviderDoesNotExist} - Thrown if the provider does not exist for the provided Signer - * @throws {ErrorUnsupportedChainID} - Thrown if the network's chainId is not supported + * @example + * ```ts + * import { StakingClient } from '@human-protocol/sdk'; + * import { Wallet, JsonRpcProvider } from 'ethers'; + * + * const rpcUrl = 'YOUR_RPC_URL'; + * const privateKey = 'YOUR_PRIVATE_KEY'; + * + * const provider = new JsonRpcProvider(rpcUrl); + * const signer = new Wallet(privateKey, provider); + * const stakingClient = await StakingClient.build(signer); + * ``` */ public static async build(runner: ContractRunner): Promise { if (!runner.provider) { @@ -179,24 +177,17 @@ export class StakingClient extends BaseEthersClient { /** * This function approves the staking contract to transfer a specified amount of tokens when the user stakes. It increases the allowance for the staking contract. * - * @param {bigint} amount Amount in WEI of tokens to approve for stake. - * @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object). - * @returns Returns void if successful. Throws error if any. - * - * **Code example** + * @param amount - Amount in WEI of tokens to approve for stake. + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @returns - + * @throws ErrorInvalidStakingValueType If the amount is not a bigint + * @throws ErrorInvalidStakingValueSign If the amount is negative * + * @example * ```ts - * import { ethers, Wallet, providers } from 'ethers'; - * import { StakingClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * const privateKey = 'YOUR_PRIVATE_KEY'; + * import { ethers } from 'ethers'; * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const signer = new Wallet(privateKey, provider); - * const stakingClient = await StakingClient.build(signer); - * - * const amount = ethers.parseUnits(5, 'ether'); //convert from ETH to WEI + * const amount = ethers.parseUnits('5', 'ether'); //convert from ETH to WEI * await stakingClient.approveStake(amount); * ``` */ @@ -230,26 +221,20 @@ export class StakingClient extends BaseEthersClient { /** * This function stakes a specified amount of tokens on a specific network. * - * > `approveStake` must be called before - * - * @param {bigint} amount Amount in WEI of tokens to stake. - * @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object). - * @returns Returns void if successful. Throws error if any. + * !!! note + * `approveStake` must be called before * - * **Code example** + * @param amount - Amount in WEI of tokens to stake. + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @returns - + * @throws ErrorInvalidStakingValueType If the amount is not a bigint + * @throws ErrorInvalidStakingValueSign If the amount is negative * + * @example * ```ts - * import { ethers, Wallet, providers } from 'ethers'; - * import { StakingClient } from '@human-protocol/sdk'; + * import { ethers } from 'ethers'; * - * const rpcUrl = 'YOUR_RPC_URL'; - * const privateKey = 'YOUR_PRIVATE_KEY'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const signer = new Wallet(privateKey, provider); - * const stakingClient = await StakingClient.build(signer); - * - * const amount = ethers.parseUnits(5, 'ether'); //convert from ETH to WEI + * const amount = ethers.parseUnits('5', 'ether'); //convert from ETH to WEI * await stakingClient.approveStake(amount); // if it was already approved before, this is not necessary * await stakingClient.stake(amount); * ``` @@ -275,26 +260,20 @@ export class StakingClient extends BaseEthersClient { /** * This function unstakes tokens from staking contract. The unstaked tokens stay locked for a period of time. * - * > Must have tokens available to unstake - * - * @param {bigint} amount Amount in WEI of tokens to unstake. - * @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object). - * @returns Returns void if successful. Throws error if any. + * !!! note + * Must have tokens available to unstake * - * **Code example** + * @param amount - Amount in WEI of tokens to unstake. + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @returns - + * @throws ErrorInvalidStakingValueType If the amount is not a bigint + * @throws ErrorInvalidStakingValueSign If the amount is negative * + * @example * ```ts - * import { ethers, Wallet, providers } from 'ethers'; - * import { StakingClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * const privateKey = 'YOUR_PRIVATE_KEY'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const signer = new Wallet(privateKey, provider); - * const stakingClient = await StakingClient.build(signer); + * import { ethers } from 'ethers'; * - * const amount = ethers.parseUnits(5, 'ether'); //convert from ETH to WEI + * const amount = ethers.parseUnits('5', 'ether'); //convert from ETH to WEI * await stakingClient.unstake(amount); * ``` */ @@ -321,25 +300,14 @@ export class StakingClient extends BaseEthersClient { /** * This function withdraws unstaked and non-locked tokens from staking contract to the user wallet. + * !!! note + * Must have tokens available to withdraw * - * > Must have tokens available to withdraw - * - * @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object). - * @returns Returns void if successful. Throws error if any. - * - * **Code example** + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @returns - * + * @example * ```ts - * import { Wallet, providers } from 'ethers'; - * import { StakingClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * const privateKey = 'YOUR_PRIVATE_KEY'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const signer = new Wallet(privateKey, provider); - * const stakingClient = await StakingClient.build(signer); - * * await stakingClient.withdraw(); * ``` */ @@ -356,28 +324,30 @@ export class StakingClient extends BaseEthersClient { /** * This function reduces the allocated amount by a staker in an escrow and transfers those tokens to the reward pool. This allows the slasher to claim them later. * - * @param {string} slasher Wallet address from who requested the slash - * @param {string} staker Wallet address from who is going to be slashed - * @param {string} escrowAddress Address of the escrow that the slash is made - * @param {bigint} amount Amount in WEI of tokens to slash. - * @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object). - * @returns Returns void if successful. Throws error if any. - * - * **Code example** - * + * @param slasher - Wallet address from who requested the slash + * @param staker - Wallet address from who is going to be slashed + * @param escrowAddress - Address of the escrow that the slash is made + * @param amount - Amount in WEI of tokens to slash. + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @returns - + * @throws ErrorInvalidStakingValueType If the amount is not a bigint + * @throws ErrorInvalidStakingValueSign If the amount is negative + * @throws ErrorInvalidSlasherAddressProvided If the slasher address is invalid + * @throws ErrorInvalidStakerAddressProvided If the staker address is invalid + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + * + * @example * ```ts - * import { ethers, Wallet, providers } from 'ethers'; - * import { StakingClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * const privateKey = 'YOUR_PRIVATE_KEY'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const signer = new Wallet(privateKey, provider); - * const stakingClient = await StakingClient.build(signer); - * - * const amount = ethers.parseUnits(5, 'ether'); //convert from ETH to WEI - * await stakingClient.slash('0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', '0x62dD51230A30401C455c8398d06F85e4EaB6309f', amount); + * import { ethers } from 'ethers'; + * + * const amount = ethers.parseUnits('5', 'ether'); //convert from ETH to WEI + * await stakingClient.slash( + * '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', + * '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', + * '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + * amount + * ); * ``` */ @requiresSigner @@ -426,21 +396,14 @@ export class StakingClient extends BaseEthersClient { /** * Retrieves comprehensive staking information for a staker. * - * @param {string} stakerAddress - The address of the staker. - * @returns {Promise} - * - * **Code example** + * @param stakerAddress - The address of the staker. + * @returns Staking information for the staker + * @throws ErrorInvalidStakerAddressProvided If the staker address is invalid * + * @example * ```ts - * import { StakingClient } from '@human-protocol/sdk'; - * - * const rpcUrl = 'YOUR_RPC_URL'; - * - * const provider = new providers.JsonRpcProvider(rpcUrl); - * const stakingClient = await StakingClient.build(provider); - * * const stakingInfo = await stakingClient.getStakerInfo('0xYourStakerAddress'); - * console.log(stakingInfo.tokensStaked); + * console.log('Tokens staked:', stakingInfo.stakedAmount); * ``` */ public async getStakerInfo(stakerAddress: string): Promise { @@ -479,16 +442,41 @@ export class StakingClient extends BaseEthersClient { } /** - * Utility class for Staking-related subgraph queries. + * Utility helpers for Staking-related queries. + * + * @example + * ```ts + * import { StakingUtils, ChainId } from '@human-protocol/sdk'; + * + * const staker = await StakingUtils.getStaker( + * ChainId.POLYGON_AMOY, + * '0xYourStakerAddress' + * ); + * console.log('Staked amount:', staker.stakedAmount); + * ``` */ export class StakingUtils { /** * Gets staking info for a staker from the subgraph. * - * @param {ChainId} chainId Network in which the staking contract is deployed - * @param {string} stakerAddress Address of the staker - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {Promise} Staker info from subgraph + * @param chainId - Network in which the staking contract is deployed + * @param stakerAddress - Address of the staker + * @param options - Optional configuration for subgraph requests. + * @returns Staker info from subgraph + * @throws ErrorInvalidStakerAddressProvided If the staker address is invalid + * @throws ErrorUnsupportedChainID If the chain ID is not supported + * @throws ErrorStakerNotFound If the staker is not found + * + * @example + * ```ts + * import { StakingUtils, ChainId } from '@human-protocol/sdk'; + * + * const staker = await StakingUtils.getStaker( + * ChainId.POLYGON_AMOY, + * '0xYourStakerAddress' + * ); + * console.log('Staked amount:', staker.stakedAmount); + * ``` */ public static async getStaker( chainId: ChainId, @@ -521,9 +509,22 @@ export class StakingUtils { /** * Gets all stakers from the subgraph with filters, pagination and ordering. * - * @param {IStakersFilter} filter Stakers filter with pagination and ordering - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {Promise} Array of stakers + * @param filter - Stakers filter with pagination and ordering + * @param options - Optional configuration for subgraph requests. + * @returns Array of stakers + * @throws ErrorUnsupportedChainID If the chain ID is not supported + * + * @example + * ```ts + * import { ChainId } from '@human-protocol/sdk'; + * + * const filter = { + * chainId: ChainId.POLYGON_AMOY, + * minStakedAmount: '1000000000000000000', // 1 token in WEI + * }; + * const stakers = await StakingUtils.getStakers(filter); + * console.log('Stakers:', stakers.length); + * ``` */ public static async getStakers( filter: IStakersFilter, diff --git a/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts b/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts index 36095e7258..fd1192a449 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts @@ -30,51 +30,21 @@ import { } from './utils'; /** - * ## Introduction + * Utility class for statistics-related queries. * - * This client enables obtaining statistical information from the subgraph. - * - * Unlike other SDK clients, `StatisticsClient` does not require `signer` or `provider` to be provided. - * We just need to create a client object using relevant network data. - * - * ```ts - * constructor(network: NetworkData) - * ``` - * - * ## Installation - * - * ### npm - * ```bash - * npm install @human-protocol/sdk - * ``` - * - * ### yarn - * ```bash - * yarn install @human-protocol/sdk - * ``` - * - * ## Code example + * Unlike other SDK clients, `StatisticsUtils` does not require `signer` or `provider` to be provided. + * We just need to pass the network data to each static method. * + * @example * ```ts - * import { StatisticsClient, ChainId, NETWORKS } from '@human-protocol/sdk'; + * import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; * - * const statisticsClient = new StatisticsClient(NETWORKS[ChainId.POLYGON_AMOY]); + * const networkData = NETWORKS[ChainId.POLYGON_AMOY]; + * const escrowStats = await StatisticsUtils.getEscrowStatistics(networkData); + * console.log('Total escrows:', escrowStats.totalEscrows); * ``` */ -export class StatisticsClient { - public networkData: NetworkData; - public subgraphUrl: string; - - /** - * **StatisticsClient constructor** - * - * @param {NetworkData} networkData - The network information required to connect to the Statistics contract - */ - constructor(networkData: NetworkData) { - this.networkData = networkData; - this.subgraphUrl = getSubgraphUrl(networkData); - } - +export class StatisticsUtils { /** * This function returns the statistical data of escrows. * @@ -106,29 +76,36 @@ export class StatisticsClient { * }; * ``` * - * @param {IStatisticsFilter} filter Statistics params with duration data - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {Promise} Escrow statistics data. - * - * **Code example** + * @param networkData - The network information required to connect to the subgraph + * @param filter - Statistics params with duration data + * @param options - Optional configuration for subgraph requests. + * @returns Escrow statistics data. * + * @example * ```ts - * import { StatisticsClient, ChainId, NETWORKS } from '@human-protocol/sdk'; - * - * const statisticsClient = new StatisticsClient(NETWORKS[ChainId.POLYGON_AMOY]); - * - * const escrowStatistics = await statisticsClient.getEscrowStatistics(); - * const escrowStatisticsApril = await statisticsClient.getEscrowStatistics({ - * from: new Date('2021-04-01'), - * to: new Date('2021-04-30'), - * }); + * import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; + * + * const networkData = NETWORKS[ChainId.POLYGON_AMOY]; + * const escrowStats = await StatisticsUtils.getEscrowStatistics(networkData); + * console.log('Total escrows:', escrowStats.totalEscrows); + * + * const escrowStatsApril = await StatisticsUtils.getEscrowStatistics( + * networkData, + * { + * from: new Date('2021-04-01'), + * to: new Date('2021-04-30'), + * } + * ); + * console.log('April escrows:', escrowStatsApril.totalEscrows); * ``` */ - async getEscrowStatistics( + static async getEscrowStatistics( + networkData: NetworkData, filter: IStatisticsFilter = {}, options?: SubgraphOptions ): Promise { try { + const subgraphUrl = getSubgraphUrl(networkData); const first = filter.first !== undefined ? Math.min(filter.first, 1000) : 10; const skip = filter.skip || 0; @@ -136,12 +113,12 @@ export class StatisticsClient { const { escrowStatistics } = await customGqlFetch<{ escrowStatistics: EscrowStatisticsData; - }>(this.subgraphUrl, GET_ESCROW_STATISTICS_QUERY, options); + }>(subgraphUrl, GET_ESCROW_STATISTICS_QUERY, options); const { eventDayDatas } = await customGqlFetch<{ eventDayDatas: EventDayData[]; }>( - this.subgraphUrl, + subgraphUrl, GET_EVENT_DAY_DATA_QUERY(filter), { from: filter.from ? getUnixTimestamp(filter.from) : undefined, @@ -197,29 +174,36 @@ export class StatisticsClient { * }; * ``` * - * @param {IStatisticsFilter} filter Statistics params with duration data - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {Promise} Worker statistics data. - * - * **Code example** + * @param networkData - The network information required to connect to the subgraph + * @param filter - Statistics params with duration data + * @param options - Optional configuration for subgraph requests. + * @returns Worker statistics data. * + * @example * ```ts - * import { StatisticsClient, ChainId, NETWORKS } from '@human-protocol/sdk'; - * - * const statisticsClient = new StatisticsClient(NETWORKS[ChainId.POLYGON_AMOY]); - * - * const workerStatistics = await statisticsClient.getWorkerStatistics(); - * const workerStatisticsApril = await statisticsClient.getWorkerStatistics({ - * from: new Date('2021-04-01'), - * to: new Date('2021-04-30'), - * }); + * import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; + * + * const networkData = NETWORKS[ChainId.POLYGON_AMOY]; + * const workerStats = await StatisticsUtils.getWorkerStatistics(networkData); + * console.log('Daily workers data:', workerStats.dailyWorkersData); + * + * const workerStatsApril = await StatisticsUtils.getWorkerStatistics( + * networkData, + * { + * from: new Date('2021-04-01'), + * to: new Date('2021-04-30'), + * } + * ); + * console.log('April workers:', workerStatsApril.dailyWorkersData.length); * ``` */ - async getWorkerStatistics( + static async getWorkerStatistics( + networkData: NetworkData, filter: IStatisticsFilter = {}, options?: SubgraphOptions ): Promise { try { + const subgraphUrl = getSubgraphUrl(networkData); const first = filter.first !== undefined ? Math.min(filter.first, 1000) : 10; const skip = filter.skip || 0; @@ -228,7 +212,7 @@ export class StatisticsClient { const { eventDayDatas } = await customGqlFetch<{ eventDayDatas: EventDayData[]; }>( - this.subgraphUrl, + subgraphUrl, GET_EVENT_DAY_DATA_QUERY(filter), { from: filter.from ? getUnixTimestamp(filter.from) : undefined, @@ -279,50 +263,43 @@ export class StatisticsClient { * }; * ``` * - * @param {IStatisticsFilter} filter Statistics params with duration data - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {Promise} Payment statistics data. - * - * **Code example** + * @param networkData - The network information required to connect to the subgraph + * @param filter - Statistics params with duration data + * @param options - Optional configuration for subgraph requests. + * @returns Payment statistics data. * + * @example * ```ts - * import { StatisticsClient, ChainId, NETWORKS } from '@human-protocol/sdk'; - * - * const statisticsClient = new StatisticsClient(NETWORKS[ChainId.POLYGON_AMOY]); + * import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; * + * const networkData = NETWORKS[ChainId.POLYGON_AMOY]; + * const paymentStats = await StatisticsUtils.getPaymentStatistics(networkData); * console.log( * 'Payment statistics:', - * (await statisticsClient.getPaymentStatistics()).dailyPaymentsData.map( - * (p) => ({ - * ...p, - * totalAmountPaid: p.totalAmountPaid.toString(), - * averageAmountPerJob: p.averageAmountPerJob.toString(), - * averageAmountPerWorker: p.averageAmountPerWorker.toString(), - * }) - * ) - * ); - * - * console.log( - * 'Payment statistics from 5/8 - 6/8:', - * ( - * await statisticsClient.getPaymentStatistics({ - * from: new Date(2023, 4, 8), - * to: new Date(2023, 5, 8), - * }) - * ).dailyPaymentsData.map((p) => ({ + * paymentStats.dailyPaymentsData.map((p) => ({ * ...p, * totalAmountPaid: p.totalAmountPaid.toString(), - * averageAmountPerJob: p.averageAmountPerJob.toString(), * averageAmountPerWorker: p.averageAmountPerWorker.toString(), * })) * ); + * + * const paymentStatsRange = await StatisticsUtils.getPaymentStatistics( + * networkData, + * { + * from: new Date(2023, 4, 8), + * to: new Date(2023, 5, 8), + * } + * ); + * console.log('Payment statistics from 5/8 - 6/8:', paymentStatsRange.dailyPaymentsData.length); * ``` */ - async getPaymentStatistics( + static async getPaymentStatistics( + networkData: NetworkData, filter: IStatisticsFilter = {}, options?: SubgraphOptions ): Promise { try { + const subgraphUrl = getSubgraphUrl(networkData); const first = filter.first !== undefined ? Math.min(filter.first, 1000) : 10; const skip = filter.skip || 0; @@ -331,7 +308,7 @@ export class StatisticsClient { const { eventDayDatas } = await customGqlFetch<{ eventDayDatas: EventDayData[]; }>( - this.subgraphUrl, + subgraphUrl, GET_EVENT_DAY_DATA_QUERY(filter), { from: filter.from ? getUnixTimestamp(filter.from) : undefined, @@ -371,29 +348,31 @@ export class StatisticsClient { * }; * ``` * - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {Promise} HMToken statistics data. - * - * **Code example** + * @param networkData - The network information required to connect to the subgraph + * @param options - Optional configuration for subgraph requests. + * @returns HMToken statistics data. * + * @example * ```ts - * import { StatisticsClient, ChainId, NETWORKS } from '@human-protocol/sdk'; - * - * const statisticsClient = new StatisticsClient(NETWORKS[ChainId.POLYGON_AMOY]); - * - * const hmtStatistics = await statisticsClient.getHMTStatistics(); + * import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; * + * const networkData = NETWORKS[ChainId.POLYGON_AMOY]; + * const hmtStats = await StatisticsUtils.getHMTStatistics(networkData); * console.log('HMT statistics:', { - * ...hmtStatistics, - * totalTransferAmount: hmtStatistics.totalTransferAmount.toString(), + * ...hmtStats, + * totalTransferAmount: hmtStats.totalTransferAmount.toString(), * }); * ``` */ - async getHMTStatistics(options?: SubgraphOptions): Promise { + static async getHMTStatistics( + networkData: NetworkData, + options?: SubgraphOptions + ): Promise { try { + const subgraphUrl = getSubgraphUrl(networkData); const { hmtokenStatistics } = await customGqlFetch<{ hmtokenStatistics: HMTStatisticsData; - }>(this.subgraphUrl, GET_HMTOKEN_STATISTICS_QUERY, options); + }>(subgraphUrl, GET_HMTOKEN_STATISTICS_QUERY, options); return { totalTransferAmount: BigInt(hmtokenStatistics.totalValueTransfered), @@ -408,39 +387,37 @@ export class StatisticsClient { /** * This function returns the holders of the HMToken with optional filters and ordering. * - * **Input parameters** - * - * @param {IHMTHoldersParams} params HMT Holders params with filters and ordering - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {Promise} List of HMToken holders. - * - * **Code example** + * @param networkData - The network information required to connect to the subgraph + * @param params - HMT Holders params with filters and ordering + * @param options - Optional configuration for subgraph requests. + * @returns List of HMToken holders. * + * @example * ```ts - * import { StatisticsClient, ChainId, NETWORKS } from '@human-protocol/sdk'; - * - * const statisticsClient = new StatisticsClient(NETWORKS[ChainId.POLYGON_AMOY]); + * import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; * - * const hmtHolders = await statisticsClient.getHMTHolders({ + * const networkData = NETWORKS[ChainId.POLYGON_AMOY]; + * const hmtHolders = await StatisticsUtils.getHMTHolders(networkData, { * orderDirection: 'asc', * }); - * * console.log('HMT holders:', hmtHolders.map((h) => ({ * ...h, * balance: h.balance.toString(), * }))); * ``` */ - async getHMTHolders( + static async getHMTHolders( + networkData: NetworkData, params: IHMTHoldersParams = {}, options?: SubgraphOptions ): Promise { try { + const subgraphUrl = getSubgraphUrl(networkData); const { address, orderDirection } = params; const query = GET_HOLDERS_QUERY(address); const { holders } = await customGqlFetch<{ holders: HMTHolderData[] }>( - this.subgraphUrl, + subgraphUrl, query, { address, @@ -484,34 +461,36 @@ export class StatisticsClient { * } * ``` * - * @param {IStatisticsFilter} filter Statistics params with duration data - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {Promise} Daily HMToken statistics data. - * - * **Code example** + * @param networkData - The network information required to connect to the subgraph + * @param filter - Statistics params with duration data + * @param options - Optional configuration for subgraph requests. + * @returns Daily HMToken statistics data. * + * @example * ```ts - * import { StatisticsClient, ChainId, NETWORKS } from '@human-protocol/sdk'; - * - * const statisticsClient = new StatisticsClient(NETWORKS[ChainId.POLYGON_AMOY]); - * - * const dailyHMTStats = await statisticsClient.getHMTStatistics(); + * import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; * + * const networkData = NETWORKS[ChainId.POLYGON_AMOY]; + * const dailyHMTStats = await StatisticsUtils.getHMTDailyData(networkData); * console.log('Daily HMT statistics:', dailyHMTStats); * - * const hmtStatisticsRange = await statisticsClient.getHMTStatistics({ - * from: new Date(2023, 4, 8), - * to: new Date(2023, 5, 8), - * }); - * - * console.log('HMT statistics from 5/8 - 6/8:', hmtStatisticsRange); + * const hmtStatsRange = await StatisticsUtils.getHMTDailyData( + * networkData, + * { + * from: new Date(2023, 4, 8), + * to: new Date(2023, 5, 8), + * } + * ); + * console.log('HMT statistics from 5/8 - 6/8:', hmtStatsRange.length); * ``` */ - async getHMTDailyData( + static async getHMTDailyData( + networkData: NetworkData, filter: IStatisticsFilter = {}, options?: SubgraphOptions ): Promise { try { + const subgraphUrl = getSubgraphUrl(networkData); const first = filter.first !== undefined ? Math.min(filter.first, 1000) : 10; const skip = filter.skip || 0; @@ -520,7 +499,7 @@ export class StatisticsClient { const { eventDayDatas } = await customGqlFetch<{ eventDayDatas: EventDayData[]; }>( - this.subgraphUrl, + subgraphUrl, GET_EVENT_DAY_DATA_QUERY(filter), { from: filter.from ? getUnixTimestamp(filter.from) : undefined, diff --git a/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts b/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts index dc792ce6d2..6359018653 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts @@ -19,6 +19,20 @@ import { } from './interfaces'; import { getSubgraphUrl, getUnixTimestamp, customGqlFetch } from './utils'; +/** + * Utility class for transaction-related queries. + * + * @example + * ```ts + * import { TransactionUtils, ChainId } from '@human-protocol/sdk'; + * + * const transaction = await TransactionUtils.getTransaction( + * ChainId.POLYGON_AMOY, + * '0x62dD51230A30401C455c8398d06F85e4EaB6309f' + * ); + * console.log('Transaction:', transaction); + * ``` + */ export class TransactionUtils { /** * This function returns the transaction data for the given hash. @@ -51,17 +65,22 @@ export class TransactionUtils { * }; * ``` * - * @param {ChainId} chainId The chain ID. - * @param {string} hash The transaction hash. - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {Promise} - Returns the transaction details or null if not found. - * - * **Code example** + * @param chainId - The chain ID. + * @param hash - The transaction hash. + * @param options - Optional configuration for subgraph requests. + * @returns Returns the transaction details or null if not found. + * @throws ErrorInvalidHashProvided If the hash is invalid + * @throws ErrorUnsupportedChainID If the chain ID is not supported * + * @example * ```ts * import { TransactionUtils, ChainId } from '@human-protocol/sdk'; * - * const transaction = await TransactionUtils.getTransaction(ChainId.POLYGON, '0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + * const transaction = await TransactionUtils.getTransaction( + * ChainId.POLYGON_AMOY, + * '0x62dD51230A30401C455c8398d06F85e4EaB6309f' + * ); + * console.log('Transaction:', transaction); * ``` */ public static async getTransaction( @@ -116,7 +135,7 @@ export class TransactionUtils { * skip?: number; // (Optional) Number of transactions to skip. Default is 0. * orderDirection?: OrderDirection; // (Optional) Order of the results. Default is DESC. * } - * + * ``` * * ```ts * type InternalTransaction = { @@ -146,17 +165,18 @@ export class TransactionUtils { * }; * ``` * - * @param {ITransactionsFilter} filter Filter for the transactions. - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {Promise} Returns an array with all the transaction details. - * - * **Code example** + * @param filter - Filter for the transactions. + * @param options - Optional configuration for subgraph requests. + * @returns Returns an array with all the transaction details. + * @throws ErrorCannotUseDateAndBlockSimultaneously If both date and block filters are used + * @throws ErrorUnsupportedChainID If the chain ID is not supported * + * @example * ```ts * import { TransactionUtils, ChainId, OrderDirection } from '@human-protocol/sdk'; * - * const filter: ITransactionsFilter = { - * chainId: ChainId.POLYGON, + * const filter = { + * chainId: ChainId.POLYGON_AMOY, * startDate: new Date('2022-01-01'), * endDate: new Date('2022-12-31'), * first: 10, @@ -164,6 +184,7 @@ export class TransactionUtils { * orderDirection: OrderDirection.DESC, * }; * const transactions = await TransactionUtils.getTransactions(filter); + * console.log('Transactions:', transactions.length); * ``` */ public static async getTransactions( diff --git a/packages/sdk/typescript/human-protocol-sdk/src/utils.ts b/packages/sdk/typescript/human-protocol-sdk/src/utils.ts index f7ef8d8fb0..ce0f45ff6d 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/utils.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/utils.ts @@ -21,10 +21,16 @@ import { NetworkData } from './types'; import { SubgraphOptions } from './interfaces'; /** - * **Handle and throw the error.* + * Handles and throws appropriate error types based on the Ethereum error. * - * @param {any} e - * @returns + * @param e - The error to handle + * @throws {InvalidArgumentError} If the error is an invalid argument error + * @throws {ContractExecutionError} If the error is a contract execution error + * @throws {TransactionReplaced} If the transaction was replaced + * @throws {ReplacementUnderpriced} If the replacement transaction was underpriced + * @throws {NumericFault} If there's a numeric fault + * @throws {NonceExpired} If the nonce has expired + * @throws {EthereumError} For any other Ethereum-related error */ export const throwError = (e: any) => { if (ethers.isError(e, 'INVALID_ARGUMENT')) { @@ -45,10 +51,10 @@ export const throwError = (e: any) => { }; /** - * **URL validation.* + * Validates if a string is a valid URL. * - * @param {string} url - * @returns + * @param url - The URL string to validate + * @returns True if the URL is valid, false otherwise */ export const isValidUrl = (url: string): boolean => { return isURL(url, { @@ -59,10 +65,10 @@ export const isValidUrl = (url: string): boolean => { }; /** - * **Check if a string is a valid JSON.* + * Checks if a string is valid JSON. * - * @param {string} input - * @returns {boolean} + * @param input - The string to check + * @returns True if the string is valid JSON, false otherwise */ export const isValidJson = (input: string): boolean => { try { @@ -74,10 +80,10 @@ export const isValidJson = (input: string): boolean => { }; /** - * **Get the subgraph URL.* + * Gets the subgraph URL for the given network, using API key if available. * - * @param {NetworkData} networkData - * @returns + * @param networkData - The network data containing subgraph URLs + * @returns The subgraph URL with API key if available */ export const getSubgraphUrl = (networkData: NetworkData) => { let subgraphUrl = networkData.subgraphUrl; @@ -95,10 +101,10 @@ export const getSubgraphUrl = (networkData: NetworkData) => { }; /** - * **Convert a date to Unix timestamp (seconds since epoch).* + * Converts a Date object to Unix timestamp (seconds since epoch). * - * @param {Date} date - * @returns {number} + * @param date - The date to convert + * @returns Unix timestamp in seconds */ export const getUnixTimestamp = (date: Date): number => { return Math.floor(date.getTime() / 1000); @@ -127,8 +133,16 @@ const buildIndexerUrl = (baseUrl: string, indexerId?: string): string => { }; /** - * Execute a GraphQL request with automatic retry logic for bad indexer errors. - * Only retries if options is provided. + * Executes a GraphQL request with automatic retry logic for bad indexer errors. + * Only retries if options is provided with maxRetries and baseDelay. + * + * @param url - The GraphQL endpoint URL + * @param query - The GraphQL query to execute + * @param variables - Variables for the GraphQL query (optional) + * @param options - Optional configuration for subgraph requests including retry logic + * @returns The response data from the GraphQL query + * @throws ErrorRetryParametersMissing If only one of maxRetries or baseDelay is provided + * @throws ErrorRoutingRequestsToIndexerRequiresApiKey If indexerId is provided without API key */ export const customGqlFetch = async ( url: string, diff --git a/packages/sdk/typescript/human-protocol-sdk/src/worker.ts b/packages/sdk/typescript/human-protocol-sdk/src/worker.ts index 6d37ec10bc..e76278bd3b 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/worker.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/worker.ts @@ -7,21 +7,40 @@ import { GET_WORKER_QUERY, GET_WORKERS_QUERY } from './graphql/queries/worker'; import { IWorker, IWorkersFilter, SubgraphOptions } from './interfaces'; import { getSubgraphUrl, customGqlFetch } from './utils'; +/** + * Utility class for worker-related operations. + * + * @example + * ```ts + * import { WorkerUtils, ChainId } from '@human-protocol/sdk'; + * + * const worker = await WorkerUtils.getWorker( + * ChainId.POLYGON_AMOY, + * '0x1234567890abcdef1234567890abcdef12345678' + * ); + * console.log('Worker:', worker); + * ``` + */ export class WorkerUtils { /** * This function returns the worker data for the given address. * - * @param {ChainId} chainId The chain ID. - * @param {string} address The worker address. - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {Promise} - Returns the worker details or null if not found. - * - * **Code example** + * @param chainId - The chain ID. + * @param address - The worker address. + * @param options - Optional configuration for subgraph requests. + * @returns Returns the worker details or null if not found. + * @throws ErrorUnsupportedChainID If the chain ID is not supported + * @throws ErrorInvalidAddress If the address is invalid * + * @example * ```ts * import { WorkerUtils, ChainId } from '@human-protocol/sdk'; * - * const worker = await WorkerUtils.getWorker(ChainId.POLYGON, '0x1234567890abcdef1234567890abcdef12345678'); + * const worker = await WorkerUtils.getWorker( + * ChainId.POLYGON_AMOY, + * '0x1234567890abcdef1234567890abcdef12345678' + * ); + * console.log('Worker:', worker); * ``` */ public static async getWorker( @@ -79,21 +98,23 @@ export class WorkerUtils { * }; * ``` * - * @param {IWorkersFilter} filter Filter for the workers. - * @param {SubgraphOptions} options Optional configuration for subgraph requests. - * @returns {Promise} Returns an array with all the worker details. - * - * **Code example** + * @param filter - Filter for the workers. + * @param options - Optional configuration for subgraph requests. + * @returns Returns an array with all the worker details. + * @throws ErrorUnsupportedChainID If the chain ID is not supported + * @throws ErrorInvalidAddress If the filter address is invalid * + * @example * ```ts * import { WorkerUtils, ChainId } from '@human-protocol/sdk'; * - * const filter: IWorkersFilter = { - * chainId: ChainId.POLYGON, + * const filter = { + * chainId: ChainId.POLYGON_AMOY, * first: 10, * skip: 0, * }; * const workers = await WorkerUtils.getWorkers(filter); + * console.log('Workers:', workers.length); * ``` */ public static async getWorkers( diff --git a/packages/sdk/typescript/human-protocol-sdk/tsconfig.eslint.json b/packages/sdk/typescript/human-protocol-sdk/tsconfig.eslint.json index 1f7243e15a..653985b892 100644 --- a/packages/sdk/typescript/human-protocol-sdk/tsconfig.eslint.json +++ b/packages/sdk/typescript/human-protocol-sdk/tsconfig.eslint.json @@ -1,4 +1,4 @@ { "extends": "./tsconfig.json", - "include": ["src", "test", "example", "vitest.config.ts"] + "include": ["src", "test", "example", "vitest.config.ts", "scripts"], } diff --git a/packages/sdk/typescript/human-protocol-sdk/typedoc.json b/packages/sdk/typescript/human-protocol-sdk/typedoc.json new file mode 100644 index 0000000000..36912e847b --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/typedoc.json @@ -0,0 +1,46 @@ +{ + "$schema": "https://typedoc-plugin-markdown.org/schema.json", + "entryPoints": [ + "src/index.ts" + ], + "entryPointStrategy": "expand", + "out": "docs", + "plugin": [ + "typedoc-plugin-markdown" + ], + "readme": "none", + "cleanOutputDir": false, + "excludePrivate": true, + "excludeInternal": true, + "excludeProtected": false, + "excludeExternals": false, + "excludeNotDocumented": true, + "categorizeByGroup": false, + "mergeReadme": false, + "blockTags": [ + "@param", + "@returns", + "@throws", + "@example", + "@remarks" + ], + "parametersFormat": "table", + "classPropertiesFormat": "table", + "interfacePropertiesFormat": "table", + "propertyMembersFormat": "table", + "enumMembersFormat": "table", + "typeDeclarationFormat": "table", + "useCodeBlocks": true, + "expandParameters": true, + "hidePageHeader": true, + "hidePageTitle": true, + "hideBreadcrumbs": true, + "disableSources": true, + "excludeTags": [ + "@overload" + ], + "sort": [ + "source-order" + ], + "includeVersion": true +} \ No newline at end of file diff --git a/yarn.lock b/yarn.lock index 09d8305a27..8d69d82c13 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4371,16 +4371,16 @@ __metadata: languageName: node linkType: hard -"@gerrit0/mini-shiki@npm:^3.12.0": - version: 3.14.0 - resolution: "@gerrit0/mini-shiki@npm:3.14.0" - dependencies: - "@shikijs/engine-oniguruma": "npm:^3.14.0" - "@shikijs/langs": "npm:^3.14.0" - "@shikijs/themes": "npm:^3.14.0" - "@shikijs/types": "npm:^3.14.0" +"@gerrit0/mini-shiki@npm:^3.17.0": + version: 3.19.0 + resolution: "@gerrit0/mini-shiki@npm:3.19.0" + dependencies: + "@shikijs/engine-oniguruma": "npm:^3.19.0" + "@shikijs/langs": "npm:^3.19.0" + "@shikijs/themes": "npm:^3.19.0" + "@shikijs/types": "npm:^3.19.0" "@shikijs/vscode-textmate": "npm:^10.0.2" - checksum: 10c0/9539688aec140f2167203b424078d34deec016c8418c497146c6c24920d0590d10b2cd5eec721668a56cb5d42fb278f6f0502bc340274398bb690317ded563b2 + checksum: 10c0/671b4dedbec6702a6ac11ef10091f596f4e63447127d7ed552d8401acfe6a97f2bd983de788739e3544a2fe4b6bc45395618ad3e7c39c9961f32a489b6fae654 languageName: node linkType: hard @@ -4986,6 +4986,7 @@ __metadata: eslint-plugin-jest: "npm:^28.9.0" eslint-plugin-prettier: "npm:^5.2.1" ethers: "npm:~6.15.0" + glob: "npm:^13.0.0" graphql: "npm:^16.8.1" graphql-request: "npm:^7.3.4" graphql-tag: "npm:^2.12.6" @@ -4993,8 +4994,8 @@ __metadata: prettier: "npm:^3.7.4" secp256k1: "npm:^5.0.1" ts-node: "npm:^10.9.2" - typedoc: "npm:^0.28.7" - typedoc-plugin-markdown: "npm:^4.2.3" + typedoc: "npm:^0.28.15" + typedoc-plugin-markdown: "npm:^4.9.0" typescript: "npm:^5.8.3" validator: "npm:^13.12.0" vitest: "npm:^3.0.9" @@ -9056,41 +9057,41 @@ __metadata: languageName: node linkType: hard -"@shikijs/engine-oniguruma@npm:^3.14.0": - version: 3.14.0 - resolution: "@shikijs/engine-oniguruma@npm:3.14.0" +"@shikijs/engine-oniguruma@npm:^3.19.0": + version: 3.19.0 + resolution: "@shikijs/engine-oniguruma@npm:3.19.0" dependencies: - "@shikijs/types": "npm:3.14.0" + "@shikijs/types": "npm:3.19.0" "@shikijs/vscode-textmate": "npm:^10.0.2" - checksum: 10c0/6dab2310c910fedd89046299c4423b2100c8c771822e487070d9eb158907782f195f1b9dd560b6b84f74432bdd1ca4e4429f4af76d30c0e45f8448f100094996 + checksum: 10c0/6f2cbc08c39af982ae3b75283c8216d1932e894a7a1318490807b383ef5f658b1b2940dbab760dfe1b8647ba8df7a365d89e16b02f4f51e397f22046df4b4b5d languageName: node linkType: hard -"@shikijs/langs@npm:^3.14.0": - version: 3.14.0 - resolution: "@shikijs/langs@npm:3.14.0" +"@shikijs/langs@npm:^3.19.0": + version: 3.19.0 + resolution: "@shikijs/langs@npm:3.19.0" dependencies: - "@shikijs/types": "npm:3.14.0" - checksum: 10c0/59ed3b0e9f893a57c8e88b77e9280d993b0dfe219b91db2f8143a65728ef47b02e17056a029f710753184e1c077dfa589cbc5491253d791472a94dca9f598fa3 + "@shikijs/types": "npm:3.19.0" + checksum: 10c0/a7e69ed7c1cea2ccf412a149bd9c4327b6d9314b03271f9782b1703d61949e9787a05d1265f8590c8aa3641657709661c719d105100e70b35a6490c443ceac19 languageName: node linkType: hard -"@shikijs/themes@npm:^3.14.0": - version: 3.14.0 - resolution: "@shikijs/themes@npm:3.14.0" +"@shikijs/themes@npm:^3.19.0": + version: 3.19.0 + resolution: "@shikijs/themes@npm:3.19.0" dependencies: - "@shikijs/types": "npm:3.14.0" - checksum: 10c0/3326482f081e313957c3e74ae86721d18efb32c022b31936f7da1b4782f4c970dea71989934baf9ab8adbeafea07235834b2e6ab83b67e71dc87fb328a1caa58 + "@shikijs/types": "npm:3.19.0" + checksum: 10c0/504d7f637bf5555314bc4a3a61c8cc4f3c712cc00d807f12a40a9d144d40f722dbc0e42409f2a83996cfb2c072326a48e237c265c048b6991844b166f607036b languageName: node linkType: hard -"@shikijs/types@npm:3.14.0, @shikijs/types@npm:^3.14.0": - version: 3.14.0 - resolution: "@shikijs/types@npm:3.14.0" +"@shikijs/types@npm:3.19.0, @shikijs/types@npm:^3.19.0": + version: 3.19.0 + resolution: "@shikijs/types@npm:3.19.0" dependencies: "@shikijs/vscode-textmate": "npm:^10.0.2" "@types/hast": "npm:^3.0.4" - checksum: 10c0/154ec7a79e3c155ed47a14d14ccf91ea09909779993f999cf3d7e424c2f732cd7d7faf8074441a543445f64af1ef9456dcf9ddd4edad96615b68ca60eca2b7bc + checksum: 10c0/fc6509e282c257e4b614d5da3e1e99c7d2e6d4fef6ade3afa668b30dee6763035ad98fadace14f97021cdb371a70eed5ae46cde87f7794fe95e098d6d8a46a3f languageName: node linkType: hard @@ -19826,6 +19827,17 @@ __metadata: languageName: node linkType: hard +"glob@npm:^13.0.0": + version: 13.0.0 + resolution: "glob@npm:13.0.0" + dependencies: + minimatch: "npm:^10.1.1" + minipass: "npm:^7.1.2" + path-scurry: "npm:^2.0.0" + checksum: 10c0/8e2f5821f3f7c312dd102e23a15b80c79e0837a9872784293ba2e15ec73b3f3749a49a42a31bfcb4e52c84820a474e92331c2eebf18819d20308f5c33876630a + languageName: node + linkType: hard + "glob@npm:^5.0.15": version: 5.0.15 resolution: "glob@npm:5.0.15" @@ -23844,7 +23856,7 @@ __metadata: languageName: node linkType: hard -"minimatch@npm:^10.0.0": +"minimatch@npm:^10.0.0, minimatch@npm:^10.1.1": version: 10.1.1 resolution: "minimatch@npm:10.1.1" dependencies: @@ -29929,7 +29941,7 @@ __metadata: languageName: node linkType: hard -"typedoc-plugin-markdown@npm:^4.2.3": +"typedoc-plugin-markdown@npm:^4.9.0": version: 4.9.0 resolution: "typedoc-plugin-markdown@npm:4.9.0" peerDependencies: @@ -29938,11 +29950,11 @@ __metadata: languageName: node linkType: hard -"typedoc@npm:^0.28.7": - version: 0.28.14 - resolution: "typedoc@npm:0.28.14" +"typedoc@npm:^0.28.15": + version: 0.28.15 + resolution: "typedoc@npm:0.28.15" dependencies: - "@gerrit0/mini-shiki": "npm:^3.12.0" + "@gerrit0/mini-shiki": "npm:^3.17.0" lunr: "npm:^2.3.9" markdown-it: "npm:^14.1.0" minimatch: "npm:^9.0.5" @@ -29951,7 +29963,7 @@ __metadata: typescript: 5.0.x || 5.1.x || 5.2.x || 5.3.x || 5.4.x || 5.5.x || 5.6.x || 5.7.x || 5.8.x || 5.9.x bin: typedoc: bin/typedoc - checksum: 10c0/a8727134991ba3f9a982e9f6ceecfbcf0fac531e4865e4865cdee68ea6fe1a594228b8654011d38ffa2332b7e84e4eaa3d0dac04a8bdf36a0686d1c3f327e80b + checksum: 10c0/b5988ebebb367fed44f110bbd37baee85fe95fe10c8d5a511c33d787eb1e924e66ba54cb0763d63ed2c406adbd32fcb87bcbc3fd61b0bc8ab6f3a6c06f2de978 languageName: node linkType: hard @@ -31998,7 +32010,7 @@ __metadata: languageName: node linkType: hard -"yaml@npm:^2.2.2, yaml@npm:^2.7.0, yaml@npm:^2.8.1": +"yaml@npm:^2.2.2, yaml@npm:^2.7.0": version: 2.8.1 resolution: "yaml@npm:2.8.1" bin: @@ -32007,6 +32019,15 @@ __metadata: languageName: node linkType: hard +"yaml@npm:^2.8.1": + version: 2.8.2 + resolution: "yaml@npm:2.8.2" + bin: + yaml: bin.mjs + checksum: 10c0/703e4dc1e34b324aa66876d63618dcacb9ed49f7e7fe9b70f1e703645be8d640f68ab84f12b86df8ac960bac37acf5513e115de7c970940617ce0343c8c9cd96 + languageName: node + linkType: hard + "yargs-parser@npm:21.1.1, yargs-parser@npm:^21.0.0, yargs-parser@npm:^21.1.1": version: 21.1.1 resolution: "yargs-parser@npm:21.1.1"