From 20f008818a47da56293cdc7b67d8f325bf2c8cd7 Mon Sep 17 00:00:00 2001 From: portuu3 Date: Thu, 4 Dec 2025 15:45:12 +0100 Subject: [PATCH 01/19] use mkdocs docstring for python sdk --- docs/overrides/assets/css/custom.css | 151 ++ docs/overrides/assets/img/logo.svg | 3 + docs/overrides/partials/header.html | 107 ++ docs/overrides/partials/logo.html | 10 + .../sdk/python/human-protocol-sdk/Makefile | 9 - .../python/human-protocol-sdk/docs/Makefile | 20 - .../human-protocol-sdk/docs/api/agreement.md | 19 + .../human-protocol-sdk/docs/api/core.md | 19 + .../python/human-protocol-sdk/docs/api/gql.md | 47 + .../human-protocol-sdk/docs/api/worker.md | 7 + .../python/human-protocol-sdk/docs/conf.py | 54 - .../human-protocol-sdk/docs/encryption.md | 1 + .../docs/encryption_utils.md | 1 + .../human-protocol-sdk/docs/escrow_client.md | 1 + .../human-protocol-sdk/docs/escrow_utils.md | 1 + ...human_protocol_sdk.agreement.bootstrap.rst | 7 - .../human_protocol_sdk.agreement.measures.rst | 7 - .../docs/human_protocol_sdk.agreement.rst | 17 - .../human_protocol_sdk.agreement.utils.rst | 7 - .../docs/human_protocol_sdk.constants.rst | 7 - .../docs/human_protocol_sdk.decorators.rst | 7 - ...man_protocol_sdk.encryption.encryption.rst | 7 - ...otocol_sdk.encryption.encryption_utils.rst | 7 - .../docs/human_protocol_sdk.encryption.rst | 16 - ...uman_protocol_sdk.escrow.escrow_client.rst | 7 - ...human_protocol_sdk.escrow.escrow_utils.rst | 7 - .../docs/human_protocol_sdk.escrow.rst | 16 - .../docs/human_protocol_sdk.filter.rst | 7 - ...an_protocol_sdk.kvstore.kvstore_client.rst | 7 - ...man_protocol_sdk.kvstore.kvstore_utils.rst | 7 - .../docs/human_protocol_sdk.kvstore.rst | 16 - .../human_protocol_sdk.legacy_encryption.rst | 7 - ...n_protocol_sdk.operator.operator_utils.rst | 7 - .../docs/human_protocol_sdk.operator.rst | 15 - .../docs/human_protocol_sdk.rst | 35 - .../docs/human_protocol_sdk.staking.rst | 16 - ...an_protocol_sdk.staking.staking_client.rst | 7 - ...man_protocol_sdk.staking.staking_utils.rst | 7 - .../docs/human_protocol_sdk.statistics.rst | 15 - ...tocol_sdk.statistics.statistics_client.rst | 7 - .../docs/human_protocol_sdk.storage.rst | 16 - ...an_protocol_sdk.storage.storage_client.rst | 7 - ...man_protocol_sdk.storage.storage_utils.rst | 7 - .../docs/human_protocol_sdk.transaction.rst | 15 - ...ocol_sdk.transaction.transaction_utils.rst | 7 - .../docs/human_protocol_sdk.utils.rst | 7 - .../docs/human_protocol_sdk.worker.rst | 15 - ...human_protocol_sdk.worker.worker_utils.rst | 7 - .../python/human-protocol-sdk/docs/index.md | 11 + .../python/human-protocol-sdk/docs/index.rst | 28 - .../human-protocol-sdk/docs/kvstore_client.md | 1 + .../human-protocol-sdk/docs/kvstore_utils.md | 1 + .../python/human-protocol-sdk/docs/make.bat | 35 - .../human-protocol-sdk/docs/operator_utils.md | 1 + .../docs/overrides/assets/css/custom.css | 151 ++ .../docs/overrides/assets/img/logo.svg | 3 + .../docs/overrides/partials/header.html | 107 ++ .../docs/overrides/partials/logo.html | 10 + .../human-protocol-sdk/docs/staking_client.md | 1 + .../human-protocol-sdk/docs/staking_utils.md | 1 + .../docs/statistics_client.md | 1 + .../docs/transaction_utils.md | 1 + .../encryption/encryption.py | 208 +-- .../encryption/encryption_utils.py | 241 +-- .../escrow/escrow_client.py | 1559 +++++++++-------- .../human_protocol_sdk/escrow/escrow_utils.py | 282 +-- .../kvstore/kvstore_client.py | 224 +-- .../kvstore/kvstore_utils.py | 172 +- .../operator/operator_utils.py | 218 +-- .../staking/staking_client.py | 351 +--- .../staking/staking_utils.py | 62 +- .../statistics/statistics_client.py | 366 ++-- .../storage/storage_client.py | 266 +-- .../transaction/transaction_utils.py | 121 +- .../sdk/python/human-protocol-sdk/mkdocs.yaml | 94 + 75 files changed, 2481 insertions(+), 2831 deletions(-) create mode 100644 docs/overrides/assets/css/custom.css create mode 100644 docs/overrides/assets/img/logo.svg create mode 100644 docs/overrides/partials/header.html create mode 100644 docs/overrides/partials/logo.html delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/Makefile create mode 100644 packages/sdk/python/human-protocol-sdk/docs/api/agreement.md create mode 100644 packages/sdk/python/human-protocol-sdk/docs/api/core.md create mode 100644 packages/sdk/python/human-protocol-sdk/docs/api/gql.md create mode 100644 packages/sdk/python/human-protocol-sdk/docs/api/worker.md delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/conf.py create mode 100644 packages/sdk/python/human-protocol-sdk/docs/encryption.md create mode 100644 packages/sdk/python/human-protocol-sdk/docs/encryption_utils.md create mode 100644 packages/sdk/python/human-protocol-sdk/docs/escrow_client.md create mode 100644 packages/sdk/python/human-protocol-sdk/docs/escrow_utils.md delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.agreement.bootstrap.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.agreement.measures.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.agreement.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.agreement.utils.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.constants.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.decorators.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.encryption.encryption.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.encryption.encryption_utils.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.encryption.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.escrow.escrow_client.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.escrow.escrow_utils.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.escrow.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.filter.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.kvstore.kvstore_client.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.kvstore.kvstore_utils.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.kvstore.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.legacy_encryption.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.operator.operator_utils.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.operator.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.staking.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.staking.staking_client.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.staking.staking_utils.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.statistics.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.statistics.statistics_client.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.storage.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.storage.storage_client.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.storage.storage_utils.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.transaction.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.transaction.transaction_utils.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.utils.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.worker.rst delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.worker.worker_utils.rst create mode 100644 packages/sdk/python/human-protocol-sdk/docs/index.md delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/index.rst create mode 100644 packages/sdk/python/human-protocol-sdk/docs/kvstore_client.md create mode 100644 packages/sdk/python/human-protocol-sdk/docs/kvstore_utils.md delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/make.bat create mode 100644 packages/sdk/python/human-protocol-sdk/docs/operator_utils.md create mode 100644 packages/sdk/python/human-protocol-sdk/docs/overrides/assets/css/custom.css create mode 100644 packages/sdk/python/human-protocol-sdk/docs/overrides/assets/img/logo.svg create mode 100644 packages/sdk/python/human-protocol-sdk/docs/overrides/partials/header.html create mode 100644 packages/sdk/python/human-protocol-sdk/docs/overrides/partials/logo.html create mode 100644 packages/sdk/python/human-protocol-sdk/docs/staking_client.md create mode 100644 packages/sdk/python/human-protocol-sdk/docs/staking_utils.md create mode 100644 packages/sdk/python/human-protocol-sdk/docs/statistics_client.md create mode 100644 packages/sdk/python/human-protocol-sdk/docs/transaction_utils.md create mode 100644 packages/sdk/python/human-protocol-sdk/mkdocs.yaml diff --git a/docs/overrides/assets/css/custom.css b/docs/overrides/assets/css/custom.css new file mode 100644 index 0000000000..c16b4cd7c4 --- /dev/null +++ b/docs/overrides/assets/css/custom.css @@ -0,0 +1,151 @@ +/* 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-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; +} + +/* Wrapper in header */ +.md-header__langswitch { + position: relative; + display: inline-flex; + align-items: center; + gap: 0.25rem; + padding: 4px 10px; + border-radius: 999px; + border: 1px solid rgba(255, 255, 255, 0.55); + font-size: 0.78rem; + color: rgba(255, 255, 255, 0.85); + cursor: pointer; +} + +/* Label + caret */ +.md-header__langlabel { + white-space: nowrap; +} + +.md-header__langcaret { + font-size: 0.7rem; + opacity: 0.8; +} + +/* Dropdown menu */ +.md-header__langmenu { + position: absolute; + top: 100%; + right: 0; + margin-top: 0.4rem; + min-width: 140px; + padding: 0.35rem 0; + border-radius: 0.4rem; + background: #201547; /* your header purple */ + box-shadow: 0 6px 18px rgba(0, 0, 0, 0.35); + display: none; + flex-direction: column; + z-index: 20; +} + +/* Show on hover/focus */ +.md-header__langswitch:hover .md-header__langmenu, +.md-header__langswitch:focus-within .md-header__langmenu { + display: flex; +} + +/* Items */ +.md-header__langitem { + padding: 0.4rem 0.9rem; + font-size: 0.78rem; + text-decoration: none; + color: rgba(255, 255, 255, 0.85); + white-space: nowrap; +} + +.md-header__langitem:hover { + background: rgba(255, 255, 255, 0.12); + color: #ffffff; +} + +.md-header__langitem--active { + font-weight: 600; + background: rgba(255, 255, 255, 0.18); +} + +/* Mobile: optionally hide or shrink */ +@media (max-width: 900px) { + .md-header__langswitch { + display: none; /* or keep and it will still work */ + } +} \ 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/partials/header.html b/docs/overrides/partials/header.html new file mode 100644 index 0000000000..84fcc08d3b --- /dev/null +++ b/docs/overrides/partials/header.html @@ -0,0 +1,107 @@ +{#- + 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 %} +
\ No newline at end of file diff --git a/docs/overrides/partials/logo.html b/docs/overrides/partials/logo.html new file mode 100644 index 0000000000..8647db9a77 --- /dev/null +++ b/docs/overrides/partials/logo.html @@ -0,0 +1,10 @@ + \ No newline at end of file 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/api/agreement.md b/packages/sdk/python/human-protocol-sdk/docs/api/agreement.md new file mode 100644 index 0000000000..ba5e855c54 --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/api/agreement.md @@ -0,0 +1,19 @@ +# Agreement + +APIs for measuring inter-rater agreement on annotated data. + +## Package + +::: human_protocol_sdk.agreement + +## Measures + +::: human_protocol_sdk.agreement.measures + +## Utilities + +::: human_protocol_sdk.agreement.utils + +## Bootstrap helpers + +::: human_protocol_sdk.agreement.bootstrap diff --git a/packages/sdk/python/human-protocol-sdk/docs/api/core.md b/packages/sdk/python/human-protocol-sdk/docs/api/core.md new file mode 100644 index 0000000000..4322e215dc --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/api/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/api/gql.md b/packages/sdk/python/human-protocol-sdk/docs/api/gql.md new file mode 100644 index 0000000000..72fa6f76c7 --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/api/gql.md @@ -0,0 +1,47 @@ +# GraphQL helpers + +Query builders used by the SDK to interact with HUMAN Protocol subgraphs. + +## Escrow + +::: human_protocol_sdk.gql.escrow + +## Staking + +::: human_protocol_sdk.gql.staking + +## Operator + +::: human_protocol_sdk.gql.operator + +## Worker + +::: human_protocol_sdk.gql.worker + +## Transaction + +::: human_protocol_sdk.gql.transaction + +## KVStore + +::: human_protocol_sdk.gql.kvstore + +## Statistics + +::: human_protocol_sdk.gql.statistics + +## Rewards + +::: human_protocol_sdk.gql.reward + +## Payouts + +::: human_protocol_sdk.gql.payout + +## Token + +::: human_protocol_sdk.gql.hmtoken + +## Cancellation + +::: human_protocol_sdk.gql.cancel diff --git a/packages/sdk/python/human-protocol-sdk/docs/api/worker.md b/packages/sdk/python/human-protocol-sdk/docs/api/worker.md new file mode 100644 index 0000000000..b8c639b1f3 --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/api/worker.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/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/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..fdbb0c78f1 --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/index.md @@ -0,0 +1,11 @@ +# HUMAN Protocol Python SDK + +The Python SDK provides a high-level, Pythonic interface to HUMAN Protocol +smart contracts and off-chain services. + +Use it to: + +- Interact with Escrow, Staking, and KVStore contracts +- Manage operators and workers +- Query statistics and on-chain data +- Build automations, bots, and back-end services 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/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/overrides/assets/css/custom.css b/packages/sdk/python/human-protocol-sdk/docs/overrides/assets/css/custom.css new file mode 100644 index 0000000000..c16b4cd7c4 --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/overrides/assets/css/custom.css @@ -0,0 +1,151 @@ +/* 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-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; +} + +/* Wrapper in header */ +.md-header__langswitch { + position: relative; + display: inline-flex; + align-items: center; + gap: 0.25rem; + padding: 4px 10px; + border-radius: 999px; + border: 1px solid rgba(255, 255, 255, 0.55); + font-size: 0.78rem; + color: rgba(255, 255, 255, 0.85); + cursor: pointer; +} + +/* Label + caret */ +.md-header__langlabel { + white-space: nowrap; +} + +.md-header__langcaret { + font-size: 0.7rem; + opacity: 0.8; +} + +/* Dropdown menu */ +.md-header__langmenu { + position: absolute; + top: 100%; + right: 0; + margin-top: 0.4rem; + min-width: 140px; + padding: 0.35rem 0; + border-radius: 0.4rem; + background: #201547; /* your header purple */ + box-shadow: 0 6px 18px rgba(0, 0, 0, 0.35); + display: none; + flex-direction: column; + z-index: 20; +} + +/* Show on hover/focus */ +.md-header__langswitch:hover .md-header__langmenu, +.md-header__langswitch:focus-within .md-header__langmenu { + display: flex; +} + +/* Items */ +.md-header__langitem { + padding: 0.4rem 0.9rem; + font-size: 0.78rem; + text-decoration: none; + color: rgba(255, 255, 255, 0.85); + white-space: nowrap; +} + +.md-header__langitem:hover { + background: rgba(255, 255, 255, 0.12); + color: #ffffff; +} + +.md-header__langitem--active { + font-weight: 600; + background: rgba(255, 255, 255, 0.18); +} + +/* Mobile: optionally hide or shrink */ +@media (max-width: 900px) { + .md-header__langswitch { + display: none; /* or keep and it will still work */ + } +} \ No newline at end of file diff --git a/packages/sdk/python/human-protocol-sdk/docs/overrides/assets/img/logo.svg b/packages/sdk/python/human-protocol-sdk/docs/overrides/assets/img/logo.svg new file mode 100644 index 0000000000..b827f1dbc7 --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/overrides/assets/img/logo.svg @@ -0,0 +1,3 @@ + + + diff --git a/packages/sdk/python/human-protocol-sdk/docs/overrides/partials/header.html b/packages/sdk/python/human-protocol-sdk/docs/overrides/partials/header.html new file mode 100644 index 0000000000..84fcc08d3b --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/overrides/partials/header.html @@ -0,0 +1,107 @@ +{#- + 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 %} +
\ No newline at end of file diff --git a/packages/sdk/python/human-protocol-sdk/docs/overrides/partials/logo.html b/packages/sdk/python/human-protocol-sdk/docs/overrides/partials/logo.html new file mode 100644 index 0000000000..8647db9a77 --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/overrides/partials/logo.html @@ -0,0 +1,10 @@ + \ No newline at end of file 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_client.md b/packages/sdk/python/human-protocol-sdk/docs/statistics_client.md new file mode 100644 index 0000000000..d8e6d4e616 --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/statistics_client.md @@ -0,0 +1 @@ +::: human_protocol_sdk.statistics.statistics_client 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/human_protocol_sdk/encryption/encryption.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/encryption/encryption.py index 284b30fbd1..a0f041eb54 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,14 @@ class Encryption: - """ - A class that provides encryption and decryption functionality using PGP (Pretty Good Privacy). - """ + """Encryption and decryption helper using PGP (Pretty Good Privacy).""" def __init__(self, private_key_armored: str, passphrase: Optional[str] = None): - """ - Initializes an Encryption instance. + """Create an Encryption helper. - :param private_key_armored: Armored representation of the private key - :param passphrase: Passphrase to unlock the private key. Defaults to None. + Args: + private_key_armored: Armored representation of the private key. + passphrase: Passphrase to unlock the private key. """ try: self.private_key, _ = PGPKey.from_blob(private_key_armored) @@ -77,69 +35,25 @@ 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----- + """Sign and encrypt a message with recipient public keys. - 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-----\"\"\" + Args: + message: Message to sign and encrypt. + public_keys: Armored public keys of the recipients. - passphrase = "passphrase" + Returns: + Armored, signed, and encrypted message. - public_key2 = \"\"\"-----BEGIN PGP PUBLIC KEY BLOCK----- + Example: + ```python + from human_protocol_sdk.encryption import Encryption - 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] - ) + 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 +78,22 @@ 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. - - :return: Decrypted message + """Decrypt a message using the private key. - :example: - .. code-block:: python + Args: + message: Armored message to decrypt. + public_key: Optional armored public key to verify signatures. - from human_protocol_sdk.encryption import Encryption + Returns: + Decrypted message bytes. - private_key = \"\"\"-----BEGIN PGP PRIVATE KEY BLOCK----- + Example: + ```python + from human_protocol_sdk.encryption import Encryption - 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) - decrypted_message = encryption.decrypt(encrypted_message) + encryption = Encryption("-----BEGIN PGP PRIVATE KEY BLOCK-----...", "passphrase") + decrypted_message = encryption.decrypt(encrypted_message) + ``` """ pgp_message = PGPMessage.from_blob(message) decrypted_message = "" @@ -229,38 +126,21 @@ 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 - - :example: - .. code-block:: python - - from human_protocol_sdk.encryption import Encryption + """Sign a message with the private key. - private_key = \"\"\"-----BEGIN PGP PRIVATE KEY BLOCK----- + Args: + message: Message to sign. - 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-----\"\"\" + Returns: + Armored signed message. - 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 = await 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..837c6813a4 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,28 @@ class EncryptionUtils: - """ - A utility class that provides additional encryption-related functionalities. - """ + """Utility helpers for PGP encryption-related functionality.""" @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 + """Encrypt a message using recipient public keys. - :return: Armored and encrypted message + Args: + message: Message to encrypt. + public_keys: Armored public keys of the recipients. - :example: - .. code-block:: python + Returns: + Armored encrypted message. - from human_protocol_sdk.encryption import EncryptionUtils + Example: + ```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] - ) + encrypted_message = EncryptionUtils.encrypt( + "MESSAGE", + ["-----BEGIN PGP PUBLIC KEY BLOCK-----..."], + ) + ``` """ pgp_message = PGPMessage.new(message) cipher = SymmetricKeyAlgorithm.AES256 @@ -118,57 +44,14 @@ 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 + """Verify the signature of a message. - private_key3 = \"\"\"-----BEGIN PGP PRIVATE KEY BLOCK----- + Args: + message: Armored message to verify. + public_key: Armored public key. - 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) + Returns: + True if the signature is valid, False otherwise. """ try: signed_message = ( @@ -182,56 +65,13 @@ 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----- + """Extract the signed data from an armored signed message. - 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-----\"\"\" + Args: + message: Armored message. - 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) + Returns: + Extracted signed data. """ try: signed_message = ( @@ -243,30 +83,13 @@ 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 - - :example: - .. code-block:: python - - from human_protocol_sdk.encryption import EncryptionUtils - - message_1 = "message" - message_2 = \"\"\"-----BEGIN PGP MESSAGE----- + """Check whether a provided message is armored and encrypted. - wV4Dh8BoKHkyM3YSAQdAMGVFo+Meahw422JdMyDkxPA4LXeN94bOqsS9OhYGliYw - 72HgGdhoRHrRBKmRyD+Bb2HUrGptx8YRYqYJXiFVs4ev1USt6pF/5XjH+pM0d44B - 0j0BcVevrVhjdBia8kEr74NJKB2qiPAffbFJFRE1asYqQgFTjNC60/egqfzpdRay - Tj8C+e0IXRMECIXnrOaw - =SjJh - -----END PGP MESSAGE-----\"\"\" + Args: + message: Text to check. - print("The message_1 is encrypted: ", EncryptionUtils.is_encrypted(message_1)) - print("The message_2 is encrypted: ", EncryptionUtils.is_encrypted(message_2)) + Returns: + True if the message is a PGP message, False otherwise. """ 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..438f677936 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 @@ -79,11 +70,11 @@ 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. + Args: + tx_hash: The hash of the transaction that cancelled the escrow. + amount_refunded: The amount refunded during the escrow cancellation. """ self.txHash = tx_hash self.amountRefunded = amount_refunded @@ -91,12 +82,12 @@ def __init__(self, tx_hash: str, amount_refunded: any): 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 cancellation 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. + Args: + tx_hash: The hash of the transaction associated with the escrow withdrawal. + token_address: The address of the token used for the withdrawal. + withdrawn_amount: The amount withdrawn from the escrow. """ self.txHash = tx_hash self.token_address = token_address @@ -104,17 +95,13 @@ def __init__(self, tx_hash: str, token_address: str, withdrawn_amount: any): class EscrowClientError(Exception): - """ - Raises when some error happens when interacting with escrow. - """ + """Raises when some error happens when interacting with escrow.""" pass class EscrowConfig: - """ - A class used to manage escrow parameters. - """ + """A class used to manage escrow parameters.""" def __init__( self, @@ -127,15 +114,15 @@ def __init__( manifest: str, 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 + """Initializes an EscrowClient instance. + + Args: + recording_oracle_address: Address of the Recording Oracle + reputation_oracle_address: Address of the Reputation Oracle + recording_oracle_fee: Fee percentage of the Recording Oracle + reputation_oracle_fee: Fee percentage of the Reputation Oracle + manifest: Manifest data (can be a URL or JSON string) + hash: Manifest file hash """ if not Web3.is_address(recording_oracle_address): raise EscrowClientError( @@ -174,15 +161,13 @@ def __init__( class EscrowClient: - """ - A client class to interact with the escrow smart contract. - """ + """A client class to interact with the escrow smart contract.""" def __init__(self, web3: Web3): - """ - Initializes a Escrow instance. + """Initializes an EscrowClient instance. - :param web3: The Web3 object + Args: + web3: The Web3 object """ # Initialize web3 instance @@ -216,46 +201,48 @@ 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 + """Creates a new escrow contract. + + Args: + token_address: Address of the token to be used in the escrow + job_requester_id: An off-chain identifier for the job requester + tx_options: (Optional) Transaction options + + Returns: + Address of the created escrow contract + + 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.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 + ) + ``` """ if not Web3.is_address(token_address): raise EscrowClientError(f"Invalid token address: {token_address}") @@ -286,65 +273,67 @@ 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' + """Creates, funds, and sets up a new escrow contract in a single transaction. + + Args: + token_address: Address of the token to be used in the escrow + amount: The token amount to fund the escrow with + job_requester_id: An off-chain identifier for the job requester + escrow_config: Configuration parameters for escrow setup + tx_options: (Optional) Transaction options + + Returns: + Address of the created escrow contract + + 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.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 - ) + escrow_address = escrow_client.create_fund_and_setup_escrow( + token_address, + amount, + job_requester_id, + escrow_config + ) + ``` """ if not Web3.is_address(token_address): raise EscrowClientError(f"Invalid token address: {token_address}") @@ -383,56 +372,56 @@ 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 + """Sets up the parameters of the escrow. + + Args: + escrow_address: Address of the escrow contract + escrow_config: Configuration parameters for the escrow + tx_options: (Optional) Transaction options + + 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.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 + ) + ``` """ if not Web3.is_address(escrow_address): raise EscrowClientError(f"Invalid escrow address: {escrow_address}") @@ -463,45 +452,47 @@ 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 + """Adds funds to the escrow. - :return: None + Args: + escrow_address: Address of the escrow to fund + amount: Amount to be added as funds + tx_options: (Optional) Additional transaction parameters - :raise EscrowClientError: If an error occurs while checking the parameters + Returns: + None - :example: - .. code-block:: python + Raises: + EscrowClientError: If an error occurs while checking the parameters - from eth_typing import URI - from web3 import Web3 - from web3.middleware import SignAndSendRawMiddlewareBuilder - from web3.providers.auto import load_provider_from_uri + 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.escrow import EscrowClient + 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) + 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) + (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 - ) + amount = Web3.to_wei(5, 'ether') # convert from ETH to WEI + escrow_client.fund( + "0x62dD51230A30401C455c8398d06F85e4EaB6309f", amount + ) + ``` """ if not Web3.is_address(escrow_address): raise EscrowClientError(f"Invalid escrow address: {escrow_address}") @@ -529,48 +520,50 @@ 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" + """Stores the results URL and hash, with optional funds to reserve. + + Args: + escrow_address: Address of the escrow + url: Results file URL + hash: Results file hash + funds_to_reserve: (Optional) Funds to reserve for payouts + tx_options: (Optional) Additional transaction parameters + + Returns: + None + + Raises: + EscrowClientError: If an error occurs while checking the parameters + + 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.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" + ) + ``` """ if not Web3.is_address(escrow_address): raise EscrowClientError(f"Invalid escrow address: {escrow_address}") @@ -614,41 +607,43 @@ 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. + """Sets the status of an escrow to completed. - :param escrow_address: Address of the escrow to complete - :param tx_options: (Optional) Additional transaction parameters + Args: + escrow_address: Address of the escrow to complete + tx_options: (Optional) Additional transaction parameters - :return: None + Returns: + None - :raise EscrowClientError: If an error occurs while checking the parameters + Raises: + EscrowClientError: If an error occurs while checking the parameters - :example: - .. code-block:: python + 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 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 - 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) + 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) + (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') + escrow_client = EscrowClient(w3) - escrow_client.complete("0x62dD51230A30401C455c8398d06F85e4EaB6309f") + escrow_client.complete("0x62dD51230A30401C455c8398d06F85e4EaB6309f") + ``` """ if not Web3.is_address(escrow_address): raise EscrowClientError(f"Invalid escrow address: {escrow_address}") @@ -675,65 +670,67 @@ 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 + """Pays out to recipients, supporting both payoutId (str) and txId (int) signatures and sets the URL of the final results file. + + Args: + escrow_address: Address of the escrow + recipients: List of recipient addresses + amounts: List of amounts + final_results_url: Final results file URL + final_results_hash: Final results file hash + payout_id: Payout ID (str) or Transaction ID (int) + force_complete: (Optional) Whether to force completion + tx_options: (Optional) Transaction options + + Returns: + None + + Raises: + EscrowClientError: If an error occurs while checking the parameters + + 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.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 + ) + ``` """ self.ensure_correct_bulk_payout_input( escrow_address, recipients, amounts, final_results_url, final_results_hash @@ -784,77 +781,78 @@ 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 - ) + """Creates a prepared transaction for bulk payout without signing or sending it. - print(f"Transaction: {transaction}") + Args: + escrow_address: Address of the escrow + recipients: Array of recipient addresses + amounts: Array of amounts the recipients will receive + final_results_url: Final results file URL + final_results_hash: Final results file hash + payoutId: Unique identifier for the payout + tx_options: (Optional) Additional transaction parameters - signed_transaction = w3.eth.account.sign_transaction( - transaction, private_key - ) - tx_hash = w3.eth.send_raw_transaction( - signed_transaction.raw_transaction + Returns: + A dictionary containing the prepared transaction + + Raises: EscrowClientError: If an error occurs while checking the parameters + + 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.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, ) - 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}") + 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}") + ``` """ self.ensure_correct_bulk_payout_input( escrow_address, recipients, amounts, final_results_url, final_results_hash @@ -904,18 +902,20 @@ def ensure_correct_bulk_payout_input( final_results_url: str, final_results_hash: str, ) -> None: - """ - Validates input parameters for bulk payout operations. + """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 + Args: + escrow_address: Address of the escrow + recipients: Array of recipient addresses + amounts: Array of amounts the recipients will receive + final_results_url: Final results file URL + final_results_hash: Final results file hash - :return: None + Returns: + None - :raise EscrowClientError: If validation fails + Raises: + EscrowClientError: If validation fails """ if not Web3.is_address(escrow_address): raise EscrowClientError(f"Invalid escrow address: {escrow_address}") @@ -949,36 +949,37 @@ def request_cancellation( ) -> None: """Requests the cancellation of the specified escrow (moves status to ToCancel or finalizes if expired). - :param escrow_address: Address of the escrow to request cancellation - :param tx_options: (Optional) Additional transaction parameters - - :example: - .. code-block:: python + Args: + escrow_address: Address of the escrow to request cancellation + tx_options: (Optional) Additional transaction parameters - from eth_typing import URI - from web3 import Web3 - from web3.middleware import SignAndSendRawMiddlewareBuilder - from web3.providers.auto import load_provider_from_uri + 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.escrow import EscrowClient + 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) + 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) + (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') + escrow_client = EscrowClient(w3) - escrow_client.request_cancellation( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + escrow_client.request_cancellation( + "0x62dD51230A30401C455c8398d06F85e4EaB6309f" + ) + ``` """ if not Web3.is_address(escrow_address): raise EscrowClientError(f"Invalid escrow address: {escrow_address}") @@ -997,47 +998,47 @@ 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. + """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 + Args: + escrow_address: Address of the escrow to cancel + 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. + Returns: + 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 + Raises: + EscrowClientError: If an error occurs while checking the parameters + EscrowClientError: If the transfer event associated with the cancellation 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 + 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.escrow import EscrowClient + 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) + 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) + (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') + escrow_client = EscrowClient(w3) - escrow_cancel_data = escrow_client.cancel( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + escrow_cancel_data = escrow_client.cancel( + "0x62dD51230A30401C455c8398d06F85e4EaB6309f" + ) + ``` """ if not Web3.is_address(escrow_address): raise EscrowClientError(f"Invalid escrow address: {escrow_address}") @@ -1059,49 +1060,48 @@ def withdraw( token_address: str, tx_options: Optional[TxParams] = None, ) -> EscrowWithdraw: - """ - Withdraws additional tokens in the escrow to the canceler. + """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 + Args: + escrow_address: Address of the escrow to withdraw + token_address: Address of the token to withdraw + 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. + Returns: + 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 + Raises: + EscrowClientError: If an error occurs while checking the parameters + EscrowClientError: If the transfer event associated with the withdrawal is not found in the transaction logs + + 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.escrow import EscrowClient - :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" + 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" + ) + ``` """ if not Web3.is_address(escrow_address): @@ -1146,30 +1146,32 @@ 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. + """Gets the balance for a specified escrow address. - :param escrow_address: Address of the escrow + Args: + escrow_address: Address of the escrow - :return: Value of the balance + Returns: + Value of the balance - :raise EscrowClientError: If an error occurs while checking the parameters + Raises: + EscrowClientError: If an error occurs while checking the parameters - :example: - .. code-block:: python + Example: + ```python + from eth_typing import URI + from web3 import Web3 + from web3.providers.auto import load_provider_from_uri - 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 - from human_protocol_sdk.escrow import EscrowClient + w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) + escrow_client = EscrowClient(w3) - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) - - balance = escrow_client.get_balance( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + balance = escrow_client.get_balance( + "0x62dD51230A30401C455c8398d06F85e4EaB6309f" + ) + ``` """ if not Web3.is_address(escrow_address): @@ -1188,30 +1190,32 @@ 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. + """Gets the reserved funds for a specified escrow address. - :param escrow_address: Address of the escrow + Args: + escrow_address: Address of the escrow - :return: Value of the reserved funds + Returns: + Value of the reserved funds - :raise EscrowClientError: If an error occurs while checking the parameters + Raises: + EscrowClientError: If an error occurs while checking the parameters - :example: - .. code-block:: python + Example: + ```python + from eth_typing import URI + from web3 import Web3 + from web3.providers.auto import load_provider_from_uri - 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 - from human_protocol_sdk.escrow import EscrowClient + w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) + escrow_client = EscrowClient(w3) - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) - - reserved_funds = escrow_client.get_reserved_funds( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + reserved_funds = escrow_client.get_reserved_funds( + "0x62dD51230A30401C455c8398d06F85e4EaB6309f" + ) + ``` """ if not Web3.is_address(escrow_address): @@ -1222,30 +1226,32 @@ def get_reserved_funds(self, escrow_address: str) -> int: ) def get_manifest_hash(self, escrow_address: str) -> str: - """ - Gets the manifest file hash. + """Gets the manifest file hash. - :param escrow_address: Address of the escrow + Args: + escrow_address: Address of the escrow - :return: Manifest file hash + Returns: + Manifest file hash - :raise EscrowClientError: If an error occurs while checking the parameters + Raises: + EscrowClientError: If an error occurs while checking the parameters - :example: - .. code-block:: python + Example: + ```python + from eth_typing import URI + from web3 import Web3 + from web3.providers.auto import load_provider_from_uri - 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 - from human_protocol_sdk.escrow import EscrowClient + w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) + escrow_client = EscrowClient(w3) - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) - - manifest_hash = escrow_client.get_manifest_hash( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + manifest_hash = escrow_client.get_manifest_hash( + "0x62dD51230A30401C455c8398d06F85e4EaB6309f" + ) + ``` """ if not Web3.is_address(escrow_address): @@ -1254,30 +1260,32 @@ 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). + """Gets the manifest data (can be a URL or JSON string). - :param escrow_address: Address of the escrow + Args: + escrow_address: Address of the escrow - :return str: Manifest data + Returns: + Manifest data - :raise EscrowClientError: If an error occurs while checking the parameters + Raises: + EscrowClientError: If an error occurs while checking the parameters - :example: - .. code-block:: python + Example: + ```python + from eth_typing import URI + from web3 import Web3 + from web3.providers.auto import load_provider_from_uri - 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 - from human_protocol_sdk.escrow import EscrowClient + w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) + escrow_client = EscrowClient(w3) - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) - - manifest = escrow_client.get_manifest( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + manifest = escrow_client.get_manifest( + "0x62dD51230A30401C455c8398d06F85e4EaB6309f" + ) + ``` """ if not Web3.is_address(escrow_address): @@ -1286,30 +1294,32 @@ 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. + """Gets the results file URL. - :param escrow_address: Address of the escrow + Args: + escrow_address: Address of the escrow - :return: Results file url + Returns: + Results file url - :raise EscrowClientError: If an error occurs while checking the parameters + Raises: + EscrowClientError: If an error occurs while checking the parameters - :example: - .. code-block:: python + Example: + ```python + from eth_typing import URI + from web3 import Web3 + from web3.providers.auto import load_provider_from_uri - 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 - from human_protocol_sdk.escrow import EscrowClient + w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) + escrow_client = EscrowClient(w3) - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) - - url = escrow_client.get_results_url( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + url = escrow_client.get_results_url( + "0x62dD51230A30401C455c8398d06F85e4EaB6309f" + ) + ``` """ if not Web3.is_address(escrow_address): @@ -1320,30 +1330,32 @@ 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. + """Gets the intermediate results file URL. - :param escrow_address: Address of the escrow + Args: + escrow_address: Address of the escrow - :return: Intermediate results file url + Returns: + Intermediate results file url - :raise EscrowClientError: If an error occurs while checking the parameters + Raises: + EscrowClientError: If an error occurs while checking the parameters - :example: - .. code-block:: python + Example: + ```python + from eth_typing import URI + from web3 import Web3 + from web3.providers.auto import load_provider_from_uri - 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 - from human_protocol_sdk.escrow import EscrowClient + w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) + escrow_client = EscrowClient(w3) - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) - - url = escrow_client.get_intermediate_results_url( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + url = escrow_client.get_intermediate_results_url( + "0x62dD51230A30401C455c8398d06F85e4EaB6309f" + ) + ``` """ if not Web3.is_address(escrow_address): @@ -1356,30 +1368,32 @@ 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. + """Gets the intermediate results file hash. - :param escrow_address: Address of the escrow + Args: + escrow_address: Address of the escrow - :return: Intermediate results file hash + Returns: + Intermediate results file hash - :raise EscrowClientError: If an error occurs while checking the parameters + Raises: + EscrowClientError: If an error occurs while checking the parameters - :example: - .. code-block:: python + Example: + ```python + from eth_typing import URI + from web3 import Web3 + from web3.providers.auto import load_provider_from_uri - 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 - from human_protocol_sdk.escrow import EscrowClient + w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) + escrow_client = EscrowClient(w3) - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) - - hash = escrow_client.get_intermediate_results_hash( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + hash = escrow_client.get_intermediate_results_hash( + "0x62dD51230A30401C455c8398d06F85e4EaB6309f" + ) + ``` """ if not Web3.is_address(escrow_address): @@ -1392,30 +1406,32 @@ 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. + """Gets the address of the token used to fund the escrow. - :param escrow_address: Address of the escrow + Args: + escrow_address: Address of the escrow - :return: Address of the token + Returns: + Address of the token - :raise EscrowClientError: If an error occurs while checking the parameters + Raises: + EscrowClientError: If an error occurs while checking the parameters - :example: - .. code-block:: python + Example: + ```python + from eth_typing import URI + from web3 import Web3 + from web3.providers.auto import load_provider_from_uri - 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 - from human_protocol_sdk.escrow import EscrowClient + w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) + escrow_client = EscrowClient(w3) - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) - - token_address = escrow_client.get_token_address( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + token_address = escrow_client.get_token_address( + "0x62dD51230A30401C455c8398d06F85e4EaB6309f" + ) + ``` """ if not Web3.is_address(escrow_address): @@ -1424,30 +1440,32 @@ 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. + """Gets the current status of the escrow. - :param escrow_address: Address of the escrow + Args: + escrow_address: Address of the escrow - :return: Current escrow status + Returns: + Current escrow status - :raise EscrowClientError: If an error occurs while checking the parameters + Raises: + EscrowClientError: If an error occurs while checking the parameters - :example: - .. code-block:: python + Example: + ```python + from eth_typing import URI + from web3 import Web3 + from web3.providers.auto import load_provider_from_uri - 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 - from human_protocol_sdk.escrow import EscrowClient + w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) + escrow_client = EscrowClient(w3) - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) - - status = escrow_client.get_status( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + status = escrow_client.get_status( + "0x62dD51230A30401C455c8398d06F85e4EaB6309f" + ) + ``` """ if not Web3.is_address(escrow_address): @@ -1458,30 +1476,32 @@ 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. + """Gets the recording oracle address of the escrow. - :param escrow_address: Address of the escrow + Args: + escrow_address: Address of the escrow - :return: Recording oracle address + Returns: + Recording oracle address - :raise EscrowClientError: If an error occurs while checking the parameters + Raises: + EscrowClientError: If an error occurs while checking the parameters - :example: - .. code-block:: python + Example: + ```python + from eth_typing import URI + from web3 import Web3 + from web3.providers.auto import load_provider_from_uri - 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 - from human_protocol_sdk.escrow import EscrowClient + w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) + escrow_client = EscrowClient(w3) - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) - - recording_oracle = escrow_client.get_recording_oracle_address( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + recording_oracle = escrow_client.get_recording_oracle_address( + "0x62dD51230A30401C455c8398d06F85e4EaB6309f" + ) + ``` """ if not Web3.is_address(escrow_address): @@ -1492,30 +1512,32 @@ 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. + """Gets the reputation oracle address of the escrow. - :param escrow_address: Address of the escrow + Args: + escrow_address: Address of the escrow - :return: Reputation oracle address + Returns: + Reputation oracle address - :raise EscrowClientError: If an error occurs while checking the parameters + Raises: + EscrowClientError: If an error occurs while checking the parameters - :example: - .. code-block:: python + Example: + ```python + from eth_typing import URI + from web3 import Web3 + from web3.providers.auto import load_provider_from_uri - 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 - from human_protocol_sdk.escrow import EscrowClient + w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) + escrow_client = EscrowClient(w3) - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) - - reputation_oracle = escrow_client.get_reputation_oracle_address( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + reputation_oracle = escrow_client.get_reputation_oracle_address( + "0x62dD51230A30401C455c8398d06F85e4EaB6309f" + ) + ``` """ if not Web3.is_address(escrow_address): @@ -1528,30 +1550,32 @@ 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. + """Gets the exchange oracle address of the escrow. - :param escrow_address: Address of the escrow + Args: + escrow_address: Address of the escrow - :return: Exchange oracle address + Returns: + Exchange oracle address - :raise EscrowClientError: If an error occurs while checking the parameters + Raises: + EscrowClientError: If an error occurs while checking the parameters - :example: - .. code-block:: python + Example: + ```python + from eth_typing import URI + from web3 import Web3 + from web3.providers.auto import load_provider_from_uri - 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 - from human_protocol_sdk.escrow import EscrowClient + w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) + escrow_client = EscrowClient(w3) - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) - - exchange_oracle = escrow_client.get_exchange_oracle_address( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + exchange_oracle = escrow_client.get_exchange_oracle_address( + "0x62dD51230A30401C455c8398d06F85e4EaB6309f" + ) + ``` """ if not Web3.is_address(escrow_address): @@ -1562,30 +1586,32 @@ 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. + """Gets the job launcher address of the escrow. - :param escrow_address: Address of the escrow + Args: + escrow_address: Address of the escrow - :return: Job launcher address + Returns: + Job launcher address - :raise EscrowClientError: If an error occurs while checking the parameters + Raises: + EscrowClientError: If an error occurs while checking the parameters - :example: - .. code-block:: python + Example: + ```python + from eth_typing import URI + from web3 import Web3 + from web3.providers.auto import load_provider_from_uri - 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 - from human_protocol_sdk.escrow import EscrowClient + w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) + escrow_client = EscrowClient(w3) - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) - - job_launcher = escrow_client.get_job_launcher_address( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + job_launcher = escrow_client.get_job_launcher_address( + "0x62dD51230A30401C455c8398d06F85e4EaB6309f" + ) + ``` """ if not Web3.is_address(escrow_address): @@ -1594,30 +1620,32 @@ 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. + """Gets the escrow factory address of the escrow. - :param escrow_address: Address of the escrow + Args: + escrow_address: Address of the escrow - :return: Escrow factory address + Returns: + Escrow factory address - :raise EscrowClientError: If an error occurs while checking the parameters + Raises: + EscrowClientError: If an error occurs while checking the parameters - :example: - .. code-block:: python + Example: + ```python + from eth_typing import URI + from web3 import Web3 + from web3.providers.auto import load_provider_from_uri - 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 - from human_protocol_sdk.escrow import EscrowClient + w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) + escrow_client = EscrowClient(w3) - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - escrow_client = EscrowClient(w3) - - escrow_factory = escrow_client.get_factory_address( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) + escrow_factory = escrow_client.get_factory_address( + "0x62dD51230A30401C455c8398d06F85e4EaB6309f" + ) + ``` """ if not Web3.is_address(escrow_address): @@ -1628,12 +1656,13 @@ def get_factory_address(self, escrow_address: str) -> str: ) def _get_escrow_contract(self, address: str) -> contract.Contract: - """ - Returns the escrow contract instance. + """Returns the escrow contract instance. - :param escrow_address: Address of the deployed escrow + Args: + escrow_address: Address of the deployed escrow - :return: The instance of the escrow contract + Returns: + The instance of the escrow contract """ 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..d8855929d3 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 operations. +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 @@ -75,34 +69,34 @@ 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. + """Represents escrow data returned from the subgraph. + + Args: + chain_id: Chain identifier. + id: Escrow identifier. + address: Escrow address. + amount_paid: Amount paid. + balance: Remaining balance. + count: Number of payouts. + factory_address: Factory address. + launcher: Job launcher address. + job_requester_id: Job requester identifier. + status: Escrow status. + token: Payment token address. + total_funded_amount: Total funded amount. + created_at: Creation timestamp in milliseconds. + final_results_url: URL for final results. + final_results_hash: Hash for final results. + intermediate_results_url: URL for intermediate results. + intermediate_results_hash: Hash for intermediate results. + manifest_hash: Manifest hash. + manifest: Manifest data (JSON/URL). + recording_oracle: Recording Oracle address. + reputation_oracle: Reputation Oracle address. + exchange_oracle: Exchange Oracle address. + recording_oracle_fee: Fee for the Recording Oracle. + reputation_oracle_fee: Fee for the Reputation Oracle. + exchange_oracle_fee: Fee for the Exchange Oracle. """ self.id = id @@ -139,18 +133,19 @@ def __init__( class StatusEvent: - """ - Initializes a StatusEvent instance. - - :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. - """ + """Represents an escrow status change event.""" def __init__( self, timestamp: int, status: str, chain_id: ChainId, escrow_address: str ): + """Create a status event. + + Args: + timestamp: Event timestamp in seconds (converted to ms internally). + status: Escrow status. + chain_id: Chain where the event occurred. + escrow_address: Address of the escrow. + """ self.timestamp = timestamp * 1000 self.status = status self.chain_id = chain_id @@ -158,20 +153,20 @@ 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.""" def __init__( self, id: str, escrow_address: str, recipient: str, amount: str, created_at: str ): + """Create a payout record. + + Args: + id: Payout ID. + escrow_address: Escrow that executed the payout. + recipient: Recipient address. + amount: Amount paid. + created_at: Creation time in seconds (converted to ms internally). + """ self.id = id self.escrow_address = escrow_address self.recipient = recipient @@ -180,17 +175,7 @@ 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.""" def __init__( self, @@ -202,6 +187,17 @@ def __init__( timestamp: str, tx_hash: str, ): + """Create a cancellation refund record. + + Args: + id: Refund ID. + escrow_address: Escrow associated with the refund. + receiver: Address receiving the refund. + amount: Refunded amount. + block: Block number where the refund was processed. + timestamp: Refund timestamp in seconds (converted to ms internally). + tx_hash: Transaction hash of the refund. + """ self.id = id self.escrow_address = escrow_address self.receiver = receiver @@ -221,29 +217,31 @@ 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), - ) + """List escrows that match the provided filter. + + Args: + filter: Parameters used to filter escrows. + options: Optional config for subgraph requests. + + Returns: + A list of escrow records. + + 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 +337,28 @@ def get_escrow( escrow_address: str, options: Optional[SubgraphOptions] = None, ) -> Optional[EscrowData]: - """Returns the escrow for a given address. + """Fetch a single escrow by 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 + Args: + chain_id: Network in which the escrow has been deployed. + escrow_address: Address of the escrow. + options: Optional config for subgraph requests. - :return: Escrow data + Returns: + Escrow data if found, otherwise ``None``. - :example: - .. code-block:: python + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.escrow import EscrowUtils - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.escrow import EscrowUtils - - print( - EscrowUtils.get_escrow( - ChainId.POLYGON_AMOY, - "0x1234567890123456789012345678901234567890" - ) + print( + EscrowUtils.get_escrow( + ChainId.POLYGON_AMOY, + "0x1234567890123456789012345678901234567890", ) + ) + ``` """ from human_protocol_sdk.gql.escrow import ( get_escrow_query, @@ -424,15 +424,17 @@ def get_status_events( filter: StatusEventFilter, options: Optional[SubgraphOptions] = None, ) -> List[StatusEvent]: - """ - Retrieve status events for specified networks and statuses within a date range. + """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 + Args: + filter: Parameters used to filter status events. + options: Optional config for subgraph requests. - :return List[StatusEvent]: List of status events matching the query parameters. + Returns: + A list of matching status events. - :raise EscrowClientError: If an unsupported chain ID or invalid launcher address is provided. + Raises: + EscrowClientError: If an unsupported chain ID or invalid launcher address is provided. """ from human_protocol_sdk.gql.escrow import get_status_query @@ -487,15 +489,17 @@ def get_payouts( filter: PayoutFilter, options: Optional[SubgraphOptions] = None, ) -> List[Payout]: - """ - Fetch payouts from the subgraph based on the provided filter. + """Fetch payouts from the subgraph based on the provided filter. - :param filter: Object containing all the necessary parameters to filter payouts. - :param options: Optional config for subgraph requests + Args: + filter: Parameters used to filter payouts. + options: Optional config for subgraph requests. - :return List[Payout]: List of payouts matching the query parameters. + Returns: + A list of payouts matching the query parameters. - :raise EscrowClientError: If an unsupported chain ID or invalid addresses are provided. + Raises: + EscrowClientError: If an unsupported chain ID or invalid addresses are provided. """ from human_protocol_sdk.gql.payout import get_payouts_query @@ -554,15 +558,17 @@ 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 refunds from the subgraph based on the provided filter. - :param filter: Object containing all the necessary parameters to filter cancellation refunds. - :param options: Optional config for subgraph requests + Args: + filter: Parameters used to filter cancellation refunds. + options: Optional config for subgraph requests. - :return List[CancellationRefund]: List of cancellation refunds matching the query parameters. + Returns: + A list of cancellation refunds matching the query parameters. - :raise EscrowClientError: If an unsupported chain ID or invalid addresses are provided. + Raises: + EscrowClientError: If an unsupported chain ID or invalid addresses are provided. """ from human_protocol_sdk.gql.cancel import get_cancellation_refunds_query @@ -624,27 +630,29 @@ def get_cancellation_refund( escrow_address: str, options: Optional[SubgraphOptions] = None, ) -> CancellationRefund: - """ - Returns the cancellation refund for a given escrow address. + """Return the cancellation refund for a given escrow 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 + Args: + chain_id: Network in which the escrow has been deployed. + escrow_address: Address of the escrow. + options: Optional config for subgraph requests. - :return: CancellationRefund data or None + Returns: + CancellationRefund data or ``None``. - :raise EscrowClientError: If an unsupported chain ID or invalid address is provided. + Raises: + EscrowClientError: If an unsupported chain ID or invalid address is provided. - :example: - .. code-block:: python + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.escrow import EscrowUtils - 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/kvstore/kvstore_client.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/kvstore/kvstore_client.py index db199fc264..5f33ce20ca 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 ------------- - -* With Signer +"""Client for interacting with the KVStore contract and subgraph. -.. 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,20 @@ def get_w3_with_priv_key(priv_key: str): class KVStoreClientError(Exception): - """ - Raises when some error happens when interacting with kvstore. - """ + """Raised when an error occurs while interacting with KVStore.""" pass class KVStoreClient: - """ - A class used to manage kvstore on the HUMAN network. - """ + """Manage KVStore interactions on the HUMAN network.""" def __init__(self, web3: Web3, gas_limit: Optional[int] = None): - """ - Initializes a KVStore instance. + """Create a KVStore client. - :param web3: The Web3 object - :param gas_limit: (Optional) Gas limit for transactions + Args: + web3: Web3 instance configured for the target network. + gas_limit: Optional gas limit for transactions. """ # Initialize web3 instance @@ -118,39 +102,20 @@ 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 the value of a key-value pair in the contract. + + Args: + key: Key to set. + value: Value to assign. + tx_options: Optional transaction parameters. + + Raises: + KVStoreClientError: On invalid input or transaction failure. + + Example: + ```python + kvstore_client.set("Role", "RecordingOracle") + ``` """ if not key: @@ -168,42 +133,23 @@ 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 + """Set multiple key-value pairs in the contract. - :return: None + Args: + keys: List of keys to set. + values: Corresponding list of values. + tx_options: Optional transaction parameters. - :example: - .. code-block:: python + Raises: + KVStoreClientError: On invalid input or transaction failure. - 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) - - 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 +174,23 @@ 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 + """Set a URL value and its hash for the sender address. - :raise KVStoreClientError: If an error occurs while validating URL, or handling transaction + Args: + url: URL to set. + key: Configurable URL key (defaults to ``url``). + tx_options: Optional transaction parameters. - :example: - .. code-block:: python + Raises: + KVStoreClientError: If validation or transaction fails. - 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_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") + 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 +206,22 @@ 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 in the contract. - :return: The value of the key-value pair if it exists + Args: + address: Ethereum address associated with the key-value pair. + key: Key to retrieve. - :example: - .. code-block:: python + Returns: + Value of the key-value pair if it exists. - 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) - role = kvstore_client.get('0x62dD51230A30401C455c8398d06F85e4EaB6309f', 'Role') + Example: + ```python + role = kvstore_client.get( + "0x62dD51230A30401C455c8398d06F85e4EaB6309f", + "Role", + ) + ``` """ 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..a45b0324da 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 on-chain KVStore data. +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 @@ -38,11 +32,11 @@ class KVStoreData: def __init__(self, key: str, value: str): - """ - Initializes a KVStoreData instance. + """Container for a key/value pair. - :param key: Key - :param value: Value + Args: + key: KVStore key. + value: KVStore value. """ self.key = key self.value = value @@ -59,26 +53,28 @@ def get_kvstore_data( address: str, options: Optional[SubgraphOptions] = None, ) -> Optional[List[KVStoreData]]: - """Returns the KVStore data for a given address. + """Return 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 + Args: + chain_id: Network in which the KVStore data has been deployed. + address: Address of the KVStore. + options: Optional config for subgraph requests. - :return: List of KVStore data + Returns: + List of KVStore data entries. - :example: - .. code-block:: python + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.kvstore import KVStoreUtils - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.kvstore import KVStoreUtils - - print( - KVStoreUtils.get_kvstore_data( - ChainId.POLYGON_AMOY, - "0x15d34aaf54267db7d7c367839aaf71a00a2c6a65" - ) + print( + KVStoreUtils.get_kvstore_data( + ChainId.POLYGON_AMOY, + "0x15d34aaf54267db7d7c367839aaf71a00a2c6a65", ) + ) + ``` """ from human_protocol_sdk.gql.kvstore import get_kvstore_by_address_query @@ -120,27 +116,29 @@ 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 key-value pair in the contract. + + Args: + chain_id: Network in which the KVStore data has been deployed. + address: Ethereum address associated with the key-value pair. + key: Key to retrieve. + options: Optional config for subgraph requests. + + Returns: + Value for the key if it exists. + + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.kvstore import KVStoreUtils + + result = KVStoreUtils.get( + ChainId.POLYGON_AMOY, + "0x62dD51230A30401C455c8398d06F85e4EaB6309f", + "role", + ) + print(result) + ``` """ from human_protocol_sdk.gql.kvstore import get_kvstore_by_address_and_key_query @@ -178,26 +176,30 @@ 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 hash. + + Args: + chain_id: Network in which the KVStore data has been deployed. + address: Address from which to get the URL value. + key: Configurable URL key (defaults to ``url``). + options: Optional config for subgraph requests. + + Returns: + URL value if it exists and the content hash matches. + + 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 +224,25 @@ 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 + """Get the public key of the given entity. - :example: - .. code-block:: python + Args: + chain_id: Network in which the KVStore data has been deployed. + address: Address from which to get the public key. - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.kvstore import KVStoreUtils + Returns: + Public key of the given address if it exists and the content is valid. - chain_id = ChainId.POLYGON_AMOY - address = '0x62dD51230A30401C455c8398d06F85e4EaB6309f' + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.kvstore import KVStoreUtils - public_key = KVStoreUtils.get_public_key(chain_id, address) + public_key = KVStoreUtils.get_public_key( + ChainId.POLYGON_AMOY, + "0x62dD51230A30401C455c8398d06F85e4EaB6309f", + ) + ``` """ public_key_url = KVStoreUtils.get_file_url_and_verify_hash( 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..843b3635c3 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 querying operator data. +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 @@ -40,9 +34,7 @@ class OperatorUtilsError(Exception): class OperatorFilter: - """ - A class used to filter operators. - """ + """Filtering options for operators.""" def __init__( self, @@ -54,16 +46,16 @@ 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). """ if chain_id not in ChainId: @@ -108,30 +100,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 @@ -181,11 +173,11 @@ def __init__( escrow_address: str, amount: int, ): - """ - Initializes a RewardData instance. + """Represents a reward slashed to the slasher. - :param escrow_address: Escrow address - :param amount: Amount + Args: + escrow_address: Escrow address. + amount: Reward amount. """ self.escrow_address = escrow_address @@ -202,24 +194,26 @@ def get_operators( filter: OperatorFilter, options: Optional[SubgraphOptions] = None, ) -> List[OperatorData]: - """Get operators data of the protocol. + """List operators that match the provided filter. - :param filter: Operator filter - :param options: Optional config for subgraph requests + Args: + filter: Operator filter. + options: Optional config for subgraph requests. - :return: List of operators data + Returns: + A list of operator details. - :example: - .. code-block:: python + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.operator import OperatorUtils, OperatorFilter - 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"]) - ) + print( + OperatorUtils.get_operators( + OperatorFilter(chain_id=ChainId.POLYGON_AMOY, roles=["Job Launcher"]) ) + ) + ``` """ from human_protocol_sdk.gql.operator import get_operators_query @@ -290,25 +284,27 @@ def get_operator( operator_address: str, options: Optional[SubgraphOptions] = None, ) -> Optional[OperatorData]: - """Gets the operator details. - - :param chain_id: Network in which the operator exists - :param operator_address: Address of the operator - :param options: Optional config for subgraph requests + """Get a single operator by address. - :return: Operator data if exists, otherwise None + Args: + chain_id: Network where the operator exists. + operator_address: Address of the operator. + options: Optional config 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 + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.operator import OperatorUtils - chain_id = ChainId.POLYGON_AMOY - operator_address = '0x62dD51230A30401C455c8398d06F85e4EaB6309f' + chain_id = ChainId.POLYGON_AMOY + operator_address = "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - operator_data = OperatorUtils.get_operator(chain_id, operator_address) - print(operator_data) + operator_data = OperatorUtils.get_operator(chain_id, operator_address) + print(operator_data) + ``` """ from human_protocol_sdk.gql.operator import get_operator_query @@ -369,26 +365,28 @@ def get_reputation_network_operators( role: Optional[str] = None, options: Optional[SubgraphOptions] = None, ) -> List[OperatorData]: - """Get the reputation network operators of the specified address. + """Get operators registered under a 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 + Args: + chain_id: Network in which the reputation network exists. + address: Reputation oracle address. + role: Optional role filter. + options: Optional config for subgraph requests. - :return: Returns an array of operator details + Returns: + A list of operator details. - :example: - .. code-block:: python + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.operator import OperatorUtils - 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) + operators = OperatorUtils.get_reputation_network_operators( + ChainId.POLYGON_AMOY, + "0x62dD51230A30401C455c8398d06F85e4EaB6309f", + ) + print(operators) + ``` """ from human_protocol_sdk.gql.operator import get_reputation_network_query @@ -454,25 +452,27 @@ def get_rewards_info( slasher: str, options: Optional[SubgraphOptions] = None, ) -> List[RewardData]: - """Get rewards of the given slasher. - - :param chain_id: Network in which the slasher exists - :param slasher: Address of the slasher - :param options: Optional config for subgraph requests + """Get rewards collected by a slasher address. - :return: List of rewards info + Args: + chain_id: Network in which the slasher exists. + slasher: Address of the slasher. + options: Optional config for subgraph requests. - :example: - .. code-block:: python + Returns: + A list of rewards for the slasher. - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.operator import OperatorUtils + 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) + rewards_info = OperatorUtils.get_rewards_info( + ChainId.POLYGON_AMOY, + "0x62dD51230A30401C455c8398d06F85e4EaB6309f", + ) + print(rewards_info) + ``` """ 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..de98b77d72 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 ------------- - -* With Signer +"""Client for staking actions and queries on HUMAN Protocol. -.. 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,19 @@ def get_w3_with_priv_key(priv_key: str): class StakingClientError(Exception): - """ - Raises when some error happens when interacting with staking. - """ + """Raised when an error occurs interacting with staking.""" pass class StakingClient: - """ - A class used to manage staking on the HUMAN network. - """ + """Manage staking on the HUMAN network.""" def __init__(self, w3: Web3): - """Initializes a Staking instance - - :param w3: Web3 instance + """Create a staking client. + Args: + w3: Web3 instance configured for the target network. """ # Initialize web3 instance @@ -132,42 +99,11 @@ 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 - - :validate: - Amount must be greater than 0 - - :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) + """Approve HMT tokens for staking. - (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) + Args: + amount: Amount to approve (must be positive). + tx_options: Optional transaction parameters. """ if amount <= 0: @@ -182,45 +118,37 @@ 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. + + Args: + amount: Amount to stake (must be greater than 0 and within approved/balance limits). + tx_options: Optional transaction parameters. + + 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 +161,20 @@ 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 - - :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) + """Unstake HMT tokens. - :example: - .. code-block:: python + Args: + amount: Amount to unstake (must be greater than 0 and <= unlocked stake). + tx_options: Optional transaction parameters. - 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 amount is invalid or the transaction fails. - 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.unstake(amount) + Example: + ```python + amount = Web3.to_wei(5, "ether") + staking_client.unstake(amount) + ``` """ if amount <= 0: @@ -284,40 +189,18 @@ 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 - - :return: None - - :validate: - - There must be unstaked tokens which is unlocked (on-chain) + """Withdraw unlocked unstaked HMT tokens. - :example: - .. code-block:: python + Args: + tx_options: Optional transaction parameters. - 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 withdrawable. - 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 +218,14 @@ 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 for a given escrow. + + Args: + slasher: Address of the slasher. + staker: Address of the staker. + escrow_address: Address of the escrow. + amount: Amount to slash (must be > 0 and within allocation). + tx_options: Optional transaction parameters. """ if amount <= 0: @@ -396,28 +241,22 @@ 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 - - :validate: - - Staker address must be valid - - :example: - .. code-block:: python + """Retrieve comprehensive staking information for a staker. - from eth_typing import URI - from web3 import Web3 - from web3.providers.auto import load_provider_from_uri + Args: + staker_address: Address of the staker. - from human_protocol_sdk.staking import StakingClient + Returns: + Dictionary containing staker information. - w3 = Web3(load_provider_from_uri(URI("http://localhost:8545"))) - staking_client = StakingClient(w3) + Raises: + StakingClientError: If the staker address is invalid. - staking_info = staking_client.get_staker_info('0xYourStakerAddress') - print(staking_info['stakedAmount']) + Example: + ```python + staking_info = staking_client.get_staker_info("0xYourStakerAddress") + print(staking_info["stakedAmount"]) + ``` """ if not Web3.is_address(staker_address): raise StakingClientError(f"Invalid staker address: {staker_address}") @@ -448,11 +287,13 @@ 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. - :param escrow_address: Address of the escrow + Args: + escrow_address: Escrow address to validate. - :return: True if the escrow address is valid, False otherwise + Returns: + True if the escrow exists in the factory registry; otherwise False. """ # 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..41db963103 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 operations.""" from typing import List, Optional from human_protocol_sdk.constants import NETWORKS, ChainId @@ -46,6 +19,18 @@ def __init__( locked_until_timestamp: str, last_deposit_timestamp: str, ): + """Represents staker data returned from the subgraph. + + Args: + id: Staker ID. + address: Staker address. + staked_amount: Total staked amount. + locked_amount: Locked amount. + withdrawn_amount: Withdrawn amount. + slashed_amount: Slashed amount. + locked_until_timestamp: Time until locked amount is released (seconds). + last_deposit_timestamp: Last deposit time (seconds). + """ self.id = id self.address = address self.staked_amount = int(staked_amount) @@ -57,7 +42,7 @@ def __init__( class StakingUtilsError(Exception): - pass + """Raised when staking utility operations fail.""" class StakingUtils: @@ -67,6 +52,16 @@ def get_staker( address: str, options: Optional[SubgraphOptions] = None, ) -> Optional[StakerData]: + """Get a single staker by address. + + Args: + chain_id: Network to request data. + address: Staker address. + options: Optional config for subgraph requests. + + Returns: + Staker data if found, otherwise ``None``. + """ network = NETWORKS.get(chain_id) if not network: raise StakingUtilsError("Unsupported Chain ID") @@ -102,6 +97,15 @@ def get_stakers( filter: StakersFilter, options: Optional[SubgraphOptions] = None, ) -> List[StakerData]: + """List stakers matching the provided filter. + + Args: + filter: Staker filter parameters. + options: Optional config for subgraph requests. + + Returns: + A list of staker records. + """ 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 index b78f927418..04975bc69c 100644 --- 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 @@ -1,18 +1,12 @@ -""" -This client enables to obtain statistical information from the subgraph. - -Code Example ------------- - -.. code-block:: python +"""Client to retrieve statistical information from the subgraph. +Example: + ```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 @@ -29,37 +23,31 @@ class StatisticsClientError(Exception): - """ - Raises when some error happens when getting data from subgraph. - """ + """Raised when an error occurs fetching data from the subgraph.""" pass class HMTHoldersParam: - """ - A class used to specify parameters for querying HMT holders. - """ + """Parameters for querying HMT holders.""" def __init__( self, address: str = None, order_direction: str = "asc", ): - """ - Initializes a HMTHoldersParam instance. + """Create holder query parameters. - :param address: Filter by holder's address - :param order_direction: Optional. Direction of sorting ('asc' for ascending, 'desc' for descending) + Args: + address: Optional holder address filter. + order_direction: Sort direction (`asc` or `desc`). """ self.address = address self.order_direction = order_direction class DailyEscrowData: - """ - A class used to specify daily escrow data. - """ + """Aggregated daily escrow metrics.""" def __init__( self, @@ -70,15 +58,15 @@ def __init__( 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 + """Initialize a daily escrow record. + + Args: + timestamp: Day boundary timestamp. + escrows_total: Total escrows. + escrows_pending: Pending escrows. + escrows_solved: Solved escrows. + escrows_paid: Paid escrows. + escrows_cancelled: Cancelled escrows. """ self.timestamp = timestamp @@ -90,20 +78,18 @@ def __init__( class EscrowStatistics: - """ - A class used to specify escrow statistics. - """ + """Escrow statistics data.""" def __init__( self, total_escrows: int, daily_escrows_data: List[DailyEscrowData], ): - """ - Initializes a EscrowStatistics instance. + """Initialize escrow statistics. - :param total_escrows: Total escrows - :param daily_escrows_data: Daily escrows data + Args: + total_escrows: Total escrows. + daily_escrows_data: Per-day escrow data. """ self.total_escrows = total_escrows @@ -111,20 +97,18 @@ def __init__( class DailyWorkerData: - """ - A class used to specify daily worker data. - """ + """Aggregated daily worker metrics.""" def __init__( self, timestamp: datetime, active_workers: int, ): - """ - Initializes a DailyWorkerData instance. + """Initialize a daily worker record. - :param timestamp: Timestamp - :param active_workers: Active workers + Args: + timestamp: Day boundary timestamp. + active_workers: Number of active workers. """ self.timestamp = timestamp @@ -132,27 +116,23 @@ def __init__( class WorkerStatistics: - """ - A class used to specify worker statistics. - """ + """Worker statistics data.""" def __init__( self, daily_workers_data: List[DailyWorkerData], ): - """ - Initializes a WorkerStatistics instance. + """Initialize worker statistics. - :param daily_workers_data: Daily workers data + Args: + daily_workers_data: Per-day worker data. """ self.daily_workers_data = daily_workers_data class DailyPaymentData: - """ - A class used to specify daily payment data. - """ + """Aggregated daily payment metrics.""" def __init__( self, @@ -161,13 +141,13 @@ def __init__( total_count: int, average_amount_per_worker: int, ): - """ - Initializes a DailyPaymentData instance. + """Initialize a daily payment record. - :param timestamp: Timestamp - :param total_amount_paid: Total amount paid - :param total_count: Total count - :param average_amount_per_worker: Average amount per worker + Args: + timestamp: Day boundary timestamp. + total_amount_paid: Total amount paid. + total_count: Payment count. + average_amount_per_worker: Average payout per worker. """ self.timestamp = timestamp @@ -177,38 +157,34 @@ def __init__( class PaymentStatistics: - """ - A class used to specify payment statistics. - """ + """Payment statistics data.""" def __init__( self, daily_payments_data: List[DailyPaymentData], ): - """ - Initializes a PaymentStatistics instance. + """Initialize payment statistics. - :param daily_payments_data: Daily payments data + Args: + daily_payments_data: Per-day payment data. """ self.daily_payments_data = daily_payments_data class HMTHolder: - """ - A class used to specify HMT holder. - """ + """HMT holder record.""" def __init__( self, address: str, balance: int, ): - """ - Initializes a HMTHolder instance. + """Initialize a holder record. - :param address: Holder address - :param balance: Holder balance + Args: + address: Holder address. + balance: Holder balance. """ self.address = address @@ -216,9 +192,7 @@ def __init__( class DailyHMTData: - """ - A class used to specify daily HMT data. - """ + """Aggregated daily HMT transfer metrics.""" def __init__( self, @@ -228,14 +202,14 @@ def __init__( 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 + """Initialize daily HMT transfer data. + + Args: + timestamp: Day boundary timestamp. + total_transaction_amount: Total transfer amount. + total_transaction_count: Total transfer count. + daily_unique_senders: Unique senders. + daily_unique_receivers: Unique receivers. """ self.timestamp = timestamp @@ -246,9 +220,7 @@ def __init__( class HMTStatistics: - """ - A class used to specify HMT statistics. - """ + """HMT aggregate statistics.""" def __init__( self, @@ -256,12 +228,12 @@ def __init__( total_transfer_count: int, total_holders: int, ): - """ - Initializes a HMTStatistics instance. + """Initialize HMT statistics. - :param total_transfer_amount: Total transfer amount - :param total_transfer_count: Total transfer count - :param total_holders: Total holders + Args: + total_transfer_amount: Total transfer amount. + total_transfer_count: Total transfer count. + total_holders: Total holder count. """ self.total_transfer_amount = total_transfer_amount @@ -270,15 +242,16 @@ def __init__( class StatisticsClient: - """ - A client used to get statistical data. - """ + """Client for retrieving statistical data.""" def __init__(self, chain_id: ChainId = ChainId.POLYGON_AMOY): - """Initializes a Statistics instance + """Create a statistics client. - :param chain_id: Chain ID to get statistical data from + Args: + chain_id: Chain ID to read statistical data from. + Raises: + StatisticsClientError: If the chain ID is invalid or config is missing. """ if chain_id.value not in [chain_id.value for chain_id in ChainId]: @@ -296,29 +269,29 @@ def get_escrow_statistics( ) -> 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 + Args: + filter: Date range and pagination filter. + options: Optional subgraph request configuration. - :example: - .. code-block:: python + Returns: + Escrow statistics data. - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.statistics import StatisticsClient - from human_protocol_sdk.filter import StatisticsFilter + 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) + 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), - ) - ) + statistics_client.get_escrow_statistics() + 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 ( @@ -379,29 +352,29 @@ def get_worker_statistics( ) -> 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 + Args: + filter: Date range and pagination filter. + options: Optional subgraph request configuration. - :example: - .. code-block:: python + Returns: + Worker statistics data. - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.statistics import StatisticsClient - from human_protocol_sdk.filter import StatisticsFilter + 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) + 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), - ) - ) + statistics_client.get_worker_statistics() + 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, @@ -440,29 +413,29 @@ def get_payment_statistics( ) -> 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 + Args: + filter: Date range and pagination filter. + options: Optional subgraph request configuration. - :example: - .. code-block:: python + Returns: + Payment statistics data. - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.statistics import StatisticsClient - from human_protocol_sdk.filter import StatisticsFilter + 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) + 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), - ) - ) + statistics_client.get_payment_statistics() + 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 ( @@ -509,19 +482,20 @@ def get_hmt_statistics( ) -> HMTStatistics: """Get HMT statistics data. - :param options: Optional config for subgraph requests + Args: + options: Optional subgraph request configuration. - :return: HMT statistics data + Returns: + HMT statistics data. - :example: - .. code-block:: python + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.statistics import StatisticsClient - 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()) + statistics_client = StatisticsClient(ChainId.POLYGON_AMOY) + statistics_client.get_hmt_statistics() + ``` """ from human_protocol_sdk.gql.statistics import ( get_event_day_data_query, @@ -552,28 +526,28 @@ def get_hmt_holders( ) -> 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 + Args: + param: Holder filters and sort preferences. + options: Optional subgraph request configuration. - :example: - .. code-block:: python + Returns: + List of HMT holders. - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.statistics import StatisticsClient, HMTHoldersParam + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.statistics import StatisticsClient, HMTHoldersParam - statistics_client = StatisticsClient(ChainId.POLYGON_AMOY) + statistics_client = StatisticsClient(ChainId.POLYGON_AMOY) - print(statistics_client.get_hmt_holders()) - print( - statistics_client.get_hmt_holders( - HMTHoldersParam( - address="0x123...", - order_direction="asc", - ) - ) + statistics_client.get_hmt_holders() + statistics_client.get_hmt_holders( + HMTHoldersParam( + address="0x123...", + order_direction="asc", ) + ) + ``` """ from human_protocol_sdk.gql.hmtoken import get_holders_query @@ -605,28 +579,28 @@ def get_hmt_daily_data( ) -> 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 + Args: + filter: Date range and pagination filter. + options: Optional subgraph request configuration. - :example: - .. code-block:: python + Returns: + Daily HMT transfer statistics. - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.statistics import StatisticsClient, StatisticsFilter + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.statistics import StatisticsClient, StatisticsFilter - statistics_client = StatisticsClient(ChainId.POLYGON_AMOY) + 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), - ) - ) + statistics_client.get_hmt_daily_data() + 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, diff --git a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/storage/storage_client.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/storage/storage_client.py index 47b2dec081..a724d60035 100644 --- a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/storage/storage_client.py +++ b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/storage/storage_client.py @@ -1,18 +1,10 @@ -""" -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). +"""Client helpers for interacting with S3-compatible storage. -Code Example ------------- +If credentials are not provided, anonymous access is used (for downloads). -.. code-block:: python - - from human_protocol_sdk.storage import ( - Credentials, - StorageClient, - ) +Example: + ```python + from human_protocol_sdk.storage import Credentials, StorageClient credentials = Credentials( access_key="my-access-key", @@ -24,9 +16,7 @@ region="us-west-2", credentials=credentials, ) - -Module ------- + ``` """ import hashlib @@ -50,40 +40,26 @@ class StorageClientError(Exception): - """ - Raises when some error happens when interacting with storage. - """ + """Raised when an error happens while interacting with storage.""" pass class StorageFileNotFoundError(StorageClientError): - """ - Raises when some error happens when file is not found by its key. - """ + """Raised when a file is not found by its key.""" pass class Credentials: - """ - A class to represent the credentials required to authenticate with an S3-compatible service. - - Example:: - - credentials = Credentials( - access_key='my-access-key', - secret_key='my-secret-key' - ) - - """ + """Credentials required to authenticate with an S3-compatible service.""" def __init__(self, access_key: str, secret_key: str): - """ - Initializes a Credentials instance. + """Create credentials. - :param access_key: The access key for the S3-compatible service. - :param secret_key: The secret key for the S3-compatible service. + Args: + access_key: Access key for the S3-compatible service. + secret_key: Secret key for the S3-compatible service. """ self.access_key = access_key @@ -91,29 +67,7 @@ def __init__(self, access_key: str, secret_key: str): class StorageClient: - """ - A class for downloading files from an S3-compatible service. - - :attribute: - - client (Minio): The S3-compatible client used for interacting with the service. - - :example: - .. code-block:: 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) - - """ + """Client for interacting with S3-compatible services.""" def __init__( self, @@ -122,17 +76,15 @@ def __init__( credentials: Optional[Credentials] = None, secure: Optional[bool] = True, ): - """ - Initializes the StorageClient with the given endpoint_url, region, and credentials. + """Create a storage client. - If credentials are not provided, anonymous access will be used. + If credentials are not provided, anonymous access is used. - :param endpoint_url: The URL of the S3-compatible service. - :param region: The region of the S3-compatible service. Defaults to None. - :param credentials: The credentials required to authenticate with the S3-compatible service. - Defaults to None for anonymous access. - :param secure: Flag to indicate to use secure (TLS) connection to S3 service or not. - Defaults to True. + Args: + endpoint_url: URL of the S3-compatible service. + region: Region of the S3-compatible service. + credentials: Credentials for authentication (optional for anonymous access). + secure: Whether to use TLS to connect to the service. """ try: self.client = ( @@ -157,40 +109,39 @@ def __init__( raise e def download_files(self, files: List[str], bucket: str) -> List[bytes]: - """ - Downloads a list of files from the specified S3-compatible bucket. - - :param files: A list of file keys to download. - :param bucket: The name of the S3-compatible bucket to download from. + """Download files from the specified bucket. - :return: A list of file contents (bytes) downloaded from the bucket. + Args: + files: List of file keys to download. + bucket: Name of the S3-compatible bucket. - :raise StorageClientError: If an error occurs while downloading the files. - :raise StorageFileNotFoundError: If one of the specified files is not found in the bucket. + Returns: + List of file contents (bytes) from the bucket. - :example: - .. code-block:: python + Raises: + StorageClientError: If an error occurs while downloading. + StorageFileNotFoundError: If a file is not found in the bucket. - from human_protocol_sdk.storage import ( - Credentials, - StorageClient, - ) + Example: + ```python + from human_protocol_sdk.storage import Credentials, StorageClient - credentials = Credentials( - access_key="my-access-key", - secret_key="my-secret-key", - ) + 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, - ) + 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" - ) + result = storage_client.download_files( + files=["file1.txt", "file2.txt"], + bucket="my-bucket", + ) + ``` """ result_files = [] for file in files: @@ -207,39 +158,40 @@ def download_files(self, files: List[str], bucket: str) -> List[bytes]: return result_files def upload_files(self, files: List[dict], bucket: str) -> List[dict]: - """ - Uploads a list of files to the specified S3-compatible bucket. + """Upload a list of files to the specified bucket. - :param files: A list of files to upload. - :param bucket: The name of the S3-compatible bucket to upload to. + Args: + files: List of file payloads to upload. Each item can be a dict with + ``file`` (bytes/str), ``key``, and ``hash`` or an arbitrary object + that will be JSON-serialized. + bucket: Name of the S3-compatible bucket to upload to. - :return: List of dict with key, url, hash fields + Returns: + List of dicts containing ``key``, ``url``, and ``hash`` fields. - :raise StorageClientError: If an error occurs while uploading the files. + Raises: + StorageClientError: If an error occurs while uploading the files. - :example: - .. code-block:: python + Example: + ```python + from human_protocol_sdk.storage import Credentials, StorageClient - from human_protocol_sdk.storage import ( - Credentials, - StorageClient, - ) - - credentials = Credentials( - access_key="my-access-key", - secret_key="my-secret-key", - ) + 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, - ) + 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" - ) + result = storage_client.upload_files( + files=[{"file": b\"content\", "key": "file1.txt", "hash": "hash1"}], + bucket="my-bucket", + ) + ``` """ result_files = [] for file in files: @@ -295,37 +247,16 @@ def upload_files(self, files: List[dict], bucket: str) -> List[dict]: return result_files def bucket_exists(self, bucket: str) -> bool: - """ - Check if a given bucket exists. - - :param bucket: The name of the bucket to check. + """Check if a given bucket exists. - :return: True if the bucket exists, False otherwise. + Args: + bucket: The name of the bucket to check. - :raise StorageClientError: If an error occurs while checking the bucket. + Returns: + True if the bucket exists, False otherwise. - :example: - .. code-block:: 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" - ) + Raises: + StorageClientError: If an error occurs while checking the bucket. """ try: return self.client.bucket_exists(bucket_name=bucket) @@ -336,37 +267,16 @@ def bucket_exists(self, bucket: str) -> bool: raise StorageClientError(str(e)) def list_objects(self, bucket: str) -> List[str]: - """ - Return a list of all objects in a given bucket. - - :param bucket: The name of the bucket to list objects from. - - :return: A list of object keys in the given bucket. - - :raise StorageClientError: If an error occurs while listing the objects. + """Return a list of all objects in a given bucket. - :example: - .. code-block:: python + Args: + bucket: The name of the bucket to list objects from. - from human_protocol_sdk.storage import ( - Credentials, - StorageClient, - ) - - credentials = Credentials( - access_key="my-access-key", - secret_key="my-secret-key", - ) + Returns: + A list of object keys in the given bucket. - 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" - ) + Raises: + StorageClientError: If an error occurs while listing the objects. """ try: objects = list(self.client.list_objects(bucket_name=bucket)) 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..39716badac 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 subgraph 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,8 @@ class InternalTransaction: + """Internal transaction detail.""" + def __init__( self, from_address: str, @@ -84,17 +78,13 @@ def __init__( class TransactionUtilsError(Exception): - """ - Raises when some error happens when getting data from subgraph. - """ + """Raised when a transaction lookup fails.""" pass class TransactionUtils: - """ - A utility class that provides additional transaction-related functionalities. - """ + """Utility helpers to query on-chain transactions from the subgraph.""" @staticmethod def get_transaction( @@ -102,24 +92,27 @@ def get_transaction( ) -> Optional[TransactionData]: """Returns the transaction for a given hash. - :param chain_id: Network in which the transaction was executed - :param hash: Hash of the transaction - :param options: Optional config for subgraph requests + Args: + chain_id: Network in which the transaction was executed. + hash: Transaction hash. + options: Optional subgraph request configuration. - :return: Transaction data + Returns: + Transaction data if found, otherwise None. - :example: - .. code-block:: python + Raises: + TransactionUtilsError: If the chain ID is unsupported. - from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.transaction import TransactionUtils + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.transaction import TransactionUtils - print( - TransactionUtils.get_transaction( - ChainId.POLYGON_AMOY, - "0x1234567890123456789012345678901234567891" - ) - ) + TransactionUtils.get_transaction( + ChainId.POLYGON_AMOY, + "0x1234567890123456789012345678901234567891", + ) + ``` """ network = NETWORKS.get(chain_id) if not network: @@ -175,31 +168,33 @@ def get_transactions( ) -> 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), - ) - ) + Args: + filter: Filter parameters (chain, addresses, date/block ranges, method, escrow, token, pagination). + options: Optional subgraph request configuration. + + Returns: + List of transactions matching the filter. + + Raises: + TransactionUtilsError: If the chain ID is unsupported. + + Example: + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.transaction import TransactionUtils, TransactionFilter + + 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), ) + ) + ``` """ from human_protocol_sdk.gql.transaction import get_transactions_query diff --git a/packages/sdk/python/human-protocol-sdk/mkdocs.yaml b/packages/sdk/python/human-protocol-sdk/mkdocs.yaml new file mode 100644 index 0000000000..bdd1656884 --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/mkdocs.yaml @@ -0,0 +1,94 @@ +site_name: HUMAN Protocol Python SDK Docs +site_url: https://sdk.humanprotocol.org/python/ +repo_name: humanprotocol/human-protocol-sdk +repo_url: https://github.com/humanprotocol/human-protocol-sdk +docs_dir: docs +site_dir: site/python +theme: + name: material + custom_dir: docs/overrides + logo: overrides/assets/img/logo.svg + favicon: overrides/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 +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: + options: + docstring_style: google # or "numpy" / "restructuredtext" + 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 + - 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: + - StatisticsClient: statistics_client.md + - Transaction: + - TransactionUtils: transaction_utils.md + - Worker: api/worker.md + - Core utilities: api/core.md +extra_css: + - overrides/assets/css/custom.css From 9399e9dbed0d5143e44f273ab5acda5d46df2bbd Mon Sep 17 00:00:00 2001 From: portuu3 Date: Thu, 4 Dec 2025 17:16:46 +0100 Subject: [PATCH 02/19] updates to python sdk --- .../human-protocol-sdk/docs/api/agreement.md | 19 - .../python/human-protocol-sdk/docs/api/gql.md | 47 - .../human-protocol-sdk/docs/{api => }/core.md | 0 .../python/human-protocol-sdk/docs/index.md | 219 +++- .../docs/legacy_encryption.md | 1 + .../docs/statistics_client.md | 1 - .../docs/statistics_utils.md | 1 + .../docs/{api/worker.md => worker_utils.md} | 0 .../human_protocol_sdk/agreement/__init__.py | 85 -- .../human_protocol_sdk/agreement/bootstrap.py | 142 --- .../human_protocol_sdk/agreement/measures.py | 377 ------ .../human_protocol_sdk/agreement/utils.py | 417 ------- .../human_protocol_sdk/constants.py | 69 +- .../human_protocol_sdk/decorators.py | 41 +- .../encryption/encryption.py | 72 +- .../encryption/encryption_utils.py | 69 +- .../escrow/escrow_client.py | 1018 +++++------------ .../human_protocol_sdk/escrow/escrow_utils.py | 253 ++-- .../human_protocol_sdk/filter.py | 236 ++-- .../kvstore/kvstore_client.py | 100 +- .../kvstore/kvstore_utils.py | 107 +- .../human_protocol_sdk/legacy_encryption.py | 305 ++--- .../operator/operator_utils.py | 149 ++- .../staking/staking_client.py | 148 ++- .../staking/staking_utils.py | 95 +- ...atistics_client.py => statistics_utils.py} | 422 ++++--- .../transaction/transaction_utils.py | 108 +- .../human_protocol_sdk/utils.py | 270 ++++- .../human_protocol_sdk/worker/worker_utils.py | 117 +- .../sdk/python/human-protocol-sdk/mkdocs.yaml | 10 +- 30 files changed, 2308 insertions(+), 2590 deletions(-) delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/api/agreement.md delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/api/gql.md rename packages/sdk/python/human-protocol-sdk/docs/{api => }/core.md (100%) create mode 100644 packages/sdk/python/human-protocol-sdk/docs/legacy_encryption.md delete mode 100644 packages/sdk/python/human-protocol-sdk/docs/statistics_client.md create mode 100644 packages/sdk/python/human-protocol-sdk/docs/statistics_utils.md rename packages/sdk/python/human-protocol-sdk/docs/{api/worker.md => worker_utils.md} (100%) delete mode 100644 packages/sdk/python/human-protocol-sdk/human_protocol_sdk/agreement/__init__.py delete mode 100644 packages/sdk/python/human-protocol-sdk/human_protocol_sdk/agreement/bootstrap.py delete mode 100644 packages/sdk/python/human-protocol-sdk/human_protocol_sdk/agreement/measures.py delete mode 100644 packages/sdk/python/human-protocol-sdk/human_protocol_sdk/agreement/utils.py rename packages/sdk/python/human-protocol-sdk/human_protocol_sdk/statistics/{statistics_client.py => statistics_utils.py} (55%) diff --git a/packages/sdk/python/human-protocol-sdk/docs/api/agreement.md b/packages/sdk/python/human-protocol-sdk/docs/api/agreement.md deleted file mode 100644 index ba5e855c54..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/api/agreement.md +++ /dev/null @@ -1,19 +0,0 @@ -# Agreement - -APIs for measuring inter-rater agreement on annotated data. - -## Package - -::: human_protocol_sdk.agreement - -## Measures - -::: human_protocol_sdk.agreement.measures - -## Utilities - -::: human_protocol_sdk.agreement.utils - -## Bootstrap helpers - -::: human_protocol_sdk.agreement.bootstrap diff --git a/packages/sdk/python/human-protocol-sdk/docs/api/gql.md b/packages/sdk/python/human-protocol-sdk/docs/api/gql.md deleted file mode 100644 index 72fa6f76c7..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/api/gql.md +++ /dev/null @@ -1,47 +0,0 @@ -# GraphQL helpers - -Query builders used by the SDK to interact with HUMAN Protocol subgraphs. - -## Escrow - -::: human_protocol_sdk.gql.escrow - -## Staking - -::: human_protocol_sdk.gql.staking - -## Operator - -::: human_protocol_sdk.gql.operator - -## Worker - -::: human_protocol_sdk.gql.worker - -## Transaction - -::: human_protocol_sdk.gql.transaction - -## KVStore - -::: human_protocol_sdk.gql.kvstore - -## Statistics - -::: human_protocol_sdk.gql.statistics - -## Rewards - -::: human_protocol_sdk.gql.reward - -## Payouts - -::: human_protocol_sdk.gql.payout - -## Token - -::: human_protocol_sdk.gql.hmtoken - -## Cancellation - -::: human_protocol_sdk.gql.cancel diff --git a/packages/sdk/python/human-protocol-sdk/docs/api/core.md b/packages/sdk/python/human-protocol-sdk/docs/core.md similarity index 100% rename from packages/sdk/python/human-protocol-sdk/docs/api/core.md rename to packages/sdk/python/human-protocol-sdk/docs/core.md diff --git a/packages/sdk/python/human-protocol-sdk/docs/index.md b/packages/sdk/python/human-protocol-sdk/docs/index.md index fdbb0c78f1..ac7c4d1720 100644 --- a/packages/sdk/python/human-protocol-sdk/docs/index.md +++ b/packages/sdk/python/human-protocol-sdk/docs/index.md @@ -1,11 +1,216 @@ # HUMAN Protocol Python SDK -The Python SDK provides a high-level, Pythonic interface to HUMAN Protocol -smart contracts and off-chain services. +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. -Use it to: +## Overview -- Interact with Escrow, Staking, and KVStore contracts -- Manage operators and workers -- Query statistics and on-chain data -- Build automations, bots, and back-end services +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 + +## 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/) + +## License + +MIT License - see [LICENSE](LICENSE) for details. 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/statistics_client.md b/packages/sdk/python/human-protocol-sdk/docs/statistics_client.md deleted file mode 100644 index d8e6d4e616..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/statistics_client.md +++ /dev/null @@ -1 +0,0 @@ -::: human_protocol_sdk.statistics.statistics_client 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/api/worker.md b/packages/sdk/python/human-protocol-sdk/docs/worker_utils.md similarity index 100% rename from packages/sdk/python/human-protocol-sdk/docs/api/worker.md rename to packages/sdk/python/human-protocol-sdk/docs/worker_utils.md 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 b02169384d..7a110270cd 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..770d1080c1 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,10 +1,49 @@ 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): + """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: 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, *args, **kwargs): if not self.w3.eth.default_account: raise RequiresSignerError("You must add an account to Web3 instance") 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 a0f041eb54..03f5b1627c 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 @@ -7,14 +7,36 @@ class Encryption: - """Encryption and decryption helper 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): - """Create an Encryption helper. + """Initialize an Encryption instance with a private key. Args: - private_key_armored: Armored representation of the private key. - passphrase: Passphrase to unlock the private key. + private_key_armored (str): Armored representation of the PGP private key. + passphrase (Optional[str]): Passphrase to unlock the private key if it's locked. + + 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) @@ -37,12 +59,17 @@ def sign_and_encrypt( ) -> str: """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: Message to sign and encrypt. - public_keys: Armored public keys of the recipients. + 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 message. + str: Armored, signed, and encrypted PGP message. + + Raises: + ValueError: If the private key cannot be unlocked or encryption fails. Example: ```python @@ -80,12 +107,19 @@ def sign_and_encrypt( def decrypt(self, message: str, public_key: Optional[str] = None) -> bytes: """Decrypt a message using the private key. + Decrypts an encrypted message and optionally verifies the signature using + the sender's public key. + Args: - message: Armored message to decrypt. - public_key: Optional armored public key to verify signatures. + message (str): Armored PGP message to decrypt. + public_key (Optional[str]): Optional armored public key to verify the message signature. Returns: - Decrypted message bytes. + bytes: Decrypted message as bytes. + + Raises: + ValueError: If the private key cannot be unlocked, decryption fails, + or signature verification fails when a public key is provided. Example: ```python @@ -93,6 +127,12 @@ def decrypt(self, message: str, public_key: Optional[str] = None) -> bytes: encryption = Encryption("-----BEGIN PGP PRIVATE KEY BLOCK-----...", "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) @@ -128,18 +168,24 @@ def decrypt(self, message: str, public_key: Optional[str] = None) -> bytes: def sign(self, message: Union[str, bytes]) -> str: """Sign a message with the private key. + Creates a cleartext signed message that can be verified by anyone with + the corresponding public key. + Args: - message: Message to sign. + message (Union[str, bytes]): Message content to sign. Returns: - Armored signed message. + str: Armored signed PGP message in cleartext format. + + Raises: + ValueError: If the private key cannot be unlocked or signing fails. Example: ```python from human_protocol_sdk.encryption import Encryption encryption = Encryption("-----BEGIN PGP PRIVATE KEY BLOCK-----...", "passphrase") - signed_message = await encryption.sign("MESSAGE") + signed_message = encryption.sign("MESSAGE") ``` """ message = PGPMessage.new(message, cleartext=True) 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 837c6813a4..d349a909a2 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 @@ -8,18 +8,29 @@ class EncryptionUtils: - """Utility helpers for PGP encryption-related functionality.""" + """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: """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: Message to encrypt. - public_keys: Armored public keys of the recipients. + message (str): Plain text message to encrypt. + public_keys (List[str]): List of armored PGP public keys of the recipients. Returns: - Armored encrypted message. + str: Armored encrypted PGP message. + + Raises: + PGPError: If encryption fails or public keys are invalid. Example: ```python @@ -46,12 +57,25 @@ def encrypt(message: str, public_keys: List[str]) -> str: def verify(message: str, public_key: str) -> bool: """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: Armored message to verify. - public_key: Armored public key. + 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. + bool: ``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 = ( @@ -67,11 +91,21 @@ def verify(message: str, public_key: str) -> bool: def get_signed_data(message: str) -> str: """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: Armored message. + message (str): Armored PGP signed message. Returns: - Extracted signed data. + str: 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 = ( @@ -83,13 +117,24 @@ def get_signed_data(message: str) -> str: @staticmethod def is_encrypted(message: str) -> bool: - """Check whether a provided message is armored and encrypted. + """Check whether a message is armored and encrypted. + + Determines if the provided text is a valid PGP encrypted message by checking + the message header. Args: - message: Text to check. + message (str): Text to check for encryption. Returns: - True if the message is a PGP message, False otherwise. + bool: ``True`` if the message is a PGP encrypted message, ``False`` otherwise. + + Example: + ```python + from human_protocol_sdk.encryption import EncryptionUtils + + 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 438f677936..2cdebeb53b 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 @@ -69,39 +69,52 @@ 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. - Args: - tx_hash: The hash of the transaction that cancelled the escrow. - 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. - Args: - tx_hash: The hash of the transaction associated with the escrow withdrawal. - token_address: The address of the token used for the withdrawal. - 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__( self, @@ -114,15 +127,10 @@ def __init__( manifest: str, hash: str, ): - """Initializes an EscrowClient instance. - - Args: - recording_oracle_address: Address of the Recording Oracle - reputation_oracle_address: Address of the Reputation Oracle - recording_oracle_fee: Fee percentage of the Recording Oracle - reputation_oracle_fee: Fee percentage of the Reputation Oracle - manifest: Manifest data (can be a URL or JSON string) - 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( @@ -161,13 +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 an EscrowClient instance. + """Initialize an EscrowClient instance. Args: - web3: The Web3 object + web3 (Web3): Web3 instance configured for the target network. + Must have a valid provider and chain ID. + + Raises: + EscrowClientError: If chain ID is invalid or network configuration is missing. """ # Initialize web3 instance @@ -201,46 +223,24 @@ def create_escrow( job_requester_id: str, tx_options: Optional[TxParams] = None, ) -> str: - """Creates a new escrow contract. + """Create a new escrow contract. Args: - token_address: Address of the token to be used in the escrow - job_requester_id: An off-chain identifier for the job requester - tx_options: (Optional) Transaction options + 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 created escrow contract + str: Address of the newly created escrow contract. + + Raises: + EscrowClientError: If the token address 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.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 + "0x1234567890abcdef1234567890abcdef12345678", + "job-requester", ) ``` """ @@ -273,65 +273,32 @@ 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. + """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: Address of the token to be used in the escrow - amount: The token amount to fund the escrow with - job_requester_id: An off-chain identifier for the job requester - escrow_config: Configuration parameters for escrow setup - tx_options: (Optional) Transaction options + 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 created escrow contract + str: Address of the newly created and configured escrow contract. + + Raises: + EscrowClientError: If inputs are 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.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 + "0x1234567890abcdef1234567890abcdef12345678", + Web3.to_wei(5, "ether"), + "job-requester", + escrow_config, ) ``` """ @@ -372,55 +339,25 @@ def setup( escrow_config: EscrowConfig, tx_options: Optional[TxParams] = None, ) -> None: - """Sets up the parameters of the escrow. + """Set escrow roles, fees, and manifest metadata. + + Configures the escrow with oracle addresses, fee percentages, and manifest information. Args: - escrow_address: Address of the escrow contract - escrow_config: Configuration parameters for the escrow - tx_options: (Optional) Transaction options + 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 - 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 - ) + escrow_client.setup("0xYourEscrow", escrow_config) ``` """ if not Web3.is_address(escrow_address): @@ -452,46 +389,25 @@ def fund( amount: int, tx_options: Optional[TxParams] = None, ) -> None: - """Adds funds to the escrow. + """Add funds to the escrow. + + Transfers tokens from the caller's account to the escrow contract. Args: - escrow_address: Address of the escrow to fund - amount: Amount to be added as funds - tx_options: (Optional) Additional transaction parameters + 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. Returns: None Raises: - EscrowClientError: If an error occurs while checking the parameters + EscrowClientError: If inputs are invalid or the transfer 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.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) - - amount = Web3.to_wei(5, 'ether') # convert from ETH to WEI - escrow_client.fund( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f", amount - ) + amount = Web3.to_wei(5, "ether") + escrow_client.fund("0x62dD51230A30401C455c8398d06F85e4EaB6309f", amount) ``` """ if not Web3.is_address(escrow_address): @@ -520,48 +436,31 @@ 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. + """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: Address of the escrow - url: Results file URL - hash: Results file hash - funds_to_reserve: (Optional) Funds to reserve for payouts - tx_options: (Optional) Additional transaction parameters + 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 an error occurs while checking the parameters + EscrowClientError: If validation fails or the transaction reverts. 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.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" + "b5dad76bf6772c0f07fd5e048f6e75a5f86ee079", ) ``` """ @@ -607,41 +506,22 @@ 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. + """Set the status of an escrow to completed. + + Marks the escrow as completed, preventing further modifications. Args: - escrow_address: Address of the escrow to complete - tx_options: (Optional) Additional transaction parameters + escrow_address (str): Address of the escrow to complete. + tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. Returns: None Raises: - EscrowClientError: If an error occurs while checking the parameters + EscrowClientError: If validation fails or the transaction reverts. 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.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.complete("0x62dD51230A30401C455c8398d06F85e4EaB6309f") ``` """ @@ -670,65 +550,38 @@ 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. + """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: Address of the escrow - recipients: List of recipient addresses - amounts: List of amounts - final_results_url: Final results file URL - final_results_hash: Final results file hash - payout_id: Payout ID (str) or Transaction ID (int) - force_complete: (Optional) Whether to force completion - tx_options: (Optional) Transaction options + 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 an error occurs while checking the parameters + EscrowClientError: If validation fails or the transaction reverts. 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.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 + ["0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"], + [Web3.to_wei(5, "ether")], + "http://localhost/results.json", + "b5dad76bf6772c0f07fd5e048f6e75a5f86ee079", + payout_id="payout-1", + force_complete=True, ) ``` """ @@ -781,77 +634,41 @@ 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. + """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: Address of the escrow - recipients: Array of recipient addresses - amounts: Array of amounts the recipients will receive - final_results_url: Final results file URL - final_results_hash: Final results file hash - payoutId: Unique identifier for the payout - tx_options: (Optional) Additional transaction parameters + 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 dictionary containing the prepared transaction + TxParams: A populated transaction dictionary ready to sign and send, + including nonce, gas estimate, gas price/fees, and chain ID. - Raises: EscrowClientError: If an error occurs while checking the parameters + Raises: + EscrowClientError: If validation 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.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( + tx = 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 + ["0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"], + [Web3.to_wei(5, "ether")], + "http://localhost/results.json", + "b5dad76bf6772c0f07fd5e048f6e75a5f86ee079", + "payout-1", + force_complete=False, ) - 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}") + signed = w3.eth.account.sign_transaction(tx, "PRIVATE_KEY") + w3.eth.send_raw_transaction(signed.raw_transaction) ``` """ self.ensure_correct_bulk_payout_input( @@ -902,20 +719,28 @@ def ensure_correct_bulk_payout_input( final_results_url: str, final_results_hash: str, ) -> None: - """Validates input parameters for bulk payout operations. + """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: Address of the escrow - recipients: Array of recipient addresses - amounts: Array of amounts the recipients will receive - final_results_url: Final results file URL - final_results_hash: Final results file hash + 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 validation fails + 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,35 +772,23 @@ 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. + + Initiates the cancellation process. If the escrow is expired, it may finalize + immediately; otherwise, it transitions to ToCancel status. Args: - escrow_address: Address of the escrow to request cancellation - tx_options: (Optional) Additional transaction parameters + escrow_address (str): Address of the escrow to request cancellation. + tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. - 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.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) + Returns: + None - (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') - escrow_client = EscrowClient(w3) + Raises: + EscrowClientError: If validation fails or the transaction reverts. + Example: + ```python escrow_client.request_cancellation( "0x62dD51230A30401C455c8398d06F85e4EaB6309f" ) @@ -998,43 +811,22 @@ 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. + """Cancel the specified escrow and refund the balance. + + Finalizes the cancellation and transfers remaining funds to the canceler. Args: - escrow_address: Address of the escrow to cancel - tx_options: (Optional) Additional transaction parameters + escrow_address (str): Address of the escrow to cancel. + tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. Returns: - An instance of the EscrowCancel class containing details of the cancellation transaction, including the transaction hash and the amount refunded. + EscrowCancel: Cancellation details including transaction hash and refunded amount. Raises: - EscrowClientError: If an error occurs while checking the parameters - EscrowClientError: If the transfer event associated with the cancellation - is not found in the transaction logs + EscrowClientError: If validation fails or the transfer event is missing. 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.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.cancel( "0x62dD51230A30401C455c8398d06F85e4EaB6309f" ) @@ -1060,46 +852,27 @@ def withdraw( token_address: str, tx_options: Optional[TxParams] = None, ) -> EscrowWithdraw: - """Withdraws additional tokens in the escrow to the canceler. + """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: Address of the escrow to withdraw - token_address: Address of the token to withdraw - tx_options: (Optional) Additional transaction parameters + 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: - An instance of the EscrowWithdraw class containing details of the withdrawal transaction, including the transaction hash and the token address and amount withdrawn. + EscrowWithdraw: Withdrawal details including transaction hash, token address, and amount. Raises: - EscrowClientError: If an error occurs while checking the parameters - EscrowClientError: If the transfer event associated with the withdrawal is not found in the transaction logs + EscrowClientError: If validation fails or transfer event is missing. 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.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( + withdrawal = escrow_client.withdraw( "0x62dD51230A30401C455c8398d06F85e4EaB6309f", - "0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4" + "0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4", ) ``` """ @@ -1146,32 +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. + + Queries the current available balance in the escrow that can be used for payouts. Args: - escrow_address: Address of the escrow + escrow_address (str): Address of the escrow. Returns: - Value of the balance + int: Remaining escrow balance in token's smallest unit. Raises: - EscrowClientError: If an error occurs while checking the parameters - - Example: - ```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" - ) - ``` + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1190,32 +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. + + Queries the amount of funds that have been reserved for future payouts. Args: - escrow_address: Address of the escrow + escrow_address (str): Address of the escrow. Returns: - Value of the reserved funds + int: Reserved funds amount in token's smallest unit. Raises: - EscrowClientError: If an error occurs while checking the parameters - - Example: - ```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" - ) - ``` + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1226,32 +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. + + Retrieves the hash of the manifest that defines the job requirements. Args: - escrow_address: Address of the escrow + escrow_address (str): Address of the escrow. Returns: - Manifest file hash + str: Manifest file hash. Raises: - EscrowClientError: If an error occurs while checking the parameters - - Example: - ```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" - ) - ``` + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1260,32 +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). + """Get the manifest data. + + Retrieves the manifest URL or JSON string that defines the job requirements. Args: - escrow_address: Address of the escrow + escrow_address (str): Address of the escrow. Returns: - Manifest data + str: Manifest data (URL or JSON string). Raises: - EscrowClientError: If an error occurs while checking the parameters - - Example: - ```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 = escrow_client.get_manifest( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) - ``` + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1294,32 +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. + """Get the final results file URL. + + Retrieves the URL where final results are stored. Args: - escrow_address: Address of the escrow + escrow_address (str): Address of the escrow. Returns: - Results file url + str: Final results URL. Raises: - EscrowClientError: If an error occurs while checking the parameters - - Example: - ```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) - - url = escrow_client.get_results_url( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) - ``` + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1330,32 +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. + """Get the intermediate results file URL. + + Retrieves the URL where intermediate results are stored. Args: - escrow_address: Address of the escrow + escrow_address (str): Address of the escrow. Returns: - Intermediate results file url + str: Intermediate results URL. Raises: - EscrowClientError: If an error occurs while checking the parameters - - Example: - ```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) - - url = escrow_client.get_intermediate_results_url( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) - ``` + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1368,32 +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. + """Get the intermediate results file hash. + + Retrieves the hash of the intermediate results file. Args: - escrow_address: Address of the escrow + escrow_address (str): Address of the escrow. Returns: - Intermediate results file hash + str: Intermediate results file hash. Raises: - EscrowClientError: If an error occurs while checking the parameters - - Example: - ```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) - - hash = escrow_client.get_intermediate_results_hash( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) - ``` + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1406,32 +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. + """Get the token address used to fund the escrow. + + Retrieves the ERC-20 token contract address used for this escrow. Args: - escrow_address: Address of the escrow + escrow_address (str): Address of the escrow. Returns: - Address of the token + str: Token address used to fund the escrow. Raises: - EscrowClientError: If an error occurs while checking the parameters - - Example: - ```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) - - token_address = escrow_client.get_token_address( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) - ``` + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1440,32 +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. + """Get the current status of the escrow. + + Retrieves the current state of the escrow (e.g., Launched, Pending, Completed). Args: - escrow_address: Address of the escrow + escrow_address (str): Address of the escrow. Returns: - Current escrow status + Status: Current escrow status enum value. Raises: - EscrowClientError: If an error occurs while checking the parameters - - Example: - ```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) - - status = escrow_client.get_status( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) - ``` + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1476,32 +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. + """Get the recording oracle address of the escrow. + + Retrieves the address of the oracle responsible for recording job results. Args: - escrow_address: Address of the escrow + escrow_address (str): Address of the escrow. Returns: - Recording oracle address + str: Recording oracle address. Raises: - EscrowClientError: If an error occurs while checking the parameters - - Example: - ```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) - - recording_oracle = escrow_client.get_recording_oracle_address( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) - ``` + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1512,32 +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. + """Get the reputation oracle address of the escrow. + + Retrieves the address of the oracle responsible for reputation tracking. Args: - escrow_address: Address of the escrow + escrow_address (str): Address of the escrow. Returns: - Reputation oracle address + str: Reputation oracle address. Raises: - EscrowClientError: If an error occurs while checking the parameters - - Example: - ```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) - - reputation_oracle = escrow_client.get_reputation_oracle_address( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) - ``` + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1550,32 +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. + """Get the exchange oracle address of the escrow. + + Retrieves the address of the oracle responsible for exchange rate data. Args: - escrow_address: Address of the escrow + escrow_address (str): Address of the escrow. Returns: - Exchange oracle address + str: Exchange oracle address. Raises: - EscrowClientError: If an error occurs while checking the parameters - - Example: - ```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) - - exchange_oracle = escrow_client.get_exchange_oracle_address( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) - ``` + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1586,32 +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. + """Get the job launcher address of the escrow. + + Retrieves the address of the account that launched/created this escrow. Args: - escrow_address: Address of the escrow + escrow_address (str): Address of the escrow. Returns: - Job launcher address + str: Job launcher address. Raises: - EscrowClientError: If an error occurs while checking the parameters - - Example: - ```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) - - job_launcher = escrow_client.get_job_launcher_address( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) - ``` + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1620,32 +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. + """Get the escrow factory address of the escrow. + + Retrieves the address of the factory contract that created this escrow. Args: - escrow_address: Address of the escrow + escrow_address (str): Address of the escrow. Returns: - Escrow factory address + str: Escrow factory address. Raises: - EscrowClientError: If an error occurs while checking the parameters - - Example: - ```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) - - escrow_factory = escrow_client.get_factory_address( - "0x62dD51230A30401C455c8398d06F85e4EaB6309f" - ) - ``` + EscrowClientError: If the escrow address is invalid. """ if not Web3.is_address(escrow_address): @@ -1656,14 +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. Args: - escrow_address: Address of the deployed escrow + address (str): Address of the deployed escrow. Returns: - The instance of the escrow contract + contract.Contract: 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 d8855929d3..0e118779c0 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 @@ -41,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, @@ -69,36 +99,6 @@ def __init__( reputation_oracle_fee: Optional[str] = None, exchange_oracle_fee: Optional[str] = None, ): - """Represents escrow data returned from the subgraph. - - Args: - chain_id: Chain identifier. - id: Escrow identifier. - address: Escrow address. - amount_paid: Amount paid. - balance: Remaining balance. - count: Number of payouts. - factory_address: Factory address. - launcher: Job launcher address. - job_requester_id: Job requester identifier. - status: Escrow status. - token: Payment token address. - total_funded_amount: Total funded amount. - created_at: Creation timestamp in milliseconds. - final_results_url: URL for final results. - final_results_hash: Hash for final results. - intermediate_results_url: URL for intermediate results. - intermediate_results_hash: Hash for intermediate results. - manifest_hash: Manifest hash. - manifest: Manifest data (JSON/URL). - recording_oracle: Recording Oracle address. - reputation_oracle: Reputation Oracle address. - exchange_oracle: Exchange Oracle address. - recording_oracle_fee: Fee for the Recording Oracle. - reputation_oracle_fee: Fee for the Reputation Oracle. - exchange_oracle_fee: Fee for the Exchange Oracle. - """ - self.id = id self.address = address self.amount_paid = int(amount_paid) @@ -133,19 +133,18 @@ def __init__( class StatusEvent: - """Represents an escrow status change event.""" + """Represents an escrow status change event. + + 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__( self, timestamp: int, status: str, chain_id: ChainId, escrow_address: str ): - """Create a status event. - - Args: - timestamp: Event timestamp in seconds (converted to ms internally). - status: Escrow status. - chain_id: Chain where the event occurred. - escrow_address: Address of the escrow. - """ self.timestamp = timestamp * 1000 self.status = status self.chain_id = chain_id @@ -153,20 +152,19 @@ def __init__( class Payout: - """Represents a payout distributed by an escrow.""" + """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__( self, id: str, escrow_address: str, recipient: str, amount: str, created_at: str ): - """Create a payout record. - - Args: - id: Payout ID. - escrow_address: Escrow that executed the payout. - recipient: Recipient address. - amount: Amount paid. - created_at: Creation time in seconds (converted to ms internally). - """ self.id = id self.escrow_address = escrow_address self.recipient = recipient @@ -175,7 +173,17 @@ def __init__( class CancellationRefund: - """Represents a cancellation 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__( self, @@ -187,17 +195,6 @@ def __init__( timestamp: str, tx_hash: str, ): - """Create a cancellation refund record. - - Args: - id: Refund ID. - escrow_address: Escrow associated with the refund. - receiver: Address receiving the refund. - amount: Refunded amount. - block: Block number where the refund was processed. - timestamp: Refund timestamp in seconds (converted to ms internally). - tx_hash: Transaction hash of the refund. - """ self.id = id self.escrow_address = escrow_address self.receiver = receiver @@ -208,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 @@ -217,14 +216,20 @@ def get_escrows( filter: EscrowFilter, options: Optional[SubgraphOptions] = None, ) -> List[EscrowData]: - """List escrows that match the provided filter. + """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: Parameters used to filter escrows. - options: Optional config for subgraph requests. + 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. + List[EscrowData]: A list of escrow records matching the filter criteria. + Returns an empty list if no matches are found. Example: ```python @@ -337,15 +342,20 @@ def get_escrow( escrow_address: str, options: Optional[SubgraphOptions] = None, ) -> Optional[EscrowData]: - """Fetch a single escrow by address. + """Fetch a single escrow by its address. + + Retrieves detailed information about a specific escrow contract from the subgraph. Args: - chain_id: Network in which the escrow has been deployed. - escrow_address: Address of the escrow. - options: Optional config for subgraph requests. + 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. Returns: - Escrow data if found, otherwise ``None``. + Optional[EscrowData]: Escrow data if found, otherwise ``None``. + + Raises: + EscrowClientError: If the chain ID is invalid or the escrow address is malformed. Example: ```python @@ -424,17 +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. + """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: Parameters used to filter status events. - options: Optional config for subgraph requests. + 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 matching status events. + List[StatusEvent]: 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 @@ -489,17 +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. Args: - filter: Parameters used to filter payouts. - options: Optional config for subgraph requests. + 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. Returns: - A list of payouts matching the query parameters. + List[Payout]: A list of payout records matching the query parameters. + Returns an empty list if no matches are found. 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 @@ -558,17 +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. Args: - filter: Parameters used to filter cancellation refunds. - options: Optional config for subgraph requests. + 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. Returns: - A list of cancellation refunds matching the query parameters. + List[CancellationRefund]: A list of cancellation refunds matching the query parameters. + Returns an empty list if no matches are found. 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 @@ -630,18 +700,21 @@ def get_cancellation_refund( escrow_address: str, options: Optional[SubgraphOptions] = None, ) -> CancellationRefund: - """Return the cancellation refund for a given escrow address. + """Retrieve the cancellation refund for a specific escrow. + + Fetches the cancellation refund event associated with a given escrow address. + Each escrow can have at most one cancellation refund. Args: - chain_id: Network in which the escrow has been deployed. - escrow_address: Address of the escrow. - options: Optional config for subgraph requests. + 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. Returns: - CancellationRefund data or ``None``. + CancellationRefund: Cancellation refund data if found, otherwise ``None``. Raises: - EscrowClientError: If an unsupported chain ID or invalid address is provided. + EscrowClientError: If an unsupported chain ID or invalid escrow address is provided. Example: ```python 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 5f33ce20ca..971248f5f7 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 @@ -59,20 +59,44 @@ def get_w3_with_priv_key(priv_key: str): class KVStoreClientError(Exception): - """Raised when an error occurs while interacting with KVStore.""" + """Exception raised when errors occur during KVStore operations.""" pass class KVStoreClient: - """Manage KVStore interactions 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): - """Create a KVStore client. + """Initialize a KVStoreClient instance. Args: - web3: Web3 instance configured for the target network. - gas_limit: Optional gas limit for transactions. + 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 @@ -102,15 +126,20 @@ 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: - """Set the value of a key-value pair in the contract. + """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: Key to set. - value: Value to assign. - tx_options: Optional transaction parameters. + 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: On invalid input or transaction failure. + KVStoreClientError: If the key is empty or the transaction fails. Example: ```python @@ -133,15 +162,22 @@ def set(self, key: str, value: str, tx_options: Optional[TxParams] = None) -> No def set_bulk( self, keys: List[str], values: List[str], tx_options: Optional[TxParams] = None ) -> None: - """Set multiple key-value pairs in the contract. + """Set multiple key-value pairs in the KVStore contract. + + Stores multiple key-value pairs on-chain in a single transaction, + all associated with the sender's address. Args: - keys: List of keys to set. - values: Corresponding list of values. - tx_options: Optional transaction parameters. + 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. + + Returns: + None Raises: - KVStoreClientError: On invalid input or transaction failure. + KVStoreClientError: If any key is empty, arrays are empty, arrays have different + lengths, or the transaction fails. Example: ```python @@ -174,19 +210,27 @@ def set_file_url_and_hash( key: Optional[str] = "url", tx_options: Optional[TxParams] = None, ) -> None: - """Set a URL value and its hash for the sender address. + """Set a URL value and its content hash in the KVStore. + + 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. Args: - url: URL to set. - key: Configurable URL key (defaults to ``url``). - tx_options: Optional transaction parameters. + 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. + + Returns: + None Raises: - KVStoreClientError: If validation or transaction fails. + KVStoreClientError: If the URL is invalid, unreachable, or the transaction fails. Example: ```python - kvstore_client.set_file_url_and_hash("http://localhost") + kvstore_client.set_file_url_and_hash("http://localhost/manifest.json") kvstore_client.set_file_url_and_hash( "https://linkedin.com/me", "linkedin_url" ) @@ -206,14 +250,19 @@ def set_file_url_and_hash( handle_error(e, KVStoreClientError) def get(self, address: str, key: str) -> str: - """Get the value of a key-value pair in the contract. + """Get the value of a key-value pair from the KVStore. + + Retrieves the value associated with a key for a specific address. Args: - address: Ethereum address associated with the key-value pair. - key: Key to retrieve. + address (str): Ethereum address associated with the key-value pair. + key (str): Key to retrieve (cannot be empty). Returns: - Value of the key-value pair if it exists. + str: Value of the key-value pair if it exists, empty string otherwise. + + Raises: + KVStoreClientError: If the key is empty, address is invalid, or the query fails. Example: ```python @@ -221,6 +270,7 @@ def get(self, address: str, key: str) -> str: "0x62dD51230A30401C455c8398d06F85e4EaB6309f", "Role", ) + print(role) # "RecordingOracle" ``` """ 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 a45b0324da..ee705aff40 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 @@ -31,20 +31,24 @@ class KVStoreData: - def __init__(self, key: str, value: str): - """Container for a key/value pair. + """Represents a key-value pair from the KVStore. - Args: - key: KVStore key. - value: KVStore 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 @@ -53,27 +57,33 @@ def get_kvstore_data( address: str, options: Optional[SubgraphOptions] = None, ) -> Optional[List[KVStoreData]]: - """Return KVStore data for a given address. + """Retrieve all KVStore data for a given address. + + Queries the subgraph for all key-value pairs associated with a specific address. Args: - chain_id: Network in which the KVStore data has been deployed. - address: Address of the KVStore. - options: Optional config for subgraph requests. + 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. + Optional[List[KVStoreData]]: 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 - print( - KVStoreUtils.get_kvstore_data( - ChainId.POLYGON_AMOY, - "0x15d34aaf54267db7d7c367839aaf71a00a2c6a65", - ) + 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 @@ -116,28 +126,34 @@ def get( key: str, options: Optional[SubgraphOptions] = None, ) -> str: - """Get the value of a key-value pair in the contract. + """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: Network in which the KVStore data has been deployed. - address: Ethereum address associated with the key-value pair. - key: Key to retrieve. - options: Optional config for subgraph requests. + 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. + str: 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 - result = KVStoreUtils.get( + role = KVStoreUtils.get( ChainId.POLYGON_AMOY, "0x62dD51230A30401C455c8398d06F85e4EaB6309f", "role", ) - print(result) + print(role) ``` """ from human_protocol_sdk.gql.kvstore import get_kvstore_by_address_and_key_query @@ -176,16 +192,26 @@ def get_file_url_and_verify_hash( key: Optional[str] = "url", options: Optional[SubgraphOptions] = None, ) -> str: - """Get a stored URL and verify its hash. + """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: Network in which the KVStore data has been deployed. - address: Address from which to get the URL value. - key: Configurable URL key (defaults to ``url``). - options: Optional config for subgraph requests. + 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. + str: 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 @@ -224,14 +250,22 @@ def get_file_url_and_verify_hash( @staticmethod def get_public_key(chain_id: ChainId, address: str) -> str: - """Get the public key of the given entity. + """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: Network in which the KVStore data has been deployed. - address: Address from which to get the public key. + chain_id (ChainId): Network where the KVStore data has been stored. + address (str): Address from which to get the public key. Returns: - Public key of the given address if it exists and the content is valid. + str: 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 @@ -242,6 +276,7 @@ def get_public_key(chain_id: ChainId, address: str) -> str: ChainId.POLYGON_AMOY, "0x62dD51230A30401C455c8398d06F85e4EaB6309f", ) + print(public_key) ``` """ 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..d0e183a331 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: + bool: ``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: + bytes: 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: + bytes: 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: + bytes: 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: + eth_datatypes.PrivateKey: 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: + eth_keys.PublicKey: 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: + bytes: 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: + bytes: 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: + bytes: 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 843b3635c3..e5d921fa3b 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 @@ -26,15 +26,23 @@ class OperatorUtilsError(Exception): - """ - Raised when an error occurs while interacting with the operator. - """ + """Exception raised when errors occur during operator operations.""" pass class OperatorFilter: - """Filtering options for 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__( self, @@ -56,6 +64,9 @@ def __init__( 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: @@ -76,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, @@ -168,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, ): - """Represents a reward slashed to the slasher. - - Args: - escrow_address: Escrow address. - amount: Reward 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 @@ -194,25 +234,31 @@ def get_operators( filter: OperatorFilter, options: Optional[SubgraphOptions] = None, ) -> List[OperatorData]: - """List operators that match the provided filter. + """Retrieve a list of operators matching the provided filter criteria. + + Queries the subgraph for operators that match the specified parameters + including roles, minimum staked amount, and ordering preferences. Args: - filter: Operator filter. - options: Optional config for subgraph requests. + 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. Returns: - A list of operator details. + List[OperatorData]: A list of operator 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.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}") ``` """ @@ -284,15 +330,20 @@ def get_operator( operator_address: str, options: Optional[SubgraphOptions] = None, ) -> Optional[OperatorData]: - """Get a single operator by address. + """Retrieve a single operator by their address. + + Fetches detailed information about a specific operator from the subgraph. Args: - chain_id: Network where the operator exists. - operator_address: Address of the operator. - options: Optional config for subgraph requests. + 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. Returns: - Operator data if found, otherwise ``None``. + Optional[OperatorData]: Operator data if found, otherwise ``None``. + + Raises: + OperatorUtilsError: If the chain ID is invalid or the operator address is malformed. Example: ```python @@ -303,7 +354,9 @@ def get_operator( operator_address = "0x62dD51230A30401C455c8398d06F85e4EaB6309f" operator_data = OperatorUtils.get_operator(chain_id, operator_address) - print(operator_data) + if operator_data: + print(f"Role: {operator_data.role}") + print(f"Staked: {operator_data.staked_amount}") ``` """ @@ -365,16 +418,23 @@ def get_reputation_network_operators( role: Optional[str] = None, options: Optional[SubgraphOptions] = None, ) -> List[OperatorData]: - """Get operators registered under a reputation network. + """Retrieve operators registered under a specific reputation network. + + Fetches all operators associated with a reputation oracle, optionally + filtered by role. Args: - chain_id: Network in which the reputation network exists. - address: Reputation oracle address. - role: Optional role filter. - options: Optional config for subgraph requests. + 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. Returns: - A list of operator details. + List[OperatorData]: A list of operators registered under the reputation network. + Returns an empty list if no operators are found. + + Raises: + OperatorUtilsError: If the chain ID is invalid or the reputation address is malformed. Example: ```python @@ -384,8 +444,9 @@ def get_reputation_network_operators( operators = OperatorUtils.get_reputation_network_operators( ChainId.POLYGON_AMOY, "0x62dD51230A30401C455c8398d06F85e4EaB6309f", + role="Recording Oracle", ) - print(operators) + print(f"Found {len(operators)} operators") ``` """ @@ -452,15 +513,22 @@ def get_rewards_info( slasher: str, options: Optional[SubgraphOptions] = None, ) -> List[RewardData]: - """Get rewards collected by a slasher address. + """Retrieve rewards collected by a slasher address. + + Fetches all reward events where the specified address acted as a slasher + and received rewards for detecting misbehavior. Args: - chain_id: Network in which the slasher exists. - slasher: Address of the slasher. - options: Optional config for subgraph requests. + chain_id (ChainId): Network where the slasher operates. + slasher (str): Ethereum address of the slasher. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. Returns: - A list of rewards for the slasher. + List[RewardData]: A list of rewards received by the slasher. + Returns an empty list if no rewards are found. + + Raises: + OperatorUtilsError: If the chain ID is invalid or the slasher address is malformed. Example: ```python @@ -471,7 +539,8 @@ def get_rewards_info( ChainId.POLYGON_AMOY, "0x62dD51230A30401C455c8398d06F85e4EaB6309f", ) - print(rewards_info) + total_rewards = sum(reward.amount for reward in rewards_info) + print(f"Total rewards: {total_rewards}") ``` """ 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 de98b77d72..1c2416c731 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 @@ -45,19 +45,46 @@ class StakingClientError(Exception): - """Raised when an error occurs interacting with staking.""" + """Exception raised when errors occur during staking operations.""" pass class StakingClient: - """Manage staking on the HUMAN network.""" + """Client for interacting with the staking smart contract. + + This client provides methods to stake, unstake, withdraw, and slash HMT tokens, + as well as query staker information on the Human Protocol network. + + 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): - """Create a staking client. + """Initialize a StakingClient instance. Args: - w3: Web3 instance configured for the target network. + 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 @@ -101,9 +128,27 @@ def __init__(self, w3: Web3): def approve_stake(self, amount: int, tx_options: Optional[TxParams] = None) -> None: """Approve HMT tokens for staking. + Grants the staking contract permission to transfer HMT tokens from the caller's + account. This must be called before staking. + Args: - amount: Amount to approve (must be positive). - tx_options: Optional transaction parameters. + 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. + + Returns: + None + + Raises: + StakingClientError: If the amount is not positive or the transaction fails. + + Example: + ```python + from web3 import Web3 + + amount = Web3.to_wei(100, "ether") + staking_client.approve_stake(amount) + ``` """ if amount <= 0: @@ -120,9 +165,16 @@ def approve_stake(self, amount: int, tx_options: Optional[TxParams] = None) -> N def stake(self, amount: int, tx_options: Optional[TxParams] = None) -> None: """Stake HMT tokens. + Deposits HMT tokens into the staking contract. The tokens must be approved first + using ``approve_stake()``. + Args: - amount: Amount to stake (must be greater than 0 and within approved/balance limits). - tx_options: Optional transaction parameters. + 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. @@ -163,9 +215,16 @@ def stake(self, amount: int, tx_options: Optional[TxParams] = None) -> None: def unstake(self, amount: int, tx_options: Optional[TxParams] = None) -> None: """Unstake HMT tokens. + Initiates the unstaking process for the specified amount. The tokens will be + locked for a period before they can be withdrawn. + Args: - amount: Amount to unstake (must be greater than 0 and <= unlocked stake). - tx_options: Optional transaction parameters. + 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. + + Returns: + None Raises: StakingClientError: If the amount is invalid or the transaction fails. @@ -191,11 +250,17 @@ def unstake(self, amount: int, tx_options: Optional[TxParams] = None) -> None: def withdraw(self, tx_options: Optional[TxParams] = None) -> None: """Withdraw unlocked unstaked HMT tokens. + Withdraws all available unstaked tokens that have completed the unlocking period + and transfers them back to the caller's account. + Args: - tx_options: Optional transaction parameters. + tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. + + Returns: + None Raises: - StakingClientError: If the transaction fails or no tokens are withdrawable. + StakingClientError: If the transaction fails or no tokens are available to withdraw. Example: ```python @@ -218,14 +283,35 @@ def slash( amount: int, tx_options: Optional[TxParams] = None, ) -> None: - """Slash a staker for a given escrow. + """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: Address of the slasher. - staker: Address of the staker. - escrow_address: Address of the escrow. - amount: Amount to slash (must be > 0 and within allocation). - tx_options: Optional transaction parameters. + 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: @@ -243,19 +329,28 @@ def slash( def get_staker_info(self, staker_address: str) -> dict: """Retrieve comprehensive staking information for a staker. + Fetches on-chain staking data including staked amount, locked amount, + lock expiration, and withdrawable amount. + Args: - staker_address: Address of the staker. + staker_address (str): Ethereum address of the staker. Returns: - Dictionary containing staker information. + dict: Dictionary containing: + - ``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. Raises: - StakingClientError: If the staker address is invalid. + StakingClientError: If the staker address is invalid or the query fails. Example: ```python staking_info = staking_client.get_staker_info("0xYourStakerAddress") - print(staking_info["stakedAmount"]) + 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): @@ -287,13 +382,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: - """Check if an escrow address exists in the factory. + """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. Args: - escrow_address: Escrow address to validate. + escrow_address (str): Escrow address to validate. Returns: - True if the escrow exists in the factory registry; otherwise False. + bool: ``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 41db963103..04dbd65bcf 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 @@ -8,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, @@ -19,18 +32,6 @@ def __init__( locked_until_timestamp: str, last_deposit_timestamp: str, ): - """Represents staker data returned from the subgraph. - - Args: - id: Staker ID. - address: Staker address. - staked_amount: Total staked amount. - locked_amount: Locked amount. - withdrawn_amount: Withdrawn amount. - slashed_amount: Slashed amount. - locked_until_timestamp: Time until locked amount is released (seconds). - last_deposit_timestamp: Last deposit time (seconds). - """ self.id = id self.address = address self.staked_amount = int(staked_amount) @@ -42,25 +43,50 @@ def __init__( class StakingUtilsError(Exception): - """Raised when staking utility operations fail.""" + """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]: - """Get a single staker by address. + """Retrieve a single staker by their address. + + Fetches detailed staking information for a specific address from the subgraph. Args: - chain_id: Network to request data. - address: Staker address. - options: Optional config for subgraph requests. + 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``. + Optional[StakerData]: 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: @@ -97,14 +123,39 @@ def get_stakers( filter: StakersFilter, options: Optional[SubgraphOptions] = None, ) -> List[StakerData]: - """List stakers matching the provided filter. + """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: Staker filter parameters. - options: Optional config for subgraph requests. + 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. + List[StakerData]: 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: 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_utils.py similarity index 55% rename from packages/sdk/python/human-protocol-sdk/human_protocol_sdk/statistics/statistics_client.py rename to packages/sdk/python/human-protocol-sdk/human_protocol_sdk/statistics/statistics_utils.py index 04975bc69c..880910c0d4 100644 --- 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_utils.py @@ -1,11 +1,11 @@ -"""Client to retrieve statistical information from the subgraph. +"""Utility helpers for retrieving statistical information from the subgraph. Example: ```python from human_protocol_sdk.constants import ChainId - from human_protocol_sdk.statistics import StatisticsClient + from human_protocol_sdk.statistics import StatisticsUtils - statistics_client = StatisticsClient(ChainId.POLYGON_AMOY) + stats = StatisticsUtils.get_escrow_statistics(ChainId.POLYGON_AMOY) ``` """ @@ -22,32 +22,40 @@ LOG = logging.getLogger("human_protocol_sdk.statistics") -class StatisticsClientError(Exception): - """Raised when an error occurs fetching data from the subgraph.""" +class StatisticsUtilsError(Exception): + """Exception raised when errors occur during statistics operations.""" pass class HMTHoldersParam: - """Parameters for querying HMT holders.""" + """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", ): - """Create holder query parameters. - - Args: - address: Optional holder address filter. - order_direction: Sort direction (`asc` or `desc`). - """ self.address = address self.order_direction = order_direction class DailyEscrowData: - """Aggregated daily escrow metrics.""" + """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, @@ -58,17 +66,6 @@ def __init__( escrows_paid: int, escrows_cancelled: int, ): - """Initialize a daily escrow record. - - Args: - timestamp: Day boundary timestamp. - escrows_total: Total escrows. - escrows_pending: Pending escrows. - escrows_solved: Solved escrows. - escrows_paid: Paid escrows. - escrows_cancelled: Cancelled escrows. - """ - self.timestamp = timestamp self.escrows_total = escrows_total self.escrows_pending = escrows_pending @@ -78,61 +75,62 @@ def __init__( class EscrowStatistics: - """Escrow statistics data.""" + """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], ): - """Initialize escrow statistics. - - Args: - total_escrows: Total escrows. - daily_escrows_data: Per-day escrow data. - """ - self.total_escrows = total_escrows self.daily_escrows_data = daily_escrows_data class DailyWorkerData: - """Aggregated daily worker metrics.""" + """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, ): - """Initialize a daily worker record. - - Args: - timestamp: Day boundary timestamp. - active_workers: Number of active workers. - """ - self.timestamp = timestamp self.active_workers = active_workers class WorkerStatistics: - """Worker statistics data.""" + """Aggregate worker statistics data. + + Attributes: + daily_workers_data (List[DailyWorkerData]): Daily breakdown of worker metrics. + """ def __init__( self, daily_workers_data: List[DailyWorkerData], ): - """Initialize worker statistics. - - Args: - daily_workers_data: Per-day worker data. - """ - self.daily_workers_data = daily_workers_data class DailyPaymentData: - """Aggregated daily payment metrics.""" + """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, @@ -141,15 +139,6 @@ def __init__( total_count: int, average_amount_per_worker: int, ): - """Initialize a daily payment record. - - Args: - timestamp: Day boundary timestamp. - total_amount_paid: Total amount paid. - total_count: Payment count. - average_amount_per_worker: Average payout per worker. - """ - self.timestamp = timestamp self.total_amount_paid = total_amount_paid self.total_count = total_count @@ -157,42 +146,46 @@ def __init__( class PaymentStatistics: - """Payment statistics data.""" + """Aggregate payment statistics data. + + Attributes: + daily_payments_data (List[DailyPaymentData]): Daily breakdown of payment metrics. + """ def __init__( self, daily_payments_data: List[DailyPaymentData], ): - """Initialize payment statistics. - - Args: - daily_payments_data: Per-day payment data. - """ - self.daily_payments_data = daily_payments_data class HMTHolder: - """HMT holder record.""" + """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, ): - """Initialize a holder record. - - Args: - address: Holder address. - balance: Holder balance. - """ - self.address = address self.balance = balance class DailyHMTData: - """Aggregated daily HMT transfer metrics.""" + """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, @@ -202,16 +195,6 @@ def __init__( daily_unique_senders: int, daily_unique_receivers: int, ): - """Initialize daily HMT transfer data. - - Args: - timestamp: Day boundary timestamp. - total_transaction_amount: Total transfer amount. - total_transaction_count: Total transfer count. - daily_unique_senders: Unique senders. - daily_unique_receivers: Unique receivers. - """ - self.timestamp = timestamp self.total_transaction_amount = total_transaction_amount self.total_transaction_count = total_transaction_count @@ -220,7 +203,13 @@ def __init__( class HMTStatistics: - """HMT aggregate statistics.""" + """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, @@ -228,71 +217,69 @@ def __init__( total_transfer_count: int, total_holders: int, ): - """Initialize HMT statistics. - - Args: - total_transfer_amount: Total transfer amount. - total_transfer_count: Total transfer count. - total_holders: Total holder count. - """ - self.total_transfer_amount = total_transfer_amount self.total_transfer_count = total_transfer_count self.total_holders = total_holders -class StatisticsClient: - """Client for retrieving statistical data.""" - - def __init__(self, chain_id: ChainId = ChainId.POLYGON_AMOY): - """Create a statistics client. - - Args: - chain_id: Chain ID to read statistical data from. - - Raises: - StatisticsClientError: If the chain ID is invalid or config is missing. - """ - - 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)] +class StatisticsUtils: + """Utility class providing statistical data retrieval functions. - if not self.network: - raise StatisticsClientError("Empty network configuration") + 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( - self, + chain_id: ChainId, filter: StatisticsFilter = StatisticsFilter(), options: Optional[SubgraphOptions] = None, ) -> EscrowStatistics: - """Get escrow statistics data for the given date range. + """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: - filter: Date range and pagination filter. - options: Optional subgraph request configuration. + 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 data. + EscrowStatistics: 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 StatisticsClient + from human_protocol_sdk.statistics import StatisticsUtils from human_protocol_sdk.filter import StatisticsFilter + import datetime - statistics_client = StatisticsClient(ChainId.POLYGON_AMOY) + # Get all-time statistics + stats = StatisticsUtils.get_escrow_statistics(ChainId.POLYGON_AMOY) + print(f"Total escrows: {stats.total_escrows}") - statistics_client.get_escrow_statistics() - statistics_client.get_escrow_statistics( + # 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, @@ -300,14 +287,14 @@ def get_escrow_statistics( ) escrow_statistics_data = custom_gql_fetch( - self.network, + network, query=get_escrow_statistics_query, options=options, ) escrow_statistics = escrow_statistics_data["data"]["escrowStatistics"] event_day_datas_data = custom_gql_fetch( - self.network, + network, query=get_event_day_data_query(filter), params={ "from": int(filter.date_from.timestamp()) if filter.date_from else None, @@ -345,43 +332,59 @@ def get_escrow_statistics( ], ) + @staticmethod def get_worker_statistics( - self, + chain_id: ChainId, filter: StatisticsFilter = StatisticsFilter(), options: Optional[SubgraphOptions] = None, ) -> WorkerStatistics: - """Get worker statistics data for the given date range. + """Retrieve worker activity statistics for a given date range. + + Fetches daily worker activity metrics showing the number of active workers + participating in escrows. Args: - filter: Date range and pagination filter. - options: Optional subgraph request configuration. + 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 data. + WorkerStatistics: 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 StatisticsClient + from human_protocol_sdk.statistics import StatisticsUtils from human_protocol_sdk.filter import StatisticsFilter + import datetime - statistics_client = StatisticsClient(ChainId.POLYGON_AMOY) - - statistics_client.get_worker_statistics() - statistics_client.get_worker_statistics( + 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( - self.network, + network, query=get_event_day_data_query(filter), params={ "from": int(filter.date_from.timestamp()) if filter.date_from else None, @@ -406,44 +409,60 @@ def get_worker_statistics( ], ) + @staticmethod def get_payment_statistics( - self, + chain_id: ChainId, filter: StatisticsFilter = StatisticsFilter(), options: Optional[SubgraphOptions] = None, ) -> PaymentStatistics: - """Get payment statistics data for the given date range. + """Retrieve payment statistics for a given date range. + + Fetches daily payment metrics including total amounts paid, transaction counts, + and average payment per worker. Args: - filter: Date range and pagination filter. - options: Optional subgraph request configuration. + 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 data. + PaymentStatistics: 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 StatisticsClient + from human_protocol_sdk.statistics import StatisticsUtils from human_protocol_sdk.filter import StatisticsFilter + import datetime - statistics_client = StatisticsClient(ChainId.POLYGON_AMOY) - - statistics_client.get_payment_statistics() - statistics_client.get_payment_statistics( + 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( - self.network, + network, query=get_event_day_data_query(filter), params={ "from": int(filter.date_from.timestamp()) if filter.date_from else None, @@ -477,33 +496,48 @@ def get_payment_statistics( ], ) + @staticmethod def get_hmt_statistics( - self, options: Optional[SubgraphOptions] = None + chain_id: ChainId, options: Optional[SubgraphOptions] = None ) -> HMTStatistics: - """Get HMT statistics data. + """Retrieve aggregate HMT token statistics. + + Fetches overall HMT token metrics including total transfers and holder counts. Args: - options: Optional subgraph request configuration. + chain_id (ChainId): Network to retrieve statistics from. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. Returns: - HMT statistics data. + HMTStatistics: 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 StatisticsClient + from human_protocol_sdk.statistics import StatisticsUtils - statistics_client = StatisticsClient(ChainId.POLYGON_AMOY) - statistics_client.get_hmt_statistics() + 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_event_day_data_query, get_hmtoken_statistics_query, ) hmtoken_statistics_data = custom_gql_fetch( - self.network, + network, query=get_hmtoken_statistics_query, options=options, ) @@ -519,40 +553,58 @@ def get_hmt_statistics( total_holders=int(hmtoken_statistics.get("holders", 0)), ) + @staticmethod def get_hmt_holders( - self, + chain_id: ChainId, param: HMTHoldersParam = HMTHoldersParam(), options: Optional[SubgraphOptions] = None, ) -> List[HMTHolder]: - """Get HMT holders data with optional filters and ordering. + """Retrieve HMT token holders with optional filters and ordering. + + Fetches a list of addresses holding HMT tokens with their balances. Args: - param: Holder filters and sort preferences. - options: Optional subgraph request configuration. + 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 HMT holders. + List[HMTHolder]: 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 StatisticsClient, HMTHoldersParam + from human_protocol_sdk.statistics import StatisticsUtils, HMTHoldersParam - statistics_client = StatisticsClient(ChainId.POLYGON_AMOY) + # 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}") - statistics_client.get_hmt_holders() - statistics_client.get_hmt_holders( + # Get specific holder + holders = StatisticsUtils.get_hmt_holders( + ChainId.POLYGON_AMOY, HMTHoldersParam( address="0x123...", - order_direction="asc", + 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( - self.network, + network, query=get_holders_query(address=param.address), params={ "address": param.address, @@ -572,42 +624,62 @@ def get_hmt_holders( for holder in holders ] + @staticmethod def get_hmt_daily_data( - self, + chain_id: ChainId, filter: StatisticsFilter = StatisticsFilter(), options: Optional[SubgraphOptions] = None, ) -> List[DailyHMTData]: - """Get HMT daily statistics data for the given date range. + """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: - filter: Date range and pagination filter. - options: Optional subgraph request configuration. + 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: - Daily HMT transfer statistics. + List[DailyHMTData]: 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 StatisticsClient, StatisticsFilter - - statistics_client = StatisticsClient(ChainId.POLYGON_AMOY) + from human_protocol_sdk.statistics import StatisticsUtils + from human_protocol_sdk.filter import StatisticsFilter + import datetime - statistics_client.get_hmt_daily_data() - statistics_client.get_hmt_daily_data( + 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( - self.network, + network, query=get_event_day_data_query(filter), params={ "from": int(filter.date_from.timestamp()) if filter.date_from else None, 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 39716badac..3c63978719 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 @@ -26,7 +26,20 @@ class InternalTransaction: - """Internal transaction detail.""" + """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, @@ -48,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, @@ -78,40 +108,54 @@ def __init__( class TransactionUtilsError(Exception): - """Raised when a transaction lookup fails.""" + """Exception raised when transaction lookup or query operations fail.""" pass class TransactionUtils: - """Utility helpers to query on-chain transactions from the subgraph.""" + """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. + + Fetches detailed transaction information including internal transactions + from the subgraph. Args: - chain_id: Network in which the transaction was executed. - hash: Transaction hash. - options: Optional subgraph request configuration. + chain_id (ChainId): Network where the transaction was executed. + hash (str): Transaction hash to look up. + options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. Returns: - Transaction data if found, otherwise None. + Optional[TransactionData]: Transaction data if found, otherwise ``None``. Raises: - TransactionUtilsError: If the chain ID is unsupported. + TransactionUtilsError: If the chain ID is not supported. Example: ```python from human_protocol_sdk.constants import ChainId from human_protocol_sdk.transaction import TransactionUtils - TransactionUtils.get_transaction( + tx = TransactionUtils.get_transaction( ChainId.POLYGON_AMOY, - "0x1234567890123456789012345678901234567891", + "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) @@ -166,34 +210,62 @@ 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. + """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: Filter parameters (chain, addresses, date/block ranges, method, escrow, token, pagination). - options: Optional subgraph request configuration. + 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: - List of transactions matching the filter. + List[TransactionData]: A list of transactions matching the filter criteria. + Returns an empty list if no matches are found. Raises: - TransactionUtilsError: If the chain ID is unsupported. + 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", + ) + ) - TransactionUtils.get_transactions( + # 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", - escrow="0x0987654321098765432109876543210987654321", 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..356db90e5d 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 @@ -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: Maximum number of retry attempts for failed queries. Must be paired with base_delay. + base_delay: Base delay in milliseconds between retry attempts. Must be paired with max_retries. + indexer_id: 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: 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 @@ -80,16 +100,39 @@ def custom_gql_fetch( params: dict = None, options: Optional[SubgraphOptions] = None, ): - """Fetch data from the subgraph with optional logic. + """Fetch data from the subgraph with optional retry logic and indexer routing. + + Args: + network: Network configuration dictionary containing subgraph URLs. + query: GraphQL query string to execute. + params: Optional query parameters/variables dictionary. + options: Optional subgraph configuration for retries and indexer selection. + + Returns: + JSON response from the subgraph containing the query results. - :param network: Network configuration dictionary - :param query: GraphQL query string - :param params: Query parameters - :param options: Optional subgraph configuration + Raises: + ValueError: If retry configuration is incomplete or indexer routing requires missing API key. + Exception: If the subgraph query fails after all retry attempts. - :return: JSON response from the subgraph + Example: + ```python + from human_protocol_sdk.constants import NETWORKS, ChainId + from human_protocol_sdk.utils import SubgraphOptions, custom_gql_fetch - :raise Exception: If the subgraph query fails + 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", "") @@ -135,6 +178,20 @@ def _fetch_subgraph_data( params: dict = None, indexer_id: Optional[str] = None, ): + """Internal function to fetch data from the subgraph API. + + Args: + network: Network configuration dictionary containing subgraph URLs. + query: GraphQL query string to execute. + params: Optional query parameters/variables dictionary. + indexer_id: 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 + """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: Wallet address to check balance for. + token_addr: ERC-20 token contract address. + w3: Web3 instance connected to the network. - :return: HMT balance (wei) - """ + Returns: + int: 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,26 @@ 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. - - :param hmtoken_contract: The HMT token contract - :param tx_receipt: The transaction receipt - - :return: A tuple indicating if HMT was transferred and the transaction balance + """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. + + Returns: + A tuple containing: + - 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 @@ -221,22 +314,36 @@ def parse_transfer_transaction( def get_contract_interface(contract_entrypoint): - """Retrieve the contract interface of a given contract. + """Retrieve the contract ABI and interface from a compiled artifact file. - :param contract_entrypoint: the entrypoint of the JSON. + Args: + contract_entrypoint: File path to the contract JSON artifact. - :return: The contract interface containing the contract abi. - """ + Returns: + dict: 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. + """Retrieve the standard ERC20 token contract interface. + + Returns: + dict: 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( @@ -247,10 +354,16 @@ def get_erc20_interface(): def get_factory_interface(): - """Retrieve the EscrowFactory interface. + """Retrieve the EscrowFactory contract interface. - :return: The EscrowFactory interface of smart contract. + Returns: + dict: 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( @@ -259,10 +372,16 @@ def get_factory_interface(): def get_staking_interface(): - """Retrieve the Staking interface. + """Retrieve the Staking contract interface. - :return: The Staking interface of smart contract. + Returns: + dict: 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( @@ -271,10 +390,16 @@ def get_staking_interface(): def get_escrow_interface(): - """Retrieve the RewardPool interface. + """Retrieve the Escrow contract interface. - :return: The RewardPool interface of smart contract. + Returns: + dict: 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( @@ -283,10 +408,16 @@ def get_escrow_interface(): def get_kvstore_interface(): - """Retrieve the KVStore interface. + """Retrieve the KVStore contract interface. - :return: The KVStore interface of smart contract. + Returns: + dict: 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( @@ -295,24 +426,29 @@ def get_kvstore_interface(): def handle_error(e, exception_class): - """ - Handles and translates errors raised during contract transactions. + """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: The exception object raised during a transaction. + exception_class: 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 +485,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: + bool: 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 +534,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: + bool: 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..498478e942 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 operations. + +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: + List[WorkerData]: 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: + Optional[WorkerData]: 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/python/human-protocol-sdk/mkdocs.yaml b/packages/sdk/python/human-protocol-sdk/mkdocs.yaml index bdd1656884..808cde6aca 100644 --- a/packages/sdk/python/human-protocol-sdk/mkdocs.yaml +++ b/packages/sdk/python/human-protocol-sdk/mkdocs.yaml @@ -61,7 +61,7 @@ plugins: handlers: python: options: - docstring_style: google # or "numpy" / "restructuredtext" + docstring_style: google show_source: false separate_signature: true merge_init_into_class: true @@ -73,6 +73,7 @@ nav: - Encryption: - Encryption: encryption.md - Encryption Utils: encryption_utils.md + - LegacyEncryption: legacy_encryption.md - Escrow: - EscrowClient: escrow_client.md - EscrowUtils: escrow_utils.md @@ -85,10 +86,11 @@ nav: - StakingClient: staking_client.md - StakingUtils: staking_utils.md - Statistics: - - StatisticsClient: statistics_client.md + - StatisticsUtils: statistics_utils.md - Transaction: - TransactionUtils: transaction_utils.md - - Worker: api/worker.md - - Core utilities: api/core.md + - Worker: + - WorkerUtils: worker_utils.md + - Core utilities: core.md extra_css: - overrides/assets/css/custom.css From 0dbfabaad417d72b88bd5c33a773a78d4af9b4fe Mon Sep 17 00:00:00 2001 From: portuu3 Date: Fri, 5 Dec 2025 10:42:40 +0100 Subject: [PATCH 03/19] delete docs --- docs/sdk/README.md | 38 - docs/sdk/SUMMARY.md | 61 - docs/sdk/changelog.md | 36 - .../human_protocol_sdk.agreement.bootstrap.md | 41 - .../python/human_protocol_sdk.agreement.md | 105 -- .../human_protocol_sdk.agreement.measures.md | 226 --- .../human_protocol_sdk.agreement.utils.md | 226 --- .../python/human_protocol_sdk.constants.md | 105 -- .../python/human_protocol_sdk.decorators.md | 9 - ...uman_protocol_sdk.encryption.encryption.md | 193 -- ...rotocol_sdk.encryption.encryption_utils.md | 236 --- .../python/human_protocol_sdk.encryption.md | 22 - ...human_protocol_sdk.escrow.escrow_client.md | 616 ------- .../human_protocol_sdk.escrow.escrow_utils.md | 231 --- docs/sdk/python/human_protocol_sdk.escrow.md | 63 - docs/sdk/python/human_protocol_sdk.filter.md | 174 -- ...man_protocol_sdk.kvstore.kvstore_client.md | 100 -- ...uman_protocol_sdk.kvstore.kvstore_utils.md | 135 -- docs/sdk/python/human_protocol_sdk.kvstore.md | 26 - .../human_protocol_sdk.legacy_encryption.md | 162 -- docs/sdk/python/human_protocol_sdk.md | 224 --- .../sdk/python/human_protocol_sdk.operator.md | 22 - ...an_protocol_sdk.operator.operator_utils.md | 188 -- docs/sdk/python/human_protocol_sdk.staking.md | 28 - ...man_protocol_sdk.staking.staking_client.md | 106 -- ...uman_protocol_sdk.staking.staking_utils.md | 49 - .../python/human_protocol_sdk.statistics.md | 38 - ...otocol_sdk.statistics.statistics_client.md | 349 ---- docs/sdk/python/human_protocol_sdk.storage.md | 22 - ...man_protocol_sdk.storage.storage_client.md | 246 --- ...uman_protocol_sdk.storage.storage_utils.md | 30 - .../python/human_protocol_sdk.transaction.md | 18 - ...tocol_sdk.transaction.transaction_utils.md | 105 -- docs/sdk/python/human_protocol_sdk.utils.md | 150 -- docs/sdk/python/human_protocol_sdk.worker.md | 13 - .../human_protocol_sdk.worker.worker_utils.md | 52 - docs/sdk/python/index.md | 83 - docs/sdk/typescript/README.md | 37 - docs/sdk/typescript/base/README.md | 11 - .../base/classes/BaseEthersClient.md | 63 - docs/sdk/typescript/encryption/README.md | 12 - .../encryption/classes/Encryption.md | 257 --- .../encryption/classes/EncryptionUtils.md | 283 --- docs/sdk/typescript/enums/README.md | 13 - .../typescript/enums/enumerations/ChainId.md | 73 - .../enums/enumerations/OperatorCategory.md | 25 - .../enums/enumerations/OrderDirection.md | 25 - docs/sdk/typescript/escrow/README.md | 12 - .../typescript/escrow/classes/EscrowClient.md | 1572 ----------------- .../typescript/escrow/classes/EscrowUtils.md | 538 ------ docs/sdk/typescript/graphql/types/README.md | 29 - .../types/interfaces/IOperatorSubgraph.md | 141 -- .../interfaces/IReputationNetworkSubgraph.md | 45 - .../type-aliases/CancellationRefundData.md | 67 - .../graphql/types/type-aliases/EscrowData.md | 203 --- .../type-aliases/EscrowStatisticsData.md | 91 - .../types/type-aliases/EventDayData.md | 155 -- .../types/type-aliases/HMTHolderData.md | 27 - .../types/type-aliases/HMTStatisticsData.md | 59 - .../type-aliases/InternalTransactionData.md | 75 - .../graphql/types/type-aliases/KVStoreData.md | 59 - .../graphql/types/type-aliases/PayoutData.md | 51 - .../type-aliases/RewardAddedEventData.md | 43 - .../graphql/types/type-aliases/StakerData.md | 75 - .../graphql/types/type-aliases/StatusEvent.md | 35 - .../types/type-aliases/TransactionData.md | 99 -- .../graphql/types/type-aliases/WorkerData.md | 43 - docs/sdk/typescript/interfaces/README.md | 47 - .../interfaces/ICancellationRefund.md | 65 - .../interfaces/ICancellationRefundFilter.md | 89 - .../interfaces/interfaces/IDailyEscrow.md | 57 - .../interfaces/interfaces/IDailyHMT.md | 49 - .../interfaces/interfaces/IDailyPayment.md | 41 - .../interfaces/interfaces/IDailyWorker.md | 25 - .../interfaces/interfaces/IEscrow.md | 209 --- .../interfaces/interfaces/IEscrowConfig.md | 73 - .../interfaces/IEscrowStatistics.md | 25 - .../interfaces/interfaces/IEscrowWithdraw.md | 33 - .../interfaces/interfaces/IEscrowsFilter.md | 121 -- .../interfaces/interfaces/IHMTHolder.md | 25 - .../interfaces/IHMTHoldersParams.md | 57 - .../interfaces/interfaces/IHMTStatistics.md | 33 - .../interfaces/interfaces/IKVStore.md | 25 - .../interfaces/interfaces/IKeyPair.md | 41 - .../interfaces/interfaces/IOperator.md | 177 -- .../interfaces/interfaces/IOperatorsFilter.md | 81 - .../interfaces/interfaces/IPagination.md | 46 - .../interfaces/IPaymentStatistics.md | 17 - .../interfaces/interfaces/IPayout.md | 49 - .../interfaces/interfaces/IPayoutFilter.md | 89 - .../interfaces/IReputationNetwork.md | 33 - .../interfaces/interfaces/IReward.md | 25 - .../interfaces/interfaces/IStaker.md | 65 - .../interfaces/interfaces/IStakersFilter.md | 129 -- .../interfaces/IStatisticsFilter.md | 65 - .../interfaces/interfaces/IStatusEvent.md | 41 - .../interfaces/IStatusEventFilter.md | 89 - .../interfaces/interfaces/ITransaction.md | 97 - .../interfaces/ITransactionsFilter.md | 129 -- .../interfaces/interfaces/IWorker.md | 41 - .../interfaces/IWorkerStatistics.md | 17 - .../interfaces/interfaces/IWorkersFilter.md | 73 - .../interfaces/InternalTransaction.md | 65 - .../interfaces/interfaces/StakerInfo.md | 41 - .../interfaces/interfaces/SubgraphOptions.md | 42 - docs/sdk/typescript/kvstore/README.md | 12 - .../kvstore/classes/KVStoreClient.md | 378 ---- .../kvstore/classes/KVStoreUtils.md | 270 --- docs/sdk/typescript/modules.md | 21 - docs/sdk/typescript/operator/README.md | 11 - .../operator/classes/OperatorUtils.md | 198 --- docs/sdk/typescript/staking/README.md | 12 - .../staking/classes/StakingClient.md | 482 ----- .../staking/classes/StakingUtils.md | 87 - docs/sdk/typescript/statistics/README.md | 11 - .../statistics/classes/StatisticsClient.md | 474 ----- docs/sdk/typescript/storage/README.md | 11 - .../storage/classes/StorageClient.md | 305 ---- docs/sdk/typescript/transaction/README.md | 11 - .../transaction/classes/TransactionUtils.md | 184 -- docs/sdk/typescript/types/README.md | 19 - .../types/enumerations/EscrowStatus.md | 81 - .../types/type-aliases/NetworkData.md | 123 -- .../types/type-aliases/StorageCredentials.md | 37 - .../types/type-aliases/StorageParams.md | 55 - .../type-aliases/TransactionLikeWithNonce.md | 17 - .../types/type-aliases/UploadFile.md | 43 - .../sdk/python/human-protocol-sdk/mkdocs.yaml | 96 - 128 files changed, 14110 deletions(-) delete mode 100644 docs/sdk/README.md delete mode 100644 docs/sdk/SUMMARY.md delete mode 100644 docs/sdk/changelog.md delete mode 100644 docs/sdk/python/human_protocol_sdk.agreement.bootstrap.md delete mode 100644 docs/sdk/python/human_protocol_sdk.agreement.md delete mode 100644 docs/sdk/python/human_protocol_sdk.agreement.measures.md delete mode 100644 docs/sdk/python/human_protocol_sdk.agreement.utils.md delete mode 100644 docs/sdk/python/human_protocol_sdk.constants.md delete mode 100644 docs/sdk/python/human_protocol_sdk.decorators.md delete mode 100644 docs/sdk/python/human_protocol_sdk.encryption.encryption.md delete mode 100644 docs/sdk/python/human_protocol_sdk.encryption.encryption_utils.md delete mode 100644 docs/sdk/python/human_protocol_sdk.encryption.md delete mode 100644 docs/sdk/python/human_protocol_sdk.escrow.escrow_client.md delete mode 100644 docs/sdk/python/human_protocol_sdk.escrow.escrow_utils.md delete mode 100644 docs/sdk/python/human_protocol_sdk.escrow.md delete mode 100644 docs/sdk/python/human_protocol_sdk.filter.md delete mode 100644 docs/sdk/python/human_protocol_sdk.kvstore.kvstore_client.md delete mode 100644 docs/sdk/python/human_protocol_sdk.kvstore.kvstore_utils.md delete mode 100644 docs/sdk/python/human_protocol_sdk.kvstore.md delete mode 100644 docs/sdk/python/human_protocol_sdk.legacy_encryption.md delete mode 100644 docs/sdk/python/human_protocol_sdk.md delete mode 100644 docs/sdk/python/human_protocol_sdk.operator.md delete mode 100644 docs/sdk/python/human_protocol_sdk.operator.operator_utils.md delete mode 100644 docs/sdk/python/human_protocol_sdk.staking.md delete mode 100644 docs/sdk/python/human_protocol_sdk.staking.staking_client.md delete mode 100644 docs/sdk/python/human_protocol_sdk.staking.staking_utils.md delete mode 100644 docs/sdk/python/human_protocol_sdk.statistics.md delete mode 100644 docs/sdk/python/human_protocol_sdk.statistics.statistics_client.md delete mode 100644 docs/sdk/python/human_protocol_sdk.storage.md delete mode 100644 docs/sdk/python/human_protocol_sdk.storage.storage_client.md delete mode 100644 docs/sdk/python/human_protocol_sdk.storage.storage_utils.md delete mode 100644 docs/sdk/python/human_protocol_sdk.transaction.md delete mode 100644 docs/sdk/python/human_protocol_sdk.transaction.transaction_utils.md delete mode 100644 docs/sdk/python/human_protocol_sdk.utils.md delete mode 100644 docs/sdk/python/human_protocol_sdk.worker.md delete mode 100644 docs/sdk/python/human_protocol_sdk.worker.worker_utils.md delete mode 100644 docs/sdk/python/index.md delete mode 100644 docs/sdk/typescript/README.md delete mode 100644 docs/sdk/typescript/base/README.md delete mode 100644 docs/sdk/typescript/base/classes/BaseEthersClient.md delete mode 100644 docs/sdk/typescript/encryption/README.md delete mode 100644 docs/sdk/typescript/encryption/classes/Encryption.md delete mode 100644 docs/sdk/typescript/encryption/classes/EncryptionUtils.md delete mode 100644 docs/sdk/typescript/enums/README.md delete mode 100644 docs/sdk/typescript/enums/enumerations/ChainId.md delete mode 100644 docs/sdk/typescript/enums/enumerations/OperatorCategory.md delete mode 100644 docs/sdk/typescript/enums/enumerations/OrderDirection.md delete mode 100644 docs/sdk/typescript/escrow/README.md delete mode 100644 docs/sdk/typescript/escrow/classes/EscrowClient.md delete mode 100644 docs/sdk/typescript/escrow/classes/EscrowUtils.md delete mode 100644 docs/sdk/typescript/graphql/types/README.md delete mode 100644 docs/sdk/typescript/graphql/types/interfaces/IOperatorSubgraph.md delete mode 100644 docs/sdk/typescript/graphql/types/interfaces/IReputationNetworkSubgraph.md delete mode 100644 docs/sdk/typescript/graphql/types/type-aliases/CancellationRefundData.md delete mode 100644 docs/sdk/typescript/graphql/types/type-aliases/EscrowData.md delete mode 100644 docs/sdk/typescript/graphql/types/type-aliases/EscrowStatisticsData.md delete mode 100644 docs/sdk/typescript/graphql/types/type-aliases/EventDayData.md delete mode 100644 docs/sdk/typescript/graphql/types/type-aliases/HMTHolderData.md delete mode 100644 docs/sdk/typescript/graphql/types/type-aliases/HMTStatisticsData.md delete mode 100644 docs/sdk/typescript/graphql/types/type-aliases/InternalTransactionData.md delete mode 100644 docs/sdk/typescript/graphql/types/type-aliases/KVStoreData.md delete mode 100644 docs/sdk/typescript/graphql/types/type-aliases/PayoutData.md delete mode 100644 docs/sdk/typescript/graphql/types/type-aliases/RewardAddedEventData.md delete mode 100644 docs/sdk/typescript/graphql/types/type-aliases/StakerData.md delete mode 100644 docs/sdk/typescript/graphql/types/type-aliases/StatusEvent.md delete mode 100644 docs/sdk/typescript/graphql/types/type-aliases/TransactionData.md delete mode 100644 docs/sdk/typescript/graphql/types/type-aliases/WorkerData.md delete mode 100644 docs/sdk/typescript/interfaces/README.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/ICancellationRefund.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/ICancellationRefundFilter.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IDailyEscrow.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IDailyHMT.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IDailyPayment.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IDailyWorker.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IEscrow.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IEscrowConfig.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IEscrowStatistics.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IEscrowWithdraw.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IEscrowsFilter.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IHMTHolder.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IHMTHoldersParams.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IHMTStatistics.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IKVStore.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IKeyPair.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IOperator.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IOperatorsFilter.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IPagination.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IPaymentStatistics.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IPayout.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IPayoutFilter.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IReputationNetwork.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IReward.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IStaker.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IStakersFilter.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IStatisticsFilter.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IStatusEvent.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IStatusEventFilter.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/ITransaction.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/ITransactionsFilter.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IWorker.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IWorkerStatistics.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/IWorkersFilter.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/InternalTransaction.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/StakerInfo.md delete mode 100644 docs/sdk/typescript/interfaces/interfaces/SubgraphOptions.md delete mode 100644 docs/sdk/typescript/kvstore/README.md delete mode 100644 docs/sdk/typescript/kvstore/classes/KVStoreClient.md delete mode 100644 docs/sdk/typescript/kvstore/classes/KVStoreUtils.md delete mode 100644 docs/sdk/typescript/modules.md delete mode 100644 docs/sdk/typescript/operator/README.md delete mode 100644 docs/sdk/typescript/operator/classes/OperatorUtils.md delete mode 100644 docs/sdk/typescript/staking/README.md delete mode 100644 docs/sdk/typescript/staking/classes/StakingClient.md delete mode 100644 docs/sdk/typescript/staking/classes/StakingUtils.md delete mode 100644 docs/sdk/typescript/statistics/README.md delete mode 100644 docs/sdk/typescript/statistics/classes/StatisticsClient.md delete mode 100644 docs/sdk/typescript/storage/README.md delete mode 100644 docs/sdk/typescript/storage/classes/StorageClient.md delete mode 100644 docs/sdk/typescript/transaction/README.md delete mode 100644 docs/sdk/typescript/transaction/classes/TransactionUtils.md delete mode 100644 docs/sdk/typescript/types/README.md delete mode 100644 docs/sdk/typescript/types/enumerations/EscrowStatus.md delete mode 100644 docs/sdk/typescript/types/type-aliases/NetworkData.md delete mode 100644 docs/sdk/typescript/types/type-aliases/StorageCredentials.md delete mode 100644 docs/sdk/typescript/types/type-aliases/StorageParams.md delete mode 100644 docs/sdk/typescript/types/type-aliases/TransactionLikeWithNonce.md delete mode 100644 docs/sdk/typescript/types/type-aliases/UploadFile.md delete mode 100644 packages/sdk/python/human-protocol-sdk/mkdocs.yaml 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/mkdocs.yaml b/packages/sdk/python/human-protocol-sdk/mkdocs.yaml deleted file mode 100644 index 808cde6aca..0000000000 --- a/packages/sdk/python/human-protocol-sdk/mkdocs.yaml +++ /dev/null @@ -1,96 +0,0 @@ -site_name: HUMAN Protocol Python SDK Docs -site_url: https://sdk.humanprotocol.org/python/ -repo_name: humanprotocol/human-protocol-sdk -repo_url: https://github.com/humanprotocol/human-protocol-sdk -docs_dir: docs -site_dir: site/python -theme: - name: material - custom_dir: docs/overrides - logo: overrides/assets/img/logo.svg - favicon: overrides/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 -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: - 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: - - overrides/assets/css/custom.css From ed2b33f5564830020166734bbd188fefec961eff Mon Sep 17 00:00:00 2001 From: portuu3 Date: Fri, 5 Dec 2025 13:10:10 +0100 Subject: [PATCH 04/19] ts docs --- .gitignore | 3 + docs/index.html | 202 +++ docs/mkdocs-python.yaml | 97 ++ docs/mkdocs-ts.yaml | 89 + docs/requirements.txt | 6 + .../human_protocol_sdk/decorators.py | 13 +- .../human_protocol_sdk/utils.py | 84 +- .../typescript/human-protocol-sdk/.gitignore | 3 - .../[object Object]/README.md | 29 + .../[object Object]/classes/Encryption.md | 157 ++ .../classes/EncryptionUtils.md | 180 ++ .../[object Object]/classes/EscrowClient.md | 1502 +++++++++++++++++ .../[object Object]/classes/EscrowUtils.md | 306 ++++ .../[object Object]/classes/KVStoreClient.md | 308 ++++ .../[object Object]/classes/KVStoreUtils.md | 214 +++ .../[object Object]/classes/OperatorUtils.md | 191 +++ .../[object Object]/classes/StakingClient.md | 389 +++++ .../[object Object]/classes/StakingUtils.md | 104 ++ .../classes/StatisticsUtils.md | 401 +++++ .../[object Object]/classes/StorageClient.md | 268 +++ .../classes/TransactionUtils.md | 186 ++ .../enumerations/EscrowStatus.md | 13 + .../interfaces/SubgraphOptions.md | 9 + .../type-aliases/NetworkData.md | 115 ++ .../type-aliases/StorageCredentials.md | 29 + .../type-aliases/StorageParams.md | 47 + .../type-aliases/UploadFile.md | 35 + .../human-protocol-sdk/docs/README.md | 29 + .../docs/classes/Encryption.md | 161 ++ .../docs/classes/EncryptionUtils.md | 182 ++ .../docs/classes/EscrowClient.md | 1403 +++++++++++++++ .../docs/classes/EscrowUtils.md | 297 ++++ .../docs/classes/KVStoreClient.md | 297 ++++ .../docs/classes/KVStoreUtils.md | 198 +++ .../docs/classes/OperatorUtils.md | 193 +++ .../docs/classes/StakingClient.md | 374 ++++ .../docs/classes/StakingUtils.md | 102 ++ .../docs/classes/StatisticsUtils.md | 401 +++++ .../docs/classes/StorageClient.md | 270 +++ .../docs/classes/TransactionUtils.md | 184 ++ .../docs/enumerations/EscrowStatus.md | 13 + .../docs/interfaces/SubgraphOptions.md | 9 + .../docs/type-aliases/NetworkData.md | 115 ++ .../docs/type-aliases/StorageCredentials.md | 29 + .../docs/type-aliases/StorageParams.md | 47 + .../docs/type-aliases/UploadFile.md | 35 + .../human-protocol-sdk/package.json | 27 +- .../scripts/postprocess-docs.ts | 146 ++ .../human-protocol-sdk/src/encryption.ts | 275 +-- .../human-protocol-sdk/src/escrow.ts | 1148 +++++-------- .../human-protocol-sdk/src/index.ts | 4 +- .../human-protocol-sdk/src/kvstore.ts | 268 ++- .../human-protocol-sdk/src/operator.ts | 89 +- .../human-protocol-sdk/src/staking.ts | 226 +-- .../human-protocol-sdk/src/statistics.ts | 259 ++- .../human-protocol-sdk/src/transaction.ts | 51 +- .../human-protocol-sdk/src/worker.ts | 49 +- .../human-protocol-sdk/tsconfig.eslint.json | 2 +- .../human-protocol-sdk/typedoc.json | 45 + yarn.lock | 97 +- 60 files changed, 10471 insertions(+), 1534 deletions(-) create mode 100644 docs/index.html create mode 100644 docs/mkdocs-python.yaml create mode 100644 docs/mkdocs-ts.yaml create mode 100644 docs/requirements.txt create mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/README.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/Encryption.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/EncryptionUtils.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/EscrowClient.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/EscrowUtils.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/KVStoreClient.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/KVStoreUtils.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/OperatorUtils.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StakingClient.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StakingUtils.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StatisticsUtils.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StorageClient.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/TransactionUtils.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/enumerations/EscrowStatus.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/interfaces/SubgraphOptions.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/NetworkData.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/StorageCredentials.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/StorageParams.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/UploadFile.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/README.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/Encryption.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/EncryptionUtils.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowClient.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowUtils.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreClient.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreUtils.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/OperatorUtils.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingClient.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingUtils.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/StatisticsUtils.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/StorageClient.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/TransactionUtils.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/enumerations/EscrowStatus.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/interfaces/SubgraphOptions.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/NetworkData.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/StorageCredentials.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/StorageParams.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/UploadFile.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/scripts/postprocess-docs.ts create mode 100644 packages/sdk/typescript/human-protocol-sdk/typedoc.json diff --git a/.gitignore b/.gitignore index 6c925760ab..84a5849c7d 100644 --- a/.gitignore +++ b/.gitignore @@ -55,3 +55,6 @@ cache # Ignore developer-only local files .local + +docs/python +docs/ts \ No newline at end of file diff --git a/docs/index.html b/docs/index.html new file mode 100644 index 0000000000..18df3aee24 --- /dev/null +++ b/docs/index.html @@ -0,0 +1,202 @@ + + + + + HUMAN Protocol SDKs + + + + +
+

HUMAN Protocol SDKs

+

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

+ +
+ +
+
🟦
+
+ TypeScript + Node.js / Browser +
+

TypeScript SDK

+

+ Typed client for Node.js and browser-based apps. Ideal if you’re building dashboards, + dApps, or services that interact with HUMAN Protocol contracts directly. +

+ +
+ + +
+
🐍
+
+ Python + Scripts / Services +
+

Python SDK

+

+ Pythonic client for automation, bots, data pipelines, and backend services. + Perfect when your stack is already built around Python and notebooks. +

+ +
+
+
+ +
+
Not sure where to start?
+
    +
  • Use TypeScript if you’re building web apps, dashboards, or dApps.
  • +
  • Use Python if you’re scripting, automating, or doing data/ML workflows.
  • +
+
+ + \ No newline at end of file diff --git a/docs/mkdocs-python.yaml b/docs/mkdocs-python.yaml new file mode 100644 index 0000000000..32f2eb8db4 --- /dev/null +++ b/docs/mkdocs-python.yaml @@ -0,0 +1,97 @@ +site_name: HUMAN Protocol Python SDK Docs +site_url: https://sdk.humanprotocol.org/python/ +repo_name: humanprotocol/human-protocol-sdk +repo_url: https://github.com/humanprotocol/human-protocol-sdk +docs_dir: ../packages/sdk/python/human-protocol-sdk/docs +site_dir: python +theme: + name: material + custom_dir: overrides + logo: overrides/assets/img/logo.svg + favicon: overrides/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 +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..2ed1e67b1a --- /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-sdk +repo_url: https://github.com/humanprotocol/human-protocol-sdk +docs_dir: ../packages/sdk/typescript/human-protocol-sdk/docs +site_dir: ts +theme: + name: material + custom_dir: overrides + logo: overrides/assets/img/logo.svg + favicon: overrides/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 +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 + - Core utilities: classes/Core.md +extra_css: + - assets/css/custom.css 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/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/decorators.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/decorators.py index 770d1080c1..6438711850 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,3 +1,8 @@ +"""Decorators for SDK functionality.""" + +from typing import Callable, Any + + class RequiresSignerError(Exception): """Raised when a transaction-signing method is called without proper Web3 account configuration. @@ -11,7 +16,7 @@ class RequiresSignerError(Exception): pass -def requires_signer(method): +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 @@ -19,10 +24,10 @@ def requires_signer(method): methods that need to sign and send transactions. Args: - method: The method to decorate (must be a method of a class with a `w3` attribute). + 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. + Callable[..., Any]: Wrapped method that performs validation before execution. Raises: RequiresSignerError: If the Web3 instance lacks a default account or signing middleware. @@ -44,7 +49,7 @@ def send_transaction(self): ``` """ - def wrapper(self, *args, **kwargs): + 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/utils.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/utils.py index 356db90e5d..6d34be624c 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 @@ -37,9 +37,9 @@ class SubgraphOptions: """Configuration options for subgraph queries with retry logic and indexer routing. Attributes: - max_retries: Maximum number of retry attempts for failed queries. Must be paired with base_delay. - base_delay: Base delay in milliseconds between retry attempts. Must be paired with max_retries. - indexer_id: Specific indexer ID to route requests to (requires SUBGRAPH_API_KEY environment variable). + 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 @@ -54,10 +54,10 @@ def is_indexer_error(error: Exception) -> bool: messages that indicate infrastructure issues rather than query problems. Args: - error: The exception to check. + error (Exception): The exception to check. Returns: - True if the error indicates indexer issues, False otherwise. + bool: True if the error indicates indexer issues, False otherwise. Example: ```python @@ -95,21 +95,21 @@ 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, -): +) -> Dict[str, Any]: """Fetch data from the subgraph with optional retry logic and indexer routing. Args: - network: Network configuration dictionary containing subgraph URLs. - query: GraphQL query string to execute. - params: Optional query parameters/variables dictionary. - options: Optional subgraph configuration for retries and indexer selection. + 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. + Dict[str, Any]: JSON response from the subgraph containing the query results. Raises: ValueError: If retry configuration is incomplete or indexer routing requires missing API key. @@ -173,21 +173,21 @@ 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: Network configuration dictionary containing subgraph URLs. - query: GraphQL query string to execute. - params: Optional query parameters/variables dictionary. - indexer_id: Optional indexer ID to route the request to. + 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. + Dict[str, Any]: JSON response from the subgraph. Raises: Exception: If the HTTP request fails or returns a non-200 status code. @@ -237,13 +237,13 @@ def _attach_indexer_id(url: str, indexer_id: Optional[str]) -> str: return f"{url}/indexers/id/{indexer_id}" -def get_hmt_balance(wallet_addr, token_addr, w3): +def get_hmt_balance(wallet_addr: str, token_addr: str, w3: Web3) -> int: """Get the HMT token balance for a wallet address. Args: - wallet_addr: Wallet address to check balance for. - token_addr: ERC-20 token contract address. - w3: Web3 instance connected to the network. + 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. Returns: int: HMT token balance in wei. @@ -313,14 +313,14 @@ def parse_transfer_transaction( return hmt_transferred and tx_balance is not None, tx_balance -def get_contract_interface(contract_entrypoint): +def get_contract_interface(contract_entrypoint: str) -> Dict[str, Any]: """Retrieve the contract ABI and interface from a compiled artifact file. Args: - contract_entrypoint: File path to the contract JSON artifact. + contract_entrypoint (str): File path to the contract JSON artifact. Returns: - dict: Contract interface dictionary containing the ABI and other metadata. + Dict[str, Any]: Contract interface dictionary containing the ABI and other metadata. Example: ```python @@ -333,11 +333,11 @@ def get_contract_interface(contract_entrypoint): return contract_interface -def get_erc20_interface(): +def get_erc20_interface() -> Dict[str, Any]: """Retrieve the standard ERC20 token contract interface. Returns: - dict: The ERC20 contract interface containing the ABI. + Dict[str, Any]: The ERC20 contract interface containing the ABI. Example: ```python @@ -353,11 +353,11 @@ def get_erc20_interface(): ) -def get_factory_interface(): +def get_factory_interface() -> Dict[str, Any]: """Retrieve the EscrowFactory contract interface. Returns: - dict: The EscrowFactory contract interface containing the ABI. + Dict[str, Any]: The EscrowFactory contract interface containing the ABI. Example: ```python @@ -371,11 +371,11 @@ def get_factory_interface(): ) -def get_staking_interface(): +def get_staking_interface() -> Dict[str, Any]: """Retrieve the Staking contract interface. Returns: - dict: The Staking contract interface containing the ABI. + Dict[str, Any]: The Staking contract interface containing the ABI. Example: ```python @@ -389,11 +389,11 @@ def get_staking_interface(): ) -def get_escrow_interface(): +def get_escrow_interface() -> Dict[str, Any]: """Retrieve the Escrow contract interface. Returns: - dict: The Escrow contract interface containing the ABI. + Dict[str, Any]: The Escrow contract interface containing the ABI. Example: ```python @@ -407,11 +407,11 @@ def get_escrow_interface(): ) -def get_kvstore_interface(): +def get_kvstore_interface() -> Dict[str, Any]: """Retrieve the KVStore contract interface. Returns: - dict: The KVStore contract interface containing the ABI. + Dict[str, Any]: The KVStore contract interface containing the ABI. Example: ```python @@ -425,7 +425,7 @@ def get_kvstore_interface(): ) -def handle_error(e, exception_class): +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), @@ -433,8 +433,8 @@ def handle_error(e, exception_class): a custom exception with a clear message for SDK users. Args: - e: The exception object raised during a transaction. - exception_class: The custom exception class to raise (e.g., EscrowClientError). + 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. diff --git a/packages/sdk/typescript/human-protocol-sdk/.gitignore b/packages/sdk/typescript/human-protocol-sdk/.gitignore index f87fcba870..0a21461bf3 100644 --- a/packages/sdk/typescript/human-protocol-sdk/.gitignore +++ b/packages/sdk/typescript/human-protocol-sdk/.gitignore @@ -6,6 +6,3 @@ dist # Logs logs - -#Docs -docs \ No newline at end of file diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/README.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/README.md new file mode 100644 index 0000000000..90a6f9d669 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/[object Object]/README.md @@ -0,0 +1,29 @@ +## Enumerations + +- [EscrowStatus](enumerations/EscrowStatus.md) + +## Classes + +- [Encryption](classes/Encryption.md) +- [EncryptionUtils](classes/EncryptionUtils.md) +- [EscrowClient](classes/EscrowClient.md) +- [EscrowUtils](classes/EscrowUtils.md) +- [KVStoreClient](classes/KVStoreClient.md) +- [KVStoreUtils](classes/KVStoreUtils.md) +- [OperatorUtils](classes/OperatorUtils.md) +- [StakingClient](classes/StakingClient.md) +- [StakingUtils](classes/StakingUtils.md) +- [StatisticsUtils](classes/StatisticsUtils.md) +- [~~StorageClient~~](classes/StorageClient.md) +- [TransactionUtils](classes/TransactionUtils.md) + +## Interfaces + +- [SubgraphOptions](interfaces/SubgraphOptions.md) + +## Type Aliases + +- [~~StorageCredentials~~](type-aliases/StorageCredentials.md) +- [~~StorageParams~~](type-aliases/StorageParams.md) +- [UploadFile](type-aliases/UploadFile.md) +- [NetworkData](type-aliases/NetworkData.md) diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/Encryption.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/Encryption.md new file mode 100644 index 0000000000..fc42d05259 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/Encryption.md @@ -0,0 +1,157 @@ +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`](/ts/classes/Encryption/#build) method. + +## Constructors + +### Constructor + +```ts +new Encryption(privateKey: PrivateKey): Encryption; +``` + +Constructor for the Encryption class. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `privateKey` | `PrivateKey` | The private key. | + +#### Returns + +`Encryption` + +## Methods + +### build() + +```ts +static build(privateKeyArmored: string, passphrase?: string): Promise; +``` + +Builds an Encryption instance by decrypting the private key from an encrypted private key and passphrase. + +#### Example + +```ts +import { Encryption } from '@human-protocol/sdk'; + +const privateKey = 'Armored_priv_key'; +const passphrase = 'example_passphrase'; +const encryption = await Encryption.build(privateKey, passphrase); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `privateKeyArmored` | `string` | The encrypted private key in armored format. | +| `passphrase?` | `string` | The passphrase for the private key (optional). | + +#### Returns + +`Promise`\<`Encryption`\> + +The Encryption instance. + +*** + +### signAndEncrypt() + +```ts +signAndEncrypt(message: MessageDataType, publicKeys: string[]): Promise; +``` + +This function signs and encrypts a message using the private key used to initialize the client and the specified public keys. + +#### Example + +```ts +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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `message` | `MessageDataType` | Message to sign and encrypt. | +| `publicKeys` | `string`[] | Array of public keys to use for encryption. | + +#### Returns + +`Promise`\<`string`\> + +Message signed and encrypted. + +*** + +### decrypt() + +```ts +decrypt(message: string, publicKey?: string): Promise>; +``` + +This function decrypts messages using the private key. In addition, the public key can be added for signature verification. + +#### Throws + +Error If signature could not be verified when public key is provided + +#### Example + +```ts +const publicKey = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; + +const resultMessage = await encryption.decrypt('message', publicKey); +console.log('Decrypted message:', resultMessage); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `message` | `string` | Message to decrypt. | +| `publicKey?` | `string` | Public key used to verify signature if needed (optional). | + +#### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +Message decrypted. + +*** + +### sign() + +```ts +sign(message: string): Promise; +``` + +This function signs a message using the private key used to initialize the client. + +#### Example + +```ts +const resultMessage = await encryption.sign('message'); +console.log('Signed message:', resultMessage); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `message` | `string` | Message to sign. | + +#### Returns + +`Promise`\<`string`\> + +Message signed. diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/EncryptionUtils.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/EncryptionUtils.md new file mode 100644 index 0000000000..34b664cc04 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/EncryptionUtils.md @@ -0,0 +1,180 @@ +Utility class for encryption-related operations. + +## Example + +```ts +import { EncryptionUtils } from '@human-protocol/sdk'; + +const publicKey = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; +const isValid = await EncryptionUtils.verify('message', publicKey); +console.log('Signature valid:', isValid); +``` + +## Methods + +### verify() + +```ts +static verify(message: string, publicKey: string): Promise; +``` + +This function verifies the signature of a signed message using the public key. + +#### Example + +```ts +const publicKey = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; +const result = await EncryptionUtils.verify('message', publicKey); +console.log('Verification result:', result); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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. + +*** + +### getSignedData() + +```ts +static getSignedData(message: string): Promise; +``` + +This function gets signed data from a signed message. + +#### Throws + +Error If data could not be extracted from the message + +#### Example + +```ts +const signedData = await EncryptionUtils.getSignedData('message'); +console.log('Signed data:', signedData); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `message` | `string` | Message. | + +#### Returns + +`Promise`\<`string`\> + +Signed data. + +*** + +### generateKeyPair() + +```ts +static generateKeyPair( + name: string, + email: string, +passphrase: string): Promise; +``` + +This function generates a key pair for encryption and decryption. + +#### Example + +```ts +const name = 'YOUR_NAME'; +const email = 'YOUR_EMAIL'; +const passphrase = 'YOUR_PASSPHRASE'; +const keyPair = await EncryptionUtils.generateKeyPair(name, email, passphrase); +console.log('Public key:', keyPair.publicKey); +``` + +#### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `name` | `string` | `undefined` | Name for the key pair. | +| `email` | `string` | `undefined` | Email for the key pair. | +| `passphrase` | `string` | `''` | Passphrase to encrypt the private key (optional, defaults to empty string). | + +#### Returns + +`Promise`\<`IKeyPair`\> + +Key pair generated. + +*** + +### encrypt() + +```ts +static encrypt(message: MessageDataType, publicKeys: string[]): Promise; +``` + +This function encrypts a message using the specified public keys. + +#### Example + +```ts +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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `message` | `MessageDataType` | Message to encrypt. | +| `publicKeys` | `string`[] | Array of public keys to use for encryption. | + +#### Returns + +`Promise`\<`string`\> + +Message encrypted. + +*** + +### isEncrypted() + +```ts +static isEncrypted(message: string): boolean; +``` + +Verifies if a message appears to be encrypted with OpenPGP. + +#### Example + +```ts +const message = '-----BEGIN PGP MESSAGE-----...'; +const isEncrypted = EncryptionUtils.isEncrypted(message); + +if (isEncrypted) { + console.log('The message is encrypted with OpenPGP.'); +} else { + console.log('The message is not encrypted with OpenPGP.'); +} +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `message` | `string` | Message to verify. | + +#### Returns + +`boolean` + +`true` if the message appears to be encrypted, `false` if not. diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/EscrowClient.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/EscrowClient.md new file mode 100644 index 0000000000..bb4c04bcad --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/EscrowClient.md @@ -0,0 +1,1502 @@ +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`](/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. + +## Example + +###Using Signer + +####Using private key (backend) + +```ts +import { EscrowClient } 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 escrowClient = await EscrowClient.build(signer); +``` + +####Using Wagmi (frontend) + +```ts +import { useSigner } from 'wagmi'; +import { EscrowClient } from '@human-protocol/sdk'; + +const { data: signer } = useSigner(); +const escrowClient = await EscrowClient.build(signer); +``` + +###Using Provider + +```ts +import { EscrowClient } from '@human-protocol/sdk'; +import { JsonRpcProvider } from 'ethers'; + +const rpcUrl = 'YOUR_RPC_URL'; +const provider = new JsonRpcProvider(rpcUrl); +const escrowClient = await EscrowClient.build(provider); +``` + +## Extends + +- `BaseEthersClient` + +## Constructors + +### Constructor + +```ts +new EscrowClient(runner: ContractRunner, networkData: NetworkData): EscrowClient; +``` + +**EscrowClient constructor** + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | +| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the Escrow contract | + +#### Returns + +`EscrowClient` + +#### Overrides + +```ts +BaseEthersClient.constructor +``` + +## Methods + +### build() + +```ts +static build(runner: ContractRunner): Promise; +``` + +Creates an instance of EscrowClient from a Runner. + +#### Throws + +ErrorProviderDoesNotExist If the provider does not exist for the provided Signer + +#### Throws + +ErrorUnsupportedChainID If the network's chainId is not supported + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | + +#### Returns + +`Promise`\<`EscrowClient`\> + +An instance of EscrowClient + +*** + +### createEscrow() + +```ts +createEscrow( + tokenAddress: string, + jobRequesterId: string, +txOptions: Overrides): Promise; +``` + +This function creates an escrow contract that uses the token passed to pay oracle fees and reward workers. + +#### Throws + +ErrorInvalidTokenAddress If the token address is invalid + +#### Throws + +ErrorLaunchedEventIsNotEmitted If the LaunchedV2 event is not emitted + +#### Example + +> Need to have available stake. + +```ts +const tokenAddress = '0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4'; +const jobRequesterId = "job-requester-id"; +const escrowAddress = await escrowClient.createEscrow(tokenAddress, jobRequesterId); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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. + +*** + +### createFundAndSetupEscrow() + +```ts +createFundAndSetupEscrow( + tokenAddress: string, + amount: bigint, + jobRequesterId: string, + escrowConfig: IEscrowConfig, +txOptions: Overrides): Promise; +``` + +Creates, funds, and sets up a new escrow contract in a single transaction. + +#### 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 + +```ts +import { ethers } from 'ethers'; +import { ERC20__factory } from '@human-protocol/sdk'; + +const tokenAddress = '0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4'; +const amount = ethers.parseUnits('1000', 18); +const jobRequesterId = 'requester-123'; + +const token = ERC20__factory.connect(tokenAddress, signer); +await token.approve(escrowClient.escrowFactoryContract.target, amount); + +const escrowConfig = { + recordingOracle: '0xRecordingOracleAddress', + reputationOracle: '0xReputationOracleAddress', + exchangeOracle: '0xExchangeOracleAddress', + recordingOracleFee: 5n, + reputationOracleFee: 5n, + exchangeOracleFee: 5n, + manifest: 'https://example.com/manifest.json', + manifestHash: 'manifestHash-123', +}; + +const escrowAddress = await escrowClient.createFundAndSetupEscrow( + tokenAddress, + amount, + jobRequesterId, + escrowConfig +); +console.log('Escrow created at:', escrowAddress); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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` | Configuration parameters for escrow setup. | +| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + +#### Returns + +`Promise`\<`string`\> + +Returns the address of the escrow created. + +*** + +### setup() + +```ts +setup( + escrowAddress: string, + escrowConfig: IEscrowConfig, +txOptions: Overrides): Promise; +``` + +This function sets up the parameters of the escrow. + +#### 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 + +#### Example + +> Only Job Launcher or admin can call it. + +```ts +const escrowAddress = '0x62dD51230A30401C455c8398d06F85e4EaB6309f'; +const escrowConfig = { + recordingOracle: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', + reputationOracle: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', + exchangeOracle: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', + recordingOracleFee: 10n, + reputationOracleFee: 10n, + exchangeOracleFee: 10n, + manifest: 'http://localhost/manifest.json', + manifestHash: 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079', +}; +await escrowClient.setup(escrowAddress, escrowConfig); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow to set up. | +| `escrowConfig` | `IEscrowConfig` | Escrow configuration parameters. | +| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + +#### Returns + +`Promise`\<`void`\> + +*** + +### fund() + +```ts +fund( + escrowAddress: string, + amount: bigint, +txOptions: Overrides): Promise; +``` + +This function adds funds of the chosen token to the escrow. + +#### 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 } from 'ethers'; + +const amount = ethers.parseUnits('5', 'ether'); +await escrowClient.fund('0x62dD51230A30401C455c8398d06F85e4EaB6309f', amount); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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`\> + +*** + +### storeResults() + +#### Call Signature + +```ts +storeResults( + escrowAddress: string, + url: string, + hash: string, + fundsToReserve: bigint, +txOptions?: Overrides): Promise; +``` + +This function stores the results URL and hash. + +##### Throws + +ErrorInvalidEscrowAddressProvided If the escrow address is invalid + +##### Throws + +ErrorInvalidUrl If the URL is invalid + +##### Throws + +ErrorHashIsEmptyString If the hash is empty + +##### Throws + +ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + +##### Throws + +ErrorStoreResultsVersion If using deprecated signature + +##### Example + +> Only Recording Oracle or admin can call it. + +```ts +import { ethers } from 'ethers'; + +await escrowClient.storeResults( + '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + 'http://localhost/results.json', + 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079', + ethers.parseEther('10') +); +``` + +##### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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`\> + +#### Call Signature + +```ts +storeResults( + escrowAddress: string, + url: string, + hash: string, +txOptions?: Overrides): Promise; +``` + +This function stores the results URL and hash. + +##### Throws + +ErrorInvalidEscrowAddressProvided If the escrow address is invalid + +##### Throws + +ErrorInvalidUrl If the URL is invalid + +##### Throws + +ErrorHashIsEmptyString If the hash is empty + +##### Throws + +ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + +##### Throws + +ErrorStoreResultsVersion If using deprecated signature + +##### Example + +> Only Recording Oracle or admin can call it. + +```ts +await escrowClient.storeResults( + '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + 'http://localhost/results.json', + 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079' +); +``` + +##### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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`\> + +*** + +### complete() + +```ts +complete(escrowAddress: string, txOptions: Overrides): Promise; +``` + +This function sets the status of an escrow to completed. + +#### Throws + +ErrorInvalidEscrowAddressProvided If the escrow address is invalid + +#### Throws + +ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + +#### Example + +> Only Recording Oracle or admin can call it. + +```ts +await escrowClient.complete('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | +| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + +#### Returns + +`Promise`\<`void`\> + +*** + +### bulkPayOut() + +#### Call Signature + +```ts +bulkPayOut( + escrowAddress: string, + recipients: string[], + amounts: bigint[], + finalResultsUrl: string, + finalResultsHash: string, + txId: number, + forceComplete: boolean, +txOptions: Overrides): Promise; +``` + +This function pays out the amounts specified to the workers and sets the URL of the final results file. + +##### 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 + +##### Example + +> Only Reputation Oracle or admin can call it. + +```ts +import { ethers } from 'ethers'; + +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 +); +``` + +##### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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`\> + +#### Call Signature + +```ts +bulkPayOut( + escrowAddress: string, + recipients: string[], + amounts: bigint[], + finalResultsUrl: string, + finalResultsHash: string, + payoutId: string, + forceComplete: boolean, +txOptions: Overrides): Promise; +``` + +This function pays out the amounts specified to the workers and sets the URL of the final results file. + +##### 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 + +##### Example + +> Only Reputation Oracle or admin can call it. + +```ts +import { ethers } from 'ethers'; +import { v4 as uuidV4 } from 'uuid'; + +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 +); +``` + +##### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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`\> + +*** + +### cancel() + +```ts +cancel(escrowAddress: string, txOptions: Overrides): Promise; +``` + +This function cancels the specified escrow and sends the balance to the canceler. + +#### Throws + +ErrorInvalidEscrowAddressProvided If the escrow address is invalid + +#### Throws + +ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + +#### Example + +> Only Job Launcher or admin can call it. + +```ts +await escrowClient.cancel('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow to cancel. | +| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + +#### Returns + +`Promise`\<`void`\> + +*** + +### requestCancellation() + +```ts +requestCancellation(escrowAddress: string, txOptions: Overrides): Promise; +``` + +This function requests the cancellation of the specified escrow (moves status to ToCancel or finalizes if expired). + +#### Throws + +ErrorInvalidEscrowAddressProvided If the escrow address is invalid + +#### Throws + +ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + +#### Example + +> Only Job Launcher or admin can call it. + +```ts +await escrowClient.requestCancellation('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow to request cancellation. | +| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + +#### Returns + +`Promise`\<`void`\> + +*** + +### withdraw() + +```ts +withdraw( + escrowAddress: string, + tokenAddress: string, +txOptions: Overrides): Promise; +``` + +This function withdraws additional tokens in the escrow to the canceler. + +#### 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 + +#### Example + +> Only Job Launcher or admin can call it. + +```ts +const withdrawData = await escrowClient.withdraw( + '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + '0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4' +); +console.log('Withdrawn amount:', withdrawData.withdrawnAmount); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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`\> + +Returns the escrow withdrawal data including transaction hash and withdrawal amount. + +*** + +### createBulkPayoutTransaction() + +```ts +createBulkPayoutTransaction( + escrowAddress: string, + recipients: string[], + amounts: bigint[], + finalResultsUrl: string, + finalResultsHash: string, + payoutId: string, + forceComplete: boolean, +txOptions: Overrides): Promise; +``` + +Creates a prepared transaction for bulk payout without immediately sending it. + +#### 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 + +#### Example + +> Only Reputation Oracle or admin can call it. + +```ts +import { ethers } from 'ethers'; +import { v4 as uuidV4 } from 'uuid'; + +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(); + +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); +``` + +#### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `escrowAddress` | `string` | `undefined` | Escrow address to payout. | +| `recipients` | `string`[] | `undefined` | Array of recipient addresses. | +| `amounts` | `bigint`[] | `undefined` | Array of amounts the recipients will receive. | +| `finalResultsUrl` | `string` | `undefined` | Final results file URL. | +| `finalResultsHash` | `string` | `undefined` | Final results file hash. | +| `payoutId` | `string` | `undefined` | 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`\> + +Returns object with raw transaction and nonce + +*** + +### getBalance() + +```ts +getBalance(escrowAddress: string): Promise; +``` + +This function returns the balance for a specified escrow address. + +#### Throws + +ErrorInvalidEscrowAddressProvided If the escrow address is invalid + +#### Throws + +ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + +#### Example + +```ts +const balance = await escrowClient.getBalance('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Balance:', balance); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +`Promise`\<`bigint`\> + +Balance of the escrow in the token used to fund it. + +*** + +### getReservedFunds() + +```ts +getReservedFunds(escrowAddress: string): Promise; +``` + +This function returns the reserved funds for a specified escrow address. + +#### Throws + +ErrorInvalidEscrowAddressProvided If the escrow address is invalid + +#### Throws + +ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + +#### Example + +```ts +const reservedFunds = await escrowClient.getReservedFunds('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Reserved funds:', reservedFunds); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +`Promise`\<`bigint`\> + +Reserved funds of the escrow in the token used to fund it. + +*** + +### getManifestHash() + +```ts +getManifestHash(escrowAddress: string): Promise; +``` + +This function returns the manifest file hash. + +#### Throws + +ErrorInvalidEscrowAddressProvided If the escrow address is invalid + +#### Throws + +ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + +#### Example + +```ts +const manifestHash = await escrowClient.getManifestHash('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Manifest hash:', manifestHash); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +`Promise`\<`string`\> + +Hash of the manifest file content. + +*** + +### getManifest() + +```ts +getManifest(escrowAddress: string): Promise; +``` + +This function returns the manifest. Could be a URL or a JSON string. + +#### Throws + +ErrorInvalidEscrowAddressProvided If the escrow address is invalid + +#### Throws + +ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + +#### Example + +```ts +const manifest = await escrowClient.getManifest('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Manifest:', manifest); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +`Promise`\<`string`\> + +Manifest URL or JSON string. + +*** + +### getResultsUrl() + +```ts +getResultsUrl(escrowAddress: string): Promise; +``` + +This function returns the results file URL. + +#### Throws + +ErrorInvalidEscrowAddressProvided If the escrow address is invalid + +#### Throws + +ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + +#### Example + +```ts +const resultsUrl = await escrowClient.getResultsUrl('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Results URL:', resultsUrl); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +`Promise`\<`string`\> + +Results file URL. + +*** + +### getIntermediateResultsUrl() + +```ts +getIntermediateResultsUrl(escrowAddress: string): Promise; +``` + +This function returns the intermediate results file URL. + +#### Throws + +ErrorInvalidEscrowAddressProvided If the escrow address is invalid + +#### Throws + +ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + +#### Example + +```ts +const intermediateResultsUrl = await escrowClient.getIntermediateResultsUrl('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Intermediate results URL:', intermediateResultsUrl); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +`Promise`\<`string`\> + +URL of the file that stores results from Recording Oracle. + +*** + +### getIntermediateResultsHash() + +```ts +getIntermediateResultsHash(escrowAddress: string): Promise; +``` + +This function returns the intermediate results hash. + +#### Throws + +ErrorInvalidEscrowAddressProvided If the escrow address is invalid + +#### Throws + +ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + +#### Example + +```ts +const intermediateResultsHash = await escrowClient.getIntermediateResultsHash('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Intermediate results hash:', intermediateResultsHash); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +`Promise`\<`string`\> + +Hash of the intermediate results file content. + +*** + +### getTokenAddress() + +```ts +getTokenAddress(escrowAddress: string): Promise; +``` + +This function returns the token address used for funding the escrow. + +#### Throws + +ErrorInvalidEscrowAddressProvided If the escrow address is invalid + +#### Throws + +ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + +#### Example + +```ts +const tokenAddress = await escrowClient.getTokenAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Token address:', tokenAddress); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +`Promise`\<`string`\> + +Address of the token used to fund the escrow. + +*** + +### getStatus() + +```ts +getStatus(escrowAddress: string): Promise; +``` + +This function returns the 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 { EscrowStatus } from '@human-protocol/sdk'; + +const status = await escrowClient.getStatus('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Status:', EscrowStatus[status]); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +`Promise`\<[`EscrowStatus`](../enumerations/EscrowStatus.md)\> + +Current status of the escrow. + +*** + +### getRecordingOracleAddress() + +```ts +getRecordingOracleAddress(escrowAddress: string): Promise; +``` + +This function returns the recording oracle address for a given escrow. + +#### Throws + +ErrorInvalidEscrowAddressProvided If the escrow address is invalid + +#### Throws + +ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + +#### Example + +```ts +const oracleAddress = await escrowClient.getRecordingOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Recording Oracle address:', oracleAddress); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +`Promise`\<`string`\> + +Address of the Recording Oracle. + +*** + +### getJobLauncherAddress() + +```ts +getJobLauncherAddress(escrowAddress: string): Promise; +``` + +This function returns the job launcher address for a given escrow. + +#### Throws + +ErrorInvalidEscrowAddressProvided If the escrow address is invalid + +#### Throws + +ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + +#### Example + +```ts +const jobLauncherAddress = await escrowClient.getJobLauncherAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Job Launcher address:', jobLauncherAddress); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +`Promise`\<`string`\> + +Address of the Job Launcher. + +*** + +### getReputationOracleAddress() + +```ts +getReputationOracleAddress(escrowAddress: string): Promise; +``` + +This function returns the reputation oracle address for a given escrow. + +#### Throws + +ErrorInvalidEscrowAddressProvided If the escrow address is invalid + +#### Throws + +ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + +#### Example + +```ts +const oracleAddress = await escrowClient.getReputationOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Reputation Oracle address:', oracleAddress); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +`Promise`\<`string`\> + +Address of the Reputation Oracle. + +*** + +### getExchangeOracleAddress() + +```ts +getExchangeOracleAddress(escrowAddress: string): Promise; +``` + +This function returns the exchange oracle address for a given escrow. + +#### Throws + +ErrorInvalidEscrowAddressProvided If the escrow address is invalid + +#### Throws + +ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + +#### Example + +```ts +const oracleAddress = await escrowClient.getExchangeOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Exchange Oracle address:', oracleAddress); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +`Promise`\<`string`\> + +Address of the Exchange Oracle. + +*** + +### getFactoryAddress() + +```ts +getFactoryAddress(escrowAddress: string): Promise; +``` + +This function returns the escrow factory address for a given escrow. + +#### Throws + +ErrorInvalidEscrowAddressProvided If the escrow address is invalid + +#### Throws + +ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + +#### Example + +```ts +const factoryAddress = await escrowClient.getFactoryAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Factory address:', factoryAddress); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +`Promise`\<`string`\> + +Address of the escrow factory. diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/EscrowUtils.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/EscrowUtils.md new file mode 100644 index 0000000000..d76db1db5d --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/EscrowUtils.md @@ -0,0 +1,306 @@ +Utility class for escrow-related operations. + +## Example + +```ts +import { ChainId, EscrowUtils } from '@human-protocol/sdk'; + +const escrows = await EscrowUtils.getEscrows({ + chainId: ChainId.POLYGON_AMOY +}); +console.log('Escrows:', escrows); +``` + +## Methods + +### getEscrows() + +```ts +static getEscrows(filter: IEscrowsFilter, options?: SubgraphOptions): Promise; +``` + +This function returns an array of escrows based on the specified filter parameters. + +#### Throws + +ErrorInvalidAddress If any filter address is invalid + +#### Throws + +ErrorUnsupportedChainID If the chain ID is not supported + +#### Example + +```ts +import { ChainId, EscrowStatus } from '@human-protocol/sdk'; + +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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `filter` | `IEscrowsFilter` | Filter parameters. | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +`Promise`\<`IEscrow`[]\> + +List of escrows that match the filter. + +*** + +### getEscrow() + +```ts +static getEscrow( + chainId: ChainId, + escrowAddress: string, +options?: SubgraphOptions): Promise; +``` + +This function returns the escrow data for a given address. + +> This uses Subgraph + +#### Throws + +ErrorUnsupportedChainID If the chain ID is not supported + +#### Throws + +ErrorInvalidAddress If the escrow address is invalid + +#### Example + +```ts +import { ChainId } from '@human-protocol/sdk'; + +const escrow = await EscrowUtils.getEscrow( + ChainId.POLYGON_AMOY, + "0x1234567890123456789012345678901234567890" +); +if (escrow) { + console.log('Escrow status:', escrow.status); +} +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `chainId` | `ChainId` | Network in which the escrow has been deployed | +| `escrowAddress` | `string` | Address of the escrow | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +`Promise`\<`IEscrow` \| `null`\> + +Escrow data or null if not found. + +*** + +### getStatusEvents() + +```ts +static getStatusEvents(filter: IStatusEventFilter, options?: SubgraphOptions): Promise; +``` + +This function returns the status events for a given set of networks within an optional date range. + +> This uses Subgraph + +#### Throws + +ErrorInvalidAddress If the launcher address is invalid + +#### Throws + +ErrorUnsupportedChainID If the chain ID is not supported + +#### Example + +```ts +import { ChainId, EscrowStatus } from '@human-protocol/sdk'; + +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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `filter` | `IStatusEventFilter` | Filter parameters. | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +`Promise`\<`IStatusEvent`[]\> + +Array of status events with their corresponding statuses. + +*** + +### getPayouts() + +```ts +static getPayouts(filter: IPayoutFilter, options?: SubgraphOptions): Promise; +``` + +This function returns the payouts for a given set of networks. + +> This uses Subgraph + +#### Throws + +ErrorUnsupportedChainID If the chain ID is not supported + +#### Throws + +ErrorInvalidAddress If any filter address is invalid + +#### Example + +```ts +import { ChainId } 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:', payouts.length); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `filter` | `IPayoutFilter` | Filter parameters. | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +`Promise`\<`IPayout`[]\> + +List of payouts matching the filters. + +*** + +### getCancellationRefunds() + +```ts +static getCancellationRefunds(filter: ICancellationRefundFilter, options?: SubgraphOptions): Promise; +``` + +This function returns the cancellation refunds for a given set of networks. + +> This uses Subgraph + +#### 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 } from '@human-protocol/sdk'; + +const cancellationRefunds = await EscrowUtils.getCancellationRefunds({ + chainId: ChainId.POLYGON_AMOY, + escrowAddress: '0x1234567890123456789012345678901234567890', +}); +console.log('Cancellation refunds:', cancellationRefunds.length); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `filter` | `ICancellationRefundFilter` | Filter parameters. | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +`Promise`\<`ICancellationRefund`[]\> + +List of cancellation refunds matching the filters. + +*** + +### getCancellationRefund() + +```ts +static getCancellationRefund( + chainId: ChainId, + escrowAddress: string, +options?: SubgraphOptions): Promise; +``` + +This function returns the cancellation refund for a given escrow address. + +> This uses Subgraph + +#### Throws + +ErrorUnsupportedChainID If the chain ID is not supported + +#### Throws + +ErrorInvalidEscrowAddressProvided If the escrow address is invalid + +#### Example + +```ts +import { ChainId } from '@human-protocol/sdk'; + +const cancellationRefund = await EscrowUtils.getCancellationRefund( + ChainId.POLYGON_AMOY, + "0x1234567890123456789012345678901234567890" +); +if (cancellationRefund) { + console.log('Refund amount:', cancellationRefund.amount); +} +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `chainId` | `ChainId` | Network in which the escrow has been deployed | +| `escrowAddress` | `string` | Address of the escrow | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +`Promise`\<`ICancellationRefund` \| `null`\> + +Cancellation refund data or null if not found. diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/KVStoreClient.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/KVStoreClient.md new file mode 100644 index 0000000000..0bef6d686a --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/KVStoreClient.md @@ -0,0 +1,308 @@ +## 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, 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); +``` + +**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 { JsonRpcProvider } from 'ethers'; + +const rpcUrl = 'YOUR_RPC_URL'; + +const provider = new JsonRpcProvider(rpcUrl); +const kvstoreClient = await KVStoreClient.build(provider); +``` + +## Extends + +- `BaseEthersClient` + +## Constructors + +### Constructor + +```ts +new KVStoreClient(runner: ContractRunner, networkData: NetworkData): KVStoreClient; +``` + +**KVStoreClient constructor** + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | +| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the KVStore contract | + +#### Returns + +`KVStoreClient` + +#### Overrides + +```ts +BaseEthersClient.constructor +``` + +## Methods + +### build() + +```ts +static build(runner: ContractRunner): Promise; +``` + +Creates an instance of KVStoreClient from a runner. + +#### Throws + +ErrorProviderDoesNotExist If the provider does not exist for the provided Signer + +#### Throws + +ErrorUnsupportedChainID 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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | + +#### Returns + +`Promise`\<`KVStoreClient`\> + +An instance of KVStoreClient + +*** + +### set() + +```ts +set( + key: string, + value: string, +txOptions: Overrides): Promise; +``` + +This function sets a key-value pair associated with the address that submits the transaction. + +#### Throws + +ErrorKVStoreEmptyKey If the key is empty + +#### Throws + +Error If the transaction fails + +#### Example + +```ts +await kvstoreClient.set('Role', 'RecordingOracle'); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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`\> + +*** + +### setBulk() + +```ts +setBulk( + keys: string[], + values: string[], +txOptions: Overrides): Promise; +``` + +This function sets key-value pairs in bulk associated with the address that submits the transaction. + +#### 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 +const keys = ['role', 'webhook_url']; +const values = ['RecordingOracle', 'http://localhost']; +await kvstoreClient.setBulk(keys, values); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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`\> + +*** + +### setFileUrlAndHash() + +```ts +setFileUrlAndHash( + url: string, + urlKey: string, +txOptions: Overrides): Promise; +``` + +Sets a URL value for the address that submits the transaction, and its hash. + +#### Throws + +ErrorInvalidUrl If the URL is invalid + +#### Throws + +Error If the transaction fails + +#### Example + +```ts +await kvstoreClient.setFileUrlAndHash('example.com'); +await kvstoreClient.setFileUrlAndHash('linkedin.com/example', 'linkedin_url'); +``` + +#### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `url` | `string` | `undefined` | 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`\> + +*** + +### get() + +```ts +get(address: string, key: string): Promise; +``` + +Gets the value of a key-value pair in the contract. + +#### Throws + +ErrorKVStoreEmptyKey If the key is empty + +#### Throws + +ErrorInvalidAddress If the address is invalid + +#### Throws + +Error If the contract call fails + +#### Example + +```ts +const value = await kvstoreClient.get('0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', 'Role'); +console.log('Value:', value); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `address` | `string` | Address from which to get the key value. | +| `key` | `string` | Key to obtain the value. | + +#### Returns + +`Promise`\<`string`\> + +Value of the key. diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/KVStoreUtils.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/KVStoreUtils.md new file mode 100644 index 0000000000..de19745812 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/KVStoreUtils.md @@ -0,0 +1,214 @@ +Utility class for KVStore-related operations. + +## Example + +```ts +import { ChainId, KVStoreUtils } from '@human-protocol/sdk'; + +const kvStoreData = await KVStoreUtils.getKVStoreData( + ChainId.POLYGON_AMOY, + "0x1234567890123456789012345678901234567890" +); +console.log('KVStore data:', kvStoreData); +``` + +## Methods + +### getKVStoreData() + +```ts +static getKVStoreData( + chainId: ChainId, + address: string, +options?: SubgraphOptions): Promise; +``` + +This function returns the KVStore data for a given address. + +#### Throws + +ErrorUnsupportedChainID If the network's chainId is not supported + +#### Throws + +ErrorInvalidAddress If the address is invalid + +#### Example + +```ts +const kvStoreData = await KVStoreUtils.getKVStoreData( + ChainId.POLYGON_AMOY, + "0x1234567890123456789012345678901234567890" +); +console.log('KVStore data:', kvStoreData); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `chainId` | `ChainId` | Network in which the KVStore is deployed | +| `address` | `string` | Address of the KVStore | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +`Promise`\<`IKVStore`[]\> + +KVStore data + +*** + +### get() + +```ts +static get( + chainId: ChainId, + address: string, + key: string, +options?: SubgraphOptions): Promise; +``` + +Gets the value of a key-value pair in the KVStore using the subgraph. + +#### 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 +const value = await KVStoreUtils.get( + ChainId.POLYGON_AMOY, + '0x1234567890123456789012345678901234567890', + 'role' +); +console.log('Value:', value); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `chainId` | `ChainId` | 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/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +`Promise`\<`string`\> + +Value of the key. + +*** + +### getFileUrlAndVerifyHash() + +```ts +static getFileUrlAndVerifyHash( + chainId: ChainId, + address: string, + urlKey: string, +options?: SubgraphOptions): Promise; +``` + +Gets the URL value of the given entity, and verifies its hash. + +#### Throws + +ErrorInvalidAddress If the address is invalid + +#### Throws + +ErrorInvalidHash If the hash verification fails + +#### Throws + +Error If fetching URL or hash fails + +#### Example + +```ts +const url = await KVStoreUtils.getFileUrlAndVerifyHash( + ChainId.POLYGON_AMOY, + '0x1234567890123456789012345678901234567890' +); +console.log('Verified URL:', url); +``` + +#### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `chainId` | `ChainId` | `undefined` | Network in which the KVStore is deployed | +| `address` | `string` | `undefined` | Address from which to get the URL value. | +| `urlKey` | `string` | `'url'` | Configurable URL key. `url` by default. | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | `undefined` | Optional configuration for subgraph requests. | + +#### Returns + +`Promise`\<`string`\> + +URL value for the given address if it exists, and the content is valid + +*** + +### getPublicKey() + +```ts +static getPublicKey( + chainId: ChainId, + address: string, +options?: SubgraphOptions): Promise; +``` + +Gets the public key of the given entity, and verifies its hash. + +#### Throws + +ErrorInvalidAddress If the address is invalid + +#### Throws + +ErrorInvalidHash If the hash verification fails + +#### Throws + +Error If fetching the public key fails + +#### Example + +```ts +const publicKey = await KVStoreUtils.getPublicKey( + ChainId.POLYGON_AMOY, + '0x1234567890123456789012345678901234567890' +); +console.log('Public key:', publicKey); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `chainId` | `ChainId` | Network in which the KVStore is deployed | +| `address` | `string` | Address from which to get the public key. | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +`Promise`\<`string`\> + +Public key for the given address if it exists, and the content is valid diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/OperatorUtils.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/OperatorUtils.md new file mode 100644 index 0000000000..0c2c6bd89e --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/OperatorUtils.md @@ -0,0 +1,191 @@ +Utility class for operator-related operations. + +## Example + +```ts +import { OperatorUtils, ChainId } from '@human-protocol/sdk'; + +const operator = await OperatorUtils.getOperator( + ChainId.POLYGON_AMOY, + '0x62dD51230A30401C455c8398d06F85e4EaB6309f' +); +console.log('Operator:', operator); +``` + +## Methods + +### getOperator() + +```ts +static getOperator( + chainId: ChainId, + address: string, +options?: SubgraphOptions): Promise; +``` + +This function returns the operator data for the given address. + +#### 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' +); +console.log('Operator:', operator); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `chainId` | `ChainId` | Network in which the operator is deployed | +| `address` | `string` | Operator address. | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +`Promise`\<`IOperator` \| `null`\> + +Returns the operator details or null if not found. + +*** + +### getOperators() + +```ts +static getOperators(filter: IOperatorsFilter, options?: SubgraphOptions): Promise; +``` + +This function returns all the operator details of the protocol. + +#### Throws + +ErrorUnsupportedChainID If the chain ID is not supported + +#### Example + +```ts +import { ChainId } from '@human-protocol/sdk'; + +const filter = { + chainId: ChainId.POLYGON_AMOY +}; +const operators = await OperatorUtils.getOperators(filter); +console.log('Operators:', operators.length); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `filter` | `IOperatorsFilter` | Filter for the operators. | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +`Promise`\<`IOperator`[]\> + +Returns an array with all the operator details. + +*** + +### getReputationNetworkOperators() + +```ts +static getReputationNetworkOperators( + chainId: ChainId, + address: string, + role?: string, +options?: SubgraphOptions): Promise; +``` + +Retrieves the reputation network operators of the specified address. + +#### 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' +); +console.log('Operators:', operators.length); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `chainId` | `ChainId` | Network in which the reputation network is deployed | +| `address` | `string` | Address of the reputation oracle. | +| `role?` | `string` | Role of the operator (optional). | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +`Promise`\<`IOperator`[]\> + +Returns an array of operator details. + +*** + +### getRewards() + +```ts +static getRewards( + chainId: ChainId, + slasherAddress: string, +options?: SubgraphOptions): Promise; +``` + +This function returns information about the rewards for a given slasher address. + +#### 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' +); +console.log('Rewards:', rewards.length); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `chainId` | `ChainId` | Network in which the rewards are deployed | +| `slasherAddress` | `string` | Slasher address. | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +`Promise`\<`IReward`[]\> + +Returns an array of Reward objects that contain the rewards earned by the user through slashing other users. diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StakingClient.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StakingClient.md new file mode 100644 index 0000000000..8666045c7c --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StakingClient.md @@ -0,0 +1,389 @@ +## 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, 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); +``` + +**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 { JsonRpcProvider } from 'ethers'; + +const rpcUrl = 'YOUR_RPC_URL'; + +const provider = new JsonRpcProvider(rpcUrl); +const stakingClient = await StakingClient.build(provider); +``` + +## Extends + +- `BaseEthersClient` + +## Constructors + +### Constructor + +```ts +new StakingClient(runner: ContractRunner, networkData: NetworkData): StakingClient; +``` + +**StakingClient constructor** + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | +| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the Staking contract | + +#### Returns + +`StakingClient` + +#### Overrides + +```ts +BaseEthersClient.constructor +``` + +## Methods + +### build() + +```ts +static build(runner: ContractRunner): Promise; +``` + +Creates an instance of StakingClient from a Runner. + +#### Throws + +ErrorProviderDoesNotExist If the provider does not exist for the provided Signer + +#### Throws + +ErrorUnsupportedChainID 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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | + +#### Returns + +`Promise`\<`StakingClient`\> + +An instance of StakingClient + +*** + +### approveStake() + +```ts +approveStake(amount: bigint, txOptions: Overrides): Promise; +``` + +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. + +#### Throws + +ErrorInvalidStakingValueType If the amount is not a bigint + +#### Throws + +ErrorInvalidStakingValueSign If the amount is negative + +#### Example + +```ts +import { ethers } from 'ethers'; + +const amount = ethers.parseUnits('5', 'ether'); //convert from ETH to WEI +await stakingClient.approveStake(amount); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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`\> + +*** + +### stake() + +```ts +stake(amount: bigint, txOptions: Overrides): Promise; +``` + +This function stakes a specified amount of tokens on a specific network. + +> `approveStake` must be called before + +#### Throws + +ErrorInvalidStakingValueType If the amount is not a bigint + +#### Throws + +ErrorInvalidStakingValueSign If the amount is negative + +#### Example + +```ts +import { ethers } from 'ethers'; + +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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `amount` | `bigint` | Amount in WEI of tokens to stake. | +| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + +#### Returns + +`Promise`\<`void`\> + +*** + +### unstake() + +```ts +unstake(amount: bigint, txOptions: Overrides): Promise; +``` + +This function unstakes tokens from staking contract. The unstaked tokens stay locked for a period of time. + +> Must have tokens available to unstake + +#### Throws + +ErrorInvalidStakingValueType If the amount is not a bigint + +#### Throws + +ErrorInvalidStakingValueSign If the amount is negative + +#### Example + +```ts +import { ethers } from 'ethers'; + +const amount = ethers.parseUnits('5', 'ether'); //convert from ETH to WEI +await stakingClient.unstake(amount); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `amount` | `bigint` | Amount in WEI of tokens to unstake. | +| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + +#### Returns + +`Promise`\<`void`\> + +*** + +### withdraw() + +```ts +withdraw(txOptions: Overrides): Promise; +``` + +This function withdraws unstaked and non-locked tokens from staking contract to the user wallet. + +> Must have tokens available to withdraw + +#### Example + +```ts +await stakingClient.withdraw(); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + +#### Returns + +`Promise`\<`void`\> + +*** + +### slash() + +```ts +slash( + slasher: string, + staker: string, + escrowAddress: string, + amount: bigint, +txOptions: Overrides): Promise; +``` + +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. + +#### 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 } from 'ethers'; + +const amount = ethers.parseUnits('5', 'ether'); //convert from ETH to WEI +await stakingClient.slash( + '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', + '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', + '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + amount +); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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`\> + +*** + +### getStakerInfo() + +```ts +getStakerInfo(stakerAddress: string): Promise; +``` + +Retrieves comprehensive staking information for a staker. + +#### Throws + +ErrorInvalidStakerAddressProvided If the staker address is invalid + +#### Example + +```ts +const stakingInfo = await stakingClient.getStakerInfo('0xYourStakerAddress'); +console.log('Tokens staked:', stakingInfo.stakedAmount); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `stakerAddress` | `string` | The address of the staker. | + +#### Returns + +`Promise`\<`StakerInfo`\> + +Staking information for the staker diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StakingUtils.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StakingUtils.md new file mode 100644 index 0000000000..ada6158081 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StakingUtils.md @@ -0,0 +1,104 @@ +Utility class for Staking-related subgraph 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); +``` + +## Methods + +### getStaker() + +```ts +static getStaker( + chainId: ChainId, + stakerAddress: string, +options?: SubgraphOptions): Promise; +``` + +Gets staking info for a staker from the 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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `chainId` | `ChainId` | Network in which the staking contract is deployed | +| `stakerAddress` | `string` | Address of the staker | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +`Promise`\<`IStaker`\> + +Staker info from subgraph + +*** + +### getStakers() + +```ts +static getStakers(filter: IStakersFilter, options?: SubgraphOptions): Promise; +``` + +Gets all stakers from the subgraph with filters, pagination and ordering. + +#### 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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `filter` | `IStakersFilter` | Stakers filter with pagination and ordering | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +`Promise`\<`IStaker`[]\> + +Array of stakers diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StatisticsUtils.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StatisticsUtils.md new file mode 100644 index 0000000000..88eb7c843c --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StatisticsUtils.md @@ -0,0 +1,401 @@ +Utility class for statistics-related operations. + +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. + +## Installation + +### npm +```bash +npm install @human-protocol/sdk +``` + +### yarn +```bash +yarn install @human-protocol/sdk +``` + +## Example + +```ts +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); +``` + +## Methods + +### getEscrowStatistics() + +```ts +static getEscrowStatistics( + networkData: NetworkData, + filter: IStatisticsFilter, +options?: SubgraphOptions): Promise; +``` + +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[]; +}; +``` + +#### Example + +```ts +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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | +| `filter` | `IStatisticsFilter` | Statistics params with duration data | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +`Promise`\<`IEscrowStatistics`\> + +Escrow statistics data. + +*** + +### getWorkerStatistics() + +```ts +static getWorkerStatistics( + networkData: NetworkData, + filter: IStatisticsFilter, +options?: SubgraphOptions): Promise; +``` + +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[]; +}; +``` + +#### Example + +```ts +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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | +| `filter` | `IStatisticsFilter` | Statistics params with duration data | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +`Promise`\<`IWorkerStatistics`\> + +Worker statistics data. + +*** + +### getPaymentStatistics() + +```ts +static getPaymentStatistics( + networkData: NetworkData, + filter: IStatisticsFilter, +options?: SubgraphOptions): Promise; +``` + +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[]; +}; +``` + +#### Example + +```ts +import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; + +const networkData = NETWORKS[ChainId.POLYGON_AMOY]; +const paymentStats = await StatisticsUtils.getPaymentStatistics(networkData); +console.log( + 'Payment statistics:', + paymentStats.dailyPaymentsData.map((p) => ({ + ...p, + totalAmountPaid: p.totalAmountPaid.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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | +| `filter` | `IStatisticsFilter` | Statistics params with duration data | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +`Promise`\<`IPaymentStatistics`\> + +Payment statistics data. + +*** + +### getHMTStatistics() + +```ts +static getHMTStatistics(networkData: NetworkData, options?: SubgraphOptions): Promise; +``` + +This function returns the statistical data of HMToken. + +```ts +interface IHMTStatistics { + totalTransferAmount: bigint; + totalTransferCount: number; + totalHolders: number; +}; +``` + +#### Example + +```ts +import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; + +const networkData = NETWORKS[ChainId.POLYGON_AMOY]; +const hmtStats = await StatisticsUtils.getHMTStatistics(networkData); +console.log('HMT statistics:', { + ...hmtStats, + totalTransferAmount: hmtStats.totalTransferAmount.toString(), +}); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +`Promise`\<`IHMTStatistics`\> + +HMToken statistics data. + +*** + +### getHMTHolders() + +```ts +static getHMTHolders( + networkData: NetworkData, + params: IHMTHoldersParams, +options?: SubgraphOptions): Promise; +``` + +This function returns the holders of the HMToken with optional filters and ordering. + +#### Example + +```ts +import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; + +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(), +}))); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | +| `params` | `IHMTHoldersParams` | HMT Holders params with filters and ordering | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +`Promise`\<`IHMTHolder`[]\> + +List of HMToken holders. + +*** + +### getHMTDailyData() + +```ts +static getHMTDailyData( + networkData: NetworkData, + filter: IStatisticsFilter, +options?: SubgraphOptions): Promise; +``` + +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; +} +``` + +#### Example + +```ts +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 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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | +| `filter` | `IStatisticsFilter` | Statistics params with duration data | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +`Promise`\<`IDailyHMT`[]\> + +Daily HMToken statistics data. diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StorageClient.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StorageClient.md new file mode 100644 index 0000000000..9010fce608 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StorageClient.md @@ -0,0 +1,268 @@ +## 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 + +```ts +new StorageClient(params: StorageParams, credentials?: StorageCredentials): StorageClient; +``` + +**Storage client constructor** + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `params` | [`StorageParams`](../type-aliases/StorageParams.md) | Cloud storage params | +| `credentials?` | [`StorageCredentials`](../type-aliases/StorageCredentials.md) | Optional. Cloud storage access data. If credentials are not provided - use anonymous access to the bucket | + +#### Returns + +`StorageClient` + +## Methods + +### ~~downloadFiles()~~ + +```ts +downloadFiles(keys: string[], bucket: string): Promise; +``` + +This function downloads files from a bucket. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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'); +``` + +*** + +### ~~downloadFileFromUrl()~~ + +```ts +static downloadFileFromUrl(url: string): Promise; +``` + +This function downloads files from a URL. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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'); +``` + +*** + +### ~~uploadFiles()~~ + +```ts +uploadFiles(files: any[], bucket: string): Promise; +``` + +This function uploads files to a bucket. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `files` | `any`[] | Array of objects to upload serialized into JSON. | +| `bucket` | `string` | Bucket name. | + +#### Returns + +`Promise`\<[`UploadFile`](../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'); +``` + +*** + +### ~~bucketExists()~~ + +```ts +bucketExists(bucket: string): Promise; +``` + +This function checks if a bucket exists. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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'); +``` + +*** + +### ~~listObjects()~~ + +```ts +listObjects(bucket: string): Promise; +``` + +This function lists all file names contained in the bucket. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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'); +``` diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/TransactionUtils.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/TransactionUtils.md new file mode 100644 index 0000000000..6699536567 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/TransactionUtils.md @@ -0,0 +1,186 @@ +Utility class for transaction-related operations. + +## Example + +```ts +import { TransactionUtils, ChainId } from '@human-protocol/sdk'; + +const transaction = await TransactionUtils.getTransaction( + ChainId.POLYGON_AMOY, + '0x62dD51230A30401C455c8398d06F85e4EaB6309f' +); +console.log('Transaction:', transaction); +``` + +## Methods + +### getTransaction() + +```ts +static getTransaction( + chainId: ChainId, + hash: string, +options?: SubgraphOptions): Promise; +``` + +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; +}; +``` + +#### 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_AMOY, + '0x62dD51230A30401C455c8398d06F85e4EaB6309f' +); +console.log('Transaction:', transaction); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `chainId` | `ChainId` | The chain ID. | +| `hash` | `string` | The transaction hash. | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +`Promise`\<`ITransaction` \| `null`\> + +Returns the transaction details or null if not found. + +*** + +### getTransactions() + +```ts +static getTransactions(filter: ITransactionsFilter, options?: SubgraphOptions): Promise; +``` + +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[]; +}; +``` + +#### 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 = { + chainId: ChainId.POLYGON_AMOY, + 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); +console.log('Transactions:', transactions.length); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `filter` | `ITransactionsFilter` | Filter for the transactions. | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +`Promise`\<`ITransaction`[]\> + +Returns an array with all the transaction details. diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/enumerations/EscrowStatus.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/enumerations/EscrowStatus.md new file mode 100644 index 0000000000..0dfa358f82 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/[object Object]/enumerations/EscrowStatus.md @@ -0,0 +1,13 @@ +Enum for escrow statuses. + +## Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `Launched` | `0` | Escrow is launched. | +| `Pending` | `1` | Escrow is funded, and waiting for the results to be submitted. | +| `Partial` | `2` | Escrow is partially paid out. | +| `Paid` | `3` | Escrow is fully paid. | +| `Complete` | `4` | Escrow is finished. | +| `Cancelled` | `5` | Escrow is cancelled. | +| `ToCancel` | `6` | Escrow is cancelled. | diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/interfaces/SubgraphOptions.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/interfaces/SubgraphOptions.md new file mode 100644 index 0000000000..3674ec4564 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/[object Object]/interfaces/SubgraphOptions.md @@ -0,0 +1,9 @@ +Configuration options for subgraph requests with retry logic. + +## Properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `maxRetries?` | `number` | Maximum number of retry attempts | +| `baseDelay?` | `number` | Base delay between retries in milliseconds | +| `indexerId?` | `string` | Optional indexer identifier. When provided, requests target `{gateway}/deployments/id//indexers/id/`. | diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/NetworkData.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/NetworkData.md new file mode 100644 index 0000000000..194d6a4843 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/NetworkData.md @@ -0,0 +1,115 @@ +```ts +type NetworkData = object; +``` + +Network data + +## Properties + +### chainId + +```ts +chainId: number; +``` + +Network chain id + +*** + +### title + +```ts +title: string; +``` + +Network title + +*** + +### scanUrl + +```ts +scanUrl: string; +``` + +Network scanner URL + +*** + +### hmtAddress + +```ts +hmtAddress: string; +``` + +HMT Token contract address + +*** + +### factoryAddress + +```ts +factoryAddress: string; +``` + +Escrow Factory contract address + +*** + +### stakingAddress + +```ts +stakingAddress: string; +``` + +Staking contract address + +*** + +### kvstoreAddress + +```ts +kvstoreAddress: string; +``` + +KVStore contract address + +*** + +### subgraphUrl + +```ts +subgraphUrl: string; +``` + +Subgraph URL + +*** + +### subgraphUrlApiKey + +```ts +subgraphUrlApiKey: string; +``` + +Subgraph URL API key + +*** + +### oldSubgraphUrl + +```ts +oldSubgraphUrl: string; +``` + +Old subgraph URL + +*** + +### oldFactoryAddress + +```ts +oldFactoryAddress: string; +``` + +Old Escrow Factory contract address diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/StorageCredentials.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/StorageCredentials.md new file mode 100644 index 0000000000..8e09ad3813 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/StorageCredentials.md @@ -0,0 +1,29 @@ +```ts +readonly type StorageCredentials = object; +``` + +AWS/GCP cloud storage access data + +## Deprecated + +StorageClient is deprecated. Use Minio.Client directly. + +## Properties + +### ~~accessKey~~ + +```ts +accessKey: string; +``` + +Access Key + +*** + +### ~~secretKey~~ + +```ts +secretKey: string; +``` + +Secret Key diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/StorageParams.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/StorageParams.md new file mode 100644 index 0000000000..fa3da8ba8e --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/StorageParams.md @@ -0,0 +1,47 @@ +```ts +type StorageParams = object; +``` + +## Deprecated + +StorageClient is deprecated. Use Minio.Client directly. + +## Properties + +### ~~endPoint~~ + +```ts +endPoint: string; +``` + +Request endPoint + +*** + +### ~~useSSL~~ + +```ts +useSSL: boolean; +``` + +Enable secure (HTTPS) access. Default value set to false + +*** + +### ~~region?~~ + +```ts +optional region: string; +``` + +Region + +*** + +### ~~port?~~ + +```ts +optional port: number; +``` + +TCP/IP port number. Default value set to 80 for HTTP and 443 for HTTPs diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/UploadFile.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/UploadFile.md new file mode 100644 index 0000000000..349fbb64a9 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/UploadFile.md @@ -0,0 +1,35 @@ +```ts +readonly type UploadFile = object; +``` + +Upload file data + +## Properties + +### key + +```ts +key: string; +``` + +Uploaded object key + +*** + +### url + +```ts +url: string; +``` + +Uploaded object URL + +*** + +### hash + +```ts +hash: string; +``` + +Hash of uploaded object key diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/README.md b/packages/sdk/typescript/human-protocol-sdk/docs/README.md new file mode 100644 index 0000000000..90a6f9d669 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/docs/README.md @@ -0,0 +1,29 @@ +## Enumerations + +- [EscrowStatus](enumerations/EscrowStatus.md) + +## Classes + +- [Encryption](classes/Encryption.md) +- [EncryptionUtils](classes/EncryptionUtils.md) +- [EscrowClient](classes/EscrowClient.md) +- [EscrowUtils](classes/EscrowUtils.md) +- [KVStoreClient](classes/KVStoreClient.md) +- [KVStoreUtils](classes/KVStoreUtils.md) +- [OperatorUtils](classes/OperatorUtils.md) +- [StakingClient](classes/StakingClient.md) +- [StakingUtils](classes/StakingUtils.md) +- [StatisticsUtils](classes/StatisticsUtils.md) +- [~~StorageClient~~](classes/StorageClient.md) +- [TransactionUtils](classes/TransactionUtils.md) + +## Interfaces + +- [SubgraphOptions](interfaces/SubgraphOptions.md) + +## Type Aliases + +- [~~StorageCredentials~~](type-aliases/StorageCredentials.md) +- [~~StorageParams~~](type-aliases/StorageParams.md) +- [UploadFile](type-aliases/UploadFile.md) +- [NetworkData](type-aliases/NetworkData.md) diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/Encryption.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/Encryption.md new file mode 100644 index 0000000000..5695eecb6f --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/Encryption.md @@ -0,0 +1,161 @@ +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`](/ts/classes/Encryption/#build) method. + +## Constructors + +### Constructor + +```ts +new Encryption(privateKey: PrivateKey): Encryption; +``` + +Constructor for the Encryption class. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `privateKey` | `PrivateKey` | The private key. | + +#### Returns + +| Type | Description | +|------|-------------| +| `Encryption` | - | + +## Methods + +### build() + +```ts +static build(privateKeyArmored: string, passphrase?: string): Promise; +``` + +Builds an Encryption instance by decrypting the private key from an encrypted private key and passphrase. + +#### Example + +```ts +import { Encryption } from '@human-protocol/sdk'; + +const privateKey = 'Armored_priv_key'; +const passphrase = 'example_passphrase'; +const encryption = await Encryption.build(privateKey, passphrase); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `privateKeyArmored` | `string` | The encrypted private key in armored format. | +| `passphrase?` | `string` | The passphrase for the private key (optional). | + +#### Returns + +| Type | Description | +|------|-------------| +| `Encryption` | The Encryption instance. | + +*** + +### signAndEncrypt() + +```ts +signAndEncrypt(message: MessageDataType, publicKeys: string[]): Promise; +``` + +This function signs and encrypts a message using the private key used to initialize the client and the specified public keys. + +#### Example + +```ts +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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `message` | `MessageDataType` | Message to sign and encrypt. | +| `publicKeys` | `string`[] | Array of public keys to use for encryption. | + +#### Returns + +| Type | Description | +|------|-------------| +| `string` | Message signed and encrypted. | + +*** + +### decrypt() + +```ts +decrypt(message: string, publicKey?: string): Promise>; +``` + +This function decrypts messages using the private key. In addition, the public key can be added for signature verification. + +#### Throws + +| Type | Description | +|------|-------------| +| `Error` | If signature could not be verified when public key is provided | + +#### Example + +```ts +const publicKey = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; + +const resultMessage = await encryption.decrypt('message', publicKey); +console.log('Decrypted message:', resultMessage); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `message` | `string` | Message to decrypt. | +| `publicKey?` | `string` | Public key used to verify signature if needed (optional). | + +#### Returns + +| Type | Description | +|------|-------------| +| `Promise>` | Message decrypted. | + +*** + +### sign() + +```ts +sign(message: string): Promise; +``` + +This function signs a message using the private key used to initialize the client. + +#### Example + +```ts +const resultMessage = await encryption.sign('message'); +console.log('Signed message:', resultMessage); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `message` | `string` | Message to sign. | + +#### Returns + +| Type | Description | +|------|-------------| +| `string` | Message signed. | diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/EncryptionUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/EncryptionUtils.md new file mode 100644 index 0000000000..e9cae435f0 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/EncryptionUtils.md @@ -0,0 +1,182 @@ +Utility class for encryption-related operations. + +## Example + +```ts +import { EncryptionUtils } from '@human-protocol/sdk'; + +const publicKey = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; +const isValid = await EncryptionUtils.verify('message', publicKey); +console.log('Signature valid:', isValid); +``` + +## Methods + +### verify() + +```ts +static verify(message: string, publicKey: string): Promise; +``` + +This function verifies the signature of a signed message using the public key. + +#### Example + +```ts +const publicKey = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; +const result = await EncryptionUtils.verify('message', publicKey); +console.log('Verification result:', result); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `message` | `string` | Message to verify. | +| `publicKey` | `string` | Public key to verify that the message was signed by a specific source. | + +#### Returns + +| Type | Description | +|------|-------------| +| `boolean` | True if verified. False if not verified. | + +*** + +### getSignedData() + +```ts +static getSignedData(message: string): Promise; +``` + +This function gets signed data from a signed message. + +#### Throws + +| Type | Description | +|------|-------------| +| `Error` | If data could not be extracted from the message | + +#### Example + +```ts +const signedData = await EncryptionUtils.getSignedData('message'); +console.log('Signed data:', signedData); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `message` | `string` | Message. | + +#### Returns + +| Type | Description | +|------|-------------| +| `string` | Signed data. | + +*** + +### generateKeyPair() + +```ts +static generateKeyPair( + name: string, + email: string, +passphrase: string): Promise; +``` + +This function generates a key pair for encryption and decryption. + +#### Example + +```ts +const name = 'YOUR_NAME'; +const email = 'YOUR_EMAIL'; +const passphrase = 'YOUR_PASSPHRASE'; +const keyPair = await EncryptionUtils.generateKeyPair(name, email, passphrase); +console.log('Public key:', keyPair.publicKey); +``` + +#### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `name` | `string` | `undefined` | Name for the key pair. | +| `email` | `string` | `undefined` | Email for the key pair. | +| `passphrase` | `string` | `''` | Passphrase to encrypt the private key (optional, defaults to empty string). | + +#### Returns + +| Type | Description | +|------|-------------| +| `IKeyPair` | Key pair generated. | + +*** + +### encrypt() + +```ts +static encrypt(message: MessageDataType, publicKeys: string[]): Promise; +``` + +This function encrypts a message using the specified public keys. + +#### Example + +```ts +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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `message` | `MessageDataType` | Message to encrypt. | +| `publicKeys` | `string`[] | Array of public keys to use for encryption. | + +#### Returns + +| Type | Description | +|------|-------------| +| `string` | Message encrypted. | + +*** + +### isEncrypted() + +```ts +static isEncrypted(message: string): boolean; +``` + +Verifies if a message appears to be encrypted with OpenPGP. + +#### Example + +```ts +const message = '-----BEGIN PGP MESSAGE-----...'; +const isEncrypted = EncryptionUtils.isEncrypted(message); + +if (isEncrypted) { + console.log('The message is encrypted with OpenPGP.'); +} else { + console.log('The message is not encrypted with OpenPGP.'); +} +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `message` | `string` | Message to verify. | + +#### Returns + +| Type | Description | +|------|-------------| +| `boolean` | `true` if the message appears to be encrypted, `false` if not. | diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowClient.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowClient.md new file mode 100644 index 0000000000..61d1300ec9 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowClient.md @@ -0,0 +1,1403 @@ +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`](/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. + +## Example + +###Using Signer + +####Using private key (backend) + +```ts +import { EscrowClient } 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 escrowClient = await EscrowClient.build(signer); +``` + +####Using Wagmi (frontend) + +```ts +import { useSigner } from 'wagmi'; +import { EscrowClient } from '@human-protocol/sdk'; + +const { data: signer } = useSigner(); +const escrowClient = await EscrowClient.build(signer); +``` + +###Using Provider + +```ts +import { EscrowClient } from '@human-protocol/sdk'; +import { JsonRpcProvider } from 'ethers'; + +const rpcUrl = 'YOUR_RPC_URL'; +const provider = new JsonRpcProvider(rpcUrl); +const escrowClient = await EscrowClient.build(provider); +``` + +## Extends + +- `BaseEthersClient` + +## Constructors + +### Constructor + +```ts +new EscrowClient(runner: ContractRunner, networkData: NetworkData): EscrowClient; +``` + +**EscrowClient constructor** + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | +| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the Escrow contract | + +#### Returns + +| Type | Description | +|------|-------------| +| `EscrowClient` | #### Overrides | + +```ts +BaseEthersClient.constructor +``` + +## Methods + +### build() + +```ts +static build(runner: ContractRunner): Promise; +``` + +Creates an instance of EscrowClient from a Runner. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorProviderDoesNotExist` | If the provider does not exist for the provided Signer | +| `ErrorUnsupportedChainID` | If the network's chainId is not supported | + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | + +#### Returns + +| Type | Description | +|------|-------------| +| `EscrowClient` | An instance of EscrowClient | + +*** + +### createEscrow() + +```ts +createEscrow( + tokenAddress: string, + jobRequesterId: string, +txOptions: Overrides): Promise; +``` + +This function creates an escrow contract that uses the token passed to pay oracle fees and reward workers. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidTokenAddress` | If the token address is invalid | +| `ErrorLaunchedEventIsNotEmitted` | If the LaunchedV2 event is not emitted | + +#### Example + +> Need to have available stake. + +```ts +const tokenAddress = '0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4'; +const jobRequesterId = "job-requester-id"; +const escrowAddress = await escrowClient.createEscrow(tokenAddress, jobRequesterId); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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 + +| Type | Description | +|------|-------------| +| `string` | Returns the address of the escrow created. | + +*** + +### createFundAndSetupEscrow() + +```ts +createFundAndSetupEscrow( + tokenAddress: string, + amount: bigint, + jobRequesterId: string, + escrowConfig: IEscrowConfig, +txOptions: Overrides): Promise; +``` + +Creates, funds, and sets up a new escrow contract in a single transaction. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidTokenAddress` | If the token address is invalid | +| `ErrorInvalidRecordingOracleAddressProvided` | If the recording oracle address is invalid | +| `ErrorInvalidReputationOracleAddressProvided` | If the reputation oracle address is invalid | +| `ErrorInvalidExchangeOracleAddressProvided` | If the exchange oracle address is invalid | +| `ErrorAmountMustBeGreaterThanZero` | If any oracle fee is less than or equal to zero | +| `ErrorTotalFeeMustBeLessThanHundred` | If the total oracle fees exceed 100 | +| `ErrorInvalidManifest` | If the manifest is not a valid URL or JSON string | +| `ErrorHashIsEmptyString` | If the manifest hash is empty | +| `ErrorLaunchedEventIsNotEmitted` | If the LaunchedV2 event is not emitted | + +#### Example + +```ts +import { ethers } from 'ethers'; +import { ERC20__factory } from '@human-protocol/sdk'; + +const tokenAddress = '0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4'; +const amount = ethers.parseUnits('1000', 18); +const jobRequesterId = 'requester-123'; + +const token = ERC20__factory.connect(tokenAddress, signer); +await token.approve(escrowClient.escrowFactoryContract.target, amount); + +const escrowConfig = { + recordingOracle: '0xRecordingOracleAddress', + reputationOracle: '0xReputationOracleAddress', + exchangeOracle: '0xExchangeOracleAddress', + recordingOracleFee: 5n, + reputationOracleFee: 5n, + exchangeOracleFee: 5n, + manifest: 'https://example.com/manifest.json', + manifestHash: 'manifestHash-123', +}; + +const escrowAddress = await escrowClient.createFundAndSetupEscrow( + tokenAddress, + amount, + jobRequesterId, + escrowConfig +); +console.log('Escrow created at:', escrowAddress); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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` | Configuration parameters for escrow setup. | +| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + +#### Returns + +| Type | Description | +|------|-------------| +| `string` | Returns the address of the escrow created. | + +*** + +### setup() + +```ts +setup( + escrowAddress: string, + escrowConfig: IEscrowConfig, +txOptions: Overrides): Promise; +``` + +This function sets up the parameters of the escrow. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidRecordingOracleAddressProvided` | If the recording oracle address is invalid | +| `ErrorInvalidReputationOracleAddressProvided` | If the reputation oracle address is invalid | +| `ErrorInvalidExchangeOracleAddressProvided` | If the exchange oracle address is invalid | +| `ErrorAmountMustBeGreaterThanZero` | If any oracle fee is less than or equal to zero | +| `ErrorTotalFeeMustBeLessThanHundred` | If the total oracle fees exceed 100 | +| `ErrorInvalidManifest` | If the manifest is not a valid URL or JSON string | +| `ErrorHashIsEmptyString` | If the manifest hash is empty | +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | + +#### Example + +> Only Job Launcher or admin can call it. + +```ts +const escrowAddress = '0x62dD51230A30401C455c8398d06F85e4EaB6309f'; +const escrowConfig = { + recordingOracle: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', + reputationOracle: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', + exchangeOracle: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', + recordingOracleFee: 10n, + reputationOracleFee: 10n, + exchangeOracleFee: 10n, + manifest: 'http://localhost/manifest.json', + manifestHash: 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079', +}; +await escrowClient.setup(escrowAddress, escrowConfig); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow to set up. | +| `escrowConfig` | `IEscrowConfig` | Escrow configuration parameters. | +| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + +#### Returns + +| Type | Description | +|------|-------------| +| `void` | *** | + +### fund() + +```ts +fund( + escrowAddress: string, + amount: bigint, +txOptions: Overrides): Promise; +``` + +This function adds funds of the chosen token to the escrow. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorAmountMustBeGreaterThanZero` | If the amount is less than or equal to zero | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | + +#### Example + +```ts +import { ethers } from 'ethers'; + +const amount = ethers.parseUnits('5', 'ether'); +await escrowClient.fund('0x62dD51230A30401C455c8398d06F85e4EaB6309f', amount); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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 + +| Type | Description | +|------|-------------| +| `void` | *** | + +### storeResults() + +#### Call Signature + +```ts +storeResults( + escrowAddress: string, + url: string, + hash: string, + fundsToReserve: bigint, +txOptions?: Overrides): Promise; +``` + +This function stores the results URL and hash. + +##### Throws + +ErrorInvalidEscrowAddressProvided If the escrow address is invalid + +##### Throws + +ErrorInvalidUrl If the URL is invalid + +##### Throws + +ErrorHashIsEmptyString If the hash is empty + +##### Throws + +ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + +##### Throws + +ErrorStoreResultsVersion If using deprecated signature + +##### Example + +> Only Recording Oracle or admin can call it. + +```ts +import { ethers } from 'ethers'; + +await escrowClient.storeResults( + '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + 'http://localhost/results.json', + 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079', + ethers.parseEther('10') +); +``` + +##### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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`\> + +#### Call Signature + +```ts +storeResults( + escrowAddress: string, + url: string, + hash: string, +txOptions?: Overrides): Promise; +``` + +This function stores the results URL and hash. + +##### Throws + +ErrorInvalidEscrowAddressProvided If the escrow address is invalid + +##### Throws + +ErrorInvalidUrl If the URL is invalid + +##### Throws + +ErrorHashIsEmptyString If the hash is empty + +##### Throws + +ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + +##### Throws + +ErrorStoreResultsVersion If using deprecated signature + +##### Example + +> Only Recording Oracle or admin can call it. + +```ts +await escrowClient.storeResults( + '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + 'http://localhost/results.json', + 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079' +); +``` + +##### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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`\> + +*** + +### complete() + +```ts +complete(escrowAddress: string, txOptions: Overrides): Promise; +``` + +This function sets the status of an escrow to completed. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | + +#### Example + +> Only Recording Oracle or admin can call it. + +```ts +await escrowClient.complete('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | +| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + +#### Returns + +| Type | Description | +|------|-------------| +| `void` | *** | + +### bulkPayOut() + +#### Call Signature + +```ts +bulkPayOut( + escrowAddress: string, + recipients: string[], + amounts: bigint[], + finalResultsUrl: string, + finalResultsHash: string, + txId: number, + forceComplete: boolean, +txOptions: Overrides): Promise; +``` + +This function pays out the amounts specified to the workers and sets the URL of the final results file. + +##### 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 + +##### Example + +> Only Reputation Oracle or admin can call it. + +```ts +import { ethers } from 'ethers'; + +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 +); +``` + +##### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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`\> + +#### Call Signature + +```ts +bulkPayOut( + escrowAddress: string, + recipients: string[], + amounts: bigint[], + finalResultsUrl: string, + finalResultsHash: string, + payoutId: string, + forceComplete: boolean, +txOptions: Overrides): Promise; +``` + +This function pays out the amounts specified to the workers and sets the URL of the final results file. + +##### 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 + +##### Example + +> Only Reputation Oracle or admin can call it. + +```ts +import { ethers } from 'ethers'; +import { v4 as uuidV4 } from 'uuid'; + +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 +); +``` + +##### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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`\> + +*** + +### cancel() + +```ts +cancel(escrowAddress: string, txOptions: Overrides): Promise; +``` + +This function cancels the specified escrow and sends the balance to the canceler. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | + +#### Example + +> Only Job Launcher or admin can call it. + +```ts +await escrowClient.cancel('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow to cancel. | +| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + +#### Returns + +| Type | Description | +|------|-------------| +| `void` | *** | + +### requestCancellation() + +```ts +requestCancellation(escrowAddress: string, txOptions: Overrides): Promise; +``` + +This function requests the cancellation of the specified escrow (moves status to ToCancel or finalizes if expired). + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | + +#### Example + +> Only Job Launcher or admin can call it. + +```ts +await escrowClient.requestCancellation('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow to request cancellation. | +| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + +#### Returns + +| Type | Description | +|------|-------------| +| `void` | *** | + +### withdraw() + +```ts +withdraw( + escrowAddress: string, + tokenAddress: string, +txOptions: Overrides): Promise; +``` + +This function withdraws additional tokens in the escrow to the canceler. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorInvalidTokenAddress` | If the token address is invalid | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | +| `ErrorTransferEventNotFoundInTransactionLogs` | If the Transfer event is not found in transaction logs | + +#### Example + +> Only Job Launcher or admin can call it. + +```ts +const withdrawData = await escrowClient.withdraw( + '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + '0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4' +); +console.log('Withdrawn amount:', withdrawData.withdrawnAmount); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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 + +| Type | Description | +|------|-------------| +| `IEscrowWithdraw` | Returns the escrow withdrawal data including transaction hash and withdrawal amount. | + +*** + +### createBulkPayoutTransaction() + +```ts +createBulkPayoutTransaction( + escrowAddress: string, + recipients: string[], + amounts: bigint[], + finalResultsUrl: string, + finalResultsHash: string, + payoutId: string, + forceComplete: boolean, +txOptions: Overrides): Promise; +``` + +Creates a prepared transaction for bulk payout without immediately sending it. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorRecipientCannotBeEmptyArray` | If the recipients array is empty | +| `ErrorTooManyRecipients` | If there are too many recipients | +| `ErrorAmountsCannotBeEmptyArray` | If the amounts array is empty | +| `ErrorRecipientAndAmountsMustBeSameLength` | If recipients and amounts arrays have different lengths | +| `InvalidEthereumAddressError` | If any recipient address is invalid | +| `ErrorInvalidUrl` | If the final results URL is invalid | +| `ErrorHashIsEmptyString` | If the final results hash is empty | +| `ErrorEscrowDoesNotHaveEnoughBalance` | If the escrow doesn't have enough balance | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | + +#### Example + +> Only Reputation Oracle or admin can call it. + +```ts +import { ethers } from 'ethers'; +import { v4 as uuidV4 } from 'uuid'; + +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(); + +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); +``` + +#### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `escrowAddress` | `string` | `undefined` | Escrow address to payout. | +| `recipients` | `string`[] | `undefined` | Array of recipient addresses. | +| `amounts` | `bigint`[] | `undefined` | Array of amounts the recipients will receive. | +| `finalResultsUrl` | `string` | `undefined` | Final results file URL. | +| `finalResultsHash` | `string` | `undefined` | Final results file hash. | +| `payoutId` | `string` | `undefined` | 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 + +| Type | Description | +|------|-------------| +| `TransactionLikeWithNonce` | Returns object with raw transaction and nonce | + +*** + +### getBalance() + +```ts +getBalance(escrowAddress: string): Promise; +``` + +This function returns the balance for a specified escrow address. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | + +#### Example + +```ts +const balance = await escrowClient.getBalance('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Balance:', balance); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +| Type | Description | +|------|-------------| +| `bigint` | Balance of the escrow in the token used to fund it. | + +*** + +### getReservedFunds() + +```ts +getReservedFunds(escrowAddress: string): Promise; +``` + +This function returns the reserved funds for a specified escrow address. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | + +#### Example + +```ts +const reservedFunds = await escrowClient.getReservedFunds('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Reserved funds:', reservedFunds); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +| Type | Description | +|------|-------------| +| `bigint` | Reserved funds of the escrow in the token used to fund it. | + +*** + +### getManifestHash() + +```ts +getManifestHash(escrowAddress: string): Promise; +``` + +This function returns the manifest file hash. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | + +#### Example + +```ts +const manifestHash = await escrowClient.getManifestHash('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Manifest hash:', manifestHash); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +| Type | Description | +|------|-------------| +| `string` | Hash of the manifest file content. | + +*** + +### getManifest() + +```ts +getManifest(escrowAddress: string): Promise; +``` + +This function returns the manifest. Could be a URL or a JSON string. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | + +#### Example + +```ts +const manifest = await escrowClient.getManifest('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Manifest:', manifest); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +| Type | Description | +|------|-------------| +| `string` | Manifest URL or JSON string. | + +*** + +### getResultsUrl() + +```ts +getResultsUrl(escrowAddress: string): Promise; +``` + +This function returns the results file URL. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | + +#### Example + +```ts +const resultsUrl = await escrowClient.getResultsUrl('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Results URL:', resultsUrl); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +| Type | Description | +|------|-------------| +| `string` | Results file URL. | + +*** + +### getIntermediateResultsUrl() + +```ts +getIntermediateResultsUrl(escrowAddress: string): Promise; +``` + +This function returns the intermediate results file URL. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | + +#### Example + +```ts +const intermediateResultsUrl = await escrowClient.getIntermediateResultsUrl('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Intermediate results URL:', intermediateResultsUrl); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +| Type | Description | +|------|-------------| +| `string` | URL of the file that stores results from Recording Oracle. | + +*** + +### getIntermediateResultsHash() + +```ts +getIntermediateResultsHash(escrowAddress: string): Promise; +``` + +This function returns the intermediate results hash. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | + +#### Example + +```ts +const intermediateResultsHash = await escrowClient.getIntermediateResultsHash('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Intermediate results hash:', intermediateResultsHash); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +| Type | Description | +|------|-------------| +| `string` | Hash of the intermediate results file content. | + +*** + +### getTokenAddress() + +```ts +getTokenAddress(escrowAddress: string): Promise; +``` + +This function returns the token address used for funding the escrow. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | + +#### Example + +```ts +const tokenAddress = await escrowClient.getTokenAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Token address:', tokenAddress); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +| Type | Description | +|------|-------------| +| `string` | Address of the token used to fund the escrow. | + +*** + +### getStatus() + +```ts +getStatus(escrowAddress: string): Promise; +``` + +This function returns the current status of the escrow. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | + +#### Example + +```ts +import { EscrowStatus } from '@human-protocol/sdk'; + +const status = await escrowClient.getStatus('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Status:', EscrowStatus[status]); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +| Type | Description | +|------|-------------| +| `[EscrowStatus](../enumerations/EscrowStatus.md)` | Current status of the escrow. | + +*** + +### getRecordingOracleAddress() + +```ts +getRecordingOracleAddress(escrowAddress: string): Promise; +``` + +This function returns the recording oracle address for a given escrow. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | + +#### Example + +```ts +const oracleAddress = await escrowClient.getRecordingOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Recording Oracle address:', oracleAddress); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +| Type | Description | +|------|-------------| +| `string` | Address of the Recording Oracle. | + +*** + +### getJobLauncherAddress() + +```ts +getJobLauncherAddress(escrowAddress: string): Promise; +``` + +This function returns the job launcher address for a given escrow. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | + +#### Example + +```ts +const jobLauncherAddress = await escrowClient.getJobLauncherAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Job Launcher address:', jobLauncherAddress); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +| Type | Description | +|------|-------------| +| `string` | Address of the Job Launcher. | + +*** + +### getReputationOracleAddress() + +```ts +getReputationOracleAddress(escrowAddress: string): Promise; +``` + +This function returns the reputation oracle address for a given escrow. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | + +#### Example + +```ts +const oracleAddress = await escrowClient.getReputationOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Reputation Oracle address:', oracleAddress); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +| Type | Description | +|------|-------------| +| `string` | Address of the Reputation Oracle. | + +*** + +### getExchangeOracleAddress() + +```ts +getExchangeOracleAddress(escrowAddress: string): Promise; +``` + +This function returns the exchange oracle address for a given escrow. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | + +#### Example + +```ts +const oracleAddress = await escrowClient.getExchangeOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Exchange Oracle address:', oracleAddress); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +| Type | Description | +|------|-------------| +| `string` | Address of the Exchange Oracle. | + +*** + +### getFactoryAddress() + +```ts +getFactoryAddress(escrowAddress: string): Promise; +``` + +This function returns the escrow factory address for a given escrow. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | + +#### Example + +```ts +const factoryAddress = await escrowClient.getFactoryAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); +console.log('Factory address:', factoryAddress); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | + +#### Returns + +| Type | Description | +|------|-------------| +| `string` | Address of the escrow factory. | diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowUtils.md new file mode 100644 index 0000000000..9a26c03e8d --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowUtils.md @@ -0,0 +1,297 @@ +Utility class for escrow-related operations. + +## Example + +```ts +import { ChainId, EscrowUtils } from '@human-protocol/sdk'; + +const escrows = await EscrowUtils.getEscrows({ + chainId: ChainId.POLYGON_AMOY +}); +console.log('Escrows:', escrows); +``` + +## Methods + +### getEscrows() + +```ts +static getEscrows(filter: IEscrowsFilter, options?: SubgraphOptions): Promise; +``` + +This function returns an array of escrows based on the specified filter parameters. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidAddress` | If any filter address is invalid | +| `ErrorUnsupportedChainID` | If the chain ID is not supported | + +#### Example + +```ts +import { ChainId, EscrowStatus } from '@human-protocol/sdk'; + +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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `filter` | `IEscrowsFilter` | Filter parameters. | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `IEscrow[]` | List of escrows that match the filter. | + +*** + +### getEscrow() + +```ts +static getEscrow( + chainId: ChainId, + escrowAddress: string, +options?: SubgraphOptions): Promise; +``` + +This function returns the escrow data for a given address. + +> This uses Subgraph + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorUnsupportedChainID` | If the chain ID is not supported | +| `ErrorInvalidAddress` | If the escrow address is invalid | + +#### Example + +```ts +import { ChainId } from '@human-protocol/sdk'; + +const escrow = await EscrowUtils.getEscrow( + ChainId.POLYGON_AMOY, + "0x1234567890123456789012345678901234567890" +); +if (escrow) { + console.log('Escrow status:', escrow.status); +} +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `chainId` | `ChainId` | Network in which the escrow has been deployed | +| `escrowAddress` | `string` | Address of the escrow | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `IEscrow \| null` | Escrow data or null if not found. | + +*** + +### getStatusEvents() + +```ts +static getStatusEvents(filter: IStatusEventFilter, options?: SubgraphOptions): Promise; +``` + +This function returns the status events for a given set of networks within an optional date range. + +> This uses Subgraph + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidAddress` | If the launcher address is invalid | +| `ErrorUnsupportedChainID` | If the chain ID is not supported | + +#### Example + +```ts +import { ChainId, EscrowStatus } from '@human-protocol/sdk'; + +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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `filter` | `IStatusEventFilter` | Filter parameters. | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `IStatusEvent[]` | Array of status events with their corresponding statuses. | + +*** + +### getPayouts() + +```ts +static getPayouts(filter: IPayoutFilter, options?: SubgraphOptions): Promise; +``` + +This function returns the payouts for a given set of networks. + +> This uses Subgraph + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorUnsupportedChainID` | If the chain ID is not supported | +| `ErrorInvalidAddress` | If any filter address is invalid | + +#### Example + +```ts +import { ChainId } 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:', payouts.length); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `filter` | `IPayoutFilter` | Filter parameters. | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `IPayout[]` | List of payouts matching the filters. | + +*** + +### getCancellationRefunds() + +```ts +static getCancellationRefunds(filter: ICancellationRefundFilter, options?: SubgraphOptions): Promise; +``` + +This function returns the cancellation refunds for a given set of networks. + +> This uses Subgraph + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorUnsupportedChainID` | If the chain ID is not supported | +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorInvalidAddress` | If the receiver address is invalid | + +#### Example + +```ts +import { ChainId } from '@human-protocol/sdk'; + +const cancellationRefunds = await EscrowUtils.getCancellationRefunds({ + chainId: ChainId.POLYGON_AMOY, + escrowAddress: '0x1234567890123456789012345678901234567890', +}); +console.log('Cancellation refunds:', cancellationRefunds.length); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `filter` | `ICancellationRefundFilter` | Filter parameters. | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `ICancellationRefund[]` | List of cancellation refunds matching the filters. | + +*** + +### getCancellationRefund() + +```ts +static getCancellationRefund( + chainId: ChainId, + escrowAddress: string, +options?: SubgraphOptions): Promise; +``` + +This function returns the cancellation refund for a given escrow address. + +> This uses Subgraph + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorUnsupportedChainID` | If the chain ID is not supported | +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | + +#### Example + +```ts +import { ChainId } from '@human-protocol/sdk'; + +const cancellationRefund = await EscrowUtils.getCancellationRefund( + ChainId.POLYGON_AMOY, + "0x1234567890123456789012345678901234567890" +); +if (cancellationRefund) { + console.log('Refund amount:', cancellationRefund.amount); +} +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `chainId` | `ChainId` | Network in which the escrow has been deployed | +| `escrowAddress` | `string` | Address of the escrow | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `ICancellationRefund \| null` | Cancellation refund data or null if not found. | diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreClient.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreClient.md new file mode 100644 index 0000000000..464c3916ba --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreClient.md @@ -0,0 +1,297 @@ +## 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, 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); +``` + +**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 { JsonRpcProvider } from 'ethers'; + +const rpcUrl = 'YOUR_RPC_URL'; + +const provider = new JsonRpcProvider(rpcUrl); +const kvstoreClient = await KVStoreClient.build(provider); +``` + +## Extends + +- `BaseEthersClient` + +## Constructors + +### Constructor + +```ts +new KVStoreClient(runner: ContractRunner, networkData: NetworkData): KVStoreClient; +``` + +**KVStoreClient constructor** + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | +| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the KVStore contract | + +#### Returns + +| Type | Description | +|------|-------------| +| `KVStoreClient` | #### Overrides | + +```ts +BaseEthersClient.constructor +``` + +## Methods + +### build() + +```ts +static build(runner: ContractRunner): Promise; +``` + +Creates an instance of KVStoreClient from a runner. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorProviderDoesNotExist` | If the provider does not exist for the provided Signer | +| `ErrorUnsupportedChainID` | 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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | + +#### Returns + +| Type | Description | +|------|-------------| +| `KVStoreClient` | An instance of KVStoreClient | + +*** + +### set() + +```ts +set( + key: string, + value: string, +txOptions: Overrides): Promise; +``` + +This function sets a key-value pair associated with the address that submits the transaction. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorKVStoreEmptyKey` | If the key is empty | +| `Error` | If the transaction fails | + +#### Example + +```ts +await kvstoreClient.set('Role', 'RecordingOracle'); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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 + +| Type | Description | +|------|-------------| +| `void` | *** | + +### setBulk() + +```ts +setBulk( + keys: string[], + values: string[], +txOptions: Overrides): Promise; +``` + +This function sets key-value pairs in bulk associated with the address that submits the transaction. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorKVStoreArrayLength` | If keys and values arrays have different lengths | +| `ErrorKVStoreEmptyKey` | If any key is empty | +| `Error` | If the transaction fails | + +#### Example + +```ts +const keys = ['role', 'webhook_url']; +const values = ['RecordingOracle', 'http://localhost']; +await kvstoreClient.setBulk(keys, values); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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 + +| Type | Description | +|------|-------------| +| `void` | *** | + +### setFileUrlAndHash() + +```ts +setFileUrlAndHash( + url: string, + urlKey: string, +txOptions: Overrides): Promise; +``` + +Sets a URL value for the address that submits the transaction, and its hash. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidUrl` | If the URL is invalid | +| `Error` | If the transaction fails | + +#### Example + +```ts +await kvstoreClient.setFileUrlAndHash('example.com'); +await kvstoreClient.setFileUrlAndHash('linkedin.com/example', 'linkedin_url'); +``` + +#### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `url` | `string` | `undefined` | URL to set | +| `urlKey` | `string` | `'url'` | Configurable URL key. `url` by default. | +| `txOptions` | `Overrides` | `{}` | Additional transaction parameters (optional, defaults to an empty object). | + +#### Returns + +| Type | Description | +|------|-------------| +| `void` | *** | + +### get() + +```ts +get(address: string, key: string): Promise; +``` + +Gets the value of a key-value pair in the contract. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorKVStoreEmptyKey` | If the key is empty | +| `ErrorInvalidAddress` | If the address is invalid | +| `Error` | If the contract call fails | + +#### Example + +```ts +const value = await kvstoreClient.get('0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', 'Role'); +console.log('Value:', value); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `address` | `string` | Address from which to get the key value. | +| `key` | `string` | Key to obtain the value. | + +#### Returns + +| Type | Description | +|------|-------------| +| `string` | Value of the key. | diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreUtils.md new file mode 100644 index 0000000000..47c546233a --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreUtils.md @@ -0,0 +1,198 @@ +Utility class for KVStore-related operations. + +## Example + +```ts +import { ChainId, KVStoreUtils } from '@human-protocol/sdk'; + +const kvStoreData = await KVStoreUtils.getKVStoreData( + ChainId.POLYGON_AMOY, + "0x1234567890123456789012345678901234567890" +); +console.log('KVStore data:', kvStoreData); +``` + +## Methods + +### getKVStoreData() + +```ts +static getKVStoreData( + chainId: ChainId, + address: string, +options?: SubgraphOptions): Promise; +``` + +This function returns the KVStore data for a given address. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorUnsupportedChainID` | If the network's chainId is not supported | +| `ErrorInvalidAddress` | If the address is invalid | + +#### Example + +```ts +const kvStoreData = await KVStoreUtils.getKVStoreData( + ChainId.POLYGON_AMOY, + "0x1234567890123456789012345678901234567890" +); +console.log('KVStore data:', kvStoreData); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `chainId` | `ChainId` | Network in which the KVStore is deployed | +| `address` | `string` | Address of the KVStore | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `IKVStore[]` | KVStore data | + +*** + +### get() + +```ts +static get( + chainId: ChainId, + address: string, + key: string, +options?: SubgraphOptions): Promise; +``` + +Gets the value of a key-value pair in the KVStore using the subgraph. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorUnsupportedChainID` | If the network's chainId is not supported | +| `ErrorInvalidAddress` | If the address is invalid | +| `ErrorKVStoreEmptyKey` | If the key is empty | +| `InvalidKeyError` | If the key is not found | + +#### Example + +```ts +const value = await KVStoreUtils.get( + ChainId.POLYGON_AMOY, + '0x1234567890123456789012345678901234567890', + 'role' +); +console.log('Value:', value); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `chainId` | `ChainId` | 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/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `string` | Value of the key. | + +*** + +### getFileUrlAndVerifyHash() + +```ts +static getFileUrlAndVerifyHash( + chainId: ChainId, + address: string, + urlKey: string, +options?: SubgraphOptions): Promise; +``` + +Gets the URL value of the given entity, and verifies its hash. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidAddress` | If the address is invalid | +| `ErrorInvalidHash` | If the hash verification fails | +| `Error` | If fetching URL or hash fails | + +#### Example + +```ts +const url = await KVStoreUtils.getFileUrlAndVerifyHash( + ChainId.POLYGON_AMOY, + '0x1234567890123456789012345678901234567890' +); +console.log('Verified URL:', url); +``` + +#### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `chainId` | `ChainId` | `undefined` | Network in which the KVStore is deployed | +| `address` | `string` | `undefined` | Address from which to get the URL value. | +| `urlKey` | `string` | `'url'` | Configurable URL key. `url` by default. | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | `undefined` | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `string` | URL value for the given address if it exists, and the content is valid | + +*** + +### getPublicKey() + +```ts +static getPublicKey( + chainId: ChainId, + address: string, +options?: SubgraphOptions): Promise; +``` + +Gets the public key of the given entity, and verifies its hash. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidAddress` | If the address is invalid | +| `ErrorInvalidHash` | If the hash verification fails | +| `Error` | If fetching the public key fails | + +#### Example + +```ts +const publicKey = await KVStoreUtils.getPublicKey( + ChainId.POLYGON_AMOY, + '0x1234567890123456789012345678901234567890' +); +console.log('Public key:', publicKey); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `chainId` | `ChainId` | Network in which the KVStore is deployed | +| `address` | `string` | Address from which to get the public key. | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `string` | Public key for the given address if it exists, and the content is valid | diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/OperatorUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/OperatorUtils.md new file mode 100644 index 0000000000..08e7f037f6 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/OperatorUtils.md @@ -0,0 +1,193 @@ +Utility class for operator-related operations. + +## Example + +```ts +import { OperatorUtils, ChainId } from '@human-protocol/sdk'; + +const operator = await OperatorUtils.getOperator( + ChainId.POLYGON_AMOY, + '0x62dD51230A30401C455c8398d06F85e4EaB6309f' +); +console.log('Operator:', operator); +``` + +## Methods + +### getOperator() + +```ts +static getOperator( + chainId: ChainId, + address: string, +options?: SubgraphOptions): Promise; +``` + +This function returns the operator data for the given address. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidStakerAddressProvided` | If the address is invalid | +| `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' +); +console.log('Operator:', operator); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `chainId` | `ChainId` | Network in which the operator is deployed | +| `address` | `string` | Operator address. | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `IOperator \| null` | Returns the operator details or null if not found. | + +*** + +### getOperators() + +```ts +static getOperators(filter: IOperatorsFilter, options?: SubgraphOptions): Promise; +``` + +This function returns all the operator details of the protocol. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorUnsupportedChainID` | If the chain ID is not supported | + +#### Example + +```ts +import { ChainId } from '@human-protocol/sdk'; + +const filter = { + chainId: ChainId.POLYGON_AMOY +}; +const operators = await OperatorUtils.getOperators(filter); +console.log('Operators:', operators.length); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `filter` | `IOperatorsFilter` | Filter for the operators. | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `IOperator[]` | Returns an array with all the operator details. | + +*** + +### getReputationNetworkOperators() + +```ts +static getReputationNetworkOperators( + chainId: ChainId, + address: string, + role?: string, +options?: SubgraphOptions): Promise; +``` + +Retrieves the reputation network operators of the specified address. + +#### Throws + +| Type | Description | +|------|-------------| +| `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' +); +console.log('Operators:', operators.length); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `chainId` | `ChainId` | Network in which the reputation network is deployed | +| `address` | `string` | Address of the reputation oracle. | +| `role?` | `string` | Role of the operator (optional). | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `IOperator[]` | Returns an array of operator details. | + +*** + +### getRewards() + +```ts +static getRewards( + chainId: ChainId, + slasherAddress: string, +options?: SubgraphOptions): Promise; +``` + +This function returns information about the rewards for a given slasher address. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidSlasherAddressProvided` | If the slasher address is invalid | +| `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' +); +console.log('Rewards:', rewards.length); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `chainId` | `ChainId` | Network in which the rewards are deployed | +| `slasherAddress` | `string` | Slasher address. | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `IReward[]` | Returns an array of Reward objects that contain the rewards earned by the user through slashing other users. | diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingClient.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingClient.md new file mode 100644 index 0000000000..31eed25c42 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingClient.md @@ -0,0 +1,374 @@ +## 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, 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); +``` + +**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 { JsonRpcProvider } from 'ethers'; + +const rpcUrl = 'YOUR_RPC_URL'; + +const provider = new JsonRpcProvider(rpcUrl); +const stakingClient = await StakingClient.build(provider); +``` + +## Extends + +- `BaseEthersClient` + +## Constructors + +### Constructor + +```ts +new StakingClient(runner: ContractRunner, networkData: NetworkData): StakingClient; +``` + +**StakingClient constructor** + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | +| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the Staking contract | + +#### Returns + +| Type | Description | +|------|-------------| +| `StakingClient` | #### Overrides | + +```ts +BaseEthersClient.constructor +``` + +## Methods + +### build() + +```ts +static build(runner: ContractRunner): Promise; +``` + +Creates an instance of StakingClient from a Runner. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorProviderDoesNotExist` | If the provider does not exist for the provided Signer | +| `ErrorUnsupportedChainID` | 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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | + +#### Returns + +| Type | Description | +|------|-------------| +| `StakingClient` | An instance of StakingClient | + +*** + +### approveStake() + +```ts +approveStake(amount: bigint, txOptions: Overrides): Promise; +``` + +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. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidStakingValueType` | If the amount is not a bigint | +| `ErrorInvalidStakingValueSign` | If the amount is negative | + +#### Example + +```ts +import { ethers } from 'ethers'; + +const amount = ethers.parseUnits('5', 'ether'); //convert from ETH to WEI +await stakingClient.approveStake(amount); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `amount` | `bigint` | Amount in WEI of tokens to approve for stake. | +| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + +#### Returns + +| Type | Description | +|------|-------------| +| `void` | *** | + +### stake() + +```ts +stake(amount: bigint, txOptions: Overrides): Promise; +``` + +This function stakes a specified amount of tokens on a specific network. + +> `approveStake` must be called before + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidStakingValueType` | If the amount is not a bigint | +| `ErrorInvalidStakingValueSign` | If the amount is negative | + +#### Example + +```ts +import { ethers } from 'ethers'; + +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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `amount` | `bigint` | Amount in WEI of tokens to stake. | +| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + +#### Returns + +| Type | Description | +|------|-------------| +| `void` | *** | + +### unstake() + +```ts +unstake(amount: bigint, txOptions: Overrides): Promise; +``` + +This function unstakes tokens from staking contract. The unstaked tokens stay locked for a period of time. + +> Must have tokens available to unstake + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidStakingValueType` | If the amount is not a bigint | +| `ErrorInvalidStakingValueSign` | If the amount is negative | + +#### Example + +```ts +import { ethers } from 'ethers'; + +const amount = ethers.parseUnits('5', 'ether'); //convert from ETH to WEI +await stakingClient.unstake(amount); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `amount` | `bigint` | Amount in WEI of tokens to unstake. | +| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + +#### Returns + +| Type | Description | +|------|-------------| +| `void` | *** | + +### withdraw() + +```ts +withdraw(txOptions: Overrides): Promise; +``` + +This function withdraws unstaked and non-locked tokens from staking contract to the user wallet. + +> Must have tokens available to withdraw + +#### Example + +```ts +await stakingClient.withdraw(); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + +#### Returns + +| Type | Description | +|------|-------------| +| `void` | *** | + +### slash() + +```ts +slash( + slasher: string, + staker: string, + escrowAddress: string, + amount: bigint, +txOptions: Overrides): Promise; +``` + +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. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidStakingValueType` | If the amount is not a bigint | +| `ErrorInvalidStakingValueSign` | If the amount is negative | +| `ErrorInvalidSlasherAddressProvided` | If the slasher address is invalid | +| `ErrorInvalidStakerAddressProvided` | If the staker address is invalid | +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | + +#### Example + +```ts +import { ethers } from 'ethers'; + +const amount = ethers.parseUnits('5', 'ether'); //convert from ETH to WEI +await stakingClient.slash( + '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', + '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', + '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + amount +); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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 + +| Type | Description | +|------|-------------| +| `void` | *** | + +### getStakerInfo() + +```ts +getStakerInfo(stakerAddress: string): Promise; +``` + +Retrieves comprehensive staking information for a staker. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidStakerAddressProvided` | If the staker address is invalid | + +#### Example + +```ts +const stakingInfo = await stakingClient.getStakerInfo('0xYourStakerAddress'); +console.log('Tokens staked:', stakingInfo.stakedAmount); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `stakerAddress` | `string` | The address of the staker. | + +#### Returns + +| Type | Description | +|------|-------------| +| `StakerInfo` | Staking information for the staker | diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingUtils.md new file mode 100644 index 0000000000..87b8a95f18 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingUtils.md @@ -0,0 +1,102 @@ +Utility class for Staking-related subgraph 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); +``` + +## Methods + +### getStaker() + +```ts +static getStaker( + chainId: ChainId, + stakerAddress: string, +options?: SubgraphOptions): Promise; +``` + +Gets staking info for a staker from the subgraph. + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidStakerAddressProvided` | If the staker address is invalid | +| `ErrorUnsupportedChainID` | If the chain ID is not supported | +| `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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `chainId` | `ChainId` | Network in which the staking contract is deployed | +| `stakerAddress` | `string` | Address of the staker | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `IStaker` | Staker info from subgraph | + +*** + +### getStakers() + +```ts +static getStakers(filter: IStakersFilter, options?: SubgraphOptions): Promise; +``` + +Gets all stakers from the subgraph with filters, pagination and ordering. + +#### Throws + +| Type | Description | +|------|-------------| +| `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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `filter` | `IStakersFilter` | Stakers filter with pagination and ordering | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `IStaker[]` | Array of stakers | diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/StatisticsUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/StatisticsUtils.md new file mode 100644 index 0000000000..8c3a923531 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/StatisticsUtils.md @@ -0,0 +1,401 @@ +Utility class for statistics-related operations. + +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. + +## Installation + +### npm +```bash +npm install @human-protocol/sdk +``` + +### yarn +```bash +yarn install @human-protocol/sdk +``` + +## Example + +```ts +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); +``` + +## Methods + +### getEscrowStatistics() + +```ts +static getEscrowStatistics( + networkData: NetworkData, + filter: IStatisticsFilter, +options?: SubgraphOptions): Promise; +``` + +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[]; +}; +``` + +#### Example + +```ts +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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | +| `filter` | `IStatisticsFilter` | Statistics params with duration data | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `IEscrowStatistics` | Escrow statistics data. | + +*** + +### getWorkerStatistics() + +```ts +static getWorkerStatistics( + networkData: NetworkData, + filter: IStatisticsFilter, +options?: SubgraphOptions): Promise; +``` + +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[]; +}; +``` + +#### Example + +```ts +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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | +| `filter` | `IStatisticsFilter` | Statistics params with duration data | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `IWorkerStatistics` | Worker statistics data. | + +*** + +### getPaymentStatistics() + +```ts +static getPaymentStatistics( + networkData: NetworkData, + filter: IStatisticsFilter, +options?: SubgraphOptions): Promise; +``` + +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[]; +}; +``` + +#### Example + +```ts +import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; + +const networkData = NETWORKS[ChainId.POLYGON_AMOY]; +const paymentStats = await StatisticsUtils.getPaymentStatistics(networkData); +console.log( + 'Payment statistics:', + paymentStats.dailyPaymentsData.map((p) => ({ + ...p, + totalAmountPaid: p.totalAmountPaid.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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | +| `filter` | `IStatisticsFilter` | Statistics params with duration data | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `IPaymentStatistics` | Payment statistics data. | + +*** + +### getHMTStatistics() + +```ts +static getHMTStatistics(networkData: NetworkData, options?: SubgraphOptions): Promise; +``` + +This function returns the statistical data of HMToken. + +```ts +interface IHMTStatistics { + totalTransferAmount: bigint; + totalTransferCount: number; + totalHolders: number; +}; +``` + +#### Example + +```ts +import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; + +const networkData = NETWORKS[ChainId.POLYGON_AMOY]; +const hmtStats = await StatisticsUtils.getHMTStatistics(networkData); +console.log('HMT statistics:', { + ...hmtStats, + totalTransferAmount: hmtStats.totalTransferAmount.toString(), +}); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `IHMTStatistics` | HMToken statistics data. | + +*** + +### getHMTHolders() + +```ts +static getHMTHolders( + networkData: NetworkData, + params: IHMTHoldersParams, +options?: SubgraphOptions): Promise; +``` + +This function returns the holders of the HMToken with optional filters and ordering. + +#### Example + +```ts +import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; + +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(), +}))); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | +| `params` | `IHMTHoldersParams` | HMT Holders params with filters and ordering | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `IHMTHolder[]` | List of HMToken holders. | + +*** + +### getHMTDailyData() + +```ts +static getHMTDailyData( + networkData: NetworkData, + filter: IStatisticsFilter, +options?: SubgraphOptions): Promise; +``` + +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; +} +``` + +#### Example + +```ts +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 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); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | +| `filter` | `IStatisticsFilter` | Statistics params with duration data | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `IDailyHMT[]` | Daily HMToken statistics data. | diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/StorageClient.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/StorageClient.md new file mode 100644 index 0000000000..4b2385fd3c --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/StorageClient.md @@ -0,0 +1,270 @@ +## 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 + +```ts +new StorageClient(params: StorageParams, credentials?: StorageCredentials): StorageClient; +``` + +**Storage client constructor** + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `params` | [`StorageParams`](../type-aliases/StorageParams.md) | Cloud storage params | +| `credentials?` | [`StorageCredentials`](../type-aliases/StorageCredentials.md) | Optional. Cloud storage access data. If credentials are not provided - use anonymous access to the bucket | + +#### Returns + +| Type | Description | +|------|-------------| +| `StorageClient` | - | + +## Methods + +### ~~downloadFiles()~~ + +```ts +downloadFiles(keys: string[], bucket: string): Promise; +``` + +This function downloads files from a bucket. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `keys` | `string`[] | Array of filenames to download. | +| `bucket` | `string` | Bucket name. | + +#### Returns + +| Type | Description | +|------|-------------| +| `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'); +``` + +*** + +### ~~downloadFileFromUrl()~~ + +```ts +static downloadFileFromUrl(url: string): Promise; +``` + +This function downloads files from a URL. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `url` | `string` | URL of the file to download. | + +#### Returns + +| Type | Description | +|------|-------------| +| `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'); +``` + +*** + +### ~~uploadFiles()~~ + +```ts +uploadFiles(files: any[], bucket: string): Promise; +``` + +This function uploads files to a bucket. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `files` | `any`[] | Array of objects to upload serialized into JSON. | +| `bucket` | `string` | Bucket name. | + +#### Returns + +| Type | Description | +|------|-------------| +| `[UploadFile](../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'); +``` + +*** + +### ~~bucketExists()~~ + +```ts +bucketExists(bucket: string): Promise; +``` + +This function checks if a bucket exists. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `bucket` | `string` | Bucket name. | + +#### Returns + +| Type | Description | +|------|-------------| +| `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'); +``` + +*** + +### ~~listObjects()~~ + +```ts +listObjects(bucket: string): Promise; +``` + +This function lists all file names contained in the bucket. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `bucket` | `string` | Bucket name. | + +#### Returns + +| Type | Description | +|------|-------------| +| `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'); +``` diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/TransactionUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/TransactionUtils.md new file mode 100644 index 0000000000..0f4a8f5936 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/TransactionUtils.md @@ -0,0 +1,184 @@ +Utility class for transaction-related operations. + +## Example + +```ts +import { TransactionUtils, ChainId } from '@human-protocol/sdk'; + +const transaction = await TransactionUtils.getTransaction( + ChainId.POLYGON_AMOY, + '0x62dD51230A30401C455c8398d06F85e4EaB6309f' +); +console.log('Transaction:', transaction); +``` + +## Methods + +### getTransaction() + +```ts +static getTransaction( + chainId: ChainId, + hash: string, +options?: SubgraphOptions): Promise; +``` + +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; +}; +``` + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidHashProvided` | If the hash is invalid | +| `ErrorUnsupportedChainID` | If the chain ID is not supported | + +#### Example + +```ts +import { TransactionUtils, ChainId } from '@human-protocol/sdk'; + +const transaction = await TransactionUtils.getTransaction( + ChainId.POLYGON_AMOY, + '0x62dD51230A30401C455c8398d06F85e4EaB6309f' +); +console.log('Transaction:', transaction); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `chainId` | `ChainId` | The chain ID. | +| `hash` | `string` | The transaction hash. | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `ITransaction \| null` | Returns the transaction details or null if not found. | + +*** + +### getTransactions() + +```ts +static getTransactions(filter: ITransactionsFilter, options?: SubgraphOptions): Promise; +``` + +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[]; +}; +``` + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorCannotUseDateAndBlockSimultaneously` | If both date and block filters are used | +| `ErrorUnsupportedChainID` | If the chain ID is not supported | + +#### Example + +```ts +import { TransactionUtils, ChainId, OrderDirection } from '@human-protocol/sdk'; + +const filter = { + chainId: ChainId.POLYGON_AMOY, + 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); +console.log('Transactions:', transactions.length); +``` + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `filter` | `ITransactionsFilter` | Filter for the transactions. | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `ITransaction[]` | Returns an array with all the transaction details. | diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/enumerations/EscrowStatus.md b/packages/sdk/typescript/human-protocol-sdk/docs/enumerations/EscrowStatus.md new file mode 100644 index 0000000000..0dfa358f82 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/docs/enumerations/EscrowStatus.md @@ -0,0 +1,13 @@ +Enum for escrow statuses. + +## Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `Launched` | `0` | Escrow is launched. | +| `Pending` | `1` | Escrow is funded, and waiting for the results to be submitted. | +| `Partial` | `2` | Escrow is partially paid out. | +| `Paid` | `3` | Escrow is fully paid. | +| `Complete` | `4` | Escrow is finished. | +| `Cancelled` | `5` | Escrow is cancelled. | +| `ToCancel` | `6` | Escrow is cancelled. | diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/interfaces/SubgraphOptions.md b/packages/sdk/typescript/human-protocol-sdk/docs/interfaces/SubgraphOptions.md new file mode 100644 index 0000000000..3674ec4564 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/docs/interfaces/SubgraphOptions.md @@ -0,0 +1,9 @@ +Configuration options for subgraph requests with retry logic. + +## Properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `maxRetries?` | `number` | Maximum number of retry attempts | +| `baseDelay?` | `number` | Base delay between retries in milliseconds | +| `indexerId?` | `string` | Optional indexer identifier. When provided, requests target `{gateway}/deployments/id//indexers/id/`. | diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/NetworkData.md b/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/NetworkData.md new file mode 100644 index 0000000000..194d6a4843 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/NetworkData.md @@ -0,0 +1,115 @@ +```ts +type NetworkData = object; +``` + +Network data + +## Properties + +### chainId + +```ts +chainId: number; +``` + +Network chain id + +*** + +### title + +```ts +title: string; +``` + +Network title + +*** + +### scanUrl + +```ts +scanUrl: string; +``` + +Network scanner URL + +*** + +### hmtAddress + +```ts +hmtAddress: string; +``` + +HMT Token contract address + +*** + +### factoryAddress + +```ts +factoryAddress: string; +``` + +Escrow Factory contract address + +*** + +### stakingAddress + +```ts +stakingAddress: string; +``` + +Staking contract address + +*** + +### kvstoreAddress + +```ts +kvstoreAddress: string; +``` + +KVStore contract address + +*** + +### subgraphUrl + +```ts +subgraphUrl: string; +``` + +Subgraph URL + +*** + +### subgraphUrlApiKey + +```ts +subgraphUrlApiKey: string; +``` + +Subgraph URL API key + +*** + +### oldSubgraphUrl + +```ts +oldSubgraphUrl: string; +``` + +Old subgraph URL + +*** + +### oldFactoryAddress + +```ts +oldFactoryAddress: string; +``` + +Old Escrow Factory contract address diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/StorageCredentials.md b/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/StorageCredentials.md new file mode 100644 index 0000000000..8e09ad3813 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/StorageCredentials.md @@ -0,0 +1,29 @@ +```ts +readonly type StorageCredentials = object; +``` + +AWS/GCP cloud storage access data + +## Deprecated + +StorageClient is deprecated. Use Minio.Client directly. + +## Properties + +### ~~accessKey~~ + +```ts +accessKey: string; +``` + +Access Key + +*** + +### ~~secretKey~~ + +```ts +secretKey: string; +``` + +Secret Key diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/StorageParams.md b/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/StorageParams.md new file mode 100644 index 0000000000..fa3da8ba8e --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/StorageParams.md @@ -0,0 +1,47 @@ +```ts +type StorageParams = object; +``` + +## Deprecated + +StorageClient is deprecated. Use Minio.Client directly. + +## Properties + +### ~~endPoint~~ + +```ts +endPoint: string; +``` + +Request endPoint + +*** + +### ~~useSSL~~ + +```ts +useSSL: boolean; +``` + +Enable secure (HTTPS) access. Default value set to false + +*** + +### ~~region?~~ + +```ts +optional region: string; +``` + +Region + +*** + +### ~~port?~~ + +```ts +optional port: number; +``` + +TCP/IP port number. Default value set to 80 for HTTP and 443 for HTTPs diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/UploadFile.md b/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/UploadFile.md new file mode 100644 index 0000000000..349fbb64a9 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/UploadFile.md @@ -0,0 +1,35 @@ +```ts +readonly type UploadFile = object; +``` + +Upload file data + +## Properties + +### key + +```ts +key: string; +``` + +Uploaded object key + +*** + +### url + +```ts +url: string; +``` + +Uploaded object URL + +*** + +### hash + +```ts +hash: string; +``` + +Hash of uploaded object key diff --git a/packages/sdk/typescript/human-protocol-sdk/package.json b/packages/sdk/typescript/human-protocol-sdk/package.json index 96a26132b8..7f578d7f57 100644 --- a/packages/sdk/typescript/human-protocol-sdk/package.json +++ b/packages/sdk/typescript/human-protocol-sdk/package.json @@ -10,9 +10,10 @@ "types": "dist/index.d.ts", "scripts": { "clean": "tsc --build --clean && rm -rf ./dist", - "clean:doc": "rm -rf ../../../../docs/sdk/typescript/", + "clean:doc": "rm -rf docs", "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": "yarn clean:doc && typedoc && yarn docs:post", "test": "vitest -u", "lint": "eslint .", "lint:fix": "eslint . --fix", @@ -55,27 +56,11 @@ "eslint": "^9.39.1", "eslint-plugin-jest": "^28.9.0", "eslint-plugin-prettier": "^5.2.1", + "glob": "^13.0.0", "prettier": "^3.4.2", "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..3211703013 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/scripts/postprocess-docs.ts @@ -0,0 +1,146 @@ +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'); + const lines = original.split('\n'); + const out = []; + + let i = 0; + + while (i < lines.length) { + const line = lines[i]; + + // ---------- THROWS: merge all into one table ---------- + if (line.startsWith('#### Throws')) { + const rows = []; + + // consume all 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 || /^###? /.test(lines[i])) break; + + const first = lines[i].trim(); + i++; + + let type = ''; + let desc = ''; + + // pattern: ErrorType Some description... + const m = first.match(/^`?([^`\s]+)`?\s*(.*)$/); + if (m) { + type = m[1].trim(); + desc = (m[2] || '').trim(); + } else { + desc = first; + } + + // if description is empty, read following lines + if (!desc) { + const descParts = []; + while ( + i < lines.length && + lines[i].trim() !== '' && + !/^###? /.test(lines[i]) + ) { + descParts.push(lines[i].trim()); + i++; + } + desc = descParts.join(' '); + } + + // skip blank lines between throws blocks + while (i < lines.length && lines[i].trim() === '') i++; + + rows.push({ type, desc }); + } + + // emit one 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: single table ---------- + 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: `Promise`\<`EscrowClient`\> + const typeLine = lines[i].trim(); + i++; + + // skip blank lines + while (i < lines.length && lines[i].trim() === '') i++; + + // description lines until next heading or blank+heading + const descParts = []; + while ( + i < lines.length && + lines[i].trim() !== '' && + !/^###? /.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(); // e.g. Promise + + // OPTIONAL: strip Promise<...> wrapper so only EscrowClient appears + 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; + } + + // default: copy line + out.push(line); + i++; + } + + writeFileSync(path, out.join('\n')); +} + +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/encryption.ts b/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts index 38d1921f93..f630f64242 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts @@ -16,44 +16,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 +28,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 +37,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 +74,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 +112,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 publicKey = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; * - * 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'); + * const resultMessage = await encryption.decrypt('message', publicKey); + * console.log('Decrypted message:', resultMessage); * ``` */ public async decrypt( @@ -233,19 +167,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 +191,30 @@ 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 - * + * @example * ```ts * import { EncryptionUtils } from '@human-protocol/sdk'; * - * const keyPair = await EncryptionUtils.generateKeyPair('Human', 'human@hmt.ai'); + * const publicKey = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; + * const isValid = await EncryptionUtils.verify('message', publicKey); + * console.log('Signature valid:', isValid); * ``` */ 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 +239,14 @@ 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 +264,18 @@ 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 +303,17 @@ 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 +339,13 @@ 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-----`; - * - * 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..7ba64e0950 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. * * 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,8 @@ 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 */ constructor(runner: ContractRunner, networkData: NetworkData) { super(runner, networkData); @@ -166,11 +147,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) { @@ -205,27 +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. * - * @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** + * @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 * + * @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); @@ -315,50 +285,44 @@ 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. + * @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 +330,8 @@ export class EscrowClient extends BaseEthersClient { * jobRequesterId, * escrowConfig * ); - * * console.log('Escrow created at:', escrowAddress); + * ``` */ @requiresSigner public async createFundAndSetupEscrow( @@ -431,35 +395,31 @@ 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. - * - * - * **Code example** + * @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). + * @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 * + * @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'), + * recordingOracleFee: 10n, + * reputationOracleFee: 10n, + * exchangeOracleFee: 10n, * manifest: 'http://localhost/manifest.json', * manifestHash: 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079', * }; @@ -519,26 +479,18 @@ 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). + * @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'; + * import { ethers } from 'ethers'; * - * 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 + * const amount = ethers.parseUnits('5', 'ether'); * await escrowClient.fund('0x62dD51230A30401C455c8398d06F85e4EaB6309f', amount); * ``` */ @@ -582,30 +534,30 @@ 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. - * + * @param escrowAddress - Address of the escrow. + * @param url - Results file URL. + * @param hash - Results file hash. + * @param fundsToReserve - Funds to reserve for payouts + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorInvalidUrl If the URL is invalid + * @throws ErrorHashIsEmptyString If the hash is empty + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + * @throws ErrorStoreResultsVersion If using deprecated signature * - * **Code example** + * @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'; + * 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', ethers.parseEther('10')); + * await escrowClient.storeResults( + * '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + * 'http://localhost/results.json', + * 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079', + * ethers.parseEther('10') + * ); * ``` */ @@ -620,29 +572,25 @@ 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 {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. + * @param url - Results file URL. + * @param hash - Results file hash. + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorInvalidUrl If the URL is invalid + * @throws ErrorHashIsEmptyString If the hash is empty + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + * @throws ErrorStoreResultsVersion If using deprecated signature * + * @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'); + * await escrowClient.storeResults( + * '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + * 'http://localhost/results.json', + * 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079' + * ); * ``` */ async storeResults( @@ -716,26 +664,15 @@ export class EscrowClient extends BaseEthersClient { /** * This function sets the status of an escrow to completed. * - * @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** + * @param escrowAddress - Address of the escrow. + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory * + * @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'); * ``` */ @@ -765,39 +702,47 @@ export class EscrowClient extends BaseEthersClient { /** * This function pays out the amounts specified to the workers and sets the URL of the final results file. * - * @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** + * @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). + * @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 * + * @example * > Only Reputation Oracle or admin can call it. * * ```ts - * import { ethers, Wallet, providers } from 'ethers'; - * import { EscrowClient } 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 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 txId = 1; * - * await escrowClient.bulkPayOut('0x62dD51230A30401C455c8398d06F85e4EaB6309f', recipients, amounts, resultsUrl, resultsHash, txId, true); + * await escrowClient.bulkPayOut( + * '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + * recipients, + * amounts, + * resultsUrl, + * resultsHash, + * txId, + * true + * ); * ``` */ async bulkPayOut( @@ -814,40 +759,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. * - * @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** + * @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). + * @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 * + * @example * > Only Reputation Oracle or admin can call it. * * ```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( @@ -926,25 +879,15 @@ export class EscrowClient extends BaseEthersClient { /** * This function cancels the specified escrow and sends the balance to the canceler. * - * @param {string} escrowAddress Address of the escrow to cancel. - * @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object). - * - * - * **Code example** + * @param escrowAddress - Address of the escrow to cancel. + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory * + * @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'); * ``` */ @@ -972,25 +915,15 @@ export class EscrowClient extends BaseEthersClient { /** * This function requests the cancellation of the specified escrow (moves status to ToCancel or finalizes if expired). * - * @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** + * @param escrowAddress - Address of the escrow to request cancellation. + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory * + * @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'); * ``` */ @@ -1018,31 +951,24 @@ export class EscrowClient extends BaseEthersClient { /** * This function withdraws additional tokens in the escrow to the canceler. * - * @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. - * - * - * **Code example** + * @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 * + * @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( + * const withdrawData = await escrowClient.withdraw( * '0x62dD51230A30401C455c8398d06F85e4EaB6309f', * '0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4' * ); + * console.log('Withdrawn amount:', withdrawData.withdrawnAmount); * ``` */ @requiresSigner @@ -1108,43 +1034,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 - * - * **Code example** * + * @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 + * + * @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); + * 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 +1212,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 +1250,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 +1281,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 +1313,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 +1345,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 +1377,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 +1409,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 +1441,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 +1473,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 +1507,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 +1539,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 +1571,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 +1603,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 +1635,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 +1665,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)** - * + * @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 +1763,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 +1814,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 +1905,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 +1922,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 +1977,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 +2050,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 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 - * - * **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 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 - * import { ChainId, EscrowUtils } from '@human-protocol/sdk'; + * import { ChainId } 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 047bfb6782..9216747633 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/index.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/index.ts @@ -2,7 +2,7 @@ import { StakingClient, StakingUtils } from './staking'; import { StorageClient } from './storage'; import { KVStoreClient, KVStoreUtils } from './kvstore'; import { EscrowClient, EscrowUtils } from './escrow'; -import { StatisticsClient } from './statistics'; +import { StatisticsUtils } from './statistics'; import { Encryption, EncryptionUtils } from './encryption'; import { OperatorUtils } from './operator'; import { TransactionUtils } from './transaction'; @@ -32,7 +32,7 @@ export { KVStoreUtils, EscrowClient, EscrowUtils, - StatisticsClient, + StatisticsUtils, Encryption, EncryptionUtils, OperatorUtils, diff --git a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts b/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts index 518217ee01..338624183b 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts @@ -62,12 +62,12 @@ import { IKVStore, SubgraphOptions } from './interfaces'; * * ```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); * ``` @@ -86,11 +86,11 @@ import { IKVStore, SubgraphOptions } from './interfaces'; * * ```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 +101,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 +116,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 +154,14 @@ 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). + * @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 +182,15 @@ 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). + * @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 +216,14 @@ 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). + * @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 +259,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 +287,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)** - * + * @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 +353,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 +405,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 +468,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..88b9e9f225 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 class for operator-related operations. + * + * @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..36a72773f2 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/staking.ts @@ -73,12 +73,12 @@ import { * * ```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); * ``` @@ -97,11 +97,11 @@ import { * * ```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 +113,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 +138,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 +191,16 @@ 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). + * @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); * ``` */ @@ -232,24 +236,16 @@ export class StakingClient extends BaseEthersClient { * * > `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. - * - * **Code example** + * @param amount - Amount in WEI of tokens to stake. + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @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); * ``` @@ -277,24 +273,16 @@ export class StakingClient extends BaseEthersClient { * * > 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. - * - * **Code example** + * @param amount - Amount in WEI of tokens to unstake. + * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @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.unstake(amount); * ``` */ @@ -324,22 +312,10 @@ export class StakingClient extends BaseEthersClient { * * > 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). * + * @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 +332,29 @@ 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). + * @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 +403,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 { @@ -480,15 +450,40 @@ export class StakingClient extends BaseEthersClient { /** * Utility class for Staking-related subgraph 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 +516,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..f60b4ef23c 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts @@ -30,16 +30,10 @@ import { } from './utils'; /** - * ## Introduction + * Utility class for statistics-related operations. * - * 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) - * ``` + * 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. * * ## Installation * @@ -53,28 +47,16 @@ import { * yarn install @human-protocol/sdk * ``` * - * ## Code example - * + * @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 +88,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 +125,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 +186,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 +224,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 +275,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 +320,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 +360,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 +399,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 +473,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 +511,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..1a8eb5d6a1 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 operations. + * + * @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/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..1fcc4b0abc --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/typedoc.json @@ -0,0 +1,45 @@ +{ + "$schema": "https://typedoc-plugin-markdown.org/schema.json", + "entryPoints": [ + "src/index.ts" + ], + "entryPointStrategy": "expand", + "out": "docs", + "plugin": [ + "typedoc-plugin-markdown" + ], + "readme": "none", + "cleanOutputDir": true, + "excludePrivate": true, + "excludeInternal": true, + "excludeProtected": false, + "excludeExternals": false, + "excludeNotDocumented": true, + "categorizeByGroup": false, + "blockTagsPreserveOrder": [ + "@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, + "sort": [ + "source-order" + ], + "includeVersion": true, + "markdown": { + "hideSignature": true + } +} \ No newline at end of file diff --git a/yarn.lock b/yarn.lock index b951ec5945..21b269b1c6 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" @@ -4994,8 +4995,8 @@ __metadata: prettier: "npm:^3.4.2" 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" @@ -9059,41 +9060,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 @@ -19780,6 +19781,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" @@ -23725,7 +23737,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: @@ -29770,7 +29782,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: @@ -29779,11 +29791,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" @@ -29792,7 +29804,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 @@ -31839,7 +31851,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: @@ -31848,6 +31860,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" From 17b4c6c44ca7a2d98aedc47e3a030303e74beda6 Mon Sep 17 00:00:00 2001 From: portuu3 Date: Mon, 8 Dec 2025 19:49:22 +0100 Subject: [PATCH 05/19] docs fixes --- docs/mkdocs-python.yaml | 4 +- docs/mkdocs-ts.yaml | 5 +- .../human_protocol_sdk/escrow/escrow_utils.py | 2 +- .../kvstore/kvstore_client.py | 2 +- .../kvstore/kvstore_utils.py | 2 +- .../operator/operator_utils.py | 2 +- .../staking/staking_client.py | 2 +- .../staking/staking_utils.py | 2 +- .../statistics/statistics_utils.py | 2 +- .../transaction/transaction_utils.py | 2 +- .../human_protocol_sdk/worker/worker_utils.py | 2 +- .../[object Object]/README.md | 29 - .../[object Object]/classes/Encryption.md | 157 -- .../classes/EncryptionUtils.md | 180 -- .../[object Object]/classes/EscrowClient.md | 1502 ----------------- .../[object Object]/classes/EscrowUtils.md | 306 ---- .../[object Object]/classes/KVStoreClient.md | 308 ---- .../[object Object]/classes/KVStoreUtils.md | 214 --- .../[object Object]/classes/OperatorUtils.md | 191 --- .../[object Object]/classes/StakingClient.md | 389 ----- .../[object Object]/classes/StakingUtils.md | 104 -- .../classes/StatisticsUtils.md | 401 ----- .../[object Object]/classes/StorageClient.md | 268 --- .../classes/TransactionUtils.md | 186 -- .../enumerations/EscrowStatus.md | 13 - .../interfaces/SubgraphOptions.md | 9 - .../type-aliases/NetworkData.md | 115 -- .../type-aliases/StorageCredentials.md | 29 - .../type-aliases/StorageParams.md | 47 - .../type-aliases/UploadFile.md | 35 - .../human-protocol-sdk/docs/README.md | 6 +- .../docs/classes/Encryption.md | 102 +- .../docs/classes/EncryptionUtils.md | 145 +- .../docs/classes/EscrowClient.md | 1040 ++++++------ .../docs/classes/EscrowUtils.md | 278 ++- .../docs/classes/KVStoreClient.md | 208 ++- .../docs/classes/KVStoreUtils.md | 160 +- .../docs/classes/OperatorUtils.md | 160 +- .../docs/classes/StakingClient.md | 284 ++-- .../docs/classes/StakingUtils.md | 84 +- .../docs/classes/StatisticsUtils.md | 254 ++- .../docs/classes/StorageClient.md | 270 --- .../docs/classes/TransactionUtils.md | 94 +- .../docs/classes/WorkerUtils.md | 123 ++ .../human-protocol-sdk/docs/index.md | 292 ++++ .../docs/type-aliases/MessageDataType.md | 6 + .../docs/type-aliases/StorageCredentials.md | 29 - .../docs/type-aliases/StorageParams.md | 47 - .../docs/type-aliases/UploadFile.md | 35 - .../human-protocol-sdk/package.json | 3 +- .../scripts/postprocess-docs.ts | 77 +- .../typescript/human-protocol-sdk/src/base.ts | 9 +- .../human-protocol-sdk/src/encryption.ts | 23 +- .../human-protocol-sdk/src/escrow.ts | 129 +- .../human-protocol-sdk/src/index.ts | 3 +- .../human-protocol-sdk/src/kvstore.ts | 30 +- .../human-protocol-sdk/src/operator.ts | 2 +- .../human-protocol-sdk/src/staking.ts | 38 +- .../human-protocol-sdk/src/statistics.ts | 14 +- .../human-protocol-sdk/src/transaction.ts | 2 +- .../human-protocol-sdk/src/utils.ts | 48 +- .../human-protocol-sdk/typedoc.json | 13 +- 62 files changed, 2083 insertions(+), 6435 deletions(-) delete mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/README.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/Encryption.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/EncryptionUtils.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/EscrowClient.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/EscrowUtils.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/KVStoreClient.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/KVStoreUtils.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/OperatorUtils.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StakingClient.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StakingUtils.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StatisticsUtils.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StorageClient.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/TransactionUtils.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/enumerations/EscrowStatus.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/interfaces/SubgraphOptions.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/NetworkData.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/StorageCredentials.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/StorageParams.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/UploadFile.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/StorageClient.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/WorkerUtils.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/index.md create mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/MessageDataType.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/StorageCredentials.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/StorageParams.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/UploadFile.md diff --git a/docs/mkdocs-python.yaml b/docs/mkdocs-python.yaml index 32f2eb8db4..bb0f87f0c3 100644 --- a/docs/mkdocs-python.yaml +++ b/docs/mkdocs-python.yaml @@ -7,8 +7,8 @@ site_dir: python theme: name: material custom_dir: overrides - logo: overrides/assets/img/logo.svg - favicon: overrides/assets/img/logo.svg + logo: assets/img/logo.svg + favicon: assets/img/logo.svg palette: - scheme: default primary: deep purple diff --git a/docs/mkdocs-ts.yaml b/docs/mkdocs-ts.yaml index 2ed1e67b1a..27f7b27574 100644 --- a/docs/mkdocs-ts.yaml +++ b/docs/mkdocs-ts.yaml @@ -7,8 +7,8 @@ site_dir: ts theme: name: material custom_dir: overrides - logo: overrides/assets/img/logo.svg - favicon: overrides/assets/img/logo.svg + logo: assets/img/logo.svg + favicon: assets/img/logo.svg palette: - scheme: default primary: deep purple @@ -84,6 +84,5 @@ nav: - TransactionUtils: classes/TransactionUtils.md - Worker: - WorkerUtils: classes/WorkerUtils.md - - Core utilities: classes/Core.md extra_css: - assets/css/custom.css 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 0e118779c0..b3619b4d4f 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,4 +1,4 @@ -"""Utility helpers for escrow-related operations. +"""Utility helpers for escrow-related queries. Example: ```python 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 971248f5f7..2226b40fbd 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,4 +1,4 @@ -"""Client for interacting with the KVStore contract and subgraph. +"""Client for interacting with the KVStore contract. 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. 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 ee705aff40..1f952cc471 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,4 +1,4 @@ -"""Utility helpers for on-chain KVStore data. +"""Utility helpers for KVStore queries. Example: ```python 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 e5d921fa3b..22153153d5 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,4 +1,4 @@ -"""Utility helpers for querying operator data. +"""Utility helpers for operator-related queries. Example: ```python 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 1c2416c731..3c5f70276c 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,4 +1,4 @@ -"""Client for staking actions and queries on HUMAN Protocol. +"""Client for staking actions on HUMAN Protocol. Internally selects network config based on the Web3 chain id. 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 04dbd65bcf..85593ee47b 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,4 +1,4 @@ -"""Utility helpers for staking-related operations.""" +"""Utility helpers for staking-related queries.""" from typing import List, Optional from human_protocol_sdk.constants import NETWORKS, ChainId 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 index 880910c0d4..26d5ea3034 100644 --- 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 @@ -1,4 +1,4 @@ -"""Utility helpers for retrieving statistical information from the subgraph. +"""Utility helpers for retrieving statistics information. Example: ```python 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 3c63978719..a5ed00cff2 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,4 +1,4 @@ -"""Utility helpers for transaction-related subgraph queries. +"""Utility helpers for transaction-related queries. Example: ```python 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 498478e942..61070d7838 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,4 +1,4 @@ -"""Utility helpers for worker-related operations. +"""Utility helpers for worker-related queries. Example: ```python diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/README.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/README.md deleted file mode 100644 index 90a6f9d669..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/[object Object]/README.md +++ /dev/null @@ -1,29 +0,0 @@ -## Enumerations - -- [EscrowStatus](enumerations/EscrowStatus.md) - -## Classes - -- [Encryption](classes/Encryption.md) -- [EncryptionUtils](classes/EncryptionUtils.md) -- [EscrowClient](classes/EscrowClient.md) -- [EscrowUtils](classes/EscrowUtils.md) -- [KVStoreClient](classes/KVStoreClient.md) -- [KVStoreUtils](classes/KVStoreUtils.md) -- [OperatorUtils](classes/OperatorUtils.md) -- [StakingClient](classes/StakingClient.md) -- [StakingUtils](classes/StakingUtils.md) -- [StatisticsUtils](classes/StatisticsUtils.md) -- [~~StorageClient~~](classes/StorageClient.md) -- [TransactionUtils](classes/TransactionUtils.md) - -## Interfaces - -- [SubgraphOptions](interfaces/SubgraphOptions.md) - -## Type Aliases - -- [~~StorageCredentials~~](type-aliases/StorageCredentials.md) -- [~~StorageParams~~](type-aliases/StorageParams.md) -- [UploadFile](type-aliases/UploadFile.md) -- [NetworkData](type-aliases/NetworkData.md) diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/Encryption.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/Encryption.md deleted file mode 100644 index fc42d05259..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/Encryption.md +++ /dev/null @@ -1,157 +0,0 @@ -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`](/ts/classes/Encryption/#build) method. - -## Constructors - -### Constructor - -```ts -new Encryption(privateKey: PrivateKey): Encryption; -``` - -Constructor for the Encryption class. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `privateKey` | `PrivateKey` | The private key. | - -#### Returns - -`Encryption` - -## Methods - -### build() - -```ts -static build(privateKeyArmored: string, passphrase?: string): Promise; -``` - -Builds an Encryption instance by decrypting the private key from an encrypted private key and passphrase. - -#### Example - -```ts -import { Encryption } from '@human-protocol/sdk'; - -const privateKey = 'Armored_priv_key'; -const passphrase = 'example_passphrase'; -const encryption = await Encryption.build(privateKey, passphrase); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `privateKeyArmored` | `string` | The encrypted private key in armored format. | -| `passphrase?` | `string` | The passphrase for the private key (optional). | - -#### Returns - -`Promise`\<`Encryption`\> - -The Encryption instance. - -*** - -### signAndEncrypt() - -```ts -signAndEncrypt(message: MessageDataType, publicKeys: string[]): Promise; -``` - -This function signs and encrypts a message using the private key used to initialize the client and the specified public keys. - -#### Example - -```ts -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); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `message` | `MessageDataType` | Message to sign and encrypt. | -| `publicKeys` | `string`[] | Array of public keys to use for encryption. | - -#### Returns - -`Promise`\<`string`\> - -Message signed and encrypted. - -*** - -### decrypt() - -```ts -decrypt(message: string, publicKey?: string): Promise>; -``` - -This function decrypts messages using the private key. In addition, the public key can be added for signature verification. - -#### Throws - -Error If signature could not be verified when public key is provided - -#### Example - -```ts -const publicKey = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; - -const resultMessage = await encryption.decrypt('message', publicKey); -console.log('Decrypted message:', resultMessage); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `message` | `string` | Message to decrypt. | -| `publicKey?` | `string` | Public key used to verify signature if needed (optional). | - -#### Returns - -`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> - -Message decrypted. - -*** - -### sign() - -```ts -sign(message: string): Promise; -``` - -This function signs a message using the private key used to initialize the client. - -#### Example - -```ts -const resultMessage = await encryption.sign('message'); -console.log('Signed message:', resultMessage); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `message` | `string` | Message to sign. | - -#### Returns - -`Promise`\<`string`\> - -Message signed. diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/EncryptionUtils.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/EncryptionUtils.md deleted file mode 100644 index 34b664cc04..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/EncryptionUtils.md +++ /dev/null @@ -1,180 +0,0 @@ -Utility class for encryption-related operations. - -## Example - -```ts -import { EncryptionUtils } from '@human-protocol/sdk'; - -const publicKey = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; -const isValid = await EncryptionUtils.verify('message', publicKey); -console.log('Signature valid:', isValid); -``` - -## Methods - -### verify() - -```ts -static verify(message: string, publicKey: string): Promise; -``` - -This function verifies the signature of a signed message using the public key. - -#### Example - -```ts -const publicKey = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; -const result = await EncryptionUtils.verify('message', publicKey); -console.log('Verification result:', result); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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. - -*** - -### getSignedData() - -```ts -static getSignedData(message: string): Promise; -``` - -This function gets signed data from a signed message. - -#### Throws - -Error If data could not be extracted from the message - -#### Example - -```ts -const signedData = await EncryptionUtils.getSignedData('message'); -console.log('Signed data:', signedData); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `message` | `string` | Message. | - -#### Returns - -`Promise`\<`string`\> - -Signed data. - -*** - -### generateKeyPair() - -```ts -static generateKeyPair( - name: string, - email: string, -passphrase: string): Promise; -``` - -This function generates a key pair for encryption and decryption. - -#### Example - -```ts -const name = 'YOUR_NAME'; -const email = 'YOUR_EMAIL'; -const passphrase = 'YOUR_PASSPHRASE'; -const keyPair = await EncryptionUtils.generateKeyPair(name, email, passphrase); -console.log('Public key:', keyPair.publicKey); -``` - -#### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `name` | `string` | `undefined` | Name for the key pair. | -| `email` | `string` | `undefined` | Email for the key pair. | -| `passphrase` | `string` | `''` | Passphrase to encrypt the private key (optional, defaults to empty string). | - -#### Returns - -`Promise`\<`IKeyPair`\> - -Key pair generated. - -*** - -### encrypt() - -```ts -static encrypt(message: MessageDataType, publicKeys: string[]): Promise; -``` - -This function encrypts a message using the specified public keys. - -#### Example - -```ts -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); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `message` | `MessageDataType` | Message to encrypt. | -| `publicKeys` | `string`[] | Array of public keys to use for encryption. | - -#### Returns - -`Promise`\<`string`\> - -Message encrypted. - -*** - -### isEncrypted() - -```ts -static isEncrypted(message: string): boolean; -``` - -Verifies if a message appears to be encrypted with OpenPGP. - -#### Example - -```ts -const message = '-----BEGIN PGP MESSAGE-----...'; -const isEncrypted = EncryptionUtils.isEncrypted(message); - -if (isEncrypted) { - console.log('The message is encrypted with OpenPGP.'); -} else { - console.log('The message is not encrypted with OpenPGP.'); -} -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `message` | `string` | Message to verify. | - -#### Returns - -`boolean` - -`true` if the message appears to be encrypted, `false` if not. diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/EscrowClient.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/EscrowClient.md deleted file mode 100644 index bb4c04bcad..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/EscrowClient.md +++ /dev/null @@ -1,1502 +0,0 @@ -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`](/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. - -## Example - -###Using Signer - -####Using private key (backend) - -```ts -import { EscrowClient } 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 escrowClient = await EscrowClient.build(signer); -``` - -####Using Wagmi (frontend) - -```ts -import { useSigner } from 'wagmi'; -import { EscrowClient } from '@human-protocol/sdk'; - -const { data: signer } = useSigner(); -const escrowClient = await EscrowClient.build(signer); -``` - -###Using Provider - -```ts -import { EscrowClient } from '@human-protocol/sdk'; -import { JsonRpcProvider } from 'ethers'; - -const rpcUrl = 'YOUR_RPC_URL'; -const provider = new JsonRpcProvider(rpcUrl); -const escrowClient = await EscrowClient.build(provider); -``` - -## Extends - -- `BaseEthersClient` - -## Constructors - -### Constructor - -```ts -new EscrowClient(runner: ContractRunner, networkData: NetworkData): EscrowClient; -``` - -**EscrowClient constructor** - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | -| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the Escrow contract | - -#### Returns - -`EscrowClient` - -#### Overrides - -```ts -BaseEthersClient.constructor -``` - -## Methods - -### build() - -```ts -static build(runner: ContractRunner): Promise; -``` - -Creates an instance of EscrowClient from a Runner. - -#### Throws - -ErrorProviderDoesNotExist If the provider does not exist for the provided Signer - -#### Throws - -ErrorUnsupportedChainID If the network's chainId is not supported - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | - -#### Returns - -`Promise`\<`EscrowClient`\> - -An instance of EscrowClient - -*** - -### createEscrow() - -```ts -createEscrow( - tokenAddress: string, - jobRequesterId: string, -txOptions: Overrides): Promise; -``` - -This function creates an escrow contract that uses the token passed to pay oracle fees and reward workers. - -#### Throws - -ErrorInvalidTokenAddress If the token address is invalid - -#### Throws - -ErrorLaunchedEventIsNotEmitted If the LaunchedV2 event is not emitted - -#### Example - -> Need to have available stake. - -```ts -const tokenAddress = '0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4'; -const jobRequesterId = "job-requester-id"; -const escrowAddress = await escrowClient.createEscrow(tokenAddress, jobRequesterId); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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. - -*** - -### createFundAndSetupEscrow() - -```ts -createFundAndSetupEscrow( - tokenAddress: string, - amount: bigint, - jobRequesterId: string, - escrowConfig: IEscrowConfig, -txOptions: Overrides): Promise; -``` - -Creates, funds, and sets up a new escrow contract in a single transaction. - -#### 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 - -```ts -import { ethers } from 'ethers'; -import { ERC20__factory } from '@human-protocol/sdk'; - -const tokenAddress = '0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4'; -const amount = ethers.parseUnits('1000', 18); -const jobRequesterId = 'requester-123'; - -const token = ERC20__factory.connect(tokenAddress, signer); -await token.approve(escrowClient.escrowFactoryContract.target, amount); - -const escrowConfig = { - recordingOracle: '0xRecordingOracleAddress', - reputationOracle: '0xReputationOracleAddress', - exchangeOracle: '0xExchangeOracleAddress', - recordingOracleFee: 5n, - reputationOracleFee: 5n, - exchangeOracleFee: 5n, - manifest: 'https://example.com/manifest.json', - manifestHash: 'manifestHash-123', -}; - -const escrowAddress = await escrowClient.createFundAndSetupEscrow( - tokenAddress, - amount, - jobRequesterId, - escrowConfig -); -console.log('Escrow created at:', escrowAddress); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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` | Configuration parameters for escrow setup. | -| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | - -#### Returns - -`Promise`\<`string`\> - -Returns the address of the escrow created. - -*** - -### setup() - -```ts -setup( - escrowAddress: string, - escrowConfig: IEscrowConfig, -txOptions: Overrides): Promise; -``` - -This function sets up the parameters of the escrow. - -#### 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 - -#### Example - -> Only Job Launcher or admin can call it. - -```ts -const escrowAddress = '0x62dD51230A30401C455c8398d06F85e4EaB6309f'; -const escrowConfig = { - recordingOracle: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', - reputationOracle: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', - exchangeOracle: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', - recordingOracleFee: 10n, - reputationOracleFee: 10n, - exchangeOracleFee: 10n, - manifest: 'http://localhost/manifest.json', - manifestHash: 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079', -}; -await escrowClient.setup(escrowAddress, escrowConfig); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow to set up. | -| `escrowConfig` | `IEscrowConfig` | Escrow configuration parameters. | -| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | - -#### Returns - -`Promise`\<`void`\> - -*** - -### fund() - -```ts -fund( - escrowAddress: string, - amount: bigint, -txOptions: Overrides): Promise; -``` - -This function adds funds of the chosen token to the escrow. - -#### 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 } from 'ethers'; - -const amount = ethers.parseUnits('5', 'ether'); -await escrowClient.fund('0x62dD51230A30401C455c8398d06F85e4EaB6309f', amount); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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`\> - -*** - -### storeResults() - -#### Call Signature - -```ts -storeResults( - escrowAddress: string, - url: string, - hash: string, - fundsToReserve: bigint, -txOptions?: Overrides): Promise; -``` - -This function stores the results URL and hash. - -##### Throws - -ErrorInvalidEscrowAddressProvided If the escrow address is invalid - -##### Throws - -ErrorInvalidUrl If the URL is invalid - -##### Throws - -ErrorHashIsEmptyString If the hash is empty - -##### Throws - -ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory - -##### Throws - -ErrorStoreResultsVersion If using deprecated signature - -##### Example - -> Only Recording Oracle or admin can call it. - -```ts -import { ethers } from 'ethers'; - -await escrowClient.storeResults( - '0x62dD51230A30401C455c8398d06F85e4EaB6309f', - 'http://localhost/results.json', - 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079', - ethers.parseEther('10') -); -``` - -##### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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`\> - -#### Call Signature - -```ts -storeResults( - escrowAddress: string, - url: string, - hash: string, -txOptions?: Overrides): Promise; -``` - -This function stores the results URL and hash. - -##### Throws - -ErrorInvalidEscrowAddressProvided If the escrow address is invalid - -##### Throws - -ErrorInvalidUrl If the URL is invalid - -##### Throws - -ErrorHashIsEmptyString If the hash is empty - -##### Throws - -ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory - -##### Throws - -ErrorStoreResultsVersion If using deprecated signature - -##### Example - -> Only Recording Oracle or admin can call it. - -```ts -await escrowClient.storeResults( - '0x62dD51230A30401C455c8398d06F85e4EaB6309f', - 'http://localhost/results.json', - 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079' -); -``` - -##### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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`\> - -*** - -### complete() - -```ts -complete(escrowAddress: string, txOptions: Overrides): Promise; -``` - -This function sets the status of an escrow to completed. - -#### Throws - -ErrorInvalidEscrowAddressProvided If the escrow address is invalid - -#### Throws - -ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory - -#### Example - -> Only Recording Oracle or admin can call it. - -```ts -await escrowClient.complete('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | -| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | - -#### Returns - -`Promise`\<`void`\> - -*** - -### bulkPayOut() - -#### Call Signature - -```ts -bulkPayOut( - escrowAddress: string, - recipients: string[], - amounts: bigint[], - finalResultsUrl: string, - finalResultsHash: string, - txId: number, - forceComplete: boolean, -txOptions: Overrides): Promise; -``` - -This function pays out the amounts specified to the workers and sets the URL of the final results file. - -##### 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 - -##### Example - -> Only Reputation Oracle or admin can call it. - -```ts -import { ethers } from 'ethers'; - -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 -); -``` - -##### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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`\> - -#### Call Signature - -```ts -bulkPayOut( - escrowAddress: string, - recipients: string[], - amounts: bigint[], - finalResultsUrl: string, - finalResultsHash: string, - payoutId: string, - forceComplete: boolean, -txOptions: Overrides): Promise; -``` - -This function pays out the amounts specified to the workers and sets the URL of the final results file. - -##### 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 - -##### Example - -> Only Reputation Oracle or admin can call it. - -```ts -import { ethers } from 'ethers'; -import { v4 as uuidV4 } from 'uuid'; - -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 -); -``` - -##### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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`\> - -*** - -### cancel() - -```ts -cancel(escrowAddress: string, txOptions: Overrides): Promise; -``` - -This function cancels the specified escrow and sends the balance to the canceler. - -#### Throws - -ErrorInvalidEscrowAddressProvided If the escrow address is invalid - -#### Throws - -ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory - -#### Example - -> Only Job Launcher or admin can call it. - -```ts -await escrowClient.cancel('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow to cancel. | -| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | - -#### Returns - -`Promise`\<`void`\> - -*** - -### requestCancellation() - -```ts -requestCancellation(escrowAddress: string, txOptions: Overrides): Promise; -``` - -This function requests the cancellation of the specified escrow (moves status to ToCancel or finalizes if expired). - -#### Throws - -ErrorInvalidEscrowAddressProvided If the escrow address is invalid - -#### Throws - -ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory - -#### Example - -> Only Job Launcher or admin can call it. - -```ts -await escrowClient.requestCancellation('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow to request cancellation. | -| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | - -#### Returns - -`Promise`\<`void`\> - -*** - -### withdraw() - -```ts -withdraw( - escrowAddress: string, - tokenAddress: string, -txOptions: Overrides): Promise; -``` - -This function withdraws additional tokens in the escrow to the canceler. - -#### 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 - -#### Example - -> Only Job Launcher or admin can call it. - -```ts -const withdrawData = await escrowClient.withdraw( - '0x62dD51230A30401C455c8398d06F85e4EaB6309f', - '0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4' -); -console.log('Withdrawn amount:', withdrawData.withdrawnAmount); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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`\> - -Returns the escrow withdrawal data including transaction hash and withdrawal amount. - -*** - -### createBulkPayoutTransaction() - -```ts -createBulkPayoutTransaction( - escrowAddress: string, - recipients: string[], - amounts: bigint[], - finalResultsUrl: string, - finalResultsHash: string, - payoutId: string, - forceComplete: boolean, -txOptions: Overrides): Promise; -``` - -Creates a prepared transaction for bulk payout without immediately sending it. - -#### 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 - -#### Example - -> Only Reputation Oracle or admin can call it. - -```ts -import { ethers } from 'ethers'; -import { v4 as uuidV4 } from 'uuid'; - -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(); - -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); -``` - -#### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `escrowAddress` | `string` | `undefined` | Escrow address to payout. | -| `recipients` | `string`[] | `undefined` | Array of recipient addresses. | -| `amounts` | `bigint`[] | `undefined` | Array of amounts the recipients will receive. | -| `finalResultsUrl` | `string` | `undefined` | Final results file URL. | -| `finalResultsHash` | `string` | `undefined` | Final results file hash. | -| `payoutId` | `string` | `undefined` | 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`\> - -Returns object with raw transaction and nonce - -*** - -### getBalance() - -```ts -getBalance(escrowAddress: string): Promise; -``` - -This function returns the balance for a specified escrow address. - -#### Throws - -ErrorInvalidEscrowAddressProvided If the escrow address is invalid - -#### Throws - -ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory - -#### Example - -```ts -const balance = await escrowClient.getBalance('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Balance:', balance); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - -#### Returns - -`Promise`\<`bigint`\> - -Balance of the escrow in the token used to fund it. - -*** - -### getReservedFunds() - -```ts -getReservedFunds(escrowAddress: string): Promise; -``` - -This function returns the reserved funds for a specified escrow address. - -#### Throws - -ErrorInvalidEscrowAddressProvided If the escrow address is invalid - -#### Throws - -ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory - -#### Example - -```ts -const reservedFunds = await escrowClient.getReservedFunds('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Reserved funds:', reservedFunds); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - -#### Returns - -`Promise`\<`bigint`\> - -Reserved funds of the escrow in the token used to fund it. - -*** - -### getManifestHash() - -```ts -getManifestHash(escrowAddress: string): Promise; -``` - -This function returns the manifest file hash. - -#### Throws - -ErrorInvalidEscrowAddressProvided If the escrow address is invalid - -#### Throws - -ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory - -#### Example - -```ts -const manifestHash = await escrowClient.getManifestHash('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Manifest hash:', manifestHash); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - -#### Returns - -`Promise`\<`string`\> - -Hash of the manifest file content. - -*** - -### getManifest() - -```ts -getManifest(escrowAddress: string): Promise; -``` - -This function returns the manifest. Could be a URL or a JSON string. - -#### Throws - -ErrorInvalidEscrowAddressProvided If the escrow address is invalid - -#### Throws - -ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory - -#### Example - -```ts -const manifest = await escrowClient.getManifest('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Manifest:', manifest); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - -#### Returns - -`Promise`\<`string`\> - -Manifest URL or JSON string. - -*** - -### getResultsUrl() - -```ts -getResultsUrl(escrowAddress: string): Promise; -``` - -This function returns the results file URL. - -#### Throws - -ErrorInvalidEscrowAddressProvided If the escrow address is invalid - -#### Throws - -ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory - -#### Example - -```ts -const resultsUrl = await escrowClient.getResultsUrl('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Results URL:', resultsUrl); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - -#### Returns - -`Promise`\<`string`\> - -Results file URL. - -*** - -### getIntermediateResultsUrl() - -```ts -getIntermediateResultsUrl(escrowAddress: string): Promise; -``` - -This function returns the intermediate results file URL. - -#### Throws - -ErrorInvalidEscrowAddressProvided If the escrow address is invalid - -#### Throws - -ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory - -#### Example - -```ts -const intermediateResultsUrl = await escrowClient.getIntermediateResultsUrl('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Intermediate results URL:', intermediateResultsUrl); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - -#### Returns - -`Promise`\<`string`\> - -URL of the file that stores results from Recording Oracle. - -*** - -### getIntermediateResultsHash() - -```ts -getIntermediateResultsHash(escrowAddress: string): Promise; -``` - -This function returns the intermediate results hash. - -#### Throws - -ErrorInvalidEscrowAddressProvided If the escrow address is invalid - -#### Throws - -ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory - -#### Example - -```ts -const intermediateResultsHash = await escrowClient.getIntermediateResultsHash('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Intermediate results hash:', intermediateResultsHash); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - -#### Returns - -`Promise`\<`string`\> - -Hash of the intermediate results file content. - -*** - -### getTokenAddress() - -```ts -getTokenAddress(escrowAddress: string): Promise; -``` - -This function returns the token address used for funding the escrow. - -#### Throws - -ErrorInvalidEscrowAddressProvided If the escrow address is invalid - -#### Throws - -ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory - -#### Example - -```ts -const tokenAddress = await escrowClient.getTokenAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Token address:', tokenAddress); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - -#### Returns - -`Promise`\<`string`\> - -Address of the token used to fund the escrow. - -*** - -### getStatus() - -```ts -getStatus(escrowAddress: string): Promise; -``` - -This function returns the 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 { EscrowStatus } from '@human-protocol/sdk'; - -const status = await escrowClient.getStatus('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Status:', EscrowStatus[status]); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - -#### Returns - -`Promise`\<[`EscrowStatus`](../enumerations/EscrowStatus.md)\> - -Current status of the escrow. - -*** - -### getRecordingOracleAddress() - -```ts -getRecordingOracleAddress(escrowAddress: string): Promise; -``` - -This function returns the recording oracle address for a given escrow. - -#### Throws - -ErrorInvalidEscrowAddressProvided If the escrow address is invalid - -#### Throws - -ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory - -#### Example - -```ts -const oracleAddress = await escrowClient.getRecordingOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Recording Oracle address:', oracleAddress); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - -#### Returns - -`Promise`\<`string`\> - -Address of the Recording Oracle. - -*** - -### getJobLauncherAddress() - -```ts -getJobLauncherAddress(escrowAddress: string): Promise; -``` - -This function returns the job launcher address for a given escrow. - -#### Throws - -ErrorInvalidEscrowAddressProvided If the escrow address is invalid - -#### Throws - -ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory - -#### Example - -```ts -const jobLauncherAddress = await escrowClient.getJobLauncherAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Job Launcher address:', jobLauncherAddress); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - -#### Returns - -`Promise`\<`string`\> - -Address of the Job Launcher. - -*** - -### getReputationOracleAddress() - -```ts -getReputationOracleAddress(escrowAddress: string): Promise; -``` - -This function returns the reputation oracle address for a given escrow. - -#### Throws - -ErrorInvalidEscrowAddressProvided If the escrow address is invalid - -#### Throws - -ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory - -#### Example - -```ts -const oracleAddress = await escrowClient.getReputationOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Reputation Oracle address:', oracleAddress); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - -#### Returns - -`Promise`\<`string`\> - -Address of the Reputation Oracle. - -*** - -### getExchangeOracleAddress() - -```ts -getExchangeOracleAddress(escrowAddress: string): Promise; -``` - -This function returns the exchange oracle address for a given escrow. - -#### Throws - -ErrorInvalidEscrowAddressProvided If the escrow address is invalid - -#### Throws - -ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory - -#### Example - -```ts -const oracleAddress = await escrowClient.getExchangeOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Exchange Oracle address:', oracleAddress); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - -#### Returns - -`Promise`\<`string`\> - -Address of the Exchange Oracle. - -*** - -### getFactoryAddress() - -```ts -getFactoryAddress(escrowAddress: string): Promise; -``` - -This function returns the escrow factory address for a given escrow. - -#### Throws - -ErrorInvalidEscrowAddressProvided If the escrow address is invalid - -#### Throws - -ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory - -#### Example - -```ts -const factoryAddress = await escrowClient.getFactoryAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Factory address:', factoryAddress); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - -#### Returns - -`Promise`\<`string`\> - -Address of the escrow factory. diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/EscrowUtils.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/EscrowUtils.md deleted file mode 100644 index d76db1db5d..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/EscrowUtils.md +++ /dev/null @@ -1,306 +0,0 @@ -Utility class for escrow-related operations. - -## Example - -```ts -import { ChainId, EscrowUtils } from '@human-protocol/sdk'; - -const escrows = await EscrowUtils.getEscrows({ - chainId: ChainId.POLYGON_AMOY -}); -console.log('Escrows:', escrows); -``` - -## Methods - -### getEscrows() - -```ts -static getEscrows(filter: IEscrowsFilter, options?: SubgraphOptions): Promise; -``` - -This function returns an array of escrows based on the specified filter parameters. - -#### Throws - -ErrorInvalidAddress If any filter address is invalid - -#### Throws - -ErrorUnsupportedChainID If the chain ID is not supported - -#### Example - -```ts -import { ChainId, EscrowStatus } from '@human-protocol/sdk'; - -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); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `filter` | `IEscrowsFilter` | Filter parameters. | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - -#### Returns - -`Promise`\<`IEscrow`[]\> - -List of escrows that match the filter. - -*** - -### getEscrow() - -```ts -static getEscrow( - chainId: ChainId, - escrowAddress: string, -options?: SubgraphOptions): Promise; -``` - -This function returns the escrow data for a given address. - -> This uses Subgraph - -#### Throws - -ErrorUnsupportedChainID If the chain ID is not supported - -#### Throws - -ErrorInvalidAddress If the escrow address is invalid - -#### Example - -```ts -import { ChainId } from '@human-protocol/sdk'; - -const escrow = await EscrowUtils.getEscrow( - ChainId.POLYGON_AMOY, - "0x1234567890123456789012345678901234567890" -); -if (escrow) { - console.log('Escrow status:', escrow.status); -} -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `chainId` | `ChainId` | Network in which the escrow has been deployed | -| `escrowAddress` | `string` | Address of the escrow | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - -#### Returns - -`Promise`\<`IEscrow` \| `null`\> - -Escrow data or null if not found. - -*** - -### getStatusEvents() - -```ts -static getStatusEvents(filter: IStatusEventFilter, options?: SubgraphOptions): Promise; -``` - -This function returns the status events for a given set of networks within an optional date range. - -> This uses Subgraph - -#### Throws - -ErrorInvalidAddress If the launcher address is invalid - -#### Throws - -ErrorUnsupportedChainID If the chain ID is not supported - -#### Example - -```ts -import { ChainId, EscrowStatus } from '@human-protocol/sdk'; - -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); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `filter` | `IStatusEventFilter` | Filter parameters. | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - -#### Returns - -`Promise`\<`IStatusEvent`[]\> - -Array of status events with their corresponding statuses. - -*** - -### getPayouts() - -```ts -static getPayouts(filter: IPayoutFilter, options?: SubgraphOptions): Promise; -``` - -This function returns the payouts for a given set of networks. - -> This uses Subgraph - -#### Throws - -ErrorUnsupportedChainID If the chain ID is not supported - -#### Throws - -ErrorInvalidAddress If any filter address is invalid - -#### Example - -```ts -import { ChainId } 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:', payouts.length); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `filter` | `IPayoutFilter` | Filter parameters. | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - -#### Returns - -`Promise`\<`IPayout`[]\> - -List of payouts matching the filters. - -*** - -### getCancellationRefunds() - -```ts -static getCancellationRefunds(filter: ICancellationRefundFilter, options?: SubgraphOptions): Promise; -``` - -This function returns the cancellation refunds for a given set of networks. - -> This uses Subgraph - -#### 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 } from '@human-protocol/sdk'; - -const cancellationRefunds = await EscrowUtils.getCancellationRefunds({ - chainId: ChainId.POLYGON_AMOY, - escrowAddress: '0x1234567890123456789012345678901234567890', -}); -console.log('Cancellation refunds:', cancellationRefunds.length); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `filter` | `ICancellationRefundFilter` | Filter parameters. | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - -#### Returns - -`Promise`\<`ICancellationRefund`[]\> - -List of cancellation refunds matching the filters. - -*** - -### getCancellationRefund() - -```ts -static getCancellationRefund( - chainId: ChainId, - escrowAddress: string, -options?: SubgraphOptions): Promise; -``` - -This function returns the cancellation refund for a given escrow address. - -> This uses Subgraph - -#### Throws - -ErrorUnsupportedChainID If the chain ID is not supported - -#### Throws - -ErrorInvalidEscrowAddressProvided If the escrow address is invalid - -#### Example - -```ts -import { ChainId } from '@human-protocol/sdk'; - -const cancellationRefund = await EscrowUtils.getCancellationRefund( - ChainId.POLYGON_AMOY, - "0x1234567890123456789012345678901234567890" -); -if (cancellationRefund) { - console.log('Refund amount:', cancellationRefund.amount); -} -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `chainId` | `ChainId` | Network in which the escrow has been deployed | -| `escrowAddress` | `string` | Address of the escrow | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - -#### Returns - -`Promise`\<`ICancellationRefund` \| `null`\> - -Cancellation refund data or null if not found. diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/KVStoreClient.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/KVStoreClient.md deleted file mode 100644 index 0bef6d686a..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/KVStoreClient.md +++ /dev/null @@ -1,308 +0,0 @@ -## 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, 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); -``` - -**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 { JsonRpcProvider } from 'ethers'; - -const rpcUrl = 'YOUR_RPC_URL'; - -const provider = new JsonRpcProvider(rpcUrl); -const kvstoreClient = await KVStoreClient.build(provider); -``` - -## Extends - -- `BaseEthersClient` - -## Constructors - -### Constructor - -```ts -new KVStoreClient(runner: ContractRunner, networkData: NetworkData): KVStoreClient; -``` - -**KVStoreClient constructor** - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | -| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the KVStore contract | - -#### Returns - -`KVStoreClient` - -#### Overrides - -```ts -BaseEthersClient.constructor -``` - -## Methods - -### build() - -```ts -static build(runner: ContractRunner): Promise; -``` - -Creates an instance of KVStoreClient from a runner. - -#### Throws - -ErrorProviderDoesNotExist If the provider does not exist for the provided Signer - -#### Throws - -ErrorUnsupportedChainID 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); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | - -#### Returns - -`Promise`\<`KVStoreClient`\> - -An instance of KVStoreClient - -*** - -### set() - -```ts -set( - key: string, - value: string, -txOptions: Overrides): Promise; -``` - -This function sets a key-value pair associated with the address that submits the transaction. - -#### Throws - -ErrorKVStoreEmptyKey If the key is empty - -#### Throws - -Error If the transaction fails - -#### Example - -```ts -await kvstoreClient.set('Role', 'RecordingOracle'); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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`\> - -*** - -### setBulk() - -```ts -setBulk( - keys: string[], - values: string[], -txOptions: Overrides): Promise; -``` - -This function sets key-value pairs in bulk associated with the address that submits the transaction. - -#### 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 -const keys = ['role', 'webhook_url']; -const values = ['RecordingOracle', 'http://localhost']; -await kvstoreClient.setBulk(keys, values); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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`\> - -*** - -### setFileUrlAndHash() - -```ts -setFileUrlAndHash( - url: string, - urlKey: string, -txOptions: Overrides): Promise; -``` - -Sets a URL value for the address that submits the transaction, and its hash. - -#### Throws - -ErrorInvalidUrl If the URL is invalid - -#### Throws - -Error If the transaction fails - -#### Example - -```ts -await kvstoreClient.setFileUrlAndHash('example.com'); -await kvstoreClient.setFileUrlAndHash('linkedin.com/example', 'linkedin_url'); -``` - -#### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `url` | `string` | `undefined` | 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`\> - -*** - -### get() - -```ts -get(address: string, key: string): Promise; -``` - -Gets the value of a key-value pair in the contract. - -#### Throws - -ErrorKVStoreEmptyKey If the key is empty - -#### Throws - -ErrorInvalidAddress If the address is invalid - -#### Throws - -Error If the contract call fails - -#### Example - -```ts -const value = await kvstoreClient.get('0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', 'Role'); -console.log('Value:', value); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `address` | `string` | Address from which to get the key value. | -| `key` | `string` | Key to obtain the value. | - -#### Returns - -`Promise`\<`string`\> - -Value of the key. diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/KVStoreUtils.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/KVStoreUtils.md deleted file mode 100644 index de19745812..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/KVStoreUtils.md +++ /dev/null @@ -1,214 +0,0 @@ -Utility class for KVStore-related operations. - -## Example - -```ts -import { ChainId, KVStoreUtils } from '@human-protocol/sdk'; - -const kvStoreData = await KVStoreUtils.getKVStoreData( - ChainId.POLYGON_AMOY, - "0x1234567890123456789012345678901234567890" -); -console.log('KVStore data:', kvStoreData); -``` - -## Methods - -### getKVStoreData() - -```ts -static getKVStoreData( - chainId: ChainId, - address: string, -options?: SubgraphOptions): Promise; -``` - -This function returns the KVStore data for a given address. - -#### Throws - -ErrorUnsupportedChainID If the network's chainId is not supported - -#### Throws - -ErrorInvalidAddress If the address is invalid - -#### Example - -```ts -const kvStoreData = await KVStoreUtils.getKVStoreData( - ChainId.POLYGON_AMOY, - "0x1234567890123456789012345678901234567890" -); -console.log('KVStore data:', kvStoreData); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `chainId` | `ChainId` | Network in which the KVStore is deployed | -| `address` | `string` | Address of the KVStore | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - -#### Returns - -`Promise`\<`IKVStore`[]\> - -KVStore data - -*** - -### get() - -```ts -static get( - chainId: ChainId, - address: string, - key: string, -options?: SubgraphOptions): Promise; -``` - -Gets the value of a key-value pair in the KVStore using the subgraph. - -#### 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 -const value = await KVStoreUtils.get( - ChainId.POLYGON_AMOY, - '0x1234567890123456789012345678901234567890', - 'role' -); -console.log('Value:', value); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `chainId` | `ChainId` | 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/SubgraphOptions.md) | Optional configuration for subgraph requests. | - -#### Returns - -`Promise`\<`string`\> - -Value of the key. - -*** - -### getFileUrlAndVerifyHash() - -```ts -static getFileUrlAndVerifyHash( - chainId: ChainId, - address: string, - urlKey: string, -options?: SubgraphOptions): Promise; -``` - -Gets the URL value of the given entity, and verifies its hash. - -#### Throws - -ErrorInvalidAddress If the address is invalid - -#### Throws - -ErrorInvalidHash If the hash verification fails - -#### Throws - -Error If fetching URL or hash fails - -#### Example - -```ts -const url = await KVStoreUtils.getFileUrlAndVerifyHash( - ChainId.POLYGON_AMOY, - '0x1234567890123456789012345678901234567890' -); -console.log('Verified URL:', url); -``` - -#### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `chainId` | `ChainId` | `undefined` | Network in which the KVStore is deployed | -| `address` | `string` | `undefined` | Address from which to get the URL value. | -| `urlKey` | `string` | `'url'` | Configurable URL key. `url` by default. | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | `undefined` | Optional configuration for subgraph requests. | - -#### Returns - -`Promise`\<`string`\> - -URL value for the given address if it exists, and the content is valid - -*** - -### getPublicKey() - -```ts -static getPublicKey( - chainId: ChainId, - address: string, -options?: SubgraphOptions): Promise; -``` - -Gets the public key of the given entity, and verifies its hash. - -#### Throws - -ErrorInvalidAddress If the address is invalid - -#### Throws - -ErrorInvalidHash If the hash verification fails - -#### Throws - -Error If fetching the public key fails - -#### Example - -```ts -const publicKey = await KVStoreUtils.getPublicKey( - ChainId.POLYGON_AMOY, - '0x1234567890123456789012345678901234567890' -); -console.log('Public key:', publicKey); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `chainId` | `ChainId` | Network in which the KVStore is deployed | -| `address` | `string` | Address from which to get the public key. | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - -#### Returns - -`Promise`\<`string`\> - -Public key for the given address if it exists, and the content is valid diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/OperatorUtils.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/OperatorUtils.md deleted file mode 100644 index 0c2c6bd89e..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/OperatorUtils.md +++ /dev/null @@ -1,191 +0,0 @@ -Utility class for operator-related operations. - -## Example - -```ts -import { OperatorUtils, ChainId } from '@human-protocol/sdk'; - -const operator = await OperatorUtils.getOperator( - ChainId.POLYGON_AMOY, - '0x62dD51230A30401C455c8398d06F85e4EaB6309f' -); -console.log('Operator:', operator); -``` - -## Methods - -### getOperator() - -```ts -static getOperator( - chainId: ChainId, - address: string, -options?: SubgraphOptions): Promise; -``` - -This function returns the operator data for the given address. - -#### 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' -); -console.log('Operator:', operator); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `chainId` | `ChainId` | Network in which the operator is deployed | -| `address` | `string` | Operator address. | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - -#### Returns - -`Promise`\<`IOperator` \| `null`\> - -Returns the operator details or null if not found. - -*** - -### getOperators() - -```ts -static getOperators(filter: IOperatorsFilter, options?: SubgraphOptions): Promise; -``` - -This function returns all the operator details of the protocol. - -#### Throws - -ErrorUnsupportedChainID If the chain ID is not supported - -#### Example - -```ts -import { ChainId } from '@human-protocol/sdk'; - -const filter = { - chainId: ChainId.POLYGON_AMOY -}; -const operators = await OperatorUtils.getOperators(filter); -console.log('Operators:', operators.length); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `filter` | `IOperatorsFilter` | Filter for the operators. | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - -#### Returns - -`Promise`\<`IOperator`[]\> - -Returns an array with all the operator details. - -*** - -### getReputationNetworkOperators() - -```ts -static getReputationNetworkOperators( - chainId: ChainId, - address: string, - role?: string, -options?: SubgraphOptions): Promise; -``` - -Retrieves the reputation network operators of the specified address. - -#### 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' -); -console.log('Operators:', operators.length); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `chainId` | `ChainId` | Network in which the reputation network is deployed | -| `address` | `string` | Address of the reputation oracle. | -| `role?` | `string` | Role of the operator (optional). | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - -#### Returns - -`Promise`\<`IOperator`[]\> - -Returns an array of operator details. - -*** - -### getRewards() - -```ts -static getRewards( - chainId: ChainId, - slasherAddress: string, -options?: SubgraphOptions): Promise; -``` - -This function returns information about the rewards for a given slasher address. - -#### 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' -); -console.log('Rewards:', rewards.length); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `chainId` | `ChainId` | Network in which the rewards are deployed | -| `slasherAddress` | `string` | Slasher address. | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - -#### Returns - -`Promise`\<`IReward`[]\> - -Returns an array of Reward objects that contain the rewards earned by the user through slashing other users. diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StakingClient.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StakingClient.md deleted file mode 100644 index 8666045c7c..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StakingClient.md +++ /dev/null @@ -1,389 +0,0 @@ -## 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, 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); -``` - -**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 { JsonRpcProvider } from 'ethers'; - -const rpcUrl = 'YOUR_RPC_URL'; - -const provider = new JsonRpcProvider(rpcUrl); -const stakingClient = await StakingClient.build(provider); -``` - -## Extends - -- `BaseEthersClient` - -## Constructors - -### Constructor - -```ts -new StakingClient(runner: ContractRunner, networkData: NetworkData): StakingClient; -``` - -**StakingClient constructor** - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | -| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the Staking contract | - -#### Returns - -`StakingClient` - -#### Overrides - -```ts -BaseEthersClient.constructor -``` - -## Methods - -### build() - -```ts -static build(runner: ContractRunner): Promise; -``` - -Creates an instance of StakingClient from a Runner. - -#### Throws - -ErrorProviderDoesNotExist If the provider does not exist for the provided Signer - -#### Throws - -ErrorUnsupportedChainID 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); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | - -#### Returns - -`Promise`\<`StakingClient`\> - -An instance of StakingClient - -*** - -### approveStake() - -```ts -approveStake(amount: bigint, txOptions: Overrides): Promise; -``` - -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. - -#### Throws - -ErrorInvalidStakingValueType If the amount is not a bigint - -#### Throws - -ErrorInvalidStakingValueSign If the amount is negative - -#### Example - -```ts -import { ethers } from 'ethers'; - -const amount = ethers.parseUnits('5', 'ether'); //convert from ETH to WEI -await stakingClient.approveStake(amount); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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`\> - -*** - -### stake() - -```ts -stake(amount: bigint, txOptions: Overrides): Promise; -``` - -This function stakes a specified amount of tokens on a specific network. - -> `approveStake` must be called before - -#### Throws - -ErrorInvalidStakingValueType If the amount is not a bigint - -#### Throws - -ErrorInvalidStakingValueSign If the amount is negative - -#### Example - -```ts -import { ethers } from 'ethers'; - -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); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `amount` | `bigint` | Amount in WEI of tokens to stake. | -| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | - -#### Returns - -`Promise`\<`void`\> - -*** - -### unstake() - -```ts -unstake(amount: bigint, txOptions: Overrides): Promise; -``` - -This function unstakes tokens from staking contract. The unstaked tokens stay locked for a period of time. - -> Must have tokens available to unstake - -#### Throws - -ErrorInvalidStakingValueType If the amount is not a bigint - -#### Throws - -ErrorInvalidStakingValueSign If the amount is negative - -#### Example - -```ts -import { ethers } from 'ethers'; - -const amount = ethers.parseUnits('5', 'ether'); //convert from ETH to WEI -await stakingClient.unstake(amount); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `amount` | `bigint` | Amount in WEI of tokens to unstake. | -| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | - -#### Returns - -`Promise`\<`void`\> - -*** - -### withdraw() - -```ts -withdraw(txOptions: Overrides): Promise; -``` - -This function withdraws unstaked and non-locked tokens from staking contract to the user wallet. - -> Must have tokens available to withdraw - -#### Example - -```ts -await stakingClient.withdraw(); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | - -#### Returns - -`Promise`\<`void`\> - -*** - -### slash() - -```ts -slash( - slasher: string, - staker: string, - escrowAddress: string, - amount: bigint, -txOptions: Overrides): Promise; -``` - -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. - -#### 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 } from 'ethers'; - -const amount = ethers.parseUnits('5', 'ether'); //convert from ETH to WEI -await stakingClient.slash( - '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', - '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', - '0x62dD51230A30401C455c8398d06F85e4EaB6309f', - amount -); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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`\> - -*** - -### getStakerInfo() - -```ts -getStakerInfo(stakerAddress: string): Promise; -``` - -Retrieves comprehensive staking information for a staker. - -#### Throws - -ErrorInvalidStakerAddressProvided If the staker address is invalid - -#### Example - -```ts -const stakingInfo = await stakingClient.getStakerInfo('0xYourStakerAddress'); -console.log('Tokens staked:', stakingInfo.stakedAmount); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `stakerAddress` | `string` | The address of the staker. | - -#### Returns - -`Promise`\<`StakerInfo`\> - -Staking information for the staker diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StakingUtils.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StakingUtils.md deleted file mode 100644 index ada6158081..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StakingUtils.md +++ /dev/null @@ -1,104 +0,0 @@ -Utility class for Staking-related subgraph 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); -``` - -## Methods - -### getStaker() - -```ts -static getStaker( - chainId: ChainId, - stakerAddress: string, -options?: SubgraphOptions): Promise; -``` - -Gets staking info for a staker from the 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); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `chainId` | `ChainId` | Network in which the staking contract is deployed | -| `stakerAddress` | `string` | Address of the staker | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - -#### Returns - -`Promise`\<`IStaker`\> - -Staker info from subgraph - -*** - -### getStakers() - -```ts -static getStakers(filter: IStakersFilter, options?: SubgraphOptions): Promise; -``` - -Gets all stakers from the subgraph with filters, pagination and ordering. - -#### 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); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `filter` | `IStakersFilter` | Stakers filter with pagination and ordering | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - -#### Returns - -`Promise`\<`IStaker`[]\> - -Array of stakers diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StatisticsUtils.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StatisticsUtils.md deleted file mode 100644 index 88eb7c843c..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StatisticsUtils.md +++ /dev/null @@ -1,401 +0,0 @@ -Utility class for statistics-related operations. - -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. - -## Installation - -### npm -```bash -npm install @human-protocol/sdk -``` - -### yarn -```bash -yarn install @human-protocol/sdk -``` - -## Example - -```ts -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); -``` - -## Methods - -### getEscrowStatistics() - -```ts -static getEscrowStatistics( - networkData: NetworkData, - filter: IStatisticsFilter, -options?: SubgraphOptions): Promise; -``` - -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[]; -}; -``` - -#### Example - -```ts -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); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | -| `filter` | `IStatisticsFilter` | Statistics params with duration data | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - -#### Returns - -`Promise`\<`IEscrowStatistics`\> - -Escrow statistics data. - -*** - -### getWorkerStatistics() - -```ts -static getWorkerStatistics( - networkData: NetworkData, - filter: IStatisticsFilter, -options?: SubgraphOptions): Promise; -``` - -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[]; -}; -``` - -#### Example - -```ts -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); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | -| `filter` | `IStatisticsFilter` | Statistics params with duration data | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - -#### Returns - -`Promise`\<`IWorkerStatistics`\> - -Worker statistics data. - -*** - -### getPaymentStatistics() - -```ts -static getPaymentStatistics( - networkData: NetworkData, - filter: IStatisticsFilter, -options?: SubgraphOptions): Promise; -``` - -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[]; -}; -``` - -#### Example - -```ts -import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; - -const networkData = NETWORKS[ChainId.POLYGON_AMOY]; -const paymentStats = await StatisticsUtils.getPaymentStatistics(networkData); -console.log( - 'Payment statistics:', - paymentStats.dailyPaymentsData.map((p) => ({ - ...p, - totalAmountPaid: p.totalAmountPaid.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); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | -| `filter` | `IStatisticsFilter` | Statistics params with duration data | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - -#### Returns - -`Promise`\<`IPaymentStatistics`\> - -Payment statistics data. - -*** - -### getHMTStatistics() - -```ts -static getHMTStatistics(networkData: NetworkData, options?: SubgraphOptions): Promise; -``` - -This function returns the statistical data of HMToken. - -```ts -interface IHMTStatistics { - totalTransferAmount: bigint; - totalTransferCount: number; - totalHolders: number; -}; -``` - -#### Example - -```ts -import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; - -const networkData = NETWORKS[ChainId.POLYGON_AMOY]; -const hmtStats = await StatisticsUtils.getHMTStatistics(networkData); -console.log('HMT statistics:', { - ...hmtStats, - totalTransferAmount: hmtStats.totalTransferAmount.toString(), -}); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - -#### Returns - -`Promise`\<`IHMTStatistics`\> - -HMToken statistics data. - -*** - -### getHMTHolders() - -```ts -static getHMTHolders( - networkData: NetworkData, - params: IHMTHoldersParams, -options?: SubgraphOptions): Promise; -``` - -This function returns the holders of the HMToken with optional filters and ordering. - -#### Example - -```ts -import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; - -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(), -}))); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | -| `params` | `IHMTHoldersParams` | HMT Holders params with filters and ordering | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - -#### Returns - -`Promise`\<`IHMTHolder`[]\> - -List of HMToken holders. - -*** - -### getHMTDailyData() - -```ts -static getHMTDailyData( - networkData: NetworkData, - filter: IStatisticsFilter, -options?: SubgraphOptions): Promise; -``` - -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; -} -``` - -#### Example - -```ts -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 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); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | -| `filter` | `IStatisticsFilter` | Statistics params with duration data | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - -#### Returns - -`Promise`\<`IDailyHMT`[]\> - -Daily HMToken statistics data. diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StorageClient.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StorageClient.md deleted file mode 100644 index 9010fce608..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/StorageClient.md +++ /dev/null @@ -1,268 +0,0 @@ -## 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 - -```ts -new StorageClient(params: StorageParams, credentials?: StorageCredentials): StorageClient; -``` - -**Storage client constructor** - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `params` | [`StorageParams`](../type-aliases/StorageParams.md) | Cloud storage params | -| `credentials?` | [`StorageCredentials`](../type-aliases/StorageCredentials.md) | Optional. Cloud storage access data. If credentials are not provided - use anonymous access to the bucket | - -#### Returns - -`StorageClient` - -## Methods - -### ~~downloadFiles()~~ - -```ts -downloadFiles(keys: string[], bucket: string): Promise; -``` - -This function downloads files from a bucket. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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'); -``` - -*** - -### ~~downloadFileFromUrl()~~ - -```ts -static downloadFileFromUrl(url: string): Promise; -``` - -This function downloads files from a URL. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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'); -``` - -*** - -### ~~uploadFiles()~~ - -```ts -uploadFiles(files: any[], bucket: string): Promise; -``` - -This function uploads files to a bucket. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `files` | `any`[] | Array of objects to upload serialized into JSON. | -| `bucket` | `string` | Bucket name. | - -#### Returns - -`Promise`\<[`UploadFile`](../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'); -``` - -*** - -### ~~bucketExists()~~ - -```ts -bucketExists(bucket: string): Promise; -``` - -This function checks if a bucket exists. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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'); -``` - -*** - -### ~~listObjects()~~ - -```ts -listObjects(bucket: string): Promise; -``` - -This function lists all file names contained in the bucket. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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'); -``` diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/TransactionUtils.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/TransactionUtils.md deleted file mode 100644 index 6699536567..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/[object Object]/classes/TransactionUtils.md +++ /dev/null @@ -1,186 +0,0 @@ -Utility class for transaction-related operations. - -## Example - -```ts -import { TransactionUtils, ChainId } from '@human-protocol/sdk'; - -const transaction = await TransactionUtils.getTransaction( - ChainId.POLYGON_AMOY, - '0x62dD51230A30401C455c8398d06F85e4EaB6309f' -); -console.log('Transaction:', transaction); -``` - -## Methods - -### getTransaction() - -```ts -static getTransaction( - chainId: ChainId, - hash: string, -options?: SubgraphOptions): Promise; -``` - -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; -}; -``` - -#### 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_AMOY, - '0x62dD51230A30401C455c8398d06F85e4EaB6309f' -); -console.log('Transaction:', transaction); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `chainId` | `ChainId` | The chain ID. | -| `hash` | `string` | The transaction hash. | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - -#### Returns - -`Promise`\<`ITransaction` \| `null`\> - -Returns the transaction details or null if not found. - -*** - -### getTransactions() - -```ts -static getTransactions(filter: ITransactionsFilter, options?: SubgraphOptions): Promise; -``` - -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[]; -}; -``` - -#### 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 = { - chainId: ChainId.POLYGON_AMOY, - 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); -console.log('Transactions:', transactions.length); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `filter` | `ITransactionsFilter` | Filter for the transactions. | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - -#### Returns - -`Promise`\<`ITransaction`[]\> - -Returns an array with all the transaction details. diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/enumerations/EscrowStatus.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/enumerations/EscrowStatus.md deleted file mode 100644 index 0dfa358f82..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/[object Object]/enumerations/EscrowStatus.md +++ /dev/null @@ -1,13 +0,0 @@ -Enum for escrow statuses. - -## Enumeration Members - -| Enumeration Member | Value | Description | -| ------ | ------ | ------ | -| `Launched` | `0` | Escrow is launched. | -| `Pending` | `1` | Escrow is funded, and waiting for the results to be submitted. | -| `Partial` | `2` | Escrow is partially paid out. | -| `Paid` | `3` | Escrow is fully paid. | -| `Complete` | `4` | Escrow is finished. | -| `Cancelled` | `5` | Escrow is cancelled. | -| `ToCancel` | `6` | Escrow is cancelled. | diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/interfaces/SubgraphOptions.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/interfaces/SubgraphOptions.md deleted file mode 100644 index 3674ec4564..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/[object Object]/interfaces/SubgraphOptions.md +++ /dev/null @@ -1,9 +0,0 @@ -Configuration options for subgraph requests with retry logic. - -## Properties - -| Property | Type | Description | -| ------ | ------ | ------ | -| `maxRetries?` | `number` | Maximum number of retry attempts | -| `baseDelay?` | `number` | Base delay between retries in milliseconds | -| `indexerId?` | `string` | Optional indexer identifier. When provided, requests target `{gateway}/deployments/id//indexers/id/`. | diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/NetworkData.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/NetworkData.md deleted file mode 100644 index 194d6a4843..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/NetworkData.md +++ /dev/null @@ -1,115 +0,0 @@ -```ts -type NetworkData = object; -``` - -Network data - -## Properties - -### chainId - -```ts -chainId: number; -``` - -Network chain id - -*** - -### title - -```ts -title: string; -``` - -Network title - -*** - -### scanUrl - -```ts -scanUrl: string; -``` - -Network scanner URL - -*** - -### hmtAddress - -```ts -hmtAddress: string; -``` - -HMT Token contract address - -*** - -### factoryAddress - -```ts -factoryAddress: string; -``` - -Escrow Factory contract address - -*** - -### stakingAddress - -```ts -stakingAddress: string; -``` - -Staking contract address - -*** - -### kvstoreAddress - -```ts -kvstoreAddress: string; -``` - -KVStore contract address - -*** - -### subgraphUrl - -```ts -subgraphUrl: string; -``` - -Subgraph URL - -*** - -### subgraphUrlApiKey - -```ts -subgraphUrlApiKey: string; -``` - -Subgraph URL API key - -*** - -### oldSubgraphUrl - -```ts -oldSubgraphUrl: string; -``` - -Old subgraph URL - -*** - -### oldFactoryAddress - -```ts -oldFactoryAddress: string; -``` - -Old Escrow Factory contract address diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/StorageCredentials.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/StorageCredentials.md deleted file mode 100644 index 8e09ad3813..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/StorageCredentials.md +++ /dev/null @@ -1,29 +0,0 @@ -```ts -readonly type StorageCredentials = object; -``` - -AWS/GCP cloud storage access data - -## Deprecated - -StorageClient is deprecated. Use Minio.Client directly. - -## Properties - -### ~~accessKey~~ - -```ts -accessKey: string; -``` - -Access Key - -*** - -### ~~secretKey~~ - -```ts -secretKey: string; -``` - -Secret Key diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/StorageParams.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/StorageParams.md deleted file mode 100644 index fa3da8ba8e..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/StorageParams.md +++ /dev/null @@ -1,47 +0,0 @@ -```ts -type StorageParams = object; -``` - -## Deprecated - -StorageClient is deprecated. Use Minio.Client directly. - -## Properties - -### ~~endPoint~~ - -```ts -endPoint: string; -``` - -Request endPoint - -*** - -### ~~useSSL~~ - -```ts -useSSL: boolean; -``` - -Enable secure (HTTPS) access. Default value set to false - -*** - -### ~~region?~~ - -```ts -optional region: string; -``` - -Region - -*** - -### ~~port?~~ - -```ts -optional port: number; -``` - -TCP/IP port number. Default value set to 80 for HTTP and 443 for HTTPs diff --git a/packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/UploadFile.md b/packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/UploadFile.md deleted file mode 100644 index 349fbb64a9..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/[object Object]/type-aliases/UploadFile.md +++ /dev/null @@ -1,35 +0,0 @@ -```ts -readonly type UploadFile = object; -``` - -Upload file data - -## Properties - -### key - -```ts -key: string; -``` - -Uploaded object key - -*** - -### url - -```ts -url: string; -``` - -Uploaded object URL - -*** - -### hash - -```ts -hash: string; -``` - -Hash of uploaded object key diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/README.md b/packages/sdk/typescript/human-protocol-sdk/docs/README.md index 90a6f9d669..095ebdd9b5 100644 --- a/packages/sdk/typescript/human-protocol-sdk/docs/README.md +++ b/packages/sdk/typescript/human-protocol-sdk/docs/README.md @@ -14,8 +14,8 @@ - [StakingClient](classes/StakingClient.md) - [StakingUtils](classes/StakingUtils.md) - [StatisticsUtils](classes/StatisticsUtils.md) -- [~~StorageClient~~](classes/StorageClient.md) - [TransactionUtils](classes/TransactionUtils.md) +- [WorkerUtils](classes/WorkerUtils.md) ## Interfaces @@ -23,7 +23,5 @@ ## Type Aliases -- [~~StorageCredentials~~](type-aliases/StorageCredentials.md) -- [~~StorageParams~~](type-aliases/StorageParams.md) -- [UploadFile](type-aliases/UploadFile.md) +- [MessageDataType](type-aliases/MessageDataType.md) - [NetworkData](type-aliases/NetworkData.md) diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/Encryption.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/Encryption.md index 5695eecb6f..1c7c69adbc 100644 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/Encryption.md +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/Encryption.md @@ -14,8 +14,6 @@ new Encryption(privateKey: PrivateKey): Encryption; Constructor for the Encryption class. -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `privateKey` | `PrivateKey` | The private key. | @@ -36,18 +34,6 @@ static build(privateKeyArmored: string, passphrase?: string): Promise; This function signs and encrypts a message using the private key used to initialize the client and the specified public keys. -#### Example - -```ts -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); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | -| `message` | `MessageDataType` | Message to sign and encrypt. | +| `message` | [`MessageDataType`](../type-aliases/MessageDataType.md) | Message to sign and encrypt. | | `publicKeys` | `string`[] | Array of public keys to use for encryption. | #### Returns @@ -93,6 +77,18 @@ console.log('Encrypted message:', resultMessage); |------|-------------| | `string` | Message signed and encrypted. | +???+ example "Example" + + ```ts + 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); + ``` + + *** ### decrypt() @@ -103,23 +99,6 @@ decrypt(message: string, publicKey?: string): Promise>` | Message decrypted. | +#### Throws + +| Type | Description | +|------|-------------| +| `Error` | If signature could not be verified when public key is provided | + +???+ example "Example" + + ```ts + const publicKey = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; + + const resultMessage = await encryption.decrypt('message', publicKey); + console.log('Decrypted message:', resultMessage); + ``` + + *** ### sign() @@ -141,15 +136,6 @@ sign(message: string): Promise; This function signs a message using the private key used to initialize the client. -#### Example - -```ts -const resultMessage = await encryption.sign('message'); -console.log('Signed message:', resultMessage); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `message` | `string` | Message to sign. | @@ -159,3 +145,11 @@ console.log('Signed message:', resultMessage); | Type | Description | |------|-------------| | `string` | Message signed. | + +???+ example "Example" + + ```ts + const resultMessage = await encryption.sign('message'); + console.log('Signed message:', resultMessage); + ``` + diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/EncryptionUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/EncryptionUtils.md index e9cae435f0..0229a249c6 100644 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/EncryptionUtils.md +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/EncryptionUtils.md @@ -1,15 +1,5 @@ Utility class for encryption-related operations. -## Example - -```ts -import { EncryptionUtils } from '@human-protocol/sdk'; - -const publicKey = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; -const isValid = await EncryptionUtils.verify('message', publicKey); -console.log('Signature valid:', isValid); -``` - ## Methods ### verify() @@ -20,16 +10,6 @@ static verify(message: string, publicKey: string): Promise; This function verifies the signature of a signed message using the public key. -#### Example - -```ts -const publicKey = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; -const result = await EncryptionUtils.verify('message', publicKey); -console.log('Verification result:', result); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `message` | `string` | Message to verify. | @@ -41,6 +21,17 @@ console.log('Verification result:', result); |------|-------------| | `boolean` | True if verified. False if not verified. | +???+ example "Example" + + ```ts + import { EncryptionUtils } from '@human-protocol/sdk'; + + const publicKey = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; + const result = await EncryptionUtils.verify('message', publicKey); + console.log('Verification result:', result); + ``` + + *** ### getSignedData() @@ -51,21 +42,6 @@ static getSignedData(message: string): Promise; This function gets signed data from a signed message. -#### Throws - -| Type | Description | -|------|-------------| -| `Error` | If data could not be extracted from the message | - -#### Example - -```ts -const signedData = await EncryptionUtils.getSignedData('message'); -console.log('Signed data:', signedData); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `message` | `string` | Message. | @@ -76,6 +52,22 @@ console.log('Signed data:', signedData); |------|-------------| | `string` | Signed data. | +#### Throws + +| Type | Description | +|------|-------------| +| `Error` | If data could not be extracted from the message | + +???+ example "Example" + + ```ts + import { EncryptionUtils } from '@human-protocol/sdk'; + + const signedData = await EncryptionUtils.getSignedData('message'); + console.log('Signed data:', signedData); + ``` + + *** ### generateKeyPair() @@ -89,18 +81,6 @@ passphrase: string): Promise; This function generates a key pair for encryption and decryption. -#### Example - -```ts -const name = 'YOUR_NAME'; -const email = 'YOUR_EMAIL'; -const passphrase = 'YOUR_PASSPHRASE'; -const keyPair = await EncryptionUtils.generateKeyPair(name, email, passphrase); -console.log('Public key:', keyPair.publicKey); -``` - -#### Parameters - | Parameter | Type | Default value | Description | | ------ | ------ | ------ | ------ | | `name` | `string` | `undefined` | Name for the key pair. | @@ -113,6 +93,19 @@ console.log('Public key:', keyPair.publicKey); |------|-------------| | `IKeyPair` | Key pair generated. | +???+ example "Example" + + ```ts + import { EncryptionUtils } from '@human-protocol/sdk'; + + const name = 'YOUR_NAME'; + const email = 'YOUR_EMAIL'; + const passphrase = 'YOUR_PASSPHRASE'; + const keyPair = await EncryptionUtils.generateKeyPair(name, email, passphrase); + console.log('Public key:', keyPair.publicKey); + ``` + + *** ### encrypt() @@ -123,21 +116,9 @@ static encrypt(message: MessageDataType, publicKeys: string[]): Promise; This function encrypts a message using the specified public keys. -#### Example - -```ts -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); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | -| `message` | `MessageDataType` | Message to encrypt. | +| `message` | [`MessageDataType`](../type-aliases/MessageDataType.md) | Message to encrypt. | | `publicKeys` | `string`[] | Array of public keys to use for encryption. | #### Returns @@ -146,6 +127,19 @@ console.log('Encrypted message:', encryptedMessage); |------|-------------| | `string` | Message encrypted. | +???+ example "Example" + + ```ts + import { EncryptionUtils } from '@human-protocol/sdk'; + + 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); + ``` + + *** ### isEncrypted() @@ -156,21 +150,6 @@ static isEncrypted(message: string): boolean; Verifies if a message appears to be encrypted with OpenPGP. -#### Example - -```ts -const message = '-----BEGIN PGP MESSAGE-----...'; -const isEncrypted = EncryptionUtils.isEncrypted(message); - -if (isEncrypted) { - console.log('The message is encrypted with OpenPGP.'); -} else { - console.log('The message is not encrypted with OpenPGP.'); -} -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `message` | `string` | Message to verify. | @@ -180,3 +159,19 @@ if (isEncrypted) { | Type | Description | |------|-------------| | `boolean` | `true` if the message appears to be encrypted, `false` if not. | + +???+ example "Example" + + ```ts + import { EncryptionUtils } from '@human-protocol/sdk'; + + const message = '-----BEGIN PGP MESSAGE-----...'; + const isEncrypted = EncryptionUtils.isEncrypted(message); + + if (isEncrypted) { + console.log('The message is encrypted with OpenPGP.'); + } else { + console.log('The message is not encrypted with OpenPGP.'); + } + ``` + diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowClient.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowClient.md index 61d1300ec9..e14764d015 100644 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowClient.md +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowClient.md @@ -1,4 +1,4 @@ -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`](/ts/classes/EscrowClient/#build) method. @@ -61,8 +61,6 @@ new EscrowClient(runner: ContractRunner, networkData: NetworkData): EscrowClient **EscrowClient constructor** -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | @@ -88,15 +86,6 @@ static build(runner: ContractRunner): Promise; Creates an instance of EscrowClient from a Runner. -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorProviderDoesNotExist` | If the provider does not exist for the provided Signer | -| `ErrorUnsupportedChainID` | If the network's chainId is not supported | - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | @@ -107,6 +96,13 @@ Creates an instance of EscrowClient from a Runner. |------|-------------| | `EscrowClient` | An instance of EscrowClient | +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorProviderDoesNotExist` | If the provider does not exist for the provided Signer | +| `ErrorUnsupportedChainID` | If the network's chainId is not supported | + *** ### createEscrow() @@ -119,25 +115,8 @@ txOptions: Overrides): Promise; ``` This function creates an escrow contract that uses the token passed to pay oracle fees and reward workers. - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidTokenAddress` | If the token address is invalid | -| `ErrorLaunchedEventIsNotEmitted` | If the LaunchedV2 event is not emitted | - -#### Example - -> Need to have available stake. - -```ts -const tokenAddress = '0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4'; -const jobRequesterId = "job-requester-id"; -const escrowAddress = await escrowClient.createEscrow(tokenAddress, jobRequesterId); -``` - -#### Parameters +!!! note + Need to have available stake. | Parameter | Type | Description | | ------ | ------ | ------ | @@ -151,6 +130,22 @@ const escrowAddress = await escrowClient.createEscrow(tokenAddress, jobRequester |------|-------------| | `string` | Returns the address of the escrow created. | +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidTokenAddress` | If the token address is invalid | +| `ErrorLaunchedEventIsNotEmitted` | If the LaunchedV2 event is not emitted | + +???+ example "Example" + + ```ts + const tokenAddress = '0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4'; + const jobRequesterId = "job-requester-id"; + const escrowAddress = await escrowClient.createEscrow(tokenAddress, jobRequesterId); + ``` + + *** ### createFundAndSetupEscrow() @@ -166,6 +161,20 @@ txOptions: Overrides): Promise; Creates, funds, and sets up a new escrow contract in a single transaction. +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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` | Configuration parameters for escrow setup. | +| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + +#### Returns + +| Type | Description | +|------|-------------| +| `string` | Returns the address of the escrow created. | + #### Throws | Type | Description | @@ -180,54 +189,39 @@ Creates, funds, and sets up a new escrow contract in a single transaction. | `ErrorHashIsEmptyString` | If the manifest hash is empty | | `ErrorLaunchedEventIsNotEmitted` | If the LaunchedV2 event is not emitted | -#### Example +???+ example "Example" + + ```ts + import { ethers } from 'ethers'; + import { ERC20__factory } from '@human-protocol/sdk'; + + const tokenAddress = '0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4'; + const amount = ethers.parseUnits('1000', 18); + const jobRequesterId = 'requester-123'; + + const token = ERC20__factory.connect(tokenAddress, signer); + await token.approve(escrowClient.escrowFactoryContract.target, amount); + + const escrowConfig = { + recordingOracle: '0xRecordingOracleAddress', + reputationOracle: '0xReputationOracleAddress', + exchangeOracle: '0xExchangeOracleAddress', + recordingOracleFee: 5n, + reputationOracleFee: 5n, + exchangeOracleFee: 5n, + manifest: 'https://example.com/manifest.json', + manifestHash: 'manifestHash-123', + }; + + const escrowAddress = await escrowClient.createFundAndSetupEscrow( + tokenAddress, + amount, + jobRequesterId, + escrowConfig + ); + console.log('Escrow created at:', escrowAddress); + ``` -```ts -import { ethers } from 'ethers'; -import { ERC20__factory } from '@human-protocol/sdk'; - -const tokenAddress = '0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4'; -const amount = ethers.parseUnits('1000', 18); -const jobRequesterId = 'requester-123'; - -const token = ERC20__factory.connect(tokenAddress, signer); -await token.approve(escrowClient.escrowFactoryContract.target, amount); - -const escrowConfig = { - recordingOracle: '0xRecordingOracleAddress', - reputationOracle: '0xReputationOracleAddress', - exchangeOracle: '0xExchangeOracleAddress', - recordingOracleFee: 5n, - reputationOracleFee: 5n, - exchangeOracleFee: 5n, - manifest: 'https://example.com/manifest.json', - manifestHash: 'manifestHash-123', -}; - -const escrowAddress = await escrowClient.createFundAndSetupEscrow( - tokenAddress, - amount, - jobRequesterId, - escrowConfig -); -console.log('Escrow created at:', escrowAddress); -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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` | Configuration parameters for escrow setup. | -| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | - -#### Returns - -| Type | Description | -|------|-------------| -| `string` | Returns the address of the escrow created. | *** @@ -242,11 +236,27 @@ txOptions: Overrides): Promise; This function sets up the parameters of the escrow. +!!! note + Only Job Launcher or admin can call it. + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow to set up. | +| `escrowConfig` | `IEscrowConfig` | Escrow configuration parameters. | +| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + +#### Returns + +| Type | Description | +|------|-------------| +| `void` | #### Throws | + +ErrorInvalidRecordingOracleAddressProvided If the recording oracle address is invalid + #### Throws | Type | Description | |------|-------------| -| `ErrorInvalidRecordingOracleAddressProvided` | If the recording oracle address is invalid | | `ErrorInvalidReputationOracleAddressProvided` | If the reputation oracle address is invalid | | `ErrorInvalidExchangeOracleAddressProvided` | If the exchange oracle address is invalid | | `ErrorAmountMustBeGreaterThanZero` | If any oracle fee is less than or equal to zero | @@ -256,82 +266,125 @@ This function sets up the parameters of the escrow. | `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | | `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | -#### Example +???+ example "Example" + + ```ts + const escrowAddress = '0x62dD51230A30401C455c8398d06F85e4EaB6309f'; + const escrowConfig = { + recordingOracle: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', + reputationOracle: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', + exchangeOracle: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', + recordingOracleFee: 10n, + reputationOracleFee: 10n, + exchangeOracleFee: 10n, + manifest: 'http://localhost/manifest.json', + manifestHash: 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079', + }; + await escrowClient.setup(escrowAddress, escrowConfig); + ``` -> Only Job Launcher or admin can call it. + +*** + +### fund() ```ts -const escrowAddress = '0x62dD51230A30401C455c8398d06F85e4EaB6309f'; -const escrowConfig = { - recordingOracle: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', - reputationOracle: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', - exchangeOracle: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', - recordingOracleFee: 10n, - reputationOracleFee: 10n, - exchangeOracleFee: 10n, - manifest: 'http://localhost/manifest.json', - manifestHash: 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079', -}; -await escrowClient.setup(escrowAddress, escrowConfig); +fund( + escrowAddress: string, + amount: bigint, +txOptions: Overrides): Promise; ``` -#### Parameters +This function adds funds of the chosen token to the escrow. | Parameter | Type | Description | | ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow to set up. | -| `escrowConfig` | `IEscrowConfig` | Escrow configuration 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 | Type | Description | |------|-------------| -| `void` | *** | +| `void` | #### Throws | -### fund() - -```ts -fund( - escrowAddress: string, - amount: bigint, -txOptions: Overrides): Promise; -``` - -This function adds funds of the chosen token to the escrow. +ErrorInvalidEscrowAddressProvided If the escrow address is invalid #### Throws | Type | Description | |------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | | `ErrorAmountMustBeGreaterThanZero` | If the amount is less than or equal to zero | | `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | -#### Example +???+ example "Example" -```ts -import { ethers } from 'ethers'; + ```ts + import { ethers } from 'ethers'; + + const amount = ethers.parseUnits('5', 'ether'); + await escrowClient.fund('0x62dD51230A30401C455c8398d06F85e4EaB6309f', amount); + ``` -const amount = ethers.parseUnits('5', 'ether'); -await escrowClient.fund('0x62dD51230A30401C455c8398d06F85e4EaB6309f', amount); -``` -#### Parameters +*** -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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). | +### storeResults() -#### Returns +Stores the result URL and result hash for an escrow. + +!!! note + Only Recording Oracle or admin can call it. + +This method has two overloads: +- `storeResults(escrowAddress, url, hash, txOptions?)` - Without funds to reserve +- `storeResults(escrowAddress, url, hash, fundsToReserve, txOptions?)` - With funds to reserve + +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). + +The escrow address. + +The URL containing the final results. May be empty only when `fundsToReserve` is `0n`. + +The hash of the results payload. + +Optional amount of funds to reserve (when using second overload). + +Optional transaction overrides. + +#### Throws | Type | Description | |------|-------------| -| `void` | *** | +| `ErrorInvalidEscrowAddressProvided` | If the provided escrow address is invalid. | +| `ErrorInvalidUrl` | If the URL format is invalid. | +| `ErrorHashIsEmptyString` | If the hash is empty and empty values are not allowed. | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow does not exist in the factory. | +| `ErrorStoreResultsVersion` | If the contract supports only the deprecated signature. | -### storeResults() +#### Example +Without funds to reserve: +```ts +await escrowClient.storeResults( + '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + 'https://example.com/results.json', + '0xHASH123' +); +``` + +With funds to reserve: +```ts +import { ethers } from 'ethers'; + +await escrowClient.storeResults( + '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + 'https://example.com/results.json', + '0xHASH123', + ethers.parseEther('5') +); +``` #### Call Signature @@ -340,61 +393,77 @@ storeResults( escrowAddress: string, url: string, hash: string, - fundsToReserve: bigint, txOptions?: Overrides): Promise; ``` -This function stores the results URL and hash. +Stores the result URL and result hash for an escrow. + +!!! note + Only Recording Oracle or admin can call it. + +This method has two overloads: +- `storeResults(escrowAddress, url, hash, txOptions?)` - Without funds to reserve +- `storeResults(escrowAddress, url, hash, fundsToReserve, txOptions?)` - With funds to reserve + +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). + +##### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | The escrow address. | +| `url` | `string` | The URL containing the final results. May be empty only when `fundsToReserve` is `0n`. | +| `hash` | `string` | The hash of the results payload. | +| `txOptions?` | `Overrides` | Optional transaction overrides. | + +##### Returns + +`Promise`\<`void`\> ##### Throws -ErrorInvalidEscrowAddressProvided If the escrow address is invalid +ErrorInvalidEscrowAddressProvided If the provided escrow address is invalid. ##### Throws -ErrorInvalidUrl If the URL is invalid +ErrorInvalidUrl If the URL format is invalid. ##### Throws -ErrorHashIsEmptyString If the hash is empty +ErrorHashIsEmptyString If the hash is empty and empty values are not allowed. ##### Throws -ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory +ErrorEscrowAddressIsNotProvidedByFactory If the escrow does not exist in the factory. ##### Throws -ErrorStoreResultsVersion If using deprecated signature +ErrorStoreResultsVersion If the contract supports only the deprecated signature. -##### Example +##### Examples -> Only Recording Oracle or admin can call it. +Without funds to reserve: +```ts +await escrowClient.storeResults( + '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + 'https://example.com/results.json', + '0xHASH123' +); +``` +With funds to reserve: ```ts import { ethers } from 'ethers'; await escrowClient.storeResults( '0x62dD51230A30401C455c8398d06F85e4EaB6309f', - 'http://localhost/results.json', - 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079', - ethers.parseEther('10') + 'https://example.com/results.json', + '0xHASH123', + ethers.parseEther('5') ); ``` -##### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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`\> - #### Call Signature ```ts @@ -402,55 +471,78 @@ storeResults( escrowAddress: string, url: string, hash: string, + fundsToReserve: bigint, txOptions?: Overrides): Promise; ``` -This function stores the results URL and hash. +Stores the result URL and result hash for an escrow. -##### Throws +!!! note + Only Recording Oracle or admin can call it. -ErrorInvalidEscrowAddressProvided If the escrow address is invalid +This method has two overloads: +- `storeResults(escrowAddress, url, hash, txOptions?)` - Without funds to reserve +- `storeResults(escrowAddress, url, hash, fundsToReserve, txOptions?)` - With funds to reserve + +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). + +##### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | The escrow address. | +| `url` | `string` | The URL containing the final results. May be empty only when `fundsToReserve` is `0n`. | +| `hash` | `string` | The hash of the results payload. | +| `fundsToReserve` | `bigint` | Optional amount of funds to reserve (when using second overload). | +| `txOptions?` | `Overrides` | Optional transaction overrides. | + +##### Returns + +`Promise`\<`void`\> ##### Throws -ErrorInvalidUrl If the URL is invalid +ErrorInvalidEscrowAddressProvided If the provided escrow address is invalid. ##### Throws -ErrorHashIsEmptyString If the hash is empty +ErrorInvalidUrl If the URL format is invalid. ##### Throws -ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory +ErrorHashIsEmptyString If the hash is empty and empty values are not allowed. ##### Throws -ErrorStoreResultsVersion If using deprecated signature +ErrorEscrowAddressIsNotProvidedByFactory If the escrow does not exist in the factory. -##### Example +##### Throws -> Only Recording Oracle or admin can call it. +ErrorStoreResultsVersion If the contract supports only the deprecated signature. + +##### Examples +Without funds to reserve: ```ts await escrowClient.storeResults( '0x62dD51230A30401C455c8398d06F85e4EaB6309f', - 'http://localhost/results.json', - 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079' + 'https://example.com/results.json', + '0xHASH123' ); ``` -##### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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 +With funds to reserve: +```ts +import { ethers } from 'ethers'; -`Promise`\<`void`\> +await escrowClient.storeResults( + '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + 'https://example.com/results.json', + '0xHASH123', + ethers.parseEther('5') +); +``` *** @@ -462,33 +554,33 @@ complete(escrowAddress: string, txOptions: Overrides): Promise; This function sets the status of an escrow to completed. +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow. | +| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + +#### Returns + +| Type | Description | +|------|-------------| +| `void` | #### Throws | + +ErrorInvalidEscrowAddressProvided If the escrow address is invalid + #### Throws | Type | Description | |------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | | `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | #### Example - > Only Recording Oracle or admin can call it. ```ts await escrowClient.complete('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); ``` -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | -| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | - -#### Returns - -| Type | Description | -|------|-------------| -| `void` | *** | +*** ### bulkPayOut() @@ -508,6 +600,23 @@ txOptions: Overrides): Promise; This function pays out the amounts specified to the workers and sets the URL of the final results file. +##### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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`\> + ##### Throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid @@ -576,23 +685,6 @@ await escrowClient.bulkPayOut( ); ``` -##### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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`\> - #### Call Signature ```ts @@ -609,6 +701,23 @@ txOptions: Overrides): Promise; This function pays out the amounts specified to the workers and sets the URL of the final results file. +##### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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`\> + ##### Throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid @@ -678,23 +787,6 @@ await escrowClient.bulkPayOut( ); ``` -##### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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`\> - *** ### cancel() @@ -705,69 +797,69 @@ cancel(escrowAddress: string, txOptions: Overrides): Promise; This function cancels the specified escrow and sends the balance to the canceler. +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `escrowAddress` | `string` | Address of the escrow to cancel. | +| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + +#### Returns + +| Type | Description | +|------|-------------| +| `void` | #### Throws | + +ErrorInvalidEscrowAddressProvided If the escrow address is invalid + #### Throws | Type | Description | |------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | | `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | #### Example - > Only Job Launcher or admin can call it. ```ts await escrowClient.cancel('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); ``` -#### Parameters +*** + +### requestCancellation() + +```ts +requestCancellation(escrowAddress: string, txOptions: Overrides): Promise; +``` + +This function requests the cancellation of the specified escrow (moves status to ToCancel or finalizes if expired). | Parameter | Type | Description | | ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow to cancel. | +| `escrowAddress` | `string` | Address of the escrow to request cancellation. | | `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | #### Returns | Type | Description | |------|-------------| -| `void` | *** | - -### requestCancellation() - -```ts -requestCancellation(escrowAddress: string, txOptions: Overrides): Promise; -``` +| `void` | #### Throws | -This function requests the cancellation of the specified escrow (moves status to ToCancel or finalizes if expired). +ErrorInvalidEscrowAddressProvided If the escrow address is invalid #### Throws | Type | Description | |------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | | `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | #### Example - > Only Job Launcher or admin can call it. ```ts await escrowClient.requestCancellation('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); ``` -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow to request cancellation. | -| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | - -#### Returns - -| Type | Description | -|------|-------------| -| `void` | *** | +*** ### withdraw() @@ -780,6 +872,18 @@ txOptions: Overrides): Promise; This function withdraws additional tokens in the escrow to the canceler. +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `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 + +| Type | Description | +|------|-------------| +| `IEscrowWithdraw` | Returns the escrow withdrawal data including transaction hash and withdrawal amount. | + #### Throws | Type | Description | @@ -790,7 +894,6 @@ This function withdraws additional tokens in the escrow to the canceler. | `ErrorTransferEventNotFoundInTransactionLogs` | If the Transfer event is not found in transaction logs | #### Example - > Only Job Launcher or admin can call it. ```ts @@ -801,20 +904,6 @@ const withdrawData = await escrowClient.withdraw( console.log('Withdrawn amount:', withdrawData.withdrawnAmount); ``` -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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 - -| Type | Description | -|------|-------------| -| `IEscrowWithdraw` | Returns the escrow withdrawal data including transaction hash and withdrawal amount. | - *** ### createBulkPayoutTransaction() @@ -833,6 +922,23 @@ txOptions: Overrides): Promise; Creates a prepared transaction for bulk payout without immediately sending it. +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `escrowAddress` | `string` | `undefined` | Escrow address to payout. | +| `recipients` | `string`[] | `undefined` | Array of recipient addresses. | +| `amounts` | `bigint`[] | `undefined` | Array of amounts the recipients will receive. | +| `finalResultsUrl` | `string` | `undefined` | Final results file URL. | +| `finalResultsHash` | `string` | `undefined` | Final results file hash. | +| `payoutId` | `string` | `undefined` | 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 + +| Type | Description | +|------|-------------| +| `TransactionLikeWithNonce` | Returns object with raw transaction and nonce | + #### Throws | Type | Description | @@ -849,7 +955,6 @@ Creates a prepared transaction for bulk payout without immediately sending it. | `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | #### Example - > Only Reputation Oracle or admin can call it. ```ts @@ -877,25 +982,6 @@ console.log('Tx hash:', ethers.keccak256(signedTransaction)); await signer.sendTransaction(rawTransaction); ``` -#### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `escrowAddress` | `string` | `undefined` | Escrow address to payout. | -| `recipients` | `string`[] | `undefined` | Array of recipient addresses. | -| `amounts` | `bigint`[] | `undefined` | Array of amounts the recipients will receive. | -| `finalResultsUrl` | `string` | `undefined` | Final results file URL. | -| `finalResultsHash` | `string` | `undefined` | Final results file hash. | -| `payoutId` | `string` | `undefined` | 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 - -| Type | Description | -|------|-------------| -| `TransactionLikeWithNonce` | Returns object with raw transaction and nonce | - *** ### getBalance() @@ -906,41 +992,15 @@ getBalance(escrowAddress: string): Promise; This function returns the balance for a specified escrow address. -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | - -#### Example - -```ts -const balance = await escrowClient.getBalance('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Balance:', balance); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `escrowAddress` | `string` | Address of the escrow. | -#### Returns - -| Type | Description | -|------|-------------| -| `bigint` | Balance of the escrow in the token used to fund it. | - -*** - -### getReservedFunds() - -```ts -getReservedFunds(escrowAddress: string): Promise; -``` +#### Returns -This function returns the reserved funds for a specified escrow address. +| Type | Description | +|------|-------------| +| `bigint` | Balance of the escrow in the token used to fund it. | #### Throws @@ -949,14 +1009,23 @@ This function returns the reserved funds for a specified escrow address. | `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | | `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | -#### Example +???+ example "Example" + + ```ts + const balance = await escrowClient.getBalance('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + console.log('Balance:', balance); + ``` + + +*** + +### getReservedFunds() ```ts -const reservedFunds = await escrowClient.getReservedFunds('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Reserved funds:', reservedFunds); +getReservedFunds(escrowAddress: string): Promise; ``` -#### Parameters +This function returns the reserved funds for a specified escrow address. | Parameter | Type | Description | | ------ | ------ | ------ | @@ -968,16 +1037,6 @@ console.log('Reserved funds:', reservedFunds); |------|-------------| | `bigint` | Reserved funds of the escrow in the token used to fund it. | -*** - -### getManifestHash() - -```ts -getManifestHash(escrowAddress: string): Promise; -``` - -This function returns the manifest file hash. - #### Throws | Type | Description | @@ -985,14 +1044,23 @@ This function returns the manifest file hash. | `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | | `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | -#### Example +???+ example "Example" + + ```ts + const reservedFunds = await escrowClient.getReservedFunds('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + console.log('Reserved funds:', reservedFunds); + ``` + + +*** + +### getManifestHash() ```ts -const manifestHash = await escrowClient.getManifestHash('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Manifest hash:', manifestHash); +getManifestHash(escrowAddress: string): Promise; ``` -#### Parameters +This function returns the manifest file hash. | Parameter | Type | Description | | ------ | ------ | ------ | @@ -1004,16 +1072,6 @@ console.log('Manifest hash:', manifestHash); |------|-------------| | `string` | Hash of the manifest file content. | -*** - -### getManifest() - -```ts -getManifest(escrowAddress: string): Promise; -``` - -This function returns the manifest. Could be a URL or a JSON string. - #### Throws | Type | Description | @@ -1021,14 +1079,23 @@ This function returns the manifest. Could be a URL or a JSON string. | `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | | `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | -#### Example +???+ example "Example" + + ```ts + const manifestHash = await escrowClient.getManifestHash('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + console.log('Manifest hash:', manifestHash); + ``` + + +*** + +### getManifest() ```ts -const manifest = await escrowClient.getManifest('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Manifest:', manifest); +getManifest(escrowAddress: string): Promise; ``` -#### Parameters +This function returns the manifest. Could be a URL or a JSON string. | Parameter | Type | Description | | ------ | ------ | ------ | @@ -1040,16 +1107,6 @@ console.log('Manifest:', manifest); |------|-------------| | `string` | Manifest URL or JSON string. | -*** - -### getResultsUrl() - -```ts -getResultsUrl(escrowAddress: string): Promise; -``` - -This function returns the results file URL. - #### Throws | Type | Description | @@ -1057,14 +1114,23 @@ This function returns the results file URL. | `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | | `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | -#### Example +???+ example "Example" + + ```ts + const manifest = await escrowClient.getManifest('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + console.log('Manifest:', manifest); + ``` + + +*** + +### getResultsUrl() ```ts -const resultsUrl = await escrowClient.getResultsUrl('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Results URL:', resultsUrl); +getResultsUrl(escrowAddress: string): Promise; ``` -#### Parameters +This function returns the results file URL. | Parameter | Type | Description | | ------ | ------ | ------ | @@ -1076,16 +1142,6 @@ console.log('Results URL:', resultsUrl); |------|-------------| | `string` | Results file URL. | -*** - -### getIntermediateResultsUrl() - -```ts -getIntermediateResultsUrl(escrowAddress: string): Promise; -``` - -This function returns the intermediate results file URL. - #### Throws | Type | Description | @@ -1093,14 +1149,23 @@ This function returns the intermediate results file URL. | `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | | `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | -#### Example +???+ example "Example" + + ```ts + const resultsUrl = await escrowClient.getResultsUrl('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + console.log('Results URL:', resultsUrl); + ``` + + +*** + +### getIntermediateResultsUrl() ```ts -const intermediateResultsUrl = await escrowClient.getIntermediateResultsUrl('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Intermediate results URL:', intermediateResultsUrl); +getIntermediateResultsUrl(escrowAddress: string): Promise; ``` -#### Parameters +This function returns the intermediate results file URL. | Parameter | Type | Description | | ------ | ------ | ------ | @@ -1112,16 +1177,6 @@ console.log('Intermediate results URL:', intermediateResultsUrl); |------|-------------| | `string` | URL of the file that stores results from Recording Oracle. | -*** - -### getIntermediateResultsHash() - -```ts -getIntermediateResultsHash(escrowAddress: string): Promise; -``` - -This function returns the intermediate results hash. - #### Throws | Type | Description | @@ -1129,14 +1184,23 @@ This function returns the intermediate results hash. | `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | | `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | -#### Example +???+ example "Example" + + ```ts + const intermediateResultsUrl = await escrowClient.getIntermediateResultsUrl('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + console.log('Intermediate results URL:', intermediateResultsUrl); + ``` + + +*** + +### getIntermediateResultsHash() ```ts -const intermediateResultsHash = await escrowClient.getIntermediateResultsHash('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Intermediate results hash:', intermediateResultsHash); +getIntermediateResultsHash(escrowAddress: string): Promise; ``` -#### Parameters +This function returns the intermediate results hash. | Parameter | Type | Description | | ------ | ------ | ------ | @@ -1148,16 +1212,6 @@ console.log('Intermediate results hash:', intermediateResultsHash); |------|-------------| | `string` | Hash of the intermediate results file content. | -*** - -### getTokenAddress() - -```ts -getTokenAddress(escrowAddress: string): Promise; -``` - -This function returns the token address used for funding the escrow. - #### Throws | Type | Description | @@ -1165,14 +1219,23 @@ This function returns the token address used for funding the escrow. | `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | | `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | -#### Example +???+ example "Example" + + ```ts + const intermediateResultsHash = await escrowClient.getIntermediateResultsHash('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + console.log('Intermediate results hash:', intermediateResultsHash); + ``` + + +*** + +### getTokenAddress() ```ts -const tokenAddress = await escrowClient.getTokenAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Token address:', tokenAddress); +getTokenAddress(escrowAddress: string): Promise; ``` -#### Parameters +This function returns the token address used for funding the escrow. | Parameter | Type | Description | | ------ | ------ | ------ | @@ -1184,16 +1247,6 @@ console.log('Token address:', tokenAddress); |------|-------------| | `string` | Address of the token used to fund the escrow. | -*** - -### getStatus() - -```ts -getStatus(escrowAddress: string): Promise; -``` - -This function returns the current status of the escrow. - #### Throws | Type | Description | @@ -1201,16 +1254,23 @@ This function returns the current status of the escrow. | `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | | `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | -#### Example +???+ example "Example" + + ```ts + const tokenAddress = await escrowClient.getTokenAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + console.log('Token address:', tokenAddress); + ``` -```ts -import { EscrowStatus } from '@human-protocol/sdk'; -const status = await escrowClient.getStatus('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Status:', EscrowStatus[status]); +*** + +### getStatus() + +```ts +getStatus(escrowAddress: string): Promise; ``` -#### Parameters +This function returns the current status of the escrow. | Parameter | Type | Description | | ------ | ------ | ------ | @@ -1222,16 +1282,6 @@ console.log('Status:', EscrowStatus[status]); |------|-------------| | `[EscrowStatus](../enumerations/EscrowStatus.md)` | Current status of the escrow. | -*** - -### getRecordingOracleAddress() - -```ts -getRecordingOracleAddress(escrowAddress: string): Promise; -``` - -This function returns the recording oracle address for a given escrow. - #### Throws | Type | Description | @@ -1239,14 +1289,25 @@ This function returns the recording oracle address for a given escrow. | `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | | `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | -#### Example +???+ example "Example" + + ```ts + import { EscrowStatus } from '@human-protocol/sdk'; + + const status = await escrowClient.getStatus('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + console.log('Status:', EscrowStatus[status]); + ``` + + +*** + +### getRecordingOracleAddress() ```ts -const oracleAddress = await escrowClient.getRecordingOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Recording Oracle address:', oracleAddress); +getRecordingOracleAddress(escrowAddress: string): Promise; ``` -#### Parameters +This function returns the recording oracle address for a given escrow. | Parameter | Type | Description | | ------ | ------ | ------ | @@ -1258,16 +1319,6 @@ console.log('Recording Oracle address:', oracleAddress); |------|-------------| | `string` | Address of the Recording Oracle. | -*** - -### getJobLauncherAddress() - -```ts -getJobLauncherAddress(escrowAddress: string): Promise; -``` - -This function returns the job launcher address for a given escrow. - #### Throws | Type | Description | @@ -1275,14 +1326,23 @@ This function returns the job launcher address for a given escrow. | `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | | `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | -#### Example +???+ example "Example" + + ```ts + const oracleAddress = await escrowClient.getRecordingOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + console.log('Recording Oracle address:', oracleAddress); + ``` + + +*** + +### getJobLauncherAddress() ```ts -const jobLauncherAddress = await escrowClient.getJobLauncherAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Job Launcher address:', jobLauncherAddress); +getJobLauncherAddress(escrowAddress: string): Promise; ``` -#### Parameters +This function returns the job launcher address for a given escrow. | Parameter | Type | Description | | ------ | ------ | ------ | @@ -1294,16 +1354,6 @@ console.log('Job Launcher address:', jobLauncherAddress); |------|-------------| | `string` | Address of the Job Launcher. | -*** - -### getReputationOracleAddress() - -```ts -getReputationOracleAddress(escrowAddress: string): Promise; -``` - -This function returns the reputation oracle address for a given escrow. - #### Throws | Type | Description | @@ -1311,14 +1361,23 @@ This function returns the reputation oracle address for a given escrow. | `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | | `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | -#### Example +???+ example "Example" + + ```ts + const jobLauncherAddress = await escrowClient.getJobLauncherAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + console.log('Job Launcher address:', jobLauncherAddress); + ``` + + +*** + +### getReputationOracleAddress() ```ts -const oracleAddress = await escrowClient.getReputationOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Reputation Oracle address:', oracleAddress); +getReputationOracleAddress(escrowAddress: string): Promise; ``` -#### Parameters +This function returns the reputation oracle address for a given escrow. | Parameter | Type | Description | | ------ | ------ | ------ | @@ -1330,16 +1389,6 @@ console.log('Reputation Oracle address:', oracleAddress); |------|-------------| | `string` | Address of the Reputation Oracle. | -*** - -### getExchangeOracleAddress() - -```ts -getExchangeOracleAddress(escrowAddress: string): Promise; -``` - -This function returns the exchange oracle address for a given escrow. - #### Throws | Type | Description | @@ -1347,14 +1396,23 @@ This function returns the exchange oracle address for a given escrow. | `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | | `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | -#### Example +???+ example "Example" + + ```ts + const oracleAddress = await escrowClient.getReputationOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + console.log('Reputation Oracle address:', oracleAddress); + ``` + + +*** + +### getExchangeOracleAddress() ```ts -const oracleAddress = await escrowClient.getExchangeOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Exchange Oracle address:', oracleAddress); +getExchangeOracleAddress(escrowAddress: string): Promise; ``` -#### Parameters +This function returns the exchange oracle address for a given escrow. | Parameter | Type | Description | | ------ | ------ | ------ | @@ -1366,16 +1424,6 @@ console.log('Exchange Oracle address:', oracleAddress); |------|-------------| | `string` | Address of the Exchange Oracle. | -*** - -### getFactoryAddress() - -```ts -getFactoryAddress(escrowAddress: string): Promise; -``` - -This function returns the escrow factory address for a given escrow. - #### Throws | Type | Description | @@ -1383,14 +1431,23 @@ This function returns the escrow factory address for a given escrow. | `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | | `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | -#### Example +???+ example "Example" + + ```ts + const oracleAddress = await escrowClient.getExchangeOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + console.log('Exchange Oracle address:', oracleAddress); + ``` + + +*** + +### getFactoryAddress() ```ts -const factoryAddress = await escrowClient.getFactoryAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -console.log('Factory address:', factoryAddress); +getFactoryAddress(escrowAddress: string): Promise; ``` -#### Parameters +This function returns the escrow factory address for a given escrow. | Parameter | Type | Description | | ------ | ------ | ------ | @@ -1401,3 +1458,18 @@ console.log('Factory address:', factoryAddress); | Type | Description | |------|-------------| | `string` | Address of the escrow factory. | + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | + +???+ example "Example" + + ```ts + const factoryAddress = await escrowClient.getFactoryAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + console.log('Factory address:', factoryAddress); + ``` + diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowUtils.md index 9a26c03e8d..745da2cef3 100644 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowUtils.md +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowUtils.md @@ -1,4 +1,4 @@ -Utility class for escrow-related operations. +Utility helpers for escrow-related queries. ## Example @@ -21,30 +21,6 @@ static getEscrows(filter: IEscrowsFilter, options?: SubgraphOptions): Promise This uses Subgraph -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorUnsupportedChainID` | If the chain ID is not supported | -| `ErrorInvalidAddress` | If the escrow address is invalid | - -#### Example - -```ts -import { ChainId } from '@human-protocol/sdk'; - -const escrow = await EscrowUtils.getEscrow( - ChainId.POLYGON_AMOY, - "0x1234567890123456789012345678901234567890" -); -if (escrow) { - console.log('Escrow status:', escrow.status); -} -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `chainId` | `ChainId` | Network in which the escrow has been deployed | @@ -106,6 +82,28 @@ if (escrow) { |------|-------------| | `IEscrow \| null` | Escrow data or null if not found. | +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorUnsupportedChainID` | If the chain ID is not supported | +| `ErrorInvalidAddress` | If the escrow address is invalid | + +???+ example "Example" + + ```ts + import { ChainId } from '@human-protocol/sdk'; + + const escrow = await EscrowUtils.getEscrow( + ChainId.POLYGON_AMOY, + "0x1234567890123456789012345678901234567890" + ); + if (escrow) { + console.log('Escrow status:', escrow.status); + } + ``` + + *** ### getStatusEvents() @@ -118,31 +116,6 @@ This function returns the status events for a given set of networks within an op > This uses Subgraph -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidAddress` | If the launcher address is invalid | -| `ErrorUnsupportedChainID` | If the chain ID is not supported | - -#### Example - -```ts -import { ChainId, EscrowStatus } from '@human-protocol/sdk'; - -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); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `filter` | `IStatusEventFilter` | Filter parameters. | @@ -154,6 +127,30 @@ console.log('Status events:', statusEvents.length); |------|-------------| | `IStatusEvent[]` | Array of status events with their corresponding statuses. | +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidAddress` | If the launcher address is invalid | +| `ErrorUnsupportedChainID` | If the chain ID is not supported | + +???+ example "Example" + + ```ts + import { ChainId, EscrowStatus } from '@human-protocol/sdk'; + + 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); + ``` + + *** ### getPayouts() @@ -166,30 +163,6 @@ This function returns the payouts for a given set of networks. > This uses Subgraph -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorUnsupportedChainID` | If the chain ID is not supported | -| `ErrorInvalidAddress` | If any filter address is invalid | - -#### Example - -```ts -import { ChainId } 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:', payouts.length); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `filter` | `IPayoutFilter` | Filter parameters. | @@ -201,6 +174,29 @@ console.log('Payouts:', payouts.length); |------|-------------| | `IPayout[]` | List of payouts matching the filters. | +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorUnsupportedChainID` | If the chain ID is not supported | +| `ErrorInvalidAddress` | If any filter address is invalid | + +???+ example "Example" + + ```ts + import { ChainId } 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:', payouts.length); + ``` + + *** ### getCancellationRefunds() @@ -213,28 +209,6 @@ This function returns the cancellation refunds for a given set of networks. > This uses Subgraph -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorUnsupportedChainID` | If the chain ID is not supported | -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorInvalidAddress` | If the receiver address is invalid | - -#### Example - -```ts -import { ChainId } from '@human-protocol/sdk'; - -const cancellationRefunds = await EscrowUtils.getCancellationRefunds({ - chainId: ChainId.POLYGON_AMOY, - escrowAddress: '0x1234567890123456789012345678901234567890', -}); -console.log('Cancellation refunds:', cancellationRefunds.length); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `filter` | `ICancellationRefundFilter` | Filter parameters. | @@ -246,6 +220,27 @@ console.log('Cancellation refunds:', cancellationRefunds.length); |------|-------------| | `ICancellationRefund[]` | List of cancellation refunds matching the filters. | +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorUnsupportedChainID` | If the chain ID is not supported | +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorInvalidAddress` | If the receiver address is invalid | + +???+ example "Example" + + ```ts + import { ChainId } from '@human-protocol/sdk'; + + const cancellationRefunds = await EscrowUtils.getCancellationRefunds({ + chainId: ChainId.POLYGON_AMOY, + escrowAddress: '0x1234567890123456789012345678901234567890', + }); + console.log('Cancellation refunds:', cancellationRefunds.length); + ``` + + *** ### getCancellationRefund() @@ -261,29 +256,6 @@ This function returns the cancellation refund for a given escrow address. > This uses Subgraph -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorUnsupportedChainID` | If the chain ID is not supported | -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | - -#### Example - -```ts -import { ChainId } from '@human-protocol/sdk'; - -const cancellationRefund = await EscrowUtils.getCancellationRefund( - ChainId.POLYGON_AMOY, - "0x1234567890123456789012345678901234567890" -); -if (cancellationRefund) { - console.log('Refund amount:', cancellationRefund.amount); -} -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `chainId` | `ChainId` | Network in which the escrow has been deployed | @@ -295,3 +267,25 @@ if (cancellationRefund) { | Type | Description | |------|-------------| | `ICancellationRefund \| null` | Cancellation refund data or null if not found. | + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorUnsupportedChainID` | If the chain ID is not supported | +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | + +???+ example "Example" + + ```ts + import { ChainId } from '@human-protocol/sdk'; + + const cancellationRefund = await EscrowUtils.getCancellationRefund( + ChainId.POLYGON_AMOY, + "0x1234567890123456789012345678901234567890" + ); + if (cancellationRefund) { + console.log('Refund amount:', cancellationRefund.amount); + } + ``` + diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreClient.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreClient.md index 464c3916ba..9de83620dd 100644 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreClient.md +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreClient.md @@ -1,9 +1,7 @@ -## 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; @@ -14,23 +12,11 @@ A `Signer` or a `Provider` should be passed depending on the use case of this mo - **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'; @@ -44,7 +30,7 @@ const signer = new Wallet(privateKey, provider); const kvstoreClient = await KVStoreClient.build(signer); ``` -**Using Wagmi (frontend)** +####Using Wagmi (frontend) ```ts import { useSigner, useChainId } from 'wagmi'; @@ -54,7 +40,7 @@ const { data: signer } = useSigner(); const kvstoreClient = await KVStoreClient.build(signer); ``` -### Provider +###Using Provider ```ts import { KVStoreClient } from '@human-protocol/sdk'; @@ -80,8 +66,6 @@ new KVStoreClient(runner: ContractRunner, networkData: NetworkData): KVStoreClie **KVStoreClient constructor** -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | @@ -107,29 +91,6 @@ static build(runner: ContractRunner): Promise; Creates an instance of KVStoreClient from a runner. -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorProviderDoesNotExist` | If the provider does not exist for the provided Signer | -| `ErrorUnsupportedChainID` | 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); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | @@ -140,6 +101,28 @@ const kvstoreClient = await KVStoreClient.build(signer); |------|-------------| | `KVStoreClient` | An instance of KVStoreClient | +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorProviderDoesNotExist` | If the provider does not exist for the provided Signer | +| `ErrorUnsupportedChainID` | If the network's chainId is not supported | + +???+ example "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); + ``` + + *** ### set() @@ -153,21 +136,6 @@ txOptions: Overrides): Promise; This function sets a key-value pair associated with the address that submits the transaction. -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorKVStoreEmptyKey` | If the key is empty | -| `Error` | If the transaction fails | - -#### Example - -```ts -await kvstoreClient.set('Role', 'RecordingOracle'); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `key` | `string` | Key of the key-value pair | @@ -178,36 +146,35 @@ await kvstoreClient.set('Role', 'RecordingOracle'); | Type | Description | |------|-------------| -| `void` | *** | +| `void` | #### Throws | -### setBulk() - -```ts -setBulk( - keys: string[], - values: string[], -txOptions: Overrides): Promise; -``` - -This function sets key-value pairs in bulk associated with the address that submits the transaction. +ErrorKVStoreEmptyKey If the key is empty #### Throws | Type | Description | |------|-------------| -| `ErrorKVStoreArrayLength` | If keys and values arrays have different lengths | -| `ErrorKVStoreEmptyKey` | If any key is empty | | `Error` | If the transaction fails | -#### Example +???+ example "Example" + + ```ts + await kvstoreClient.set('Role', 'RecordingOracle'); + ``` + + +*** + +### setBulk() ```ts -const keys = ['role', 'webhook_url']; -const values = ['RecordingOracle', 'http://localhost']; -await kvstoreClient.setBulk(keys, values); +setBulk( + keys: string[], + values: string[], +txOptions: Overrides): Promise; ``` -#### Parameters +This function sets key-value pairs in bulk associated with the address that submits the transaction. | Parameter | Type | Description | | ------ | ------ | ------ | @@ -219,34 +186,38 @@ await kvstoreClient.setBulk(keys, values); | Type | Description | |------|-------------| -| `void` | *** | +| `void` | #### Throws | -### setFileUrlAndHash() - -```ts -setFileUrlAndHash( - url: string, - urlKey: string, -txOptions: Overrides): Promise; -``` - -Sets a URL value for the address that submits the transaction, and its hash. +ErrorKVStoreArrayLength If keys and values arrays have different lengths #### Throws | Type | Description | |------|-------------| -| `ErrorInvalidUrl` | If the URL is invalid | +| `ErrorKVStoreEmptyKey` | If any key is empty | | `Error` | If the transaction fails | -#### Example +???+ example "Example" + + ```ts + const keys = ['role', 'webhook_url']; + const values = ['RecordingOracle', 'http://localhost']; + await kvstoreClient.setBulk(keys, values); + ``` + + +*** + +### setFileUrlAndHash() ```ts -await kvstoreClient.setFileUrlAndHash('example.com'); -await kvstoreClient.setFileUrlAndHash('linkedin.com/example', 'linkedin_url'); +setFileUrlAndHash( + url: string, + urlKey: string, +txOptions: Overrides): Promise; ``` -#### Parameters +Sets a URL value for the address that submits the transaction, and its hash. | Parameter | Type | Default value | Description | | ------ | ------ | ------ | ------ | @@ -258,32 +229,33 @@ await kvstoreClient.setFileUrlAndHash('linkedin.com/example', 'linkedin_url'); | Type | Description | |------|-------------| -| `void` | *** | - -### get() - -```ts -get(address: string, key: string): Promise; -``` +| `void` | #### Throws | -Gets the value of a key-value pair in the contract. +ErrorInvalidUrl If the URL is invalid #### Throws | Type | Description | |------|-------------| -| `ErrorKVStoreEmptyKey` | If the key is empty | -| `ErrorInvalidAddress` | If the address is invalid | -| `Error` | If the contract call fails | +| `Error` | If the transaction fails | -#### Example +???+ example "Example" + + ```ts + await kvstoreClient.setFileUrlAndHash('example.com'); + await kvstoreClient.setFileUrlAndHash('linkedin.com/example', 'linkedin_url'); + ``` + + +*** + +### get() ```ts -const value = await kvstoreClient.get('0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', 'Role'); -console.log('Value:', value); +get(address: string, key: string): Promise; ``` -#### Parameters +Gets the value of a key-value pair in the contract. | Parameter | Type | Description | | ------ | ------ | ------ | @@ -295,3 +267,19 @@ console.log('Value:', value); | Type | Description | |------|-------------| | `string` | Value of the key. | + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorKVStoreEmptyKey` | If the key is empty | +| `ErrorInvalidAddress` | If the address is invalid | +| `Error` | If the contract call fails | + +???+ example "Example" + + ```ts + const value = await kvstoreClient.get('0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', 'Role'); + console.log('Value:', value); + ``` + diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreUtils.md index 47c546233a..d23fe3232e 100644 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreUtils.md +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreUtils.md @@ -1,4 +1,4 @@ -Utility class for KVStore-related operations. +Utility helpers for KVStore-related queries. ## Example @@ -25,25 +25,6 @@ options?: SubgraphOptions): Promise; This function returns the KVStore data for a given address. -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorUnsupportedChainID` | If the network's chainId is not supported | -| `ErrorInvalidAddress` | If the address is invalid | - -#### Example - -```ts -const kvStoreData = await KVStoreUtils.getKVStoreData( - ChainId.POLYGON_AMOY, - "0x1234567890123456789012345678901234567890" -); -console.log('KVStore data:', kvStoreData); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `chainId` | `ChainId` | Network in which the KVStore is deployed | @@ -56,6 +37,24 @@ console.log('KVStore data:', kvStoreData); |------|-------------| | `IKVStore[]` | KVStore data | +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorUnsupportedChainID` | If the network's chainId is not supported | +| `ErrorInvalidAddress` | If the address is invalid | + +???+ example "Example" + + ```ts + const kvStoreData = await KVStoreUtils.getKVStoreData( + ChainId.POLYGON_AMOY, + "0x1234567890123456789012345678901234567890" + ); + console.log('KVStore data:', kvStoreData); + ``` + + *** ### get() @@ -70,28 +69,6 @@ options?: SubgraphOptions): Promise; Gets the value of a key-value pair in the KVStore using the subgraph. -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorUnsupportedChainID` | If the network's chainId is not supported | -| `ErrorInvalidAddress` | If the address is invalid | -| `ErrorKVStoreEmptyKey` | If the key is empty | -| `InvalidKeyError` | If the key is not found | - -#### Example - -```ts -const value = await KVStoreUtils.get( - ChainId.POLYGON_AMOY, - '0x1234567890123456789012345678901234567890', - 'role' -); -console.log('Value:', value); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `chainId` | `ChainId` | Network in which the KVStore is deployed | @@ -105,6 +82,27 @@ console.log('Value:', value); |------|-------------| | `string` | Value of the key. | +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorUnsupportedChainID` | If the network's chainId is not supported | +| `ErrorInvalidAddress` | If the address is invalid | +| `ErrorKVStoreEmptyKey` | If the key is empty | +| `InvalidKeyError` | If the key is not found | + +???+ example "Example" + + ```ts + const value = await KVStoreUtils.get( + ChainId.POLYGON_AMOY, + '0x1234567890123456789012345678901234567890', + 'role' + ); + console.log('Value:', value); + ``` + + *** ### getFileUrlAndVerifyHash() @@ -119,26 +117,6 @@ options?: SubgraphOptions): Promise; Gets the URL value of the given entity, and verifies its hash. -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidAddress` | If the address is invalid | -| `ErrorInvalidHash` | If the hash verification fails | -| `Error` | If fetching URL or hash fails | - -#### Example - -```ts -const url = await KVStoreUtils.getFileUrlAndVerifyHash( - ChainId.POLYGON_AMOY, - '0x1234567890123456789012345678901234567890' -); -console.log('Verified URL:', url); -``` - -#### Parameters - | Parameter | Type | Default value | Description | | ------ | ------ | ------ | ------ | | `chainId` | `ChainId` | `undefined` | Network in which the KVStore is deployed | @@ -152,6 +130,25 @@ console.log('Verified URL:', url); |------|-------------| | `string` | URL value for the given address if it exists, and the content is valid | +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidAddress` | If the address is invalid | +| `ErrorInvalidHash` | If the hash verification fails | +| `Error` | If fetching URL or hash fails | + +???+ example "Example" + + ```ts + const url = await KVStoreUtils.getFileUrlAndVerifyHash( + ChainId.POLYGON_AMOY, + '0x1234567890123456789012345678901234567890' + ); + console.log('Verified URL:', url); + ``` + + *** ### getPublicKey() @@ -165,26 +162,6 @@ options?: SubgraphOptions): Promise; Gets the public key of the given entity, and verifies its hash. -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidAddress` | If the address is invalid | -| `ErrorInvalidHash` | If the hash verification fails | -| `Error` | If fetching the public key fails | - -#### Example - -```ts -const publicKey = await KVStoreUtils.getPublicKey( - ChainId.POLYGON_AMOY, - '0x1234567890123456789012345678901234567890' -); -console.log('Public key:', publicKey); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `chainId` | `ChainId` | Network in which the KVStore is deployed | @@ -196,3 +173,22 @@ console.log('Public key:', publicKey); | Type | Description | |------|-------------| | `string` | Public key for the given address if it exists, and the content is valid | + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidAddress` | If the address is invalid | +| `ErrorInvalidHash` | If the hash verification fails | +| `Error` | If fetching the public key fails | + +???+ example "Example" + + ```ts + const publicKey = await KVStoreUtils.getPublicKey( + ChainId.POLYGON_AMOY, + '0x1234567890123456789012345678901234567890' + ); + console.log('Public key:', publicKey); + ``` + diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/OperatorUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/OperatorUtils.md index 08e7f037f6..91d91e11e4 100644 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/OperatorUtils.md +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/OperatorUtils.md @@ -1,4 +1,4 @@ -Utility class for operator-related operations. +Utility helpers for operator-related queries. ## Example @@ -25,27 +25,6 @@ options?: SubgraphOptions): Promise; This function returns the operator data for the given address. -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidStakerAddressProvided` | If the address is invalid | -| `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' -); -console.log('Operator:', operator); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `chainId` | `ChainId` | Network in which the operator is deployed | @@ -58,35 +37,35 @@ console.log('Operator:', operator); |------|-------------| | `IOperator \| null` | Returns the operator details or null if not found. | -*** - -### getOperators() - -```ts -static getOperators(filter: IOperatorsFilter, options?: SubgraphOptions): Promise; -``` - -This function returns all the operator details of the protocol. - #### Throws | Type | Description | |------|-------------| +| `ErrorInvalidStakerAddressProvided` | If the address is invalid | | `ErrorUnsupportedChainID` | If the chain ID is not supported | -#### Example +???+ example "Example" + + ```ts + import { OperatorUtils, ChainId } from '@human-protocol/sdk'; + + const operator = await OperatorUtils.getOperator( + ChainId.POLYGON_AMOY, + '0x62dD51230A30401C455c8398d06F85e4EaB6309f' + ); + console.log('Operator:', operator); + ``` -```ts -import { ChainId } from '@human-protocol/sdk'; -const filter = { - chainId: ChainId.POLYGON_AMOY -}; -const operators = await OperatorUtils.getOperators(filter); -console.log('Operators:', operators.length); +*** + +### getOperators() + +```ts +static getOperators(filter: IOperatorsFilter, options?: SubgraphOptions): Promise; ``` -#### Parameters +This function returns all the operator details of the protocol. | Parameter | Type | Description | | ------ | ------ | ------ | @@ -99,6 +78,25 @@ console.log('Operators:', operators.length); |------|-------------| | `IOperator[]` | Returns an array with all the operator details. | +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorUnsupportedChainID` | If the chain ID is not supported | + +???+ example "Example" + + ```ts + import { ChainId } from '@human-protocol/sdk'; + + const filter = { + chainId: ChainId.POLYGON_AMOY + }; + const operators = await OperatorUtils.getOperators(filter); + console.log('Operators:', operators.length); + ``` + + *** ### getReputationNetworkOperators() @@ -113,26 +111,6 @@ options?: SubgraphOptions): Promise; Retrieves the reputation network operators of the specified address. -#### Throws - -| Type | Description | -|------|-------------| -| `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' -); -console.log('Operators:', operators.length); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `chainId` | `ChainId` | Network in which the reputation network is deployed | @@ -146,6 +124,25 @@ console.log('Operators:', operators.length); |------|-------------| | `IOperator[]` | Returns an array of operator details. | +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorUnsupportedChainID` | If the chain ID is not supported | + +???+ example "Example" + + ```ts + import { OperatorUtils, ChainId } from '@human-protocol/sdk'; + + const operators = await OperatorUtils.getReputationNetworkOperators( + ChainId.POLYGON_AMOY, + '0x62dD51230A30401C455c8398d06F85e4EaB6309f' + ); + console.log('Operators:', operators.length); + ``` + + *** ### getRewards() @@ -159,27 +156,6 @@ options?: SubgraphOptions): Promise; This function returns information about the rewards for a given slasher address. -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidSlasherAddressProvided` | If the slasher address is invalid | -| `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' -); -console.log('Rewards:', rewards.length); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `chainId` | `ChainId` | Network in which the rewards are deployed | @@ -191,3 +167,23 @@ console.log('Rewards:', rewards.length); | Type | Description | |------|-------------| | `IReward[]` | Returns an array of Reward objects that contain the rewards earned by the user through slashing other users. | + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidSlasherAddressProvided` | If the slasher address is invalid | +| `ErrorUnsupportedChainID` | If the chain ID is not supported | + +???+ example "Example" + + ```ts + import { OperatorUtils, ChainId } from '@human-protocol/sdk'; + + const rewards = await OperatorUtils.getRewards( + ChainId.POLYGON_AMOY, + '0x62dD51230A30401C455c8398d06F85e4EaB6309f' + ); + console.log('Rewards:', rewards.length); + ``` + diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingClient.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingClient.md index 31eed25c42..e40d0d5086 100644 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingClient.md +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingClient.md @@ -1,6 +1,4 @@ -## 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. @@ -14,23 +12,11 @@ A `Signer` or a `Provider` should be passed depending on the use case of this mo - **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'; @@ -44,7 +30,7 @@ const signer = new Wallet(privateKey, provider); const stakingClient = await StakingClient.build(signer); ``` -**Using Wagmi (frontend)** +####Using Wagmi (frontend) ```ts import { useSigner, useChainId } from 'wagmi'; @@ -54,7 +40,7 @@ const { data: signer } = useSigner(); const stakingClient = await StakingClient.build(signer); ``` -### Provider +###Using Provider ```ts import { StakingClient } from '@human-protocol/sdk'; @@ -80,8 +66,6 @@ new StakingClient(runner: ContractRunner, networkData: NetworkData): StakingClie **StakingClient constructor** -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | @@ -107,29 +91,6 @@ static build(runner: ContractRunner): Promise; Creates an instance of StakingClient from a Runner. -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorProviderDoesNotExist` | If the provider does not exist for the provided Signer | -| `ErrorUnsupportedChainID` | 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); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | @@ -140,33 +101,37 @@ const stakingClient = await StakingClient.build(signer); |------|-------------| | `StakingClient` | An instance of StakingClient | -*** +#### Throws -### approveStake() +| Type | Description | +|------|-------------| +| `ErrorProviderDoesNotExist` | If the provider does not exist for the provided Signer | +| `ErrorUnsupportedChainID` | If the network's chainId is not supported | -```ts -approveStake(amount: bigint, txOptions: Overrides): Promise; -``` +???+ example "Example" -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. + ```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); + ``` -#### Throws -| Type | Description | -|------|-------------| -| `ErrorInvalidStakingValueType` | If the amount is not a bigint | -| `ErrorInvalidStakingValueSign` | If the amount is negative | +*** -#### Example +### approveStake() ```ts -import { ethers } from 'ethers'; - -const amount = ethers.parseUnits('5', 'ether'); //convert from ETH to WEI -await stakingClient.approveStake(amount); +approveStake(amount: bigint, txOptions: Overrides): Promise; ``` -#### Parameters +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. | Parameter | Type | Description | | ------ | ------ | ------ | @@ -177,36 +142,38 @@ await stakingClient.approveStake(amount); | Type | Description | |------|-------------| -| `void` | *** | +| `void` | #### Throws | -### stake() - -```ts -stake(amount: bigint, txOptions: Overrides): Promise; -``` - -This function stakes a specified amount of tokens on a specific network. - -> `approveStake` must be called before +ErrorInvalidStakingValueType If the amount is not a bigint #### Throws | Type | Description | |------|-------------| -| `ErrorInvalidStakingValueType` | If the amount is not a bigint | | `ErrorInvalidStakingValueSign` | If the amount is negative | -#### Example +???+ example "Example" -```ts -import { ethers } from 'ethers'; + ```ts + import { ethers } from 'ethers'; + + const amount = ethers.parseUnits('5', 'ether'); //convert from ETH to WEI + await stakingClient.approveStake(amount); + ``` -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); + +*** + +### stake() + +```ts +stake(amount: bigint, txOptions: Overrides): Promise; ``` -#### Parameters +This function stakes a specified amount of tokens on a specific network. + +!!! note + `approveStake` must be called before | Parameter | Type | Description | | ------ | ------ | ------ | @@ -217,35 +184,39 @@ await stakingClient.stake(amount); | Type | Description | |------|-------------| -| `void` | *** | +| `void` | #### Throws | -### unstake() - -```ts -unstake(amount: bigint, txOptions: Overrides): Promise; -``` - -This function unstakes tokens from staking contract. The unstaked tokens stay locked for a period of time. - -> Must have tokens available to unstake +ErrorInvalidStakingValueType If the amount is not a bigint #### Throws | Type | Description | |------|-------------| -| `ErrorInvalidStakingValueType` | If the amount is not a bigint | | `ErrorInvalidStakingValueSign` | If the amount is negative | -#### Example +???+ example "Example" -```ts -import { ethers } from 'ethers'; + ```ts + import { ethers } from 'ethers'; + + 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); + ``` -const amount = ethers.parseUnits('5', 'ether'); //convert from ETH to WEI -await stakingClient.unstake(amount); + +*** + +### unstake() + +```ts +unstake(amount: bigint, txOptions: Overrides): Promise; ``` -#### Parameters +This function unstakes tokens from staking contract. The unstaked tokens stay locked for a period of time. + +!!! note + Must have tokens available to unstake | Parameter | Type | Description | | ------ | ------ | ------ | @@ -256,25 +227,37 @@ await stakingClient.unstake(amount); | Type | Description | |------|-------------| -| `void` | *** | +| `void` | #### Throws | -### withdraw() +ErrorInvalidStakingValueType If the amount is not a bigint -```ts -withdraw(txOptions: Overrides): Promise; -``` +#### Throws -This function withdraws unstaked and non-locked tokens from staking contract to the user wallet. +| Type | Description | +|------|-------------| +| `ErrorInvalidStakingValueSign` | If the amount is negative | + +???+ example "Example" -> Must have tokens available to withdraw + ```ts + import { ethers } from 'ethers'; + + const amount = ethers.parseUnits('5', 'ether'); //convert from ETH to WEI + await stakingClient.unstake(amount); + ``` -#### Example + +*** + +### withdraw() ```ts -await stakingClient.withdraw(); +withdraw(txOptions: Overrides): Promise; ``` -#### Parameters +This function withdraws unstaked and non-locked tokens from staking contract to the user wallet. +!!! note + Must have tokens available to withdraw | Parameter | Type | Description | | ------ | ------ | ------ | @@ -284,7 +267,13 @@ await stakingClient.withdraw(); | Type | Description | |------|-------------| -| `void` | *** | +| `void` | #### Example | + +```ts +await stakingClient.withdraw(); +``` + +*** ### slash() @@ -299,33 +288,6 @@ txOptions: Overrides): Promise; 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. -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidStakingValueType` | If the amount is not a bigint | -| `ErrorInvalidStakingValueSign` | If the amount is negative | -| `ErrorInvalidSlasherAddressProvided` | If the slasher address is invalid | -| `ErrorInvalidStakerAddressProvided` | If the staker address is invalid | -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | - -#### Example - -```ts -import { ethers } from 'ethers'; - -const amount = ethers.parseUnits('5', 'ether'); //convert from ETH to WEI -await stakingClient.slash( - '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', - '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', - '0x62dD51230A30401C455c8398d06F85e4EaB6309f', - amount -); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `slasher` | `string` | Wallet address from who requested the slash | @@ -338,30 +300,44 @@ await stakingClient.slash( | Type | Description | |------|-------------| -| `void` | *** | +| `void` | #### Throws | -### getStakerInfo() - -```ts -getStakerInfo(stakerAddress: string): Promise; -``` - -Retrieves comprehensive staking information for a staker. +ErrorInvalidStakingValueType If the amount is not a bigint #### Throws | Type | Description | |------|-------------| +| `ErrorInvalidStakingValueSign` | If the amount is negative | +| `ErrorInvalidSlasherAddressProvided` | If the slasher address is invalid | | `ErrorInvalidStakerAddressProvided` | If the staker address is invalid | +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | + +???+ example "Example" + + ```ts + import { ethers } from 'ethers'; + + const amount = ethers.parseUnits('5', 'ether'); //convert from ETH to WEI + await stakingClient.slash( + '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', + '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', + '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + amount + ); + ``` -#### Example + +*** + +### getStakerInfo() ```ts -const stakingInfo = await stakingClient.getStakerInfo('0xYourStakerAddress'); -console.log('Tokens staked:', stakingInfo.stakedAmount); +getStakerInfo(stakerAddress: string): Promise; ``` -#### Parameters +Retrieves comprehensive staking information for a staker. | Parameter | Type | Description | | ------ | ------ | ------ | @@ -372,3 +348,17 @@ console.log('Tokens staked:', stakingInfo.stakedAmount); | Type | Description | |------|-------------| | `StakerInfo` | Staking information for the staker | + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidStakerAddressProvided` | If the staker address is invalid | + +???+ example "Example" + + ```ts + const stakingInfo = await stakingClient.getStakerInfo('0xYourStakerAddress'); + console.log('Tokens staked:', stakingInfo.stakedAmount); + ``` + diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingUtils.md index 87b8a95f18..55528ed01f 100644 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingUtils.md +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingUtils.md @@ -1,4 +1,4 @@ -Utility class for Staking-related subgraph queries. +Utility helpers for Staking-related queries. ## Example @@ -25,28 +25,6 @@ options?: SubgraphOptions): Promise; Gets staking info for a staker from the subgraph. -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidStakerAddressProvided` | If the staker address is invalid | -| `ErrorUnsupportedChainID` | If the chain ID is not supported | -| `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); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `chainId` | `ChainId` | Network in which the staking contract is deployed | @@ -59,36 +37,36 @@ console.log('Staked amount:', staker.stakedAmount); |------|-------------| | `IStaker` | Staker info from subgraph | -*** - -### getStakers() - -```ts -static getStakers(filter: IStakersFilter, options?: SubgraphOptions): Promise; -``` - -Gets all stakers from the subgraph with filters, pagination and ordering. - #### Throws | Type | Description | |------|-------------| +| `ErrorInvalidStakerAddressProvided` | If the staker address is invalid | | `ErrorUnsupportedChainID` | If the chain ID is not supported | +| `ErrorStakerNotFound` | If the staker is not found | + +???+ example "Example" + + ```ts + import { StakingUtils, ChainId } from '@human-protocol/sdk'; + + const staker = await StakingUtils.getStaker( + ChainId.POLYGON_AMOY, + '0xYourStakerAddress' + ); + console.log('Staked amount:', staker.stakedAmount); + ``` + + +*** -#### Example +### getStakers() ```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); +static getStakers(filter: IStakersFilter, options?: SubgraphOptions): Promise; ``` -#### Parameters +Gets all stakers from the subgraph with filters, pagination and ordering. | Parameter | Type | Description | | ------ | ------ | ------ | @@ -100,3 +78,23 @@ console.log('Stakers:', stakers.length); | Type | Description | |------|-------------| | `IStaker[]` | Array of stakers | + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorUnsupportedChainID` | If the chain ID is not supported | + +???+ example "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); + ``` + diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/StatisticsUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/StatisticsUtils.md index 8c3a923531..eee132c535 100644 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/StatisticsUtils.md +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/StatisticsUtils.md @@ -1,20 +1,8 @@ -Utility class for statistics-related operations. +Utility class for statistics-related queries. 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. -## Installation - -### npm -```bash -npm install @human-protocol/sdk -``` - -### yarn -```bash -yarn install @human-protocol/sdk -``` - ## Example ```ts @@ -66,27 +54,6 @@ interface IEscrowStatistics { }; ``` -#### Example - -```ts -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); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | @@ -99,6 +66,26 @@ console.log('April escrows:', escrowStatsApril.totalEscrows); |------|-------------| | `IEscrowStatistics` | Escrow statistics data. | +???+ example "Example" + + ```ts + 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); + ``` + + *** ### getWorkerStatistics() @@ -135,27 +122,6 @@ interface IWorkerStatistics { }; ``` -#### Example - -```ts -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); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | @@ -168,6 +134,26 @@ console.log('April workers:', workerStatsApril.dailyWorkersData.length); |------|-------------| | `IWorkerStatistics` | Worker statistics data. | +???+ example "Example" + + ```ts + 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); + ``` + + *** ### getPaymentStatistics() @@ -206,34 +192,6 @@ interface IPaymentStatistics { }; ``` -#### Example - -```ts -import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; - -const networkData = NETWORKS[ChainId.POLYGON_AMOY]; -const paymentStats = await StatisticsUtils.getPaymentStatistics(networkData); -console.log( - 'Payment statistics:', - paymentStats.dailyPaymentsData.map((p) => ({ - ...p, - totalAmountPaid: p.totalAmountPaid.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); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | @@ -246,6 +204,33 @@ console.log('Payment statistics from 5/8 - 6/8:', paymentStatsRange.dailyPayment |------|-------------| | `IPaymentStatistics` | Payment statistics data. | +???+ example "Example" + + ```ts + import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; + + const networkData = NETWORKS[ChainId.POLYGON_AMOY]; + const paymentStats = await StatisticsUtils.getPaymentStatistics(networkData); + console.log( + 'Payment statistics:', + paymentStats.dailyPaymentsData.map((p) => ({ + ...p, + totalAmountPaid: p.totalAmountPaid.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); + ``` + + *** ### getHMTStatistics() @@ -264,21 +249,6 @@ interface IHMTStatistics { }; ``` -#### Example - -```ts -import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; - -const networkData = NETWORKS[ChainId.POLYGON_AMOY]; -const hmtStats = await StatisticsUtils.getHMTStatistics(networkData); -console.log('HMT statistics:', { - ...hmtStats, - totalTransferAmount: hmtStats.totalTransferAmount.toString(), -}); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | @@ -290,6 +260,20 @@ console.log('HMT statistics:', { |------|-------------| | `IHMTStatistics` | HMToken statistics data. | +???+ example "Example" + + ```ts + import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; + + const networkData = NETWORKS[ChainId.POLYGON_AMOY]; + const hmtStats = await StatisticsUtils.getHMTStatistics(networkData); + console.log('HMT statistics:', { + ...hmtStats, + totalTransferAmount: hmtStats.totalTransferAmount.toString(), + }); + ``` + + *** ### getHMTHolders() @@ -303,23 +287,6 @@ options?: SubgraphOptions): Promise; This function returns the holders of the HMToken with optional filters and ordering. -#### Example - -```ts -import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; - -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(), -}))); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | @@ -332,6 +299,22 @@ console.log('HMT holders:', hmtHolders.map((h) => ({ |------|-------------| | `IHMTHolder[]` | List of HMToken holders. | +???+ example "Example" + + ```ts + import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; + + 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(), + }))); + ``` + + *** ### getHMTDailyData() @@ -367,27 +350,6 @@ interface IDailyHMT { } ``` -#### Example - -```ts -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 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); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | @@ -399,3 +361,23 @@ console.log('HMT statistics from 5/8 - 6/8:', hmtStatsRange.length); | Type | Description | |------|-------------| | `IDailyHMT[]` | Daily HMToken statistics data. | + +???+ example "Example" + + ```ts + 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 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); + ``` + diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/StorageClient.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/StorageClient.md deleted file mode 100644 index 4b2385fd3c..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/StorageClient.md +++ /dev/null @@ -1,270 +0,0 @@ -## 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 - -```ts -new StorageClient(params: StorageParams, credentials?: StorageCredentials): StorageClient; -``` - -**Storage client constructor** - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `params` | [`StorageParams`](../type-aliases/StorageParams.md) | Cloud storage params | -| `credentials?` | [`StorageCredentials`](../type-aliases/StorageCredentials.md) | Optional. Cloud storage access data. If credentials are not provided - use anonymous access to the bucket | - -#### Returns - -| Type | Description | -|------|-------------| -| `StorageClient` | - | - -## Methods - -### ~~downloadFiles()~~ - -```ts -downloadFiles(keys: string[], bucket: string): Promise; -``` - -This function downloads files from a bucket. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `keys` | `string`[] | Array of filenames to download. | -| `bucket` | `string` | Bucket name. | - -#### Returns - -| Type | Description | -|------|-------------| -| `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'); -``` - -*** - -### ~~downloadFileFromUrl()~~ - -```ts -static downloadFileFromUrl(url: string): Promise; -``` - -This function downloads files from a URL. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `url` | `string` | URL of the file to download. | - -#### Returns - -| Type | Description | -|------|-------------| -| `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'); -``` - -*** - -### ~~uploadFiles()~~ - -```ts -uploadFiles(files: any[], bucket: string): Promise; -``` - -This function uploads files to a bucket. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `files` | `any`[] | Array of objects to upload serialized into JSON. | -| `bucket` | `string` | Bucket name. | - -#### Returns - -| Type | Description | -|------|-------------| -| `[UploadFile](../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'); -``` - -*** - -### ~~bucketExists()~~ - -```ts -bucketExists(bucket: string): Promise; -``` - -This function checks if a bucket exists. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `bucket` | `string` | Bucket name. | - -#### Returns - -| Type | Description | -|------|-------------| -| `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'); -``` - -*** - -### ~~listObjects()~~ - -```ts -listObjects(bucket: string): Promise; -``` - -This function lists all file names contained in the bucket. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `bucket` | `string` | Bucket name. | - -#### Returns - -| Type | Description | -|------|-------------| -| `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'); -``` diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/TransactionUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/TransactionUtils.md index 0f4a8f5936..61b1b10f09 100644 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/TransactionUtils.md +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/TransactionUtils.md @@ -1,4 +1,4 @@ -Utility class for transaction-related operations. +Utility class for transaction-related queries. ## Example @@ -53,27 +53,6 @@ type InternalTransaction = { }; ``` -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidHashProvided` | If the hash is invalid | -| `ErrorUnsupportedChainID` | If the chain ID is not supported | - -#### Example - -```ts -import { TransactionUtils, ChainId } from '@human-protocol/sdk'; - -const transaction = await TransactionUtils.getTransaction( - ChainId.POLYGON_AMOY, - '0x62dD51230A30401C455c8398d06F85e4EaB6309f' -); -console.log('Transaction:', transaction); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `chainId` | `ChainId` | The chain ID. | @@ -86,6 +65,26 @@ console.log('Transaction:', transaction); |------|-------------| | `ITransaction \| null` | Returns the transaction details or null if not found. | +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorInvalidHashProvided` | If the hash is invalid | +| `ErrorUnsupportedChainID` | If the chain ID is not supported | + +???+ example "Example" + + ```ts + import { TransactionUtils, ChainId } from '@human-protocol/sdk'; + + const transaction = await TransactionUtils.getTransaction( + ChainId.POLYGON_AMOY, + '0x62dD51230A30401C455c8398d06F85e4EaB6309f' + ); + console.log('Transaction:', transaction); + ``` + + *** ### getTransactions() @@ -146,32 +145,6 @@ type ITransaction = { }; ``` -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorCannotUseDateAndBlockSimultaneously` | If both date and block filters are used | -| `ErrorUnsupportedChainID` | If the chain ID is not supported | - -#### Example - -```ts -import { TransactionUtils, ChainId, OrderDirection } from '@human-protocol/sdk'; - -const filter = { - chainId: ChainId.POLYGON_AMOY, - 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); -console.log('Transactions:', transactions.length); -``` - -#### Parameters - | Parameter | Type | Description | | ------ | ------ | ------ | | `filter` | `ITransactionsFilter` | Filter for the transactions. | @@ -182,3 +155,28 @@ console.log('Transactions:', transactions.length); | Type | Description | |------|-------------| | `ITransaction[]` | Returns an array with all the transaction details. | + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorCannotUseDateAndBlockSimultaneously` | If both date and block filters are used | +| `ErrorUnsupportedChainID` | If the chain ID is not supported | + +???+ example "Example" + + ```ts + import { TransactionUtils, ChainId, OrderDirection } from '@human-protocol/sdk'; + + const filter = { + chainId: ChainId.POLYGON_AMOY, + 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); + console.log('Transactions:', transactions.length); + ``` + diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/WorkerUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/WorkerUtils.md new file mode 100644 index 0000000000..b00c6c3158 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/WorkerUtils.md @@ -0,0 +1,123 @@ +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); +``` + +## Methods + +### getWorker() + +```ts +static getWorker( + chainId: ChainId, + address: string, +options?: SubgraphOptions): Promise; +``` + +This function returns the worker data for the given address. + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `chainId` | `ChainId` | The chain ID. | +| `address` | `string` | The worker address. | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `IWorker \| null` | Returns the worker details or null if not found. | + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorUnsupportedChainID` | If the chain ID is not supported | +| `ErrorInvalidAddress` | If the address is invalid | + +???+ example "Example" + + ```ts + import { WorkerUtils, ChainId } from '@human-protocol/sdk'; + + const worker = await WorkerUtils.getWorker( + ChainId.POLYGON_AMOY, + '0x1234567890abcdef1234567890abcdef12345678' + ); + console.log('Worker:', worker); + ``` + + +*** + +### getWorkers() + +```ts +static getWorkers(filter: IWorkersFilter, options?: SubgraphOptions): Promise; +``` + +This function returns all worker details based on the provided filter. + +**Input parameters** + +```ts +interface IWorkersFilter { + chainId: ChainId; // List of chain IDs to query. + address?: string; // (Optional) The worker address to filter by. + orderBy?: string; // (Optional) The field to order by. Default is 'payoutCount'. + orderDirection?: OrderDirection; // (Optional) The direction of the order. Default is 'DESC'. + first?: number; // (Optional) Number of workers per page. Default is 10. + skip?: number; // (Optional) Number of workers to skip. Default is 0. +} +``` + +```ts +type IWorker = { + id: string; + address: string; + totalHMTAmountReceived: bigint; + payoutCount: number; +}; +``` + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `filter` | `IWorkersFilter` | Filter for the workers. | +| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + +#### Returns + +| Type | Description | +|------|-------------| +| `IWorker[]` | Returns an array with all the worker details. | + +#### Throws + +| Type | Description | +|------|-------------| +| `ErrorUnsupportedChainID` | If the chain ID is not supported | +| `ErrorInvalidAddress` | If the filter address is invalid | + +???+ example "Example" + + ```ts + import { WorkerUtils, ChainId } from '@human-protocol/sdk'; + + const filter = { + chainId: ChainId.POLYGON_AMOY, + first: 10, + skip: 0, + }; + const workers = await WorkerUtils.getWorkers(filter); + console.log('Workers:', workers.length); + ``` + 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..18ec1a8ade --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/docs/index.md @@ -0,0 +1,292 @@ +# 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 + +## 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 +``` + +## 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/) + +## License + +MIT License - see [LICENSE](LICENSE) for details. diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/MessageDataType.md b/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/MessageDataType.md new file mode 100644 index 0000000000..c84d8374d3 --- /dev/null +++ b/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/MessageDataType.md @@ -0,0 +1,6 @@ +```ts +type MessageDataType = string | Uint8Array; +``` + +Type representing the data type of a message. +It can be either a string or a Uint8Array. diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/StorageCredentials.md b/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/StorageCredentials.md deleted file mode 100644 index 8e09ad3813..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/StorageCredentials.md +++ /dev/null @@ -1,29 +0,0 @@ -```ts -readonly type StorageCredentials = object; -``` - -AWS/GCP cloud storage access data - -## Deprecated - -StorageClient is deprecated. Use Minio.Client directly. - -## Properties - -### ~~accessKey~~ - -```ts -accessKey: string; -``` - -Access Key - -*** - -### ~~secretKey~~ - -```ts -secretKey: string; -``` - -Secret Key diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/StorageParams.md b/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/StorageParams.md deleted file mode 100644 index fa3da8ba8e..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/StorageParams.md +++ /dev/null @@ -1,47 +0,0 @@ -```ts -type StorageParams = object; -``` - -## Deprecated - -StorageClient is deprecated. Use Minio.Client directly. - -## Properties - -### ~~endPoint~~ - -```ts -endPoint: string; -``` - -Request endPoint - -*** - -### ~~useSSL~~ - -```ts -useSSL: boolean; -``` - -Enable secure (HTTPS) access. Default value set to false - -*** - -### ~~region?~~ - -```ts -optional region: string; -``` - -Region - -*** - -### ~~port?~~ - -```ts -optional port: number; -``` - -TCP/IP port number. Default value set to 80 for HTTP and 443 for HTTPs diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/UploadFile.md b/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/UploadFile.md deleted file mode 100644 index 349fbb64a9..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/UploadFile.md +++ /dev/null @@ -1,35 +0,0 @@ -```ts -readonly type UploadFile = object; -``` - -Upload file data - -## Properties - -### key - -```ts -key: string; -``` - -Uploaded object key - -*** - -### url - -```ts -url: string; -``` - -Uploaded object URL - -*** - -### hash - -```ts -hash: string; -``` - -Hash of uploaded object key diff --git a/packages/sdk/typescript/human-protocol-sdk/package.json b/packages/sdk/typescript/human-protocol-sdk/package.json index 225fb07a6c..6e22502714 100644 --- a/packages/sdk/typescript/human-protocol-sdk/package.json +++ b/packages/sdk/typescript/human-protocol-sdk/package.json @@ -10,10 +10,9 @@ "types": "dist/index.d.ts", "scripts": { "clean": "tsc --build --clean && rm -rf ./dist", - "clean:doc": "rm -rf docs", "build": "yarn clean && tsc --build", "docs:post": "ts-node scripts/postprocess-docs.ts", - "build:doc": "yarn clean:doc && typedoc && yarn docs:post", + "build:doc": "typedoc && yarn docs:post", "test": "vitest -u", "lint": "eslint .", "lint:fix": "eslint . --fix", diff --git a/packages/sdk/typescript/human-protocol-sdk/scripts/postprocess-docs.ts b/packages/sdk/typescript/human-protocol-sdk/scripts/postprocess-docs.ts index 3211703013..9c52914923 100644 --- a/packages/sdk/typescript/human-protocol-sdk/scripts/postprocess-docs.ts +++ b/packages/sdk/typescript/human-protocol-sdk/scripts/postprocess-docs.ts @@ -8,7 +8,7 @@ const ROOT = 'docs'; // adjust if needed function processFile(path: PathOrFileDescriptor) { const original = readFileSync(path, 'utf8'); const lines = original.split('\n'); - const out = []; + const out: string[] = []; let i = 0; @@ -17,7 +17,7 @@ function processFile(path: PathOrFileDescriptor) { // ---------- THROWS: merge all into one table ---------- if (line.startsWith('#### Throws')) { - const rows = []; + const rows: { type: string; desc: string }[] = []; // consume all consecutive "#### Throws" sections while (i < lines.length && lines[i].startsWith('#### Throws')) { @@ -45,7 +45,7 @@ function processFile(path: PathOrFileDescriptor) { // if description is empty, read following lines if (!desc) { - const descParts = []; + const descParts: string[] = []; while ( i < lines.length && lines[i].trim() !== '' && @@ -94,7 +94,7 @@ function processFile(path: PathOrFileDescriptor) { while (i < lines.length && lines[i].trim() === '') i++; // description lines until next heading or blank+heading - const descParts = []; + const descParts: string[] = []; while ( i < lines.length && lines[i].trim() !== '' && @@ -128,12 +128,79 @@ function processFile(path: PathOrFileDescriptor) { 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++; } - writeFileSync(path, out.join('\n')); + // second pass: transform Examples into admonitions + let text = out.join('\n'); + text = transformExamples(text); + + writeFileSync(path, text); +} + +// ---------- 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" + if (line.startsWith('#### Example')) { + 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; + } + + out.push(line); + i++; + } + + return out.join('\n'); } function 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 f630f64242..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') { @@ -192,15 +194,6 @@ export class Encryption { /** * Utility class for encryption-related operations. - * - * @example - * ```ts - * import { EncryptionUtils } from '@human-protocol/sdk'; - * - * const publicKey = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; - * const isValid = await EncryptionUtils.verify('message', publicKey); - * console.log('Signature valid:', isValid); - * ``` */ export class EncryptionUtils { /** @@ -212,6 +205,8 @@ export class EncryptionUtils { * * @example * ```ts + * import { EncryptionUtils } from '@human-protocol/sdk'; + * * const publicKey = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; * const result = await EncryptionUtils.verify('message', publicKey); * console.log('Verification result:', result); @@ -245,6 +240,8 @@ export class EncryptionUtils { * * @example * ```ts + * import { EncryptionUtils } from '@human-protocol/sdk'; + * * const signedData = await EncryptionUtils.getSignedData('message'); * console.log('Signed data:', signedData); * ``` @@ -271,6 +268,8 @@ export class EncryptionUtils { * * @example * ```ts + * import { EncryptionUtils } from '@human-protocol/sdk'; + * * const name = 'YOUR_NAME'; * const email = 'YOUR_EMAIL'; * const passphrase = 'YOUR_PASSPHRASE'; @@ -309,6 +308,8 @@ export class EncryptionUtils { * * @example * ```ts + * import { EncryptionUtils } from '@human-protocol/sdk'; + * * const publicKey1 = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; * const publicKey2 = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; * const publicKeys = [publicKey1, publicKey2]; @@ -344,6 +345,8 @@ export class EncryptionUtils { * * @example * ```ts + * import { EncryptionUtils } from '@human-protocol/sdk'; + * * const message = '-----BEGIN PGP MESSAGE-----...'; * const isEncrypted = EncryptionUtils.isEncrypted(message); * diff --git a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts b/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts index 7ba64e0950..d4d1b54d42 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts @@ -77,7 +77,7 @@ import { } from './utils'; /** - * 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`](/ts/classes/EscrowClient/#build) method. @@ -184,7 +184,8 @@ export class EscrowClient extends BaseEthersClient { /** * This function creates an escrow contract that uses the token passed to pay oracle fees and reward workers. - * + * !!! note + * 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). @@ -193,7 +194,6 @@ export class EscrowClient extends BaseEthersClient { * @throws ErrorLaunchedEventIsNotEmitted If the LaunchedV2 event is not emitted * * @example - * > Need to have available stake. * * ```ts * const tokenAddress = '0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4'; @@ -395,9 +395,13 @@ export class EscrowClient extends BaseEthersClient { /** * This function sets up the parameters of the escrow. * + * !!! note + * 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). + * * @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 @@ -409,7 +413,6 @@ export class EscrowClient extends BaseEthersClient { * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory * * @example - * > Only Job Launcher or admin can call it. * * ```ts * const escrowAddress = '0x62dD51230A30401C455c8398d06F85e4EaB6309f'; @@ -532,35 +535,59 @@ export class EscrowClient extends BaseEthersClient { } /** - * This function stores the results URL and hash. + * Stores the result URL and result hash for an escrow. * - * @param escrowAddress - Address of the escrow. - * @param url - Results file URL. - * @param hash - Results file hash. - * @param fundsToReserve - Funds to reserve for payouts - * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). - * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid - * @throws ErrorInvalidUrl If the URL is invalid - * @throws ErrorHashIsEmptyString If the hash is empty - * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory - * @throws ErrorStoreResultsVersion If using deprecated signature + * !!! note + * Only Recording Oracle or admin can call it. * - * @example + * This method has two overloads: + * - `storeResults(escrowAddress, url, hash, txOptions?)` - Without funds to reserve + * - `storeResults(escrowAddress, url, hash, fundsToReserve, txOptions?)` - With funds to reserve * - * > Only Recording Oracle or admin can call it. + * 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). + * + * @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. + * + * @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 + * Without funds to reserve: + * ```ts + * await escrowClient.storeResults( + * '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + * 'https://example.com/results.json', + * '0xHASH123' + * ); + * ``` * + * @example + * With funds to reserve: * ```ts * import { ethers } from 'ethers'; * * await escrowClient.storeResults( * '0x62dD51230A30401C455c8398d06F85e4EaB6309f', - * 'http://localhost/results.json', - * 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079', - * ethers.parseEther('10') + * 'https://example.com/results.json', + * '0xHASH123', + * ethers.parseEther('5') * ); * ``` */ - + async storeResults( + escrowAddress: string, + url: string, + hash: string, + txOptions?: Overrides + ): Promise; async storeResults( escrowAddress: string, url: string, @@ -570,36 +597,53 @@ export class EscrowClient extends BaseEthersClient { ): Promise; /** - * This function stores the results URL and hash. + * Stores the result URL and result hash for an escrow. * - * @param escrowAddress - Address of the escrow. - * @param url - Results file URL. - * @param hash - Results file hash. - * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). - * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid - * @throws ErrorInvalidUrl If the URL is invalid - * @throws ErrorHashIsEmptyString If the hash is empty - * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory - * @throws ErrorStoreResultsVersion If using deprecated signature + * !!! note + * Only Recording Oracle or admin can call it. + * + * This method has two overloads: + * - `storeResults(escrowAddress, url, hash, txOptions?)` - Without funds to reserve + * - `storeResults(escrowAddress, url, hash, fundsToReserve, txOptions?)` - With funds to reserve + * + * 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). + * + * @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. + * + * @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 - * > Only Recording Oracle or admin can call it. + * Without funds to reserve: + * ```ts + * await escrowClient.storeResults( + * '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + * 'https://example.com/results.json', + * '0xHASH123' + * ); + * ``` * + * @example + * With funds to reserve: * ```ts + * import { ethers } from 'ethers'; + * * await escrowClient.storeResults( * '0x62dD51230A30401C455c8398d06F85e4EaB6309f', - * 'http://localhost/results.json', - * 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079' + * 'https://example.com/results.json', + * '0xHASH123', + * ethers.parseEther('5') * ); * ``` */ - async storeResults( - escrowAddress: string, - url: string, - hash: string, - txOptions?: Overrides - ): Promise; - @requiresSigner async storeResults( escrowAddress: string, @@ -1665,7 +1709,7 @@ export class EscrowClient extends BaseEthersClient { } } /** - * Utility class for escrow-related operations. + * Utility helpers for escrow-related queries. * * @example * ```ts @@ -2061,6 +2105,7 @@ export class EscrowUtils { * ```ts * import { ChainId } from '@human-protocol/sdk'; * + * * const cancellationRefund = await EscrowUtils.getCancellationRefund( * ChainId.POLYGON_AMOY, * "0x1234567890123456789012345678901234567890" diff --git a/packages/sdk/typescript/human-protocol-sdk/src/index.ts b/packages/sdk/typescript/human-protocol-sdk/src/index.ts index 07f1944098..0e07f51949 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/index.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/index.ts @@ -2,7 +2,7 @@ import { StakingClient, StakingUtils } from './staking'; import { KVStoreClient, KVStoreUtils } from './kvstore'; import { EscrowClient, EscrowUtils } from './escrow'; import { StatisticsUtils } from './statistics'; -import { Encryption, EncryptionUtils } from './encryption'; +import { Encryption, EncryptionUtils, MessageDataType } from './encryption'; import { OperatorUtils } from './operator'; import { TransactionUtils } from './transaction'; import { WorkerUtils } from './worker'; @@ -37,4 +37,5 @@ export { 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 338624183b..af4b5cfe34 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,23 +40,11 @@ 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'; @@ -72,7 +58,7 @@ import { IKVStore, SubgraphOptions } from './interfaces'; * const kvstoreClient = await KVStoreClient.build(signer); * ``` * - * **Using Wagmi (frontend)** + * ####Using Wagmi (frontend) * * ```ts * import { useSigner, useChainId } from 'wagmi'; @@ -82,7 +68,7 @@ import { IKVStore, SubgraphOptions } from './interfaces'; * const kvstoreClient = await KVStoreClient.build(signer); * ``` * - * ### Provider + * ###Using Provider * * ```ts * import { KVStoreClient } from '@human-protocol/sdk'; @@ -287,7 +273,7 @@ export class KVStoreClient extends BaseEthersClient { } /** - * Utility class for KVStore-related operations. + * Utility helpers for KVStore-related queries. * * @example * ```ts diff --git a/packages/sdk/typescript/human-protocol-sdk/src/operator.ts b/packages/sdk/typescript/human-protocol-sdk/src/operator.ts index 88b9e9f225..ad0dd150d7 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/operator.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/operator.ts @@ -27,7 +27,7 @@ import { ChainId, OrderDirection } from './enums'; import { NETWORKS } from './constants'; /** - * Utility class for operator-related operations. + * Utility helpers for operator-related queries. * * @example * ```ts diff --git a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts b/packages/sdk/typescript/human-protocol-sdk/src/staking.ts index 36a72773f2..c7c047b983 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,23 +51,11 @@ 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'; @@ -83,7 +69,7 @@ import { * const stakingClient = await StakingClient.build(signer); * ``` * - * **Using Wagmi (frontend)** + * ####Using Wagmi (frontend) * * ```ts * import { useSigner, useChainId } from 'wagmi'; @@ -93,7 +79,7 @@ import { * const stakingClient = await StakingClient.build(signer); * ``` * - * ### Provider + * ###Using Provider * * ```ts * import { StakingClient } from '@human-protocol/sdk'; @@ -234,7 +220,8 @@ export class StakingClient extends BaseEthersClient { /** * This function stakes a specified amount of tokens on a specific network. * - * > `approveStake` must be called before + * !!! note + * `approveStake` must be called before * * @param amount - Amount in WEI of tokens to stake. * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). @@ -271,7 +258,8 @@ 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 + * !!! note + * Must have tokens available to unstake * * @param amount - Amount in WEI of tokens to unstake. * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). @@ -309,8 +297,8 @@ export class StakingClient extends BaseEthersClient { /** * This function withdraws unstaked and non-locked tokens from staking contract to the user wallet. - * - * > Must have tokens available to withdraw + * !!! note + * Must have tokens available to withdraw * * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). * @@ -449,7 +437,7 @@ export class StakingClient extends BaseEthersClient { } /** - * Utility class for Staking-related subgraph queries. + * Utility helpers for Staking-related queries. * * @example * ```ts diff --git a/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts b/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts index f60b4ef23c..fd1192a449 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts @@ -30,23 +30,11 @@ import { } from './utils'; /** - * Utility class for statistics-related operations. + * Utility class for statistics-related queries. * * 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. * - * ## Installation - * - * ### npm - * ```bash - * npm install @human-protocol/sdk - * ``` - * - * ### yarn - * ```bash - * yarn install @human-protocol/sdk - * ``` - * * @example * ```ts * import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; diff --git a/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts b/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts index 1a8eb5d6a1..6359018653 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts @@ -20,7 +20,7 @@ import { import { getSubgraphUrl, getUnixTimestamp, customGqlFetch } from './utils'; /** - * Utility class for transaction-related operations. + * Utility class for transaction-related queries. * * @example * ```ts 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/typedoc.json b/packages/sdk/typescript/human-protocol-sdk/typedoc.json index 1fcc4b0abc..36912e847b 100644 --- a/packages/sdk/typescript/human-protocol-sdk/typedoc.json +++ b/packages/sdk/typescript/human-protocol-sdk/typedoc.json @@ -9,14 +9,15 @@ "typedoc-plugin-markdown" ], "readme": "none", - "cleanOutputDir": true, + "cleanOutputDir": false, "excludePrivate": true, "excludeInternal": true, "excludeProtected": false, "excludeExternals": false, "excludeNotDocumented": true, "categorizeByGroup": false, - "blockTagsPreserveOrder": [ + "mergeReadme": false, + "blockTags": [ "@param", "@returns", "@throws", @@ -35,11 +36,11 @@ "hidePageTitle": true, "hideBreadcrumbs": true, "disableSources": true, + "excludeTags": [ + "@overload" + ], "sort": [ "source-order" ], - "includeVersion": true, - "markdown": { - "hideSignature": true - } + "includeVersion": true } \ No newline at end of file From 4333af587976edf434a50674f7bdf5d5fa9888cd Mon Sep 17 00:00:00 2001 From: portuu3 Date: Tue, 9 Dec 2025 16:24:48 +0100 Subject: [PATCH 06/19] docs fixes --- .../human_protocol_sdk/decorators.py | 2 +- .../encryption/encryption.py | 6 +- .../encryption/encryption_utils.py | 8 +- .../escrow/escrow_client.py | 38 +- .../human_protocol_sdk/escrow/escrow_utils.py | 12 +- .../kvstore/kvstore_client.py | 2 +- .../kvstore/kvstore_utils.py | 8 +- .../human_protocol_sdk/legacy_encryption.py | 18 +- .../operator/operator_utils.py | 8 +- .../staking/staking_client.py | 13 +- .../staking/staking_utils.py | 4 +- .../statistics/statistics_utils.py | 12 +- .../transaction/transaction_utils.py | 4 +- .../human_protocol_sdk/utils.py | 25 +- .../human_protocol_sdk/worker/worker_utils.py | 4 +- .../docs/classes/Encryption.md | 15 + .../docs/classes/EncryptionUtils.md | 15 + .../docs/classes/EscrowClient.md | 643 ++++++++---------- .../docs/classes/EscrowUtils.md | 18 + .../docs/classes/KVStoreClient.md | 37 +- .../docs/classes/KVStoreUtils.md | 12 + .../docs/classes/OperatorUtils.md | 12 + .../docs/classes/StakingClient.md | 59 +- .../docs/classes/StakingUtils.md | 6 + .../docs/classes/StatisticsUtils.md | 18 + .../docs/classes/TransactionUtils.md | 6 + .../docs/classes/WorkerUtils.md | 6 + .../scripts/postprocess-docs.ts | 324 +++++++-- .../human-protocol-sdk/src/escrow.ts | 102 +-- .../human-protocol-sdk/src/kvstore.ts | 3 + .../human-protocol-sdk/src/staking.ts | 5 + 31 files changed, 884 insertions(+), 561 deletions(-) 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 6438711850..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 @@ -27,7 +27,7 @@ def requires_signer(method: Callable[..., Any]) -> Callable[..., Any]: method (Callable[..., Any]): The method to decorate (must be a method of a class with a `w3` attribute). Returns: - Callable[..., Any]: Wrapped method that performs validation before execution. + Wrapped method that performs validation before execution. Raises: RequiresSignerError: If the Web3 instance lacks a default account or signing middleware. 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 03f5b1627c..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 @@ -66,7 +66,7 @@ def sign_and_encrypt( public_keys (List[str]): List of armored PGP public keys of the recipients. Returns: - str: Armored, signed, and encrypted PGP message. + Armored, signed, and encrypted PGP message. Raises: ValueError: If the private key cannot be unlocked or encryption fails. @@ -115,7 +115,7 @@ def decrypt(self, message: str, public_key: Optional[str] = None) -> bytes: public_key (Optional[str]): Optional armored public key to verify the message signature. Returns: - bytes: Decrypted message as bytes. + Decrypted message as bytes. Raises: ValueError: If the private key cannot be unlocked, decryption fails, @@ -175,7 +175,7 @@ def sign(self, message: Union[str, bytes]) -> str: message (Union[str, bytes]): Message content to sign. Returns: - str: Armored signed PGP message in cleartext format. + Armored signed PGP message in cleartext format. Raises: ValueError: If the private key cannot be unlocked or signing fails. 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 d349a909a2..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 @@ -27,7 +27,7 @@ def encrypt(message: str, public_keys: List[str]) -> str: public_keys (List[str]): List of armored PGP public keys of the recipients. Returns: - str: Armored encrypted PGP message. + Armored encrypted PGP message. Raises: PGPError: If encryption fails or public keys are invalid. @@ -65,7 +65,7 @@ def verify(message: str, public_key: str) -> bool: public_key (str): Armored PGP public key to verify the signature against. Returns: - bool: ``True`` if the signature is valid, ``False`` otherwise. + ``True`` if the signature is valid, ``False`` otherwise. Example: ```python @@ -98,7 +98,7 @@ def get_signed_data(message: str) -> str: message (str): Armored PGP signed message. Returns: - str: Extracted message content, or ``False`` if extraction fails. + Extracted message content, or ``False`` if extraction fails. Example: ```python @@ -126,7 +126,7 @@ def is_encrypted(message: str) -> bool: message (str): Text to check for encryption. Returns: - bool: ``True`` if the message is a PGP encrypted message, ``False`` otherwise. + ``True`` if the message is a PGP encrypted message, ``False`` otherwise. Example: ```python 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 2cdebeb53b..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 @@ -231,7 +231,7 @@ def create_escrow( tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. Returns: - str: Address of the newly created escrow contract. + Address of the newly created escrow contract. Raises: EscrowClientError: If the token address is invalid or the transaction fails. @@ -287,7 +287,7 @@ def create_fund_and_setup_escrow( tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. Returns: - str: Address of the newly created and configured escrow contract. + Address of the newly created and configured escrow contract. Raises: EscrowClientError: If inputs are invalid or the transaction fails. @@ -650,7 +650,7 @@ def create_bulk_payout_transaction( tx_options (Optional[TxParams]): Optional transaction parameters to seed the transaction. Returns: - TxParams: A populated transaction dictionary ready to sign and send, + A populated transaction dictionary ready to sign and send, including nonce, gas estimate, gas price/fees, and chain ID. Raises: @@ -820,7 +820,7 @@ def cancel( tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. Returns: - EscrowCancel: Cancellation details including transaction hash and refunded amount. + Cancellation details including transaction hash and refunded amount. Raises: EscrowClientError: If validation fails or the transfer event is missing. @@ -863,7 +863,7 @@ def withdraw( tx_options (Optional[TxParams]): Optional transaction parameters such as gas limit. Returns: - EscrowWithdraw: Withdrawal details including transaction hash, token address, and amount. + Withdrawal details including transaction hash, token address, and amount. Raises: EscrowClientError: If validation fails or transfer event is missing. @@ -927,7 +927,7 @@ def get_balance(self, escrow_address: str) -> int: escrow_address (str): Address of the escrow. Returns: - int: Remaining escrow balance in token's smallest unit. + Remaining escrow balance in token's smallest unit. Raises: EscrowClientError: If the escrow address is invalid. @@ -957,7 +957,7 @@ def get_reserved_funds(self, escrow_address: str) -> int: escrow_address (str): Address of the escrow. Returns: - int: Reserved funds amount in token's smallest unit. + Reserved funds amount in token's smallest unit. Raises: EscrowClientError: If the escrow address is invalid. @@ -979,7 +979,7 @@ def get_manifest_hash(self, escrow_address: str) -> str: escrow_address (str): Address of the escrow. Returns: - str: Manifest file hash. + Manifest file hash. Raises: EscrowClientError: If the escrow address is invalid. @@ -1019,7 +1019,7 @@ def get_results_url(self, escrow_address: str) -> str: escrow_address (str): Address of the escrow. Returns: - str: Final results URL. + Final results URL. Raises: EscrowClientError: If the escrow address is invalid. @@ -1041,7 +1041,7 @@ def get_intermediate_results_url(self, escrow_address: str) -> str: escrow_address (str): Address of the escrow. Returns: - str: Intermediate results URL. + Intermediate results URL. Raises: EscrowClientError: If the escrow address is invalid. @@ -1065,7 +1065,7 @@ def get_intermediate_results_hash(self, escrow_address: str) -> str: escrow_address (str): Address of the escrow. Returns: - str: Intermediate results file hash. + Intermediate results file hash. Raises: EscrowClientError: If the escrow address is invalid. @@ -1089,7 +1089,7 @@ def get_token_address(self, escrow_address: str) -> str: escrow_address (str): Address of the escrow. Returns: - str: Token address used to fund the escrow. + Token address used to fund the escrow. Raises: EscrowClientError: If the escrow address is invalid. @@ -1109,7 +1109,7 @@ def get_status(self, escrow_address: str) -> Status: escrow_address (str): Address of the escrow. Returns: - Status: Current escrow status enum value. + Current escrow status enum value. Raises: EscrowClientError: If the escrow address is invalid. @@ -1131,7 +1131,7 @@ def get_recording_oracle_address(self, escrow_address: str) -> str: escrow_address (str): Address of the escrow. Returns: - str: Recording oracle address. + Recording oracle address. Raises: EscrowClientError: If the escrow address is invalid. @@ -1153,7 +1153,7 @@ def get_reputation_oracle_address(self, escrow_address: str) -> str: escrow_address (str): Address of the escrow. Returns: - str: Reputation oracle address. + Reputation oracle address. Raises: EscrowClientError: If the escrow address is invalid. @@ -1177,7 +1177,7 @@ def get_exchange_oracle_address(self, escrow_address: str) -> str: escrow_address (str): Address of the escrow. Returns: - str: Exchange oracle address. + Exchange oracle address. Raises: EscrowClientError: If the escrow address is invalid. @@ -1199,7 +1199,7 @@ def get_job_launcher_address(self, escrow_address: str) -> str: escrow_address (str): Address of the escrow. Returns: - str: Job launcher address. + Job launcher address. Raises: EscrowClientError: If the escrow address is invalid. @@ -1219,7 +1219,7 @@ def get_factory_address(self, escrow_address: str) -> str: escrow_address (str): Address of the escrow. Returns: - str: Escrow factory address. + Escrow factory address. Raises: EscrowClientError: If the escrow address is invalid. @@ -1242,7 +1242,7 @@ def _get_escrow_contract(self, address: str) -> contract.Contract: address (str): Address of the deployed escrow. Returns: - contract.Contract: The instance of the escrow contract. + The instance of the escrow contract. Raises: EscrowClientError: If the address is not a valid escrow from the factory. 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 b3619b4d4f..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 @@ -228,7 +228,7 @@ def get_escrows( such as custom endpoints or timeout settings. Returns: - List[EscrowData]: A list of escrow records matching the filter criteria. + A list of escrow records matching the filter criteria. Returns an empty list if no matches are found. Example: @@ -352,7 +352,7 @@ def get_escrow( options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. Returns: - Optional[EscrowData]: Escrow data if found, otherwise ``None``. + Escrow data if found, otherwise ``None``. Raises: EscrowClientError: If the chain ID is invalid or the escrow address is malformed. @@ -445,7 +445,7 @@ def get_status_events( options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. Returns: - List[StatusEvent]: A list of status change events matching the filter criteria. + A list of status change events matching the filter criteria. Returns an empty list if no matches are found. Raises: @@ -532,7 +532,7 @@ def get_payouts( options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. Returns: - List[Payout]: A list of payout records matching the query parameters. + A list of payout records matching the query parameters. Returns an empty list if no matches are found. Raises: @@ -620,7 +620,7 @@ def get_cancellation_refunds( options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. Returns: - List[CancellationRefund]: A list of cancellation refunds matching the query parameters. + A list of cancellation refunds matching the query parameters. Returns an empty list if no matches are found. Raises: @@ -711,7 +711,7 @@ def get_cancellation_refund( options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. Returns: - CancellationRefund: Cancellation refund data if found, otherwise ``None``. + Cancellation refund data if found, otherwise ``None``. Raises: EscrowClientError: If an unsupported chain ID or invalid escrow address is provided. 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 2226b40fbd..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 @@ -259,7 +259,7 @@ def get(self, address: str, key: str) -> str: key (str): Key to retrieve (cannot be empty). Returns: - str: Value of the key-value pair if it exists, empty string otherwise. + Value of the key-value pair if it exists, empty string otherwise. Raises: KVStoreClientError: If the key is empty, address is invalid, or the query fails. 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 1f952cc471..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 @@ -68,7 +68,7 @@ def get_kvstore_data( such as custom endpoints or timeout settings. Returns: - Optional[List[KVStoreData]]: List of KVStore data entries if found, empty list otherwise. + List of KVStore data entries if found, empty list otherwise. Raises: KVStoreClientError: If the chain ID is invalid or the address is malformed. @@ -137,7 +137,7 @@ def get( options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. Returns: - str: Value for the key if it exists. + Value for the key if it exists. Raises: KVStoreClientError: If the key is empty, address is invalid, chain ID is invalid, @@ -206,7 +206,7 @@ def get_file_url_and_verify_hash( options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. Returns: - str: URL value if it exists and the content hash matches. + URL value if it exists and the content hash matches. Returns empty string if URL is not set. Raises: @@ -261,7 +261,7 @@ def get_public_key(chain_id: ChainId, address: str) -> str: address (str): Address from which to get the public key. Returns: - str: Public key content if it exists and is valid. + Public key content if it exists and is valid. Returns empty string if no public key is set. Raises: 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 d0e183a331..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 @@ -83,7 +83,7 @@ def is_encrypted(data: bytes) -> bool: data (bytes): Data to be checked for encryption. Returns: - bool: ``True`` if data has valid ECIES header (starts with 0x04), ``False`` otherwise. + ``True`` if data has valid ECIES header (starts with 0x04), ``False`` otherwise. Example: ```python @@ -118,7 +118,7 @@ def encrypt( shared_mac_data (bytes): Additional data to include in MAC computation. Defaults to empty bytes. Returns: - bytes: Encrypted message in ECIES format. + Encrypted message in ECIES format. Raises: DecryptionError: If key exchange fails or public key is invalid. @@ -193,7 +193,7 @@ def decrypt( shared_mac_data (bytes): Additional data used in MAC computation. Defaults to empty bytes. Returns: - bytes: Decrypted plaintext data. + Decrypted plaintext data. Raises: DecryptionError: If ECIES header is invalid, tag verification fails, @@ -270,7 +270,7 @@ def _process_key_exchange( public_key (eth_datatypes.PublicKey): Public key for the responder. Returns: - bytes: Shared secret key material resulting from the ECDH exchange. + Shared secret key material resulting from the ECDH exchange. Raises: InvalidPublicKey: If the public key cannot be converted to a valid elliptic curve point. @@ -300,7 +300,7 @@ def generate_private_key(self) -> eth_datatypes.PrivateKey: """Generate a new SECP256K1 private key. Returns: - eth_datatypes.PrivateKey: Newly generated SECP256K1 private key. + Newly generated SECP256K1 private key. Example: ```python @@ -324,7 +324,7 @@ def generate_public_key(private_key: bytes) -> eth_keys.PublicKey: private_key (bytes): Private key bytes to derive the public key from. Returns: - eth_keys.PublicKey: Public key object corresponding to the private key. + Public key object corresponding to the private key. Example: ```python @@ -348,7 +348,7 @@ def _get_key_derivation(self, key_material: bytes) -> bytes: key_material (bytes): Shared secret from ECDH key exchange. Returns: - bytes: Derived key secret (concatenation of encryption key and MAC key). + Derived key secret (concatenation of encryption key and MAC key). """ key = b"" @@ -375,7 +375,7 @@ def _hmac_sha256(key: bytes, msg: bytes) -> bytes: msg (bytes): Message to authenticate. Returns: - bytes: HMAC-SHA256 digest. + HMAC-SHA256 digest. """ mac = hmac.HMAC(key, hashes.SHA256()) @@ -390,5 +390,5 @@ def _pad32(value: bytes) -> bytes: value (bytes): Value to pad. Returns: - bytes: Value padded to 32 bytes. + 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 22153153d5..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 @@ -246,7 +246,7 @@ def get_operators( such as custom endpoints or timeout settings. Returns: - List[OperatorData]: A list of operator records matching the filter criteria. + A list of operator records matching the filter criteria. Returns an empty list if no matches are found. Example: @@ -340,7 +340,7 @@ def get_operator( options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. Returns: - Optional[OperatorData]: Operator data if found, otherwise ``None``. + Operator data if found, otherwise ``None``. Raises: OperatorUtilsError: If the chain ID is invalid or the operator address is malformed. @@ -430,7 +430,7 @@ def get_reputation_network_operators( options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. Returns: - List[OperatorData]: A list of operators registered under the reputation network. + A list of operators registered under the reputation network. Returns an empty list if no operators are found. Raises: @@ -524,7 +524,7 @@ def get_rewards_info( options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. Returns: - List[RewardData]: A list of rewards received by the slasher. + A list of rewards received by the slasher. Returns an empty list if no rewards are found. Raises: 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 3c5f70276c..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 @@ -336,11 +336,12 @@ def get_staker_info(self, staker_address: str) -> dict: staker_address (str): Ethereum address of the staker. Returns: - dict: Dictionary containing: - - ``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. + Staker info with keys: + + - `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. Raises: StakingClientError: If the staker address is invalid or the query fails. @@ -391,7 +392,7 @@ def _is_valid_escrow(self, escrow_address: str) -> bool: escrow_address (str): Escrow address to validate. Returns: - bool: ``True`` if the escrow exists in the factory registry, ``False`` otherwise. + ``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 85593ee47b..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 @@ -69,7 +69,7 @@ def get_staker( options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. Returns: - Optional[StakerData]: Staker data if found, otherwise ``None``. + Staker data if found, otherwise ``None``. Raises: StakingUtilsError: If the chain ID is not supported. @@ -134,7 +134,7 @@ def get_stakers( options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. Returns: - List[StakerData]: A list of staker records matching the filter criteria. + A list of staker records matching the filter criteria. Returns an empty list if no matches are found. Raises: 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 index 26d5ea3034..5d79cb567a 100644 --- 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 @@ -246,7 +246,7 @@ def get_escrow_statistics( options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. Returns: - EscrowStatistics: Escrow statistics including total count and daily data. + Escrow statistics including total count and daily data. Raises: StatisticsUtilsError: If the chain ID is invalid or network configuration is missing. @@ -349,7 +349,7 @@ def get_worker_statistics( options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. Returns: - WorkerStatistics: Worker statistics with daily activity breakdown. + Worker statistics with daily activity breakdown. Raises: StatisticsUtilsError: If the chain ID is invalid or network configuration is missing. @@ -426,7 +426,7 @@ def get_payment_statistics( options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. Returns: - PaymentStatistics: Payment statistics with daily breakdown. + Payment statistics with daily breakdown. Raises: StatisticsUtilsError: If the chain ID is invalid or network configuration is missing. @@ -509,7 +509,7 @@ def get_hmt_statistics( options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. Returns: - HMTStatistics: Aggregate HMT token statistics. + Aggregate HMT token statistics. Raises: StatisticsUtilsError: If the chain ID is invalid or network configuration is missing. @@ -569,7 +569,7 @@ def get_hmt_holders( options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. Returns: - List[HMTHolder]: List of token holders with addresses and balances. + List of token holders with addresses and balances. Raises: StatisticsUtilsError: If the chain ID is invalid or network configuration is missing. @@ -641,7 +641,7 @@ def get_hmt_daily_data( options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. Returns: - List[DailyHMTData]: Daily HMT transfer statistics. + List of daily HMT transfer statistics. Raises: StatisticsUtilsError: If the chain ID is invalid or network configuration is missing. 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 a5ed00cff2..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 @@ -136,7 +136,7 @@ def get_transaction( options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. Returns: - Optional[TransactionData]: Transaction data if found, otherwise ``None``. + Transaction data if found, otherwise ``None``. Raises: TransactionUtilsError: If the chain ID is not supported. @@ -222,7 +222,7 @@ def get_transactions( options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. Returns: - List[TransactionData]: A list of transactions matching the filter criteria. + A list of transactions matching the filter criteria. Returns an empty list if no matches are found. Raises: 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 6d34be624c..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 @@ -57,7 +57,7 @@ def is_indexer_error(error: Exception) -> bool: error (Exception): The exception to check. Returns: - bool: True if the error indicates indexer issues, False otherwise. + True if the error indicates indexer issues, False otherwise. Example: ```python @@ -109,7 +109,7 @@ def custom_gql_fetch( options (Optional[SubgraphOptions]): Optional subgraph configuration for retries and indexer selection. Returns: - Dict[str, Any]: JSON response from the subgraph containing the query results. + JSON response from the subgraph containing the query results. Raises: ValueError: If retry configuration is incomplete or indexer routing requires missing API key. @@ -187,7 +187,7 @@ def _fetch_subgraph_data( indexer_id (Optional[str]): Optional indexer ID to route the request to. Returns: - Dict[str, Any]: JSON response from the subgraph. + JSON response from the subgraph. Raises: Exception: If the HTTP request fails or returns a non-200 status code. @@ -246,7 +246,7 @@ def get_hmt_balance(wallet_addr: str, token_addr: str, w3: Web3) -> int: w3 (Web3): Web3 instance connected to the network. Returns: - int: HMT token balance in wei. + HMT token balance in wei. Example: ```python @@ -284,6 +284,7 @@ def parse_transfer_transaction( Returns: A tuple containing: + - bool: True if HMT was successfully transferred, False otherwise. - Optional[int]: The transfer amount in wei if successful, None otherwise. @@ -320,7 +321,7 @@ def get_contract_interface(contract_entrypoint: str) -> Dict[str, Any]: contract_entrypoint (str): File path to the contract JSON artifact. Returns: - Dict[str, Any]: Contract interface dictionary containing the ABI and other metadata. + Contract interface dictionary containing the ABI and other metadata. Example: ```python @@ -337,7 +338,7 @@ def get_erc20_interface() -> Dict[str, Any]: """Retrieve the standard ERC20 token contract interface. Returns: - Dict[str, Any]: The ERC20 contract interface containing the ABI. + The ERC20 contract interface containing the ABI. Example: ```python @@ -357,7 +358,7 @@ def get_factory_interface() -> Dict[str, Any]: """Retrieve the EscrowFactory contract interface. Returns: - Dict[str, Any]: The EscrowFactory contract interface containing the ABI. + The EscrowFactory contract interface containing the ABI. Example: ```python @@ -375,7 +376,7 @@ def get_staking_interface() -> Dict[str, Any]: """Retrieve the Staking contract interface. Returns: - Dict[str, Any]: The Staking contract interface containing the ABI. + The Staking contract interface containing the ABI. Example: ```python @@ -393,7 +394,7 @@ def get_escrow_interface() -> Dict[str, Any]: """Retrieve the Escrow contract interface. Returns: - Dict[str, Any]: The Escrow contract interface containing the ABI. + The Escrow contract interface containing the ABI. Example: ```python @@ -411,7 +412,7 @@ def get_kvstore_interface() -> Dict[str, Any]: """Retrieve the KVStore contract interface. Returns: - Dict[str, Any]: The KVStore contract interface containing the ABI. + The KVStore contract interface containing the ABI. Example: ```python @@ -494,7 +495,7 @@ def validate_url(url: str) -> bool: url: URL string to validate (e.g., "https://example.com" or "http://localhost:8080"). Returns: - bool: True if the URL is valid, False otherwise. + True if the URL is valid, False otherwise. Raises: ValidationFailure: If the URL format is invalid according to the validators library. @@ -540,7 +541,7 @@ def validate_json(data: str) -> bool: data: String to validate as JSON. Returns: - bool: True if the string is valid JSON, False otherwise. + True if the string is valid JSON, False otherwise. Example: ```python 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 61070d7838..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 @@ -78,7 +78,7 @@ def get_workers( such as custom endpoints or timeout settings. Returns: - List[WorkerData]: A list of worker records matching the filter criteria. + A list of worker records matching the filter criteria. Returns an empty list if no matches are found. Raises: @@ -165,7 +165,7 @@ def get_worker( options (Optional[SubgraphOptions]): Optional configuration for subgraph requests. Returns: - Optional[WorkerData]: Worker data if found, otherwise ``None``. + Worker data if found, otherwise ``None``. Raises: WorkerUtilsError: If the chain ID is not supported or the worker address is invalid. diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/Encryption.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/Encryption.md index 1c7c69adbc..9480739d06 100644 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/Encryption.md +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/Encryption.md @@ -14,10 +14,13 @@ new Encryption(privateKey: PrivateKey): Encryption; Constructor for the Encryption class. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `privateKey` | `PrivateKey` | The private key. | + #### Returns | Type | Description | @@ -34,11 +37,14 @@ static build(privateKeyArmored: string, passphrase?: string): Promise; This function signs and encrypts a message using the private key used to initialize the client and the specified public keys. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `message` | [`MessageDataType`](../type-aliases/MessageDataType.md) | Message to sign and encrypt. | | `publicKeys` | `string`[] | Array of public keys to use for encryption. | + #### Returns | Type | Description | @@ -99,11 +108,14 @@ decrypt(message: string, publicKey?: string): Promise; This function signs a message using the private key used to initialize the client. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `message` | `string` | Message to sign. | + #### Returns | Type | Description | diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/EncryptionUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/EncryptionUtils.md index 0229a249c6..ae06dcd04a 100644 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/EncryptionUtils.md +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/EncryptionUtils.md @@ -10,11 +10,14 @@ static verify(message: string, publicKey: string): Promise; This function verifies the signature of a signed message using the public key. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `message` | `string` | Message to verify. | | `publicKey` | `string` | Public key to verify that the message was signed by a specific source. | + #### Returns | Type | Description | @@ -42,10 +45,13 @@ static getSignedData(message: string): Promise; This function gets signed data from a signed message. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `message` | `string` | Message. | + #### Returns | Type | Description | @@ -81,12 +87,15 @@ passphrase: string): Promise; This function generates a key pair for encryption and decryption. +#### Parameters + | Parameter | Type | Default value | Description | | ------ | ------ | ------ | ------ | | `name` | `string` | `undefined` | Name for the key pair. | | `email` | `string` | `undefined` | Email for the key pair. | | `passphrase` | `string` | `''` | Passphrase to encrypt the private key (optional, defaults to empty string). | + #### Returns | Type | Description | @@ -116,11 +125,14 @@ static encrypt(message: MessageDataType, publicKeys: string[]): Promise; This function encrypts a message using the specified public keys. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `message` | [`MessageDataType`](../type-aliases/MessageDataType.md) | Message to encrypt. | | `publicKeys` | `string`[] | Array of public keys to use for encryption. | + #### Returns | Type | Description | @@ -150,10 +162,13 @@ static isEncrypted(message: string): boolean; Verifies if a message appears to be encrypted with OpenPGP. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `message` | `string` | Message to verify. | + #### Returns | Type | Description | diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowClient.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowClient.md index e14764d015..1c517db6e5 100644 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowClient.md +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowClient.md @@ -61,16 +61,21 @@ new EscrowClient(runner: ContractRunner, networkData: NetworkData): EscrowClient **EscrowClient constructor** +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | | `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the Escrow contract | + #### Returns | Type | Description | |------|-------------| -| `EscrowClient` | #### Overrides | +| `EscrowClient` | An instance of EscrowClient | + +#### Overrides ```ts BaseEthersClient.constructor @@ -86,10 +91,13 @@ static build(runner: ContractRunner): Promise; Creates an instance of EscrowClient from a Runner. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | + #### Returns | Type | Description | @@ -115,8 +123,8 @@ txOptions: Overrides): Promise; ``` This function creates an escrow contract that uses the token passed to pay oracle fees and reward workers. -!!! note - Need to have available stake. + +#### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | @@ -124,12 +132,17 @@ This function creates an escrow contract that uses the token passed to pay oracl | `jobRequesterId` | `string` | Identifier for the job requester. | | `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + #### Returns | Type | Description | |------|-------------| | `string` | Returns the address of the escrow created. | +#### Remarks + +Need to have available stake. + #### Throws | Type | Description | @@ -161,6 +174,8 @@ txOptions: Overrides): Promise; Creates, funds, and sets up a new escrow contract in a single transaction. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `tokenAddress` | `string` | The ERC-20 token address used to fund the escrow. | @@ -169,12 +184,17 @@ Creates, funds, and sets up a new escrow contract in a single transaction. | `escrowConfig` | `IEscrowConfig` | Configuration parameters for escrow setup. | | `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + #### Returns | Type | Description | |------|-------------| | `string` | Returns the address of the escrow created. | +#### Remarks + +Need to have available stake and approve allowance in the token contract before calling this method. + #### Throws | Type | Description | @@ -236,8 +256,7 @@ txOptions: Overrides): Promise; This function sets up the parameters of the escrow. -!!! note - Only Job Launcher or admin can call it. +#### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | @@ -245,18 +264,22 @@ This function sets up the parameters of the escrow. | `escrowConfig` | `IEscrowConfig` | Escrow configuration parameters. | | `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + #### Returns | Type | Description | |------|-------------| -| `void` | #### Throws | +| `void` | - | + +#### Remarks -ErrorInvalidRecordingOracleAddressProvided If the recording oracle address is invalid +Only Job Launcher or admin can call it. #### Throws | Type | Description | |------|-------------| +| `ErrorInvalidRecordingOracleAddressProvided` | If the recording oracle address is invalid | | `ErrorInvalidReputationOracleAddressProvided` | If the reputation oracle address is invalid | | `ErrorInvalidExchangeOracleAddressProvided` | If the exchange oracle address is invalid | | `ErrorAmountMustBeGreaterThanZero` | If any oracle fee is less than or equal to zero | @@ -297,24 +320,26 @@ txOptions: Overrides): Promise; This function adds funds of the chosen token to the escrow. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `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 | Type | Description | |------|-------------| -| `void` | #### Throws | - -ErrorInvalidEscrowAddressProvided If the escrow address is invalid +| `void` | - | #### Throws | Type | Description | |------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | | `ErrorAmountMustBeGreaterThanZero` | If the amount is less than or equal to zero | | `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | @@ -332,60 +357,6 @@ ErrorInvalidEscrowAddressProvided If the escrow address is invalid ### storeResults() -Stores the result URL and result hash for an escrow. - -!!! note - Only Recording Oracle or admin can call it. - -This method has two overloads: -- `storeResults(escrowAddress, url, hash, txOptions?)` - Without funds to reserve -- `storeResults(escrowAddress, url, hash, fundsToReserve, txOptions?)` - With funds to reserve - -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). - -The escrow address. - -The URL containing the final results. May be empty only when `fundsToReserve` is `0n`. - -The hash of the results payload. - -Optional amount of funds to reserve (when using second overload). - -Optional transaction overrides. - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the provided escrow address is invalid. | -| `ErrorInvalidUrl` | If the URL format is invalid. | -| `ErrorHashIsEmptyString` | If the hash is empty and empty values are not allowed. | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow does not exist in the factory. | -| `ErrorStoreResultsVersion` | If the contract supports only the deprecated signature. | - -#### Example -Without funds to reserve: -```ts -await escrowClient.storeResults( - '0x62dD51230A30401C455c8398d06F85e4EaB6309f', - 'https://example.com/results.json', - '0xHASH123' -); -``` - -With funds to reserve: -```ts -import { ethers } from 'ethers'; - -await escrowClient.storeResults( - '0x62dD51230A30401C455c8398d06F85e4EaB6309f', - 'https://example.com/results.json', - '0xHASH123', - ethers.parseEther('5') -); -``` - #### Call Signature ```ts @@ -398,17 +369,7 @@ txOptions?: Overrides): Promise; Stores the result URL and result hash for an escrow. -!!! note - Only Recording Oracle or admin can call it. - -This method has two overloads: -- `storeResults(escrowAddress, url, hash, txOptions?)` - Without funds to reserve -- `storeResults(escrowAddress, url, hash, fundsToReserve, txOptions?)` - With funds to reserve - -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). - -##### Parameters +#### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | @@ -417,52 +378,37 @@ When `fundsToReserve` is `0n`, an empty URL is allowed (for cases where no solut | `hash` | `string` | The hash of the results payload. | | `txOptions?` | `Overrides` | Optional transaction overrides. | -##### Returns - -`Promise`\<`void`\> - -##### Throws - -ErrorInvalidEscrowAddressProvided If the provided escrow address is invalid. - -##### Throws -ErrorInvalidUrl If the URL format is invalid. - -##### Throws +#### Returns -ErrorHashIsEmptyString If the hash is empty and empty values are not allowed. +| Type | Description | +|------|-------------| +| `void` | - | -##### Throws +#### Remarks -ErrorEscrowAddressIsNotProvidedByFactory If the escrow does not exist in the factory. +Only Recording Oracle or admin can call it. -##### Throws +#### Throws -ErrorStoreResultsVersion If the contract supports only the deprecated signature. +| Type | Description | +|------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the provided escrow address is invalid. | +| `ErrorInvalidUrl` | If the URL format is invalid. | +| `ErrorHashIsEmptyString` | If the hash is empty and empty values are not allowed. | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow does not exist in the factory. | +| `ErrorStoreResultsVersion` | If the contract supports only the deprecated signature. | -##### Examples +???+ example "Example" -Without funds to reserve: -```ts -await escrowClient.storeResults( - '0x62dD51230A30401C455c8398d06F85e4EaB6309f', - 'https://example.com/results.json', - '0xHASH123' -); -``` + ```ts + await escrowClient.storeResults( + '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + 'https://example.com/results.json', + '0xHASH123' + ); + ``` -With funds to reserve: -```ts -import { ethers } from 'ethers'; - -await escrowClient.storeResults( - '0x62dD51230A30401C455c8398d06F85e4EaB6309f', - 'https://example.com/results.json', - '0xHASH123', - ethers.parseEther('5') -); -``` #### Call Signature @@ -477,17 +423,7 @@ txOptions?: Overrides): Promise; Stores the result URL and result hash for an escrow. -!!! note - Only Recording Oracle or admin can call it. - -This method has two overloads: -- `storeResults(escrowAddress, url, hash, txOptions?)` - Without funds to reserve -- `storeResults(escrowAddress, url, hash, fundsToReserve, txOptions?)` - With funds to reserve - -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). - -##### Parameters +#### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | @@ -497,52 +433,43 @@ When `fundsToReserve` is `0n`, an empty URL is allowed (for cases where no solut | `fundsToReserve` | `bigint` | Optional amount of funds to reserve (when using second overload). | | `txOptions?` | `Overrides` | Optional transaction overrides. | -##### Returns - -`Promise`\<`void`\> -##### Throws - -ErrorInvalidEscrowAddressProvided If the provided escrow address is invalid. - -##### Throws - -ErrorInvalidUrl If the URL format is invalid. +#### Returns -##### Throws +| Type | Description | +|------|-------------| +| `void` | - | -ErrorHashIsEmptyString If the hash is empty and empty values are not allowed. +#### Remarks -##### Throws +Only Recording Oracle or admin can call it. -ErrorEscrowAddressIsNotProvidedByFactory If the escrow does not exist in the factory. +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). -##### Throws +#### Throws -ErrorStoreResultsVersion If the contract supports only the deprecated signature. +| Type | Description | +|------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the provided escrow address is invalid. | +| `ErrorInvalidUrl` | If the URL format is invalid. | +| `ErrorHashIsEmptyString` | If the hash is empty and empty values are not allowed. | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow does not exist in the factory. | +| `ErrorStoreResultsVersion` | If the contract supports only the deprecated signature. | -##### Examples +???+ example "Example" -Without funds to reserve: -```ts -await escrowClient.storeResults( - '0x62dD51230A30401C455c8398d06F85e4EaB6309f', - 'https://example.com/results.json', - '0xHASH123' -); -``` + ```ts + import { ethers } from 'ethers'; + + await escrowClient.storeResults( + '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + 'https://example.com/results.json', + '0xHASH123', + ethers.parseEther('5') + ); + ``` -With funds to reserve: -```ts -import { ethers } from 'ethers'; - -await escrowClient.storeResults( - '0x62dD51230A30401C455c8398d06F85e4EaB6309f', - 'https://example.com/results.json', - '0xHASH123', - ethers.parseEther('5') -); -``` *** @@ -554,31 +481,37 @@ complete(escrowAddress: string, txOptions: Overrides): Promise; This function sets the status of an escrow to completed. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `escrowAddress` | `string` | Address of the escrow. | | `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + #### Returns | Type | Description | |------|-------------| -| `void` | #### Throws | +| `void` | - | -ErrorInvalidEscrowAddressProvided If the escrow address is invalid +#### Remarks + +Only Recording Oracle or admin can call it. #### Throws | Type | Description | |------|-------------| -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid. | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory. | -#### Example -> Only Recording Oracle or admin can call it. +???+ example "Example" + + ```ts + await escrowClient.complete('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + ``` -```ts -await escrowClient.complete('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` *** @@ -600,7 +533,7 @@ txOptions: Overrides): Promise; This function pays out the amounts specified to the workers and sets the URL of the final results file. -##### Parameters +#### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | @@ -613,77 +546,55 @@ This function pays out the amounts specified to the workers and sets the URL of | `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`\> - -##### 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 +#### Returns -ErrorEscrowDoesNotHaveEnoughBalance If the escrow doesn't have enough balance +| Type | Description | +|------|-------------| +| `void` | - | -##### Throws +#### Remarks -ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory +Only Reputation Oracle or admin can call it. -##### Throws +#### Throws -ErrorBulkPayOutVersion If using deprecated signature +| Type | Description | +|------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorRecipientCannotBeEmptyArray` | If the recipients array is empty | +| `ErrorTooManyRecipients` | If there are too many recipients | +| `ErrorAmountsCannotBeEmptyArray` | If the amounts array is empty | +| `ErrorRecipientAndAmountsMustBeSameLength` | If recipients and amounts arrays have different lengths | +| `InvalidEthereumAddressError` | If any recipient address is invalid | +| `ErrorInvalidUrl` | If the final results URL is invalid | +| `ErrorHashIsEmptyString` | If the final results hash is empty | +| `ErrorEscrowDoesNotHaveEnoughBalance` | If the escrow doesn't have enough balance | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | +| `ErrorBulkPayOutVersion` | If using deprecated signature | -##### Example +???+ example "Example" -> Only Reputation Oracle or admin can call it. + ```ts + import { ethers } from 'ethers'; + + 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 + ); + ``` -```ts -import { ethers } from 'ethers'; - -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 -); -``` #### Call Signature @@ -701,7 +612,7 @@ txOptions: Overrides): Promise; This function pays out the amounts specified to the workers and sets the URL of the final results file. -##### Parameters +#### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | @@ -714,78 +625,56 @@ This function pays out the amounts specified to the workers and sets the URL of | `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`\> - -##### 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 +#### Returns -ErrorEscrowDoesNotHaveEnoughBalance If the escrow doesn't have enough balance +| Type | Description | +|------|-------------| +| `void` | - | -##### Throws +#### Remarks -ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory +Only Reputation Oracle or admin can call it. -##### Throws +#### Throws -ErrorBulkPayOutVersion If using deprecated signature +| Type | Description | +|------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | +| `ErrorRecipientCannotBeEmptyArray` | If the recipients array is empty | +| `ErrorTooManyRecipients` | If there are too many recipients | +| `ErrorAmountsCannotBeEmptyArray` | If the amounts array is empty | +| `ErrorRecipientAndAmountsMustBeSameLength` | If recipients and amounts arrays have different lengths | +| `InvalidEthereumAddressError` | If any recipient address is invalid | +| `ErrorInvalidUrl` | If the final results URL is invalid | +| `ErrorHashIsEmptyString` | If the final results hash is empty | +| `ErrorEscrowDoesNotHaveEnoughBalance` | If the escrow doesn't have enough balance | +| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | +| `ErrorBulkPayOutVersion` | If using deprecated signature | -##### Example +???+ example "Example" -> Only Reputation Oracle or admin can call it. + ```ts + import { ethers } from 'ethers'; + import { v4 as uuidV4 } from 'uuid'; + + 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 + ); + ``` -```ts -import { ethers } from 'ethers'; -import { v4 as uuidV4 } from 'uuid'; - -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 -); -``` *** @@ -797,31 +686,37 @@ cancel(escrowAddress: string, txOptions: Overrides): Promise; This function cancels the specified escrow and sends the balance to the canceler. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `escrowAddress` | `string` | Address of the escrow to cancel. | | `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + #### Returns | Type | Description | |------|-------------| -| `void` | #### Throws | +| `void` | - | + +#### Remarks -ErrorInvalidEscrowAddressProvided If the escrow address is invalid +Only Job Launcher or admin can call it. #### Throws | Type | Description | |------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | | `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | -#### Example -> Only Job Launcher or admin can call it. +???+ example "Example" + + ```ts + await escrowClient.cancel('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + ``` -```ts -await escrowClient.cancel('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` *** @@ -833,31 +728,37 @@ requestCancellation(escrowAddress: string, txOptions: Overrides): Promise; This function requests the cancellation of the specified escrow (moves status to ToCancel or finalizes if expired). +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `escrowAddress` | `string` | Address of the escrow to request cancellation. | | `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + #### Returns | Type | Description | |------|-------------| -| `void` | #### Throws | +| `void` | - | -ErrorInvalidEscrowAddressProvided If the escrow address is invalid +#### Remarks + +Only Job Launcher or admin can call it. #### Throws | Type | Description | |------|-------------| +| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | | `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | -#### Example -> Only Job Launcher or admin can call it. +???+ example "Example" + + ```ts + await escrowClient.requestCancellation('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); + ``` -```ts -await escrowClient.requestCancellation('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); -``` *** @@ -872,18 +773,25 @@ txOptions: Overrides): Promise; This function withdraws additional tokens in the escrow to the canceler. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `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 | Type | Description | |------|-------------| | `IEscrowWithdraw` | Returns the escrow withdrawal data including transaction hash and withdrawal amount. | +#### Remarks + +Only Job Launcher or admin can call it. + #### Throws | Type | Description | @@ -893,16 +801,16 @@ This function withdraws additional tokens in the escrow to the canceler. | `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | | `ErrorTransferEventNotFoundInTransactionLogs` | If the Transfer event is not found in transaction logs | -#### Example -> Only Job Launcher or admin can call it. +???+ example "Example" + + ```ts + const withdrawData = await escrowClient.withdraw( + '0x62dD51230A30401C455c8398d06F85e4EaB6309f', + '0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4' + ); + console.log('Withdrawn amount:', withdrawData.withdrawnAmount); + ``` -```ts -const withdrawData = await escrowClient.withdraw( - '0x62dD51230A30401C455c8398d06F85e4EaB6309f', - '0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4' -); -console.log('Withdrawn amount:', withdrawData.withdrawnAmount); -``` *** @@ -922,6 +830,8 @@ txOptions: Overrides): Promise; Creates a prepared transaction for bulk payout without immediately sending it. +#### Parameters + | Parameter | Type | Default value | Description | | ------ | ------ | ------ | ------ | | `escrowAddress` | `string` | `undefined` | Escrow address to payout. | @@ -933,12 +843,17 @@ Creates a prepared transaction for bulk payout without immediately sending it. | `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 | Type | Description | |------|-------------| | `TransactionLikeWithNonce` | Returns object with raw transaction and nonce | +#### Remarks + +Only Reputation Oracle or admin can call it. + #### Throws | Type | Description | @@ -954,33 +869,33 @@ Creates a prepared transaction for bulk payout without immediately sending it. | `ErrorEscrowDoesNotHaveEnoughBalance` | If the escrow doesn't have enough balance | | `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | -#### Example -> Only Reputation Oracle or admin can call it. +???+ example "Example" + + ```ts + import { ethers } from 'ethers'; + import { v4 as uuidV4 } from 'uuid'; + + 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(); + + 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); + ``` -```ts -import { ethers } from 'ethers'; -import { v4 as uuidV4 } from 'uuid'; - -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(); - -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); -``` *** @@ -992,10 +907,13 @@ getBalance(escrowAddress: string): Promise; This function returns the balance for a specified escrow address. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `escrowAddress` | `string` | Address of the escrow. | + #### Returns | Type | Description | @@ -1027,10 +945,13 @@ getReservedFunds(escrowAddress: string): Promise; This function returns the reserved funds for a specified escrow address. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `escrowAddress` | `string` | Address of the escrow. | + #### Returns | Type | Description | @@ -1062,10 +983,13 @@ getManifestHash(escrowAddress: string): Promise; This function returns the manifest file hash. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `escrowAddress` | `string` | Address of the escrow. | + #### Returns | Type | Description | @@ -1097,10 +1021,13 @@ getManifest(escrowAddress: string): Promise; This function returns the manifest. Could be a URL or a JSON string. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `escrowAddress` | `string` | Address of the escrow. | + #### Returns | Type | Description | @@ -1132,10 +1059,13 @@ getResultsUrl(escrowAddress: string): Promise; This function returns the results file URL. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `escrowAddress` | `string` | Address of the escrow. | + #### Returns | Type | Description | @@ -1167,10 +1097,13 @@ getIntermediateResultsUrl(escrowAddress: string): Promise; This function returns the intermediate results file URL. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `escrowAddress` | `string` | Address of the escrow. | + #### Returns | Type | Description | @@ -1202,10 +1135,13 @@ getIntermediateResultsHash(escrowAddress: string): Promise; This function returns the intermediate results hash. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `escrowAddress` | `string` | Address of the escrow. | + #### Returns | Type | Description | @@ -1237,10 +1173,13 @@ getTokenAddress(escrowAddress: string): Promise; This function returns the token address used for funding the escrow. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `escrowAddress` | `string` | Address of the escrow. | + #### Returns | Type | Description | @@ -1272,10 +1211,13 @@ getStatus(escrowAddress: string): Promise; This function returns the current status of the escrow. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `escrowAddress` | `string` | Address of the escrow. | + #### Returns | Type | Description | @@ -1309,10 +1251,13 @@ getRecordingOracleAddress(escrowAddress: string): Promise; This function returns the recording oracle address for a given escrow. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `escrowAddress` | `string` | Address of the escrow. | + #### Returns | Type | Description | @@ -1344,10 +1289,13 @@ getJobLauncherAddress(escrowAddress: string): Promise; This function returns the job launcher address for a given escrow. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `escrowAddress` | `string` | Address of the escrow. | + #### Returns | Type | Description | @@ -1379,10 +1327,13 @@ getReputationOracleAddress(escrowAddress: string): Promise; This function returns the reputation oracle address for a given escrow. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `escrowAddress` | `string` | Address of the escrow. | + #### Returns | Type | Description | @@ -1414,10 +1365,13 @@ getExchangeOracleAddress(escrowAddress: string): Promise; This function returns the exchange oracle address for a given escrow. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `escrowAddress` | `string` | Address of the escrow. | + #### Returns | Type | Description | @@ -1449,10 +1403,13 @@ getFactoryAddress(escrowAddress: string): Promise; This function returns the escrow factory address for a given escrow. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `escrowAddress` | `string` | Address of the escrow. | + #### Returns | Type | Description | diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowUtils.md index 745da2cef3..200901197d 100644 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowUtils.md +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowUtils.md @@ -21,11 +21,14 @@ static getEscrows(filter: IEscrowsFilter, options?: SubgraphOptions): Promise This uses Subgraph +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `chainId` | `ChainId` | Network in which the escrow has been deployed | | `escrowAddress` | `string` | Address of the escrow | | `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + #### Returns | Type | Description | @@ -116,11 +122,14 @@ This function returns the status events for a given set of networks within an op > This uses Subgraph +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `filter` | `IStatusEventFilter` | Filter parameters. | | `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + #### Returns | Type | Description | @@ -163,11 +172,14 @@ This function returns the payouts for a given set of networks. > This uses Subgraph +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `filter` | `IPayoutFilter` | Filter parameters. | | `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + #### Returns | Type | Description | @@ -209,11 +221,14 @@ This function returns the cancellation refunds for a given set of networks. > This uses Subgraph +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `filter` | `ICancellationRefundFilter` | Filter parameters. | | `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + #### Returns | Type | Description | @@ -256,12 +271,15 @@ This function returns the cancellation refund for a given escrow address. > This uses Subgraph +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `chainId` | `ChainId` | Network in which the escrow has been deployed | | `escrowAddress` | `string` | Address of the escrow | | `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + #### Returns | Type | Description | diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreClient.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreClient.md index 9de83620dd..70e26f2f32 100644 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreClient.md +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreClient.md @@ -66,16 +66,21 @@ new KVStoreClient(runner: ContractRunner, networkData: NetworkData): KVStoreClie **KVStoreClient constructor** +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | | `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the KVStore contract | + #### Returns | Type | Description | |------|-------------| -| `KVStoreClient` | #### Overrides | +| `KVStoreClient` | - | + +#### Overrides ```ts BaseEthersClient.constructor @@ -91,10 +96,13 @@ static build(runner: ContractRunner): Promise; Creates an instance of KVStoreClient from a runner. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | + #### Returns | Type | Description | @@ -136,24 +144,26 @@ txOptions: Overrides): Promise; This function sets a key-value pair associated with the address that submits the transaction. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `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 | Type | Description | |------|-------------| -| `void` | #### Throws | - -ErrorKVStoreEmptyKey If the key is empty +| `void` | - | #### Throws | Type | Description | |------|-------------| +| `ErrorKVStoreEmptyKey` | If the key is empty | | `Error` | If the transaction fails | ???+ example "Example" @@ -176,24 +186,26 @@ txOptions: Overrides): Promise; This function sets key-value pairs in bulk associated with the address that submits the transaction. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `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 | Type | Description | |------|-------------| -| `void` | #### Throws | - -ErrorKVStoreArrayLength If keys and values arrays have different lengths +| `void` | - | #### Throws | Type | Description | |------|-------------| +| `ErrorKVStoreArrayLength` | If keys and values arrays have different lengths | | `ErrorKVStoreEmptyKey` | If any key is empty | | `Error` | If the transaction fails | @@ -219,24 +231,26 @@ txOptions: Overrides): Promise; Sets a URL value for the address that submits the transaction, and its hash. +#### Parameters + | Parameter | Type | Default value | Description | | ------ | ------ | ------ | ------ | | `url` | `string` | `undefined` | URL to set | | `urlKey` | `string` | `'url'` | Configurable URL key. `url` by default. | | `txOptions` | `Overrides` | `{}` | Additional transaction parameters (optional, defaults to an empty object). | + #### Returns | Type | Description | |------|-------------| -| `void` | #### Throws | - -ErrorInvalidUrl If the URL is invalid +| `void` | - | #### Throws | Type | Description | |------|-------------| +| `ErrorInvalidUrl` | If the URL is invalid | | `Error` | If the transaction fails | ???+ example "Example" @@ -257,11 +271,14 @@ get(address: string, key: string): Promise; Gets the value of a key-value pair in the contract. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `address` | `string` | Address from which to get the key value. | | `key` | `string` | Key to obtain the value. | + #### Returns | Type | Description | diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreUtils.md index d23fe3232e..cd345ec972 100644 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreUtils.md +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreUtils.md @@ -25,12 +25,15 @@ options?: SubgraphOptions): Promise; This function returns the KVStore data for a given address. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `chainId` | `ChainId` | Network in which the KVStore is deployed | | `address` | `string` | Address of the KVStore | | `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + #### Returns | Type | Description | @@ -69,6 +72,8 @@ options?: SubgraphOptions): Promise; Gets the value of a key-value pair in the KVStore using the subgraph. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `chainId` | `ChainId` | Network in which the KVStore is deployed | @@ -76,6 +81,7 @@ Gets the value of a key-value pair in the KVStore using the subgraph. | `key` | `string` | Key to obtain the value. | | `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + #### Returns | Type | Description | @@ -117,6 +123,8 @@ options?: SubgraphOptions): Promise; Gets the URL value of the given entity, and verifies its hash. +#### Parameters + | Parameter | Type | Default value | Description | | ------ | ------ | ------ | ------ | | `chainId` | `ChainId` | `undefined` | Network in which the KVStore is deployed | @@ -124,6 +132,7 @@ Gets the URL value of the given entity, and verifies its hash. | `urlKey` | `string` | `'url'` | Configurable URL key. `url` by default. | | `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | `undefined` | Optional configuration for subgraph requests. | + #### Returns | Type | Description | @@ -162,12 +171,15 @@ options?: SubgraphOptions): Promise; Gets the public key of the given entity, and verifies its hash. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `chainId` | `ChainId` | Network in which the KVStore is deployed | | `address` | `string` | Address from which to get the public key. | | `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + #### Returns | Type | Description | diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/OperatorUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/OperatorUtils.md index 91d91e11e4..ccb0a8e745 100644 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/OperatorUtils.md +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/OperatorUtils.md @@ -25,12 +25,15 @@ options?: SubgraphOptions): Promise; This function returns the operator data for the given address. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `chainId` | `ChainId` | Network in which the operator is deployed | | `address` | `string` | Operator address. | | `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + #### Returns | Type | Description | @@ -67,11 +70,14 @@ static getOperators(filter: IOperatorsFilter, options?: SubgraphOptions): Promis This function returns all the operator details of the protocol. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `filter` | `IOperatorsFilter` | Filter for the operators. | | `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + #### Returns | Type | Description | @@ -111,6 +117,8 @@ options?: SubgraphOptions): Promise; Retrieves the reputation network operators of the specified address. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `chainId` | `ChainId` | Network in which the reputation network is deployed | @@ -118,6 +126,7 @@ Retrieves the reputation network operators of the specified address. | `role?` | `string` | Role of the operator (optional). | | `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + #### Returns | Type | Description | @@ -156,12 +165,15 @@ options?: SubgraphOptions): Promise; This function returns information about the rewards for a given slasher address. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `chainId` | `ChainId` | Network in which the rewards are deployed | | `slasherAddress` | `string` | Slasher address. | | `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + #### Returns | Type | Description | diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingClient.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingClient.md index e40d0d5086..3a42b1133a 100644 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingClient.md +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingClient.md @@ -66,16 +66,21 @@ new StakingClient(runner: ContractRunner, networkData: NetworkData): StakingClie **StakingClient constructor** +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | | `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the Staking contract | + #### Returns | Type | Description | |------|-------------| -| `StakingClient` | #### Overrides | +| `StakingClient` | - | + +#### Overrides ```ts BaseEthersClient.constructor @@ -91,10 +96,13 @@ static build(runner: ContractRunner): Promise; Creates an instance of StakingClient from a Runner. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | + #### Returns | Type | Description | @@ -133,23 +141,25 @@ approveStake(amount: bigint, txOptions: Overrides): Promise; 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 + | Parameter | Type | Description | | ------ | ------ | ------ | | `amount` | `bigint` | Amount in WEI of tokens to approve for stake. | | `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + #### Returns | Type | Description | |------|-------------| -| `void` | #### Throws | - -ErrorInvalidStakingValueType If the amount is not a bigint +| `void` | - | #### Throws | Type | Description | |------|-------------| +| `ErrorInvalidStakingValueType` | If the amount is not a bigint | | `ErrorInvalidStakingValueSign` | If the amount is negative | ???+ example "Example" @@ -175,23 +185,25 @@ This function stakes a specified amount of tokens on a specific network. !!! note `approveStake` must be called before +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `amount` | `bigint` | Amount in WEI of tokens to stake. | | `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + #### Returns | Type | Description | |------|-------------| -| `void` | #### Throws | - -ErrorInvalidStakingValueType If the amount is not a bigint +| `void` | - | #### Throws | Type | Description | |------|-------------| +| `ErrorInvalidStakingValueType` | If the amount is not a bigint | | `ErrorInvalidStakingValueSign` | If the amount is negative | ???+ example "Example" @@ -218,23 +230,25 @@ This function unstakes tokens from staking contract. The unstaked tokens stay lo !!! note Must have tokens available to unstake +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `amount` | `bigint` | Amount in WEI of tokens to unstake. | | `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + #### Returns | Type | Description | |------|-------------| -| `void` | #### Throws | - -ErrorInvalidStakingValueType If the amount is not a bigint +| `void` | - | #### Throws | Type | Description | |------|-------------| +| `ErrorInvalidStakingValueType` | If the amount is not a bigint | | `ErrorInvalidStakingValueSign` | If the amount is negative | ???+ example "Example" @@ -259,19 +273,25 @@ This function withdraws unstaked and non-locked tokens from staking contract to !!! note Must have tokens available to withdraw +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + #### Returns | Type | Description | |------|-------------| -| `void` | #### Example | +| `void` | - | + +???+ example "Example" + + ```ts + await stakingClient.withdraw(); + ``` -```ts -await stakingClient.withdraw(); -``` *** @@ -288,6 +308,8 @@ txOptions: Overrides): Promise; 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 + | Parameter | Type | Description | | ------ | ------ | ------ | | `slasher` | `string` | Wallet address from who requested the slash | @@ -296,18 +318,18 @@ This function reduces the allocated amount by a staker in an escrow and transfer | `amount` | `bigint` | Amount in WEI of tokens to slash. | | `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | + #### Returns | Type | Description | |------|-------------| -| `void` | #### Throws | - -ErrorInvalidStakingValueType If the amount is not a bigint +| `void` | - | #### Throws | Type | Description | |------|-------------| +| `ErrorInvalidStakingValueType` | If the amount is not a bigint | | `ErrorInvalidStakingValueSign` | If the amount is negative | | `ErrorInvalidSlasherAddressProvided` | If the slasher address is invalid | | `ErrorInvalidStakerAddressProvided` | If the staker address is invalid | @@ -339,10 +361,13 @@ getStakerInfo(stakerAddress: string): Promise; Retrieves comprehensive staking information for a staker. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `stakerAddress` | `string` | The address of the staker. | + #### Returns | Type | Description | diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingUtils.md index 55528ed01f..431e4bb3f1 100644 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingUtils.md +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingUtils.md @@ -25,12 +25,15 @@ options?: SubgraphOptions): Promise; Gets staking info for a staker from the subgraph. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `chainId` | `ChainId` | Network in which the staking contract is deployed | | `stakerAddress` | `string` | Address of the staker | | `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + #### Returns | Type | Description | @@ -68,11 +71,14 @@ static getStakers(filter: IStakersFilter, options?: SubgraphOptions): Promise; This function returns the holders of the HMToken with optional filters and ordering. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | | `params` | `IHMTHoldersParams` | HMT Holders params with filters and ordering | | `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + #### Returns | Type | Description | @@ -350,12 +365,15 @@ interface IDailyHMT { } ``` +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | | `filter` | `IStatisticsFilter` | Statistics params with duration data | | `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + #### Returns | Type | Description | diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/TransactionUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/TransactionUtils.md index 61b1b10f09..84138cfa63 100644 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/TransactionUtils.md +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/TransactionUtils.md @@ -53,12 +53,15 @@ type InternalTransaction = { }; ``` +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `chainId` | `ChainId` | The chain ID. | | `hash` | `string` | The transaction hash. | | `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + #### Returns | Type | Description | @@ -145,11 +148,14 @@ type ITransaction = { }; ``` +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `filter` | `ITransactionsFilter` | Filter for the transactions. | | `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + #### Returns | Type | Description | diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/WorkerUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/WorkerUtils.md index b00c6c3158..739ecde4b1 100644 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/WorkerUtils.md +++ b/packages/sdk/typescript/human-protocol-sdk/docs/classes/WorkerUtils.md @@ -25,12 +25,15 @@ options?: SubgraphOptions): Promise; This function returns the worker data for the given address. +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `chainId` | `ChainId` | The chain ID. | | `address` | `string` | The worker address. | | `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + #### Returns | Type | Description | @@ -89,11 +92,14 @@ type IWorker = { }; ``` +#### Parameters + | Parameter | Type | Description | | ------ | ------ | ------ | | `filter` | `IWorkersFilter` | Filter for the workers. | | `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | + #### Returns | Type | Description | diff --git a/packages/sdk/typescript/human-protocol-sdk/scripts/postprocess-docs.ts b/packages/sdk/typescript/human-protocol-sdk/scripts/postprocess-docs.ts index 9c52914923..daeb65972e 100644 --- a/packages/sdk/typescript/human-protocol-sdk/scripts/postprocess-docs.ts +++ b/packages/sdk/typescript/human-protocol-sdk/scripts/postprocess-docs.ts @@ -7,74 +7,147 @@ const ROOT = 'docs'; // adjust if needed function processFile(path: PathOrFileDescriptor) { const original = readFileSync(path, 'utf8'); - const lines = original.split('\n'); + 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) { - const line = lines[i]; + 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; + } - // ---------- THROWS: merge all into one table ---------- + // ---------- 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')) { - const rows: { type: string; desc: string }[] = []; + 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 all consecutive "#### Throws" sections + // 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 || /^###? /.test(lines[i])) break; - - const first = lines[i].trim(); - i++; - - let type = ''; - let desc = ''; + if (i >= lines.length) break; - // pattern: ErrorType Some description... - const m = first.match(/^`?([^`\s]+)`?\s*(.*)$/); - if (m) { - type = m[1].trim(); - desc = (m[2] || '').trim(); + // 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 { - desc = first; - } - - // if description is empty, read following lines - if (!desc) { - const descParts: string[] = []; + // freeform lines until next heading or blank line while ( i < lines.length && lines[i].trim() !== '' && - !/^###? /.test(lines[i]) + !/^### /.test(lines[i]) && + !/^#### /.test(lines[i]) && + !/^##### /.test(lines[i]) ) { - descParts.push(lines[i].trim()); + pushLineAsRow(lines[i]); i++; } - desc = descParts.join(' '); } // skip blank lines between throws blocks while (i < lines.length && lines[i].trim() === '') i++; - - rows.push({ type, desc }); } - // emit one table + // 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(`| \`${r.type || '-'}\` | ${r.desc || '-'} |`); } out.push(''); continue; } - // ---------- RETURNS: single table ---------- + // ---------- RETURNS: normalize into a table (after heading normalization) ---------- if (line.startsWith('#### Returns')) { i++; // skip heading @@ -86,19 +159,21 @@ function processFile(path: PathOrFileDescriptor) { break; } - // type line: `Promise`\<`EscrowClient`\> + // 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 next heading or blank+heading + // 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]) && + !/^##### /.test(lines[i]) ) { descParts.push(lines[i].trim()); i++; @@ -109,9 +184,9 @@ function processFile(path: PathOrFileDescriptor) { .replace(/`/g, '') .replace(/\\/g, '>'); - rawType = rawType.trim(); // e.g. Promise + rawType = rawType.trim(); - // OPTIONAL: strip Promise<...> wrapper so only EscrowClient appears + // strip Promise<...> wrapper const type = rawType.replace(/^Promise\s*<\s*([^>]+)\s*>$/i, '$1').trim(); const desc = descParts.join(' '); @@ -142,14 +217,170 @@ function processFile(path: PathOrFileDescriptor) { } // second pass: transform Examples into admonitions - let text = out.join('\n'); + text = out.join('\n'); text = transformExamples(text); writeFileSync(path, text); } -// ---------- EXAMPLES -> admonition ---------- +// ---------- 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[] = []; @@ -158,8 +389,8 @@ function transformExamples(text: string): string { while (i < lines.length) { const line = lines[i]; - // Match "#### Example" - if (line.startsWith('#### Example')) { + // Match "#### Example" or "#### Examples" + if (/^####\s+Examples?/.test(line)) { i++; // skip heading // Skip blank lines @@ -196,6 +427,13 @@ function transformExamples(text: string): string { 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++; } @@ -203,6 +441,12 @@ function transformExamples(text: string): string { 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) { diff --git a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts b/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts index d4d1b54d42..065bd369fb 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts @@ -134,6 +134,7 @@ export class EscrowClient extends BaseEthersClient { * * @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); @@ -184,8 +185,7 @@ export class EscrowClient extends BaseEthersClient { /** * This function creates an escrow contract that uses the token passed to pay oracle fees and reward workers. - * !!! note - * Need to have available stake. + * @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). @@ -285,6 +285,7 @@ export class EscrowClient extends BaseEthersClient { /** * Creates, funds, and sets up a new escrow contract in a single transaction. * + * @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. @@ -395,13 +396,12 @@ export class EscrowClient extends BaseEthersClient { /** * This function sets up the parameters of the escrow. * - * !!! note - * Only Job Launcher or admin can call it. + * @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 @@ -485,6 +485,7 @@ export class EscrowClient extends BaseEthersClient { * @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 @@ -537,22 +538,13 @@ export class EscrowClient extends BaseEthersClient { /** * Stores the result URL and result hash for an escrow. * - * !!! note - * Only Recording Oracle or admin can call it. - * - * This method has two overloads: - * - `storeResults(escrowAddress, url, hash, txOptions?)` - Without funds to reserve - * - `storeResults(escrowAddress, url, hash, fundsToReserve, txOptions?)` - With funds to reserve - * - * 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). + * @remarks 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. @@ -560,7 +552,6 @@ export class EscrowClient extends BaseEthersClient { * @throws ErrorStoreResultsVersion If the contract supports only the deprecated signature. * * @example - * Without funds to reserve: * ```ts * await escrowClient.storeResults( * '0x62dD51230A30401C455c8398d06F85e4EaB6309f', @@ -568,19 +559,6 @@ export class EscrowClient extends BaseEthersClient { * '0xHASH123' * ); * ``` - * - * @example - * With funds to reserve: - * ```ts - * import { ethers } from 'ethers'; - * - * await escrowClient.storeResults( - * '0x62dD51230A30401C455c8398d06F85e4EaB6309f', - * 'https://example.com/results.json', - * '0xHASH123', - * ethers.parseEther('5') - * ); - * ``` */ async storeResults( escrowAddress: string, @@ -588,23 +566,11 @@ export class EscrowClient extends BaseEthersClient { hash: string, txOptions?: Overrides ): Promise; - async storeResults( - escrowAddress: string, - url: string, - hash: string, - fundsToReserve: bigint, - txOptions?: Overrides - ): Promise; /** * Stores the result URL and result hash for an escrow. * - * !!! note - * Only Recording Oracle or admin can call it. - * - * This method has two overloads: - * - `storeResults(escrowAddress, url, hash, txOptions?)` - Without funds to reserve - * - `storeResults(escrowAddress, url, hash, fundsToReserve, txOptions?)` - With funds to reserve + * @remarks Only Recording Oracle or admin can call it. * * 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). @@ -614,7 +580,7 @@ export class EscrowClient extends BaseEthersClient { * @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. @@ -622,17 +588,6 @@ export class EscrowClient extends BaseEthersClient { * @throws ErrorStoreResultsVersion If the contract supports only the deprecated signature. * * @example - * Without funds to reserve: - * ```ts - * await escrowClient.storeResults( - * '0x62dD51230A30401C455c8398d06F85e4EaB6309f', - * 'https://example.com/results.json', - * '0xHASH123' - * ); - * ``` - * - * @example - * With funds to reserve: * ```ts * import { ethers } from 'ethers'; * @@ -644,6 +599,14 @@ export class EscrowClient extends BaseEthersClient { * ); * ``` */ + async storeResults( + escrowAddress: string, + url: string, + hash: string, + fundsToReserve: bigint, + txOptions?: Overrides + ): Promise; + @requiresSigner async storeResults( escrowAddress: string, @@ -707,15 +670,14 @@ 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). - * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid - * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory + * @returns - + * @throws ErrorInvalidEscrowAddressProvided If the escrow address is invalid. + * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory. * * @example - * > Only Recording Oracle or admin can call it. - * * ```ts * await escrowClient.complete('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); * ``` @@ -745,6 +707,7 @@ 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. @@ -754,6 +717,7 @@ export class EscrowClient extends BaseEthersClient { * @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 @@ -767,8 +731,6 @@ export class EscrowClient extends BaseEthersClient { * @throws ErrorBulkPayOutVersion If using deprecated signature * * @example - * > Only Reputation Oracle or admin can call it. - * * ```ts * import { ethers } from 'ethers'; * @@ -802,7 +764,7 @@ 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. @@ -811,6 +773,7 @@ export class EscrowClient extends BaseEthersClient { * @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 @@ -824,7 +787,6 @@ export class EscrowClient extends BaseEthersClient { * @throws ErrorBulkPayOutVersion If using deprecated signature * * @example - * > Only Reputation Oracle or admin can call it. * * ```ts * import { ethers } from 'ethers'; @@ -922,14 +884,14 @@ 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 * * @example - * > Only Job Launcher or admin can call it. * * ```ts * await escrowClient.cancel('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); @@ -958,14 +920,14 @@ 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 * * @example - * > Only Job Launcher or admin can call it. * * ```ts * await escrowClient.requestCancellation('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); @@ -994,6 +956,7 @@ 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 escrowAddress - Address of the escrow to withdraw. * @param tokenAddress - Address of the token to withdraw. @@ -1005,7 +968,6 @@ export class EscrowClient extends BaseEthersClient { * @throws ErrorTransferEventNotFoundInTransactionLogs If the Transfer event is not found in transaction logs * * @example - * > Only Job Launcher or admin can call it. * * ```ts * const withdrawData = await escrowClient.withdraw( @@ -1078,6 +1040,7 @@ export class EscrowClient extends BaseEthersClient { /** * Creates a prepared transaction for bulk payout without immediately sending it. + * @remarks Only Reputation Oracle or admin can call it. * * @param escrowAddress - Escrow address to payout. * @param recipients - Array of recipient addresses. @@ -1100,7 +1063,6 @@ export class EscrowClient extends BaseEthersClient { * @throws ErrorEscrowAddressIsNotProvidedByFactory If the escrow is not provided by the factory * * @example - * > Only Reputation Oracle or admin can call it. * * ```ts * import { ethers } from 'ethers'; diff --git a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts b/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts index af4b5cfe34..de4a03457e 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts @@ -143,6 +143,7 @@ export class KVStoreClient extends BaseEthersClient { * @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 * @@ -171,6 +172,7 @@ export class KVStoreClient extends BaseEthersClient { * @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 @@ -205,6 +207,7 @@ export class KVStoreClient extends BaseEthersClient { * @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 * diff --git a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts b/packages/sdk/typescript/human-protocol-sdk/src/staking.ts index c7c047b983..c39669db25 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/staking.ts @@ -179,6 +179,7 @@ export class StakingClient extends BaseEthersClient { * * @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 * @@ -225,6 +226,7 @@ export class StakingClient extends BaseEthersClient { * * @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 * @@ -263,6 +265,7 @@ export class StakingClient extends BaseEthersClient { * * @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 * @@ -301,6 +304,7 @@ export class StakingClient extends BaseEthersClient { * Must have tokens available to withdraw * * @param txOptions - Additional transaction parameters (optional, defaults to an empty object). + * @returns - * * @example * ```ts @@ -325,6 +329,7 @@ export class StakingClient extends BaseEthersClient { * @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 From 6e84e79e4482c8ed3c75ce762b63aa76ac09e4b1 Mon Sep 17 00:00:00 2001 From: portuu3 Date: Tue, 9 Dec 2025 16:33:32 +0100 Subject: [PATCH 07/19] delete folders from gitignore --- .gitignore | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index 84a5849c7d..294af55f2a 100644 --- a/.gitignore +++ b/.gitignore @@ -54,7 +54,4 @@ package.tgz cache # Ignore developer-only local files -.local - -docs/python -docs/ts \ No newline at end of file +.local \ No newline at end of file From 73afe99b4940280574e466565e429f9be9806bd6 Mon Sep 17 00:00:00 2001 From: portuu3 Date: Tue, 9 Dec 2025 17:01:39 +0100 Subject: [PATCH 08/19] update gitignore --- .gitignore | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 294af55f2a..afefc0200f 100644 --- a/.gitignore +++ b/.gitignore @@ -54,4 +54,8 @@ package.tgz cache # Ignore developer-only local files -.local \ No newline at end of file +.local + + +docs/ts +docs/python \ No newline at end of file From b04cefd289d29012567dad43d4f08dc605f55865 Mon Sep 17 00:00:00 2001 From: portuu3 Date: Tue, 9 Dec 2025 17:05:44 +0100 Subject: [PATCH 09/19] gitignore update --- .../typescript/human-protocol-sdk/.gitignore | 3 + .../human-protocol-sdk/docs/README.md | 27 - .../docs/classes/Encryption.md | 170 -- .../docs/classes/EncryptionUtils.md | 192 --- .../docs/classes/EscrowClient.md | 1432 ----------------- .../docs/classes/EscrowUtils.md | 309 ---- .../docs/classes/KVStoreClient.md | 302 ---- .../docs/classes/KVStoreUtils.md | 206 --- .../docs/classes/OperatorUtils.md | 201 --- .../docs/classes/StakingClient.md | 389 ----- .../docs/classes/StakingUtils.md | 106 -- .../docs/classes/StatisticsUtils.md | 401 ----- .../docs/classes/TransactionUtils.md | 188 --- .../docs/classes/WorkerUtils.md | 129 -- .../docs/enumerations/EscrowStatus.md | 13 - .../docs/interfaces/SubgraphOptions.md | 9 - .../docs/type-aliases/MessageDataType.md | 6 - .../docs/type-aliases/NetworkData.md | 115 -- 18 files changed, 3 insertions(+), 4195 deletions(-) delete mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/README.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/Encryption.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/EncryptionUtils.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowClient.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowUtils.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreClient.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreUtils.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/OperatorUtils.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingClient.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingUtils.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/StatisticsUtils.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/TransactionUtils.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/classes/WorkerUtils.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/enumerations/EscrowStatus.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/interfaces/SubgraphOptions.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/MessageDataType.md delete mode 100644 packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/NetworkData.md diff --git a/packages/sdk/typescript/human-protocol-sdk/.gitignore b/packages/sdk/typescript/human-protocol-sdk/.gitignore index 0a21461bf3..4d3fb3fcc4 100644 --- a/packages/sdk/typescript/human-protocol-sdk/.gitignore +++ b/packages/sdk/typescript/human-protocol-sdk/.gitignore @@ -6,3 +6,6 @@ dist # Logs logs + +docs +!docs/index.md \ No newline at end of file diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/README.md b/packages/sdk/typescript/human-protocol-sdk/docs/README.md deleted file mode 100644 index 095ebdd9b5..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/docs/README.md +++ /dev/null @@ -1,27 +0,0 @@ -## Enumerations - -- [EscrowStatus](enumerations/EscrowStatus.md) - -## Classes - -- [Encryption](classes/Encryption.md) -- [EncryptionUtils](classes/EncryptionUtils.md) -- [EscrowClient](classes/EscrowClient.md) -- [EscrowUtils](classes/EscrowUtils.md) -- [KVStoreClient](classes/KVStoreClient.md) -- [KVStoreUtils](classes/KVStoreUtils.md) -- [OperatorUtils](classes/OperatorUtils.md) -- [StakingClient](classes/StakingClient.md) -- [StakingUtils](classes/StakingUtils.md) -- [StatisticsUtils](classes/StatisticsUtils.md) -- [TransactionUtils](classes/TransactionUtils.md) -- [WorkerUtils](classes/WorkerUtils.md) - -## Interfaces - -- [SubgraphOptions](interfaces/SubgraphOptions.md) - -## Type Aliases - -- [MessageDataType](type-aliases/MessageDataType.md) -- [NetworkData](type-aliases/NetworkData.md) diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/Encryption.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/Encryption.md deleted file mode 100644 index 9480739d06..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/Encryption.md +++ /dev/null @@ -1,170 +0,0 @@ -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`](/ts/classes/Encryption/#build) method. - -## Constructors - -### Constructor - -```ts -new Encryption(privateKey: PrivateKey): Encryption; -``` - -Constructor for the Encryption class. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `privateKey` | `PrivateKey` | The private key. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `Encryption` | - | - -## Methods - -### build() - -```ts -static build(privateKeyArmored: string, passphrase?: string): Promise; -``` - -Builds an Encryption instance by decrypting the private key from an encrypted private key and passphrase. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `privateKeyArmored` | `string` | The encrypted private key in armored format. | -| `passphrase?` | `string` | The passphrase for the private key (optional). | - - -#### Returns - -| Type | Description | -|------|-------------| -| `Encryption` | The Encryption instance. | - -???+ example "Example" - - ```ts - import { Encryption } from '@human-protocol/sdk'; - - const privateKey = 'Armored_priv_key'; - const passphrase = 'example_passphrase'; - const encryption = await Encryption.build(privateKey, passphrase); - ``` - - -*** - -### signAndEncrypt() - -```ts -signAndEncrypt(message: MessageDataType, publicKeys: string[]): Promise; -``` - -This function signs and encrypts a message using the private key used to initialize the client and the specified public keys. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `message` | [`MessageDataType`](../type-aliases/MessageDataType.md) | Message to sign and encrypt. | -| `publicKeys` | `string`[] | Array of public keys to use for encryption. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `string` | Message signed and encrypted. | - -???+ example "Example" - - ```ts - 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); - ``` - - -*** - -### decrypt() - -```ts -decrypt(message: string, publicKey?: string): Promise>; -``` - -This function decrypts messages using the private key. In addition, the public key can be added for signature verification. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `message` | `string` | Message to decrypt. | -| `publicKey?` | `string` | Public key used to verify signature if needed (optional). | - - -#### Returns - -| Type | Description | -|------|-------------| -| `Promise>` | Message decrypted. | - -#### Throws - -| Type | Description | -|------|-------------| -| `Error` | If signature could not be verified when public key is provided | - -???+ example "Example" - - ```ts - const publicKey = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; - - const resultMessage = await encryption.decrypt('message', publicKey); - console.log('Decrypted message:', resultMessage); - ``` - - -*** - -### sign() - -```ts -sign(message: string): Promise; -``` - -This function signs a message using the private key used to initialize the client. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `message` | `string` | Message to sign. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `string` | Message signed. | - -???+ example "Example" - - ```ts - const resultMessage = await encryption.sign('message'); - console.log('Signed message:', resultMessage); - ``` - diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/EncryptionUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/EncryptionUtils.md deleted file mode 100644 index ae06dcd04a..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/EncryptionUtils.md +++ /dev/null @@ -1,192 +0,0 @@ -Utility class for encryption-related operations. - -## Methods - -### verify() - -```ts -static verify(message: string, publicKey: string): Promise; -``` - -This function verifies the signature of a signed message using the public key. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `message` | `string` | Message to verify. | -| `publicKey` | `string` | Public key to verify that the message was signed by a specific source. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `boolean` | True if verified. False if not verified. | - -???+ example "Example" - - ```ts - import { EncryptionUtils } from '@human-protocol/sdk'; - - const publicKey = '-----BEGIN PGP PUBLIC KEY BLOCK-----...'; - const result = await EncryptionUtils.verify('message', publicKey); - console.log('Verification result:', result); - ``` - - -*** - -### getSignedData() - -```ts -static getSignedData(message: string): Promise; -``` - -This function gets signed data from a signed message. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `message` | `string` | Message. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `string` | Signed data. | - -#### Throws - -| Type | Description | -|------|-------------| -| `Error` | If data could not be extracted from the message | - -???+ example "Example" - - ```ts - import { EncryptionUtils } from '@human-protocol/sdk'; - - const signedData = await EncryptionUtils.getSignedData('message'); - console.log('Signed data:', signedData); - ``` - - -*** - -### generateKeyPair() - -```ts -static generateKeyPair( - name: string, - email: string, -passphrase: string): Promise; -``` - -This function generates a key pair for encryption and decryption. - -#### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `name` | `string` | `undefined` | Name for the key pair. | -| `email` | `string` | `undefined` | Email for the key pair. | -| `passphrase` | `string` | `''` | Passphrase to encrypt the private key (optional, defaults to empty string). | - - -#### Returns - -| Type | Description | -|------|-------------| -| `IKeyPair` | Key pair generated. | - -???+ example "Example" - - ```ts - import { EncryptionUtils } from '@human-protocol/sdk'; - - const name = 'YOUR_NAME'; - const email = 'YOUR_EMAIL'; - const passphrase = 'YOUR_PASSPHRASE'; - const keyPair = await EncryptionUtils.generateKeyPair(name, email, passphrase); - console.log('Public key:', keyPair.publicKey); - ``` - - -*** - -### encrypt() - -```ts -static encrypt(message: MessageDataType, publicKeys: string[]): Promise; -``` - -This function encrypts a message using the specified public keys. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `message` | [`MessageDataType`](../type-aliases/MessageDataType.md) | Message to encrypt. | -| `publicKeys` | `string`[] | Array of public keys to use for encryption. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `string` | Message encrypted. | - -???+ example "Example" - - ```ts - import { EncryptionUtils } from '@human-protocol/sdk'; - - 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); - ``` - - -*** - -### isEncrypted() - -```ts -static isEncrypted(message: string): boolean; -``` - -Verifies if a message appears to be encrypted with OpenPGP. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `message` | `string` | Message to verify. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `boolean` | `true` if the message appears to be encrypted, `false` if not. | - -???+ example "Example" - - ```ts - import { EncryptionUtils } from '@human-protocol/sdk'; - - const message = '-----BEGIN PGP MESSAGE-----...'; - const isEncrypted = EncryptionUtils.isEncrypted(message); - - if (isEncrypted) { - console.log('The message is encrypted with OpenPGP.'); - } else { - console.log('The message is not encrypted with OpenPGP.'); - } - ``` - diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowClient.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowClient.md deleted file mode 100644 index 1c517db6e5..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowClient.md +++ /dev/null @@ -1,1432 +0,0 @@ -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`](/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. - -## Example - -###Using Signer - -####Using private key (backend) - -```ts -import { EscrowClient } 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 escrowClient = await EscrowClient.build(signer); -``` - -####Using Wagmi (frontend) - -```ts -import { useSigner } from 'wagmi'; -import { EscrowClient } from '@human-protocol/sdk'; - -const { data: signer } = useSigner(); -const escrowClient = await EscrowClient.build(signer); -``` - -###Using Provider - -```ts -import { EscrowClient } from '@human-protocol/sdk'; -import { JsonRpcProvider } from 'ethers'; - -const rpcUrl = 'YOUR_RPC_URL'; -const provider = new JsonRpcProvider(rpcUrl); -const escrowClient = await EscrowClient.build(provider); -``` - -## Extends - -- `BaseEthersClient` - -## Constructors - -### Constructor - -```ts -new EscrowClient(runner: ContractRunner, networkData: NetworkData): EscrowClient; -``` - -**EscrowClient constructor** - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | -| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the Escrow contract | - - -#### Returns - -| Type | Description | -|------|-------------| -| `EscrowClient` | An instance of EscrowClient | - -#### Overrides - -```ts -BaseEthersClient.constructor -``` - -## Methods - -### build() - -```ts -static build(runner: ContractRunner): Promise; -``` - -Creates an instance of EscrowClient from a Runner. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | - - -#### Returns - -| Type | Description | -|------|-------------| -| `EscrowClient` | An instance of EscrowClient | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorProviderDoesNotExist` | If the provider does not exist for the provided Signer | -| `ErrorUnsupportedChainID` | If the network's chainId is not supported | - -*** - -### createEscrow() - -```ts -createEscrow( - tokenAddress: string, - jobRequesterId: string, -txOptions: Overrides): Promise; -``` - -This function creates an escrow contract that uses the token passed to pay oracle fees and reward workers. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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 - -| Type | Description | -|------|-------------| -| `string` | Returns the address of the escrow created. | - -#### Remarks - -Need to have available stake. - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidTokenAddress` | If the token address is invalid | -| `ErrorLaunchedEventIsNotEmitted` | If the LaunchedV2 event is not emitted | - -???+ example "Example" - - ```ts - const tokenAddress = '0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4'; - const jobRequesterId = "job-requester-id"; - const escrowAddress = await escrowClient.createEscrow(tokenAddress, jobRequesterId); - ``` - - -*** - -### createFundAndSetupEscrow() - -```ts -createFundAndSetupEscrow( - tokenAddress: string, - amount: bigint, - jobRequesterId: string, - escrowConfig: IEscrowConfig, -txOptions: Overrides): Promise; -``` - -Creates, funds, and sets up a new escrow contract in a single transaction. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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` | Configuration parameters for escrow setup. | -| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | - - -#### Returns - -| Type | Description | -|------|-------------| -| `string` | Returns the address of the escrow created. | - -#### Remarks - -Need to have available stake and approve allowance in the token contract before calling this method. - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidTokenAddress` | If the token address is invalid | -| `ErrorInvalidRecordingOracleAddressProvided` | If the recording oracle address is invalid | -| `ErrorInvalidReputationOracleAddressProvided` | If the reputation oracle address is invalid | -| `ErrorInvalidExchangeOracleAddressProvided` | If the exchange oracle address is invalid | -| `ErrorAmountMustBeGreaterThanZero` | If any oracle fee is less than or equal to zero | -| `ErrorTotalFeeMustBeLessThanHundred` | If the total oracle fees exceed 100 | -| `ErrorInvalidManifest` | If the manifest is not a valid URL or JSON string | -| `ErrorHashIsEmptyString` | If the manifest hash is empty | -| `ErrorLaunchedEventIsNotEmitted` | If the LaunchedV2 event is not emitted | - -???+ example "Example" - - ```ts - import { ethers } from 'ethers'; - import { ERC20__factory } from '@human-protocol/sdk'; - - const tokenAddress = '0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4'; - const amount = ethers.parseUnits('1000', 18); - const jobRequesterId = 'requester-123'; - - const token = ERC20__factory.connect(tokenAddress, signer); - await token.approve(escrowClient.escrowFactoryContract.target, amount); - - const escrowConfig = { - recordingOracle: '0xRecordingOracleAddress', - reputationOracle: '0xReputationOracleAddress', - exchangeOracle: '0xExchangeOracleAddress', - recordingOracleFee: 5n, - reputationOracleFee: 5n, - exchangeOracleFee: 5n, - manifest: 'https://example.com/manifest.json', - manifestHash: 'manifestHash-123', - }; - - const escrowAddress = await escrowClient.createFundAndSetupEscrow( - tokenAddress, - amount, - jobRequesterId, - escrowConfig - ); - console.log('Escrow created at:', escrowAddress); - ``` - - -*** - -### setup() - -```ts -setup( - escrowAddress: string, - escrowConfig: IEscrowConfig, -txOptions: Overrides): Promise; -``` - -This function sets up the parameters of the escrow. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow to set up. | -| `escrowConfig` | `IEscrowConfig` | Escrow configuration parameters. | -| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | - - -#### Returns - -| Type | Description | -|------|-------------| -| `void` | - | - -#### Remarks - -Only Job Launcher or admin can call it. - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidRecordingOracleAddressProvided` | If the recording oracle address is invalid | -| `ErrorInvalidReputationOracleAddressProvided` | If the reputation oracle address is invalid | -| `ErrorInvalidExchangeOracleAddressProvided` | If the exchange oracle address is invalid | -| `ErrorAmountMustBeGreaterThanZero` | If any oracle fee is less than or equal to zero | -| `ErrorTotalFeeMustBeLessThanHundred` | If the total oracle fees exceed 100 | -| `ErrorInvalidManifest` | If the manifest is not a valid URL or JSON string | -| `ErrorHashIsEmptyString` | If the manifest hash is empty | -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | - -???+ example "Example" - - ```ts - const escrowAddress = '0x62dD51230A30401C455c8398d06F85e4EaB6309f'; - const escrowConfig = { - recordingOracle: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', - reputationOracle: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', - exchangeOracle: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', - recordingOracleFee: 10n, - reputationOracleFee: 10n, - exchangeOracleFee: 10n, - manifest: 'http://localhost/manifest.json', - manifestHash: 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079', - }; - await escrowClient.setup(escrowAddress, escrowConfig); - ``` - - -*** - -### fund() - -```ts -fund( - escrowAddress: string, - amount: bigint, -txOptions: Overrides): Promise; -``` - -This function adds funds of the chosen token to the escrow. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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 - -| Type | Description | -|------|-------------| -| `void` | - | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorAmountMustBeGreaterThanZero` | If the amount is less than or equal to zero | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | - -???+ example "Example" - - ```ts - import { ethers } from 'ethers'; - - const amount = ethers.parseUnits('5', 'ether'); - await escrowClient.fund('0x62dD51230A30401C455c8398d06F85e4EaB6309f', amount); - ``` - - -*** - -### storeResults() - -#### Call Signature - -```ts -storeResults( - escrowAddress: string, - url: string, - hash: string, -txOptions?: Overrides): Promise; -``` - -Stores the result URL and result hash for an escrow. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | The escrow address. | -| `url` | `string` | The URL containing the final results. May be empty only when `fundsToReserve` is `0n`. | -| `hash` | `string` | The hash of the results payload. | -| `txOptions?` | `Overrides` | Optional transaction overrides. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `void` | - | - -#### Remarks - -Only Recording Oracle or admin can call it. - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the provided escrow address is invalid. | -| `ErrorInvalidUrl` | If the URL format is invalid. | -| `ErrorHashIsEmptyString` | If the hash is empty and empty values are not allowed. | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow does not exist in the factory. | -| `ErrorStoreResultsVersion` | If the contract supports only the deprecated signature. | - -???+ example "Example" - - ```ts - await escrowClient.storeResults( - '0x62dD51230A30401C455c8398d06F85e4EaB6309f', - 'https://example.com/results.json', - '0xHASH123' - ); - ``` - - -#### Call Signature - -```ts -storeResults( - escrowAddress: string, - url: string, - hash: string, - fundsToReserve: bigint, -txOptions?: Overrides): Promise; -``` - -Stores the result URL and result hash for an escrow. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | The escrow address. | -| `url` | `string` | The URL containing the final results. May be empty only when `fundsToReserve` is `0n`. | -| `hash` | `string` | The hash of the results payload. | -| `fundsToReserve` | `bigint` | Optional amount of funds to reserve (when using second overload). | -| `txOptions?` | `Overrides` | Optional transaction overrides. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `void` | - | - -#### Remarks - -Only Recording Oracle or admin can call it. - -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). - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the provided escrow address is invalid. | -| `ErrorInvalidUrl` | If the URL format is invalid. | -| `ErrorHashIsEmptyString` | If the hash is empty and empty values are not allowed. | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow does not exist in the factory. | -| `ErrorStoreResultsVersion` | If the contract supports only the deprecated signature. | - -???+ example "Example" - - ```ts - import { ethers } from 'ethers'; - - await escrowClient.storeResults( - '0x62dD51230A30401C455c8398d06F85e4EaB6309f', - 'https://example.com/results.json', - '0xHASH123', - ethers.parseEther('5') - ); - ``` - - -*** - -### complete() - -```ts -complete(escrowAddress: string, txOptions: Overrides): Promise; -``` - -This function sets the status of an escrow to completed. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | -| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | - - -#### Returns - -| Type | Description | -|------|-------------| -| `void` | - | - -#### Remarks - -Only Recording Oracle or admin can call it. - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid. | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory. | - -???+ example "Example" - - ```ts - await escrowClient.complete('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); - ``` - - -*** - -### bulkPayOut() - -#### Call Signature - -```ts -bulkPayOut( - escrowAddress: string, - recipients: string[], - amounts: bigint[], - finalResultsUrl: string, - finalResultsHash: string, - txId: number, - forceComplete: boolean, -txOptions: Overrides): Promise; -``` - -This function pays out the amounts specified to the workers and sets the URL of the final results file. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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 - -| Type | Description | -|------|-------------| -| `void` | - | - -#### Remarks - -Only Reputation Oracle or admin can call it. - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorRecipientCannotBeEmptyArray` | If the recipients array is empty | -| `ErrorTooManyRecipients` | If there are too many recipients | -| `ErrorAmountsCannotBeEmptyArray` | If the amounts array is empty | -| `ErrorRecipientAndAmountsMustBeSameLength` | If recipients and amounts arrays have different lengths | -| `InvalidEthereumAddressError` | If any recipient address is invalid | -| `ErrorInvalidUrl` | If the final results URL is invalid | -| `ErrorHashIsEmptyString` | If the final results hash is empty | -| `ErrorEscrowDoesNotHaveEnoughBalance` | If the escrow doesn't have enough balance | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | -| `ErrorBulkPayOutVersion` | If using deprecated signature | - -???+ example "Example" - - ```ts - import { ethers } from 'ethers'; - - 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 - ); - ``` - - -#### Call Signature - -```ts -bulkPayOut( - escrowAddress: string, - recipients: string[], - amounts: bigint[], - finalResultsUrl: string, - finalResultsHash: string, - payoutId: string, - forceComplete: boolean, -txOptions: Overrides): Promise; -``` - -This function pays out the amounts specified to the workers and sets the URL of the final results file. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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 - -| Type | Description | -|------|-------------| -| `void` | - | - -#### Remarks - -Only Reputation Oracle or admin can call it. - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorRecipientCannotBeEmptyArray` | If the recipients array is empty | -| `ErrorTooManyRecipients` | If there are too many recipients | -| `ErrorAmountsCannotBeEmptyArray` | If the amounts array is empty | -| `ErrorRecipientAndAmountsMustBeSameLength` | If recipients and amounts arrays have different lengths | -| `InvalidEthereumAddressError` | If any recipient address is invalid | -| `ErrorInvalidUrl` | If the final results URL is invalid | -| `ErrorHashIsEmptyString` | If the final results hash is empty | -| `ErrorEscrowDoesNotHaveEnoughBalance` | If the escrow doesn't have enough balance | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | -| `ErrorBulkPayOutVersion` | If using deprecated signature | - -???+ example "Example" - - ```ts - import { ethers } from 'ethers'; - import { v4 as uuidV4 } from 'uuid'; - - 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 - ); - ``` - - -*** - -### cancel() - -```ts -cancel(escrowAddress: string, txOptions: Overrides): Promise; -``` - -This function cancels the specified escrow and sends the balance to the canceler. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow to cancel. | -| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | - - -#### Returns - -| Type | Description | -|------|-------------| -| `void` | - | - -#### Remarks - -Only Job Launcher or admin can call it. - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | - -???+ example "Example" - - ```ts - await escrowClient.cancel('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); - ``` - - -*** - -### requestCancellation() - -```ts -requestCancellation(escrowAddress: string, txOptions: Overrides): Promise; -``` - -This function requests the cancellation of the specified escrow (moves status to ToCancel or finalizes if expired). - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow to request cancellation. | -| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | - - -#### Returns - -| Type | Description | -|------|-------------| -| `void` | - | - -#### Remarks - -Only Job Launcher or admin can call it. - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | - -???+ example "Example" - - ```ts - await escrowClient.requestCancellation('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); - ``` - - -*** - -### withdraw() - -```ts -withdraw( - escrowAddress: string, - tokenAddress: string, -txOptions: Overrides): Promise; -``` - -This function withdraws additional tokens in the escrow to the canceler. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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 - -| Type | Description | -|------|-------------| -| `IEscrowWithdraw` | Returns the escrow withdrawal data including transaction hash and withdrawal amount. | - -#### Remarks - -Only Job Launcher or admin can call it. - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorInvalidTokenAddress` | If the token address is invalid | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | -| `ErrorTransferEventNotFoundInTransactionLogs` | If the Transfer event is not found in transaction logs | - -???+ example "Example" - - ```ts - const withdrawData = await escrowClient.withdraw( - '0x62dD51230A30401C455c8398d06F85e4EaB6309f', - '0x0376D26246Eb35FF4F9924cF13E6C05fd0bD7Fb4' - ); - console.log('Withdrawn amount:', withdrawData.withdrawnAmount); - ``` - - -*** - -### createBulkPayoutTransaction() - -```ts -createBulkPayoutTransaction( - escrowAddress: string, - recipients: string[], - amounts: bigint[], - finalResultsUrl: string, - finalResultsHash: string, - payoutId: string, - forceComplete: boolean, -txOptions: Overrides): Promise; -``` - -Creates a prepared transaction for bulk payout without immediately sending it. - -#### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `escrowAddress` | `string` | `undefined` | Escrow address to payout. | -| `recipients` | `string`[] | `undefined` | Array of recipient addresses. | -| `amounts` | `bigint`[] | `undefined` | Array of amounts the recipients will receive. | -| `finalResultsUrl` | `string` | `undefined` | Final results file URL. | -| `finalResultsHash` | `string` | `undefined` | Final results file hash. | -| `payoutId` | `string` | `undefined` | 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 - -| Type | Description | -|------|-------------| -| `TransactionLikeWithNonce` | Returns object with raw transaction and nonce | - -#### Remarks - -Only Reputation Oracle or admin can call it. - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorRecipientCannotBeEmptyArray` | If the recipients array is empty | -| `ErrorTooManyRecipients` | If there are too many recipients | -| `ErrorAmountsCannotBeEmptyArray` | If the amounts array is empty | -| `ErrorRecipientAndAmountsMustBeSameLength` | If recipients and amounts arrays have different lengths | -| `InvalidEthereumAddressError` | If any recipient address is invalid | -| `ErrorInvalidUrl` | If the final results URL is invalid | -| `ErrorHashIsEmptyString` | If the final results hash is empty | -| `ErrorEscrowDoesNotHaveEnoughBalance` | If the escrow doesn't have enough balance | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | - -???+ example "Example" - - ```ts - import { ethers } from 'ethers'; - import { v4 as uuidV4 } from 'uuid'; - - 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(); - - 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); - ``` - - -*** - -### getBalance() - -```ts -getBalance(escrowAddress: string): Promise; -``` - -This function returns the balance for a specified escrow address. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `bigint` | Balance of the escrow in the token used to fund it. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | - -???+ example "Example" - - ```ts - const balance = await escrowClient.getBalance('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); - console.log('Balance:', balance); - ``` - - -*** - -### getReservedFunds() - -```ts -getReservedFunds(escrowAddress: string): Promise; -``` - -This function returns the reserved funds for a specified escrow address. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `bigint` | Reserved funds of the escrow in the token used to fund it. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | - -???+ example "Example" - - ```ts - const reservedFunds = await escrowClient.getReservedFunds('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); - console.log('Reserved funds:', reservedFunds); - ``` - - -*** - -### getManifestHash() - -```ts -getManifestHash(escrowAddress: string): Promise; -``` - -This function returns the manifest file hash. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `string` | Hash of the manifest file content. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | - -???+ example "Example" - - ```ts - const manifestHash = await escrowClient.getManifestHash('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); - console.log('Manifest hash:', manifestHash); - ``` - - -*** - -### getManifest() - -```ts -getManifest(escrowAddress: string): Promise; -``` - -This function returns the manifest. Could be a URL or a JSON string. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `string` | Manifest URL or JSON string. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | - -???+ example "Example" - - ```ts - const manifest = await escrowClient.getManifest('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); - console.log('Manifest:', manifest); - ``` - - -*** - -### getResultsUrl() - -```ts -getResultsUrl(escrowAddress: string): Promise; -``` - -This function returns the results file URL. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `string` | Results file URL. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | - -???+ example "Example" - - ```ts - const resultsUrl = await escrowClient.getResultsUrl('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); - console.log('Results URL:', resultsUrl); - ``` - - -*** - -### getIntermediateResultsUrl() - -```ts -getIntermediateResultsUrl(escrowAddress: string): Promise; -``` - -This function returns the intermediate results file URL. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `string` | URL of the file that stores results from Recording Oracle. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | - -???+ example "Example" - - ```ts - const intermediateResultsUrl = await escrowClient.getIntermediateResultsUrl('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); - console.log('Intermediate results URL:', intermediateResultsUrl); - ``` - - -*** - -### getIntermediateResultsHash() - -```ts -getIntermediateResultsHash(escrowAddress: string): Promise; -``` - -This function returns the intermediate results hash. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `string` | Hash of the intermediate results file content. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | - -???+ example "Example" - - ```ts - const intermediateResultsHash = await escrowClient.getIntermediateResultsHash('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); - console.log('Intermediate results hash:', intermediateResultsHash); - ``` - - -*** - -### getTokenAddress() - -```ts -getTokenAddress(escrowAddress: string): Promise; -``` - -This function returns the token address used for funding the escrow. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `string` | Address of the token used to fund the escrow. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | - -???+ example "Example" - - ```ts - const tokenAddress = await escrowClient.getTokenAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); - console.log('Token address:', tokenAddress); - ``` - - -*** - -### getStatus() - -```ts -getStatus(escrowAddress: string): Promise; -``` - -This function returns the current status of the escrow. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `[EscrowStatus](../enumerations/EscrowStatus.md)` | Current status of the escrow. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | - -???+ example "Example" - - ```ts - import { EscrowStatus } from '@human-protocol/sdk'; - - const status = await escrowClient.getStatus('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); - console.log('Status:', EscrowStatus[status]); - ``` - - -*** - -### getRecordingOracleAddress() - -```ts -getRecordingOracleAddress(escrowAddress: string): Promise; -``` - -This function returns the recording oracle address for a given escrow. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `string` | Address of the Recording Oracle. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | - -???+ example "Example" - - ```ts - const oracleAddress = await escrowClient.getRecordingOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); - console.log('Recording Oracle address:', oracleAddress); - ``` - - -*** - -### getJobLauncherAddress() - -```ts -getJobLauncherAddress(escrowAddress: string): Promise; -``` - -This function returns the job launcher address for a given escrow. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `string` | Address of the Job Launcher. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | - -???+ example "Example" - - ```ts - const jobLauncherAddress = await escrowClient.getJobLauncherAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); - console.log('Job Launcher address:', jobLauncherAddress); - ``` - - -*** - -### getReputationOracleAddress() - -```ts -getReputationOracleAddress(escrowAddress: string): Promise; -``` - -This function returns the reputation oracle address for a given escrow. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `string` | Address of the Reputation Oracle. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | - -???+ example "Example" - - ```ts - const oracleAddress = await escrowClient.getReputationOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); - console.log('Reputation Oracle address:', oracleAddress); - ``` - - -*** - -### getExchangeOracleAddress() - -```ts -getExchangeOracleAddress(escrowAddress: string): Promise; -``` - -This function returns the exchange oracle address for a given escrow. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `string` | Address of the Exchange Oracle. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | - -???+ example "Example" - - ```ts - const oracleAddress = await escrowClient.getExchangeOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); - console.log('Exchange Oracle address:', oracleAddress); - ``` - - -*** - -### getFactoryAddress() - -```ts -getFactoryAddress(escrowAddress: string): Promise; -``` - -This function returns the escrow factory address for a given escrow. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `escrowAddress` | `string` | Address of the escrow. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `string` | Address of the escrow factory. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | - -???+ example "Example" - - ```ts - const factoryAddress = await escrowClient.getFactoryAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); - console.log('Factory address:', factoryAddress); - ``` - diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowUtils.md deleted file mode 100644 index 200901197d..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/EscrowUtils.md +++ /dev/null @@ -1,309 +0,0 @@ -Utility helpers for escrow-related queries. - -## Example - -```ts -import { ChainId, EscrowUtils } from '@human-protocol/sdk'; - -const escrows = await EscrowUtils.getEscrows({ - chainId: ChainId.POLYGON_AMOY -}); -console.log('Escrows:', escrows); -``` - -## Methods - -### getEscrows() - -```ts -static getEscrows(filter: IEscrowsFilter, options?: SubgraphOptions): Promise; -``` - -This function returns an array of escrows based on the specified filter parameters. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `filter` | `IEscrowsFilter` | Filter parameters. | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `IEscrow[]` | List of escrows that match the filter. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidAddress` | If any filter address is invalid | -| `ErrorUnsupportedChainID` | If the chain ID is not supported | - -???+ example "Example" - - ```ts - import { ChainId, EscrowStatus } from '@human-protocol/sdk'; - - 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); - ``` - - -*** - -### getEscrow() - -```ts -static getEscrow( - chainId: ChainId, - escrowAddress: string, -options?: SubgraphOptions): Promise; -``` - -This function returns the escrow data for a given address. - -> This uses Subgraph - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `chainId` | `ChainId` | Network in which the escrow has been deployed | -| `escrowAddress` | `string` | Address of the escrow | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `IEscrow \| null` | Escrow data or null if not found. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorUnsupportedChainID` | If the chain ID is not supported | -| `ErrorInvalidAddress` | If the escrow address is invalid | - -???+ example "Example" - - ```ts - import { ChainId } from '@human-protocol/sdk'; - - const escrow = await EscrowUtils.getEscrow( - ChainId.POLYGON_AMOY, - "0x1234567890123456789012345678901234567890" - ); - if (escrow) { - console.log('Escrow status:', escrow.status); - } - ``` - - -*** - -### getStatusEvents() - -```ts -static getStatusEvents(filter: IStatusEventFilter, options?: SubgraphOptions): Promise; -``` - -This function returns the status events for a given set of networks within an optional date range. - -> This uses Subgraph - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `filter` | `IStatusEventFilter` | Filter parameters. | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `IStatusEvent[]` | Array of status events with their corresponding statuses. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidAddress` | If the launcher address is invalid | -| `ErrorUnsupportedChainID` | If the chain ID is not supported | - -???+ example "Example" - - ```ts - import { ChainId, EscrowStatus } from '@human-protocol/sdk'; - - 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); - ``` - - -*** - -### getPayouts() - -```ts -static getPayouts(filter: IPayoutFilter, options?: SubgraphOptions): Promise; -``` - -This function returns the payouts for a given set of networks. - -> This uses Subgraph - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `filter` | `IPayoutFilter` | Filter parameters. | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `IPayout[]` | List of payouts matching the filters. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorUnsupportedChainID` | If the chain ID is not supported | -| `ErrorInvalidAddress` | If any filter address is invalid | - -???+ example "Example" - - ```ts - import { ChainId } 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:', payouts.length); - ``` - - -*** - -### getCancellationRefunds() - -```ts -static getCancellationRefunds(filter: ICancellationRefundFilter, options?: SubgraphOptions): Promise; -``` - -This function returns the cancellation refunds for a given set of networks. - -> This uses Subgraph - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `filter` | `ICancellationRefundFilter` | Filter parameters. | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `ICancellationRefund[]` | List of cancellation refunds matching the filters. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorUnsupportedChainID` | If the chain ID is not supported | -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorInvalidAddress` | If the receiver address is invalid | - -???+ example "Example" - - ```ts - import { ChainId } from '@human-protocol/sdk'; - - const cancellationRefunds = await EscrowUtils.getCancellationRefunds({ - chainId: ChainId.POLYGON_AMOY, - escrowAddress: '0x1234567890123456789012345678901234567890', - }); - console.log('Cancellation refunds:', cancellationRefunds.length); - ``` - - -*** - -### getCancellationRefund() - -```ts -static getCancellationRefund( - chainId: ChainId, - escrowAddress: string, -options?: SubgraphOptions): Promise; -``` - -This function returns the cancellation refund for a given escrow address. - -> This uses Subgraph - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `chainId` | `ChainId` | Network in which the escrow has been deployed | -| `escrowAddress` | `string` | Address of the escrow | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `ICancellationRefund \| null` | Cancellation refund data or null if not found. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorUnsupportedChainID` | If the chain ID is not supported | -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | - -???+ example "Example" - - ```ts - import { ChainId } from '@human-protocol/sdk'; - - const cancellationRefund = await EscrowUtils.getCancellationRefund( - ChainId.POLYGON_AMOY, - "0x1234567890123456789012345678901234567890" - ); - if (cancellationRefund) { - console.log('Refund amount:', cancellationRefund.amount); - } - ``` - diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreClient.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreClient.md deleted file mode 100644 index 70e26f2f32..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreClient.md +++ /dev/null @@ -1,302 +0,0 @@ -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`](/ts/classes/KVStoreClient/#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. - -## Example - -###Using Signer - -####Using private key (backend) - -```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); -``` - -####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); -``` - -###Using Provider - -```ts -import { KVStoreClient } from '@human-protocol/sdk'; -import { JsonRpcProvider } from 'ethers'; - -const rpcUrl = 'YOUR_RPC_URL'; - -const provider = new JsonRpcProvider(rpcUrl); -const kvstoreClient = await KVStoreClient.build(provider); -``` - -## Extends - -- `BaseEthersClient` - -## Constructors - -### Constructor - -```ts -new KVStoreClient(runner: ContractRunner, networkData: NetworkData): KVStoreClient; -``` - -**KVStoreClient constructor** - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | -| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the KVStore contract | - - -#### Returns - -| Type | Description | -|------|-------------| -| `KVStoreClient` | - | - -#### Overrides - -```ts -BaseEthersClient.constructor -``` - -## Methods - -### build() - -```ts -static build(runner: ContractRunner): Promise; -``` - -Creates an instance of KVStoreClient from a runner. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | - - -#### Returns - -| Type | Description | -|------|-------------| -| `KVStoreClient` | An instance of KVStoreClient | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorProviderDoesNotExist` | If the provider does not exist for the provided Signer | -| `ErrorUnsupportedChainID` | If the network's chainId is not supported | - -???+ example "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); - ``` - - -*** - -### set() - -```ts -set( - key: string, - value: string, -txOptions: Overrides): Promise; -``` - -This function sets a key-value pair associated with the address that submits the transaction. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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 - -| Type | Description | -|------|-------------| -| `void` | - | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorKVStoreEmptyKey` | If the key is empty | -| `Error` | If the transaction fails | - -???+ example "Example" - - ```ts - await kvstoreClient.set('Role', 'RecordingOracle'); - ``` - - -*** - -### setBulk() - -```ts -setBulk( - keys: string[], - values: string[], -txOptions: Overrides): Promise; -``` - -This function sets key-value pairs in bulk associated with the address that submits the transaction. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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 - -| Type | Description | -|------|-------------| -| `void` | - | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorKVStoreArrayLength` | If keys and values arrays have different lengths | -| `ErrorKVStoreEmptyKey` | If any key is empty | -| `Error` | If the transaction fails | - -???+ example "Example" - - ```ts - const keys = ['role', 'webhook_url']; - const values = ['RecordingOracle', 'http://localhost']; - await kvstoreClient.setBulk(keys, values); - ``` - - -*** - -### setFileUrlAndHash() - -```ts -setFileUrlAndHash( - url: string, - urlKey: string, -txOptions: Overrides): Promise; -``` - -Sets a URL value for the address that submits the transaction, and its hash. - -#### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `url` | `string` | `undefined` | URL to set | -| `urlKey` | `string` | `'url'` | Configurable URL key. `url` by default. | -| `txOptions` | `Overrides` | `{}` | Additional transaction parameters (optional, defaults to an empty object). | - - -#### Returns - -| Type | Description | -|------|-------------| -| `void` | - | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidUrl` | If the URL is invalid | -| `Error` | If the transaction fails | - -???+ example "Example" - - ```ts - await kvstoreClient.setFileUrlAndHash('example.com'); - await kvstoreClient.setFileUrlAndHash('linkedin.com/example', 'linkedin_url'); - ``` - - -*** - -### get() - -```ts -get(address: string, key: string): Promise; -``` - -Gets the value of a key-value pair in the contract. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `address` | `string` | Address from which to get the key value. | -| `key` | `string` | Key to obtain the value. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `string` | Value of the key. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorKVStoreEmptyKey` | If the key is empty | -| `ErrorInvalidAddress` | If the address is invalid | -| `Error` | If the contract call fails | - -???+ example "Example" - - ```ts - const value = await kvstoreClient.get('0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', 'Role'); - console.log('Value:', value); - ``` - diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreUtils.md deleted file mode 100644 index cd345ec972..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/KVStoreUtils.md +++ /dev/null @@ -1,206 +0,0 @@ -Utility helpers for KVStore-related queries. - -## Example - -```ts -import { ChainId, KVStoreUtils } from '@human-protocol/sdk'; - -const kvStoreData = await KVStoreUtils.getKVStoreData( - ChainId.POLYGON_AMOY, - "0x1234567890123456789012345678901234567890" -); -console.log('KVStore data:', kvStoreData); -``` - -## Methods - -### getKVStoreData() - -```ts -static getKVStoreData( - chainId: ChainId, - address: string, -options?: SubgraphOptions): Promise; -``` - -This function returns the KVStore data for a given address. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `chainId` | `ChainId` | Network in which the KVStore is deployed | -| `address` | `string` | Address of the KVStore | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `IKVStore[]` | KVStore data | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorUnsupportedChainID` | If the network's chainId is not supported | -| `ErrorInvalidAddress` | If the address is invalid | - -???+ example "Example" - - ```ts - const kvStoreData = await KVStoreUtils.getKVStoreData( - ChainId.POLYGON_AMOY, - "0x1234567890123456789012345678901234567890" - ); - console.log('KVStore data:', kvStoreData); - ``` - - -*** - -### get() - -```ts -static get( - chainId: ChainId, - address: string, - key: string, -options?: SubgraphOptions): Promise; -``` - -Gets the value of a key-value pair in the KVStore using the subgraph. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `chainId` | `ChainId` | 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/SubgraphOptions.md) | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `string` | Value of the key. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorUnsupportedChainID` | If the network's chainId is not supported | -| `ErrorInvalidAddress` | If the address is invalid | -| `ErrorKVStoreEmptyKey` | If the key is empty | -| `InvalidKeyError` | If the key is not found | - -???+ example "Example" - - ```ts - const value = await KVStoreUtils.get( - ChainId.POLYGON_AMOY, - '0x1234567890123456789012345678901234567890', - 'role' - ); - console.log('Value:', value); - ``` - - -*** - -### getFileUrlAndVerifyHash() - -```ts -static getFileUrlAndVerifyHash( - chainId: ChainId, - address: string, - urlKey: string, -options?: SubgraphOptions): Promise; -``` - -Gets the URL value of the given entity, and verifies its hash. - -#### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `chainId` | `ChainId` | `undefined` | Network in which the KVStore is deployed | -| `address` | `string` | `undefined` | Address from which to get the URL value. | -| `urlKey` | `string` | `'url'` | Configurable URL key. `url` by default. | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | `undefined` | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `string` | URL value for the given address if it exists, and the content is valid | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidAddress` | If the address is invalid | -| `ErrorInvalidHash` | If the hash verification fails | -| `Error` | If fetching URL or hash fails | - -???+ example "Example" - - ```ts - const url = await KVStoreUtils.getFileUrlAndVerifyHash( - ChainId.POLYGON_AMOY, - '0x1234567890123456789012345678901234567890' - ); - console.log('Verified URL:', url); - ``` - - -*** - -### getPublicKey() - -```ts -static getPublicKey( - chainId: ChainId, - address: string, -options?: SubgraphOptions): Promise; -``` - -Gets the public key of the given entity, and verifies its hash. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `chainId` | `ChainId` | Network in which the KVStore is deployed | -| `address` | `string` | Address from which to get the public key. | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `string` | Public key for the given address if it exists, and the content is valid | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidAddress` | If the address is invalid | -| `ErrorInvalidHash` | If the hash verification fails | -| `Error` | If fetching the public key fails | - -???+ example "Example" - - ```ts - const publicKey = await KVStoreUtils.getPublicKey( - ChainId.POLYGON_AMOY, - '0x1234567890123456789012345678901234567890' - ); - console.log('Public key:', publicKey); - ``` - diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/OperatorUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/OperatorUtils.md deleted file mode 100644 index ccb0a8e745..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/OperatorUtils.md +++ /dev/null @@ -1,201 +0,0 @@ -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); -``` - -## Methods - -### getOperator() - -```ts -static getOperator( - chainId: ChainId, - address: string, -options?: SubgraphOptions): Promise; -``` - -This function returns the operator data for the given address. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `chainId` | `ChainId` | Network in which the operator is deployed | -| `address` | `string` | Operator address. | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `IOperator \| null` | Returns the operator details or null if not found. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidStakerAddressProvided` | If the address is invalid | -| `ErrorUnsupportedChainID` | If the chain ID is not supported | - -???+ example "Example" - - ```ts - import { OperatorUtils, ChainId } from '@human-protocol/sdk'; - - const operator = await OperatorUtils.getOperator( - ChainId.POLYGON_AMOY, - '0x62dD51230A30401C455c8398d06F85e4EaB6309f' - ); - console.log('Operator:', operator); - ``` - - -*** - -### getOperators() - -```ts -static getOperators(filter: IOperatorsFilter, options?: SubgraphOptions): Promise; -``` - -This function returns all the operator details of the protocol. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `filter` | `IOperatorsFilter` | Filter for the operators. | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `IOperator[]` | Returns an array with all the operator details. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorUnsupportedChainID` | If the chain ID is not supported | - -???+ example "Example" - - ```ts - import { ChainId } from '@human-protocol/sdk'; - - const filter = { - chainId: ChainId.POLYGON_AMOY - }; - const operators = await OperatorUtils.getOperators(filter); - console.log('Operators:', operators.length); - ``` - - -*** - -### getReputationNetworkOperators() - -```ts -static getReputationNetworkOperators( - chainId: ChainId, - address: string, - role?: string, -options?: SubgraphOptions): Promise; -``` - -Retrieves the reputation network operators of the specified address. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `chainId` | `ChainId` | Network in which the reputation network is deployed | -| `address` | `string` | Address of the reputation oracle. | -| `role?` | `string` | Role of the operator (optional). | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `IOperator[]` | Returns an array of operator details. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorUnsupportedChainID` | If the chain ID is not supported | - -???+ example "Example" - - ```ts - import { OperatorUtils, ChainId } from '@human-protocol/sdk'; - - const operators = await OperatorUtils.getReputationNetworkOperators( - ChainId.POLYGON_AMOY, - '0x62dD51230A30401C455c8398d06F85e4EaB6309f' - ); - console.log('Operators:', operators.length); - ``` - - -*** - -### getRewards() - -```ts -static getRewards( - chainId: ChainId, - slasherAddress: string, -options?: SubgraphOptions): Promise; -``` - -This function returns information about the rewards for a given slasher address. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `chainId` | `ChainId` | Network in which the rewards are deployed | -| `slasherAddress` | `string` | Slasher address. | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `IReward[]` | Returns an array of Reward objects that contain the rewards earned by the user through slashing other users. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidSlasherAddressProvided` | If the slasher address is invalid | -| `ErrorUnsupportedChainID` | If the chain ID is not supported | - -???+ example "Example" - - ```ts - import { OperatorUtils, ChainId } from '@human-protocol/sdk'; - - const rewards = await OperatorUtils.getRewards( - ChainId.POLYGON_AMOY, - '0x62dD51230A30401C455c8398d06F85e4EaB6309f' - ); - console.log('Rewards:', rewards.length); - ``` - diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingClient.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingClient.md deleted file mode 100644 index 3a42b1133a..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingClient.md +++ /dev/null @@ -1,389 +0,0 @@ -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. - -```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. - -## Example - -###Using Signer - -####Using private key (backend) - -```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); -``` - -####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); -``` - -###Using Provider - -```ts -import { StakingClient } from '@human-protocol/sdk'; -import { JsonRpcProvider } from 'ethers'; - -const rpcUrl = 'YOUR_RPC_URL'; - -const provider = new JsonRpcProvider(rpcUrl); -const stakingClient = await StakingClient.build(provider); -``` - -## Extends - -- `BaseEthersClient` - -## Constructors - -### Constructor - -```ts -new StakingClient(runner: ContractRunner, networkData: NetworkData): StakingClient; -``` - -**StakingClient constructor** - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | -| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the Staking contract | - - -#### Returns - -| Type | Description | -|------|-------------| -| `StakingClient` | - | - -#### Overrides - -```ts -BaseEthersClient.constructor -``` - -## Methods - -### build() - -```ts -static build(runner: ContractRunner): Promise; -``` - -Creates an instance of StakingClient from a Runner. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `runner` | `ContractRunner` | The Runner object to interact with the Ethereum network | - - -#### Returns - -| Type | Description | -|------|-------------| -| `StakingClient` | An instance of StakingClient | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorProviderDoesNotExist` | If the provider does not exist for the provided Signer | -| `ErrorUnsupportedChainID` | If the network's chainId is not supported | - -???+ example "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); - ``` - - -*** - -### approveStake() - -```ts -approveStake(amount: bigint, txOptions: Overrides): Promise; -``` - -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 - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `amount` | `bigint` | Amount in WEI of tokens to approve for stake. | -| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | - - -#### Returns - -| Type | Description | -|------|-------------| -| `void` | - | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidStakingValueType` | If the amount is not a bigint | -| `ErrorInvalidStakingValueSign` | If the amount is negative | - -???+ example "Example" - - ```ts - import { ethers } from 'ethers'; - - const amount = ethers.parseUnits('5', 'ether'); //convert from ETH to WEI - await stakingClient.approveStake(amount); - ``` - - -*** - -### stake() - -```ts -stake(amount: bigint, txOptions: Overrides): Promise; -``` - -This function stakes a specified amount of tokens on a specific network. - -!!! note - `approveStake` must be called before - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `amount` | `bigint` | Amount in WEI of tokens to stake. | -| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | - - -#### Returns - -| Type | Description | -|------|-------------| -| `void` | - | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidStakingValueType` | If the amount is not a bigint | -| `ErrorInvalidStakingValueSign` | If the amount is negative | - -???+ example "Example" - - ```ts - import { ethers } from 'ethers'; - - 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() - -```ts -unstake(amount: bigint, txOptions: Overrides): Promise; -``` - -This function unstakes tokens from staking contract. The unstaked tokens stay locked for a period of time. - -!!! note - Must have tokens available to unstake - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `amount` | `bigint` | Amount in WEI of tokens to unstake. | -| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | - - -#### Returns - -| Type | Description | -|------|-------------| -| `void` | - | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidStakingValueType` | If the amount is not a bigint | -| `ErrorInvalidStakingValueSign` | If the amount is negative | - -???+ example "Example" - - ```ts - import { ethers } from 'ethers'; - - const amount = ethers.parseUnits('5', 'ether'); //convert from ETH to WEI - await stakingClient.unstake(amount); - ``` - - -*** - -### withdraw() - -```ts -withdraw(txOptions: Overrides): Promise; -``` - -This function withdraws unstaked and non-locked tokens from staking contract to the user wallet. -!!! note - Must have tokens available to withdraw - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `txOptions` | `Overrides` | Additional transaction parameters (optional, defaults to an empty object). | - - -#### Returns - -| Type | Description | -|------|-------------| -| `void` | - | - -???+ example "Example" - - ```ts - await stakingClient.withdraw(); - ``` - - -*** - -### slash() - -```ts -slash( - slasher: string, - staker: string, - escrowAddress: string, - amount: bigint, -txOptions: Overrides): Promise; -``` - -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 - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `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 - -| Type | Description | -|------|-------------| -| `void` | - | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidStakingValueType` | If the amount is not a bigint | -| `ErrorInvalidStakingValueSign` | If the amount is negative | -| `ErrorInvalidSlasherAddressProvided` | If the slasher address is invalid | -| `ErrorInvalidStakerAddressProvided` | If the staker address is invalid | -| `ErrorInvalidEscrowAddressProvided` | If the escrow address is invalid | -| `ErrorEscrowAddressIsNotProvidedByFactory` | If the escrow is not provided by the factory | - -???+ example "Example" - - ```ts - import { ethers } from 'ethers'; - - const amount = ethers.parseUnits('5', 'ether'); //convert from ETH to WEI - await stakingClient.slash( - '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', - '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', - '0x62dD51230A30401C455c8398d06F85e4EaB6309f', - amount - ); - ``` - - -*** - -### getStakerInfo() - -```ts -getStakerInfo(stakerAddress: string): Promise; -``` - -Retrieves comprehensive staking information for a staker. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `stakerAddress` | `string` | The address of the staker. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `StakerInfo` | Staking information for the staker | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidStakerAddressProvided` | If the staker address is invalid | - -???+ example "Example" - - ```ts - const stakingInfo = await stakingClient.getStakerInfo('0xYourStakerAddress'); - console.log('Tokens staked:', stakingInfo.stakedAmount); - ``` - diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingUtils.md deleted file mode 100644 index 431e4bb3f1..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/StakingUtils.md +++ /dev/null @@ -1,106 +0,0 @@ -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); -``` - -## Methods - -### getStaker() - -```ts -static getStaker( - chainId: ChainId, - stakerAddress: string, -options?: SubgraphOptions): Promise; -``` - -Gets staking info for a staker from the subgraph. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `chainId` | `ChainId` | Network in which the staking contract is deployed | -| `stakerAddress` | `string` | Address of the staker | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `IStaker` | Staker info from subgraph | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidStakerAddressProvided` | If the staker address is invalid | -| `ErrorUnsupportedChainID` | If the chain ID is not supported | -| `ErrorStakerNotFound` | If the staker is not found | - -???+ example "Example" - - ```ts - import { StakingUtils, ChainId } from '@human-protocol/sdk'; - - const staker = await StakingUtils.getStaker( - ChainId.POLYGON_AMOY, - '0xYourStakerAddress' - ); - console.log('Staked amount:', staker.stakedAmount); - ``` - - -*** - -### getStakers() - -```ts -static getStakers(filter: IStakersFilter, options?: SubgraphOptions): Promise; -``` - -Gets all stakers from the subgraph with filters, pagination and ordering. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `filter` | `IStakersFilter` | Stakers filter with pagination and ordering | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `IStaker[]` | Array of stakers | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorUnsupportedChainID` | If the chain ID is not supported | - -???+ example "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); - ``` - diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/StatisticsUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/StatisticsUtils.md deleted file mode 100644 index d7419750ce..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/StatisticsUtils.md +++ /dev/null @@ -1,401 +0,0 @@ -Utility class for statistics-related queries. - -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 { 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); -``` - -## Methods - -### getEscrowStatistics() - -```ts -static getEscrowStatistics( - networkData: NetworkData, - filter: IStatisticsFilter, -options?: SubgraphOptions): Promise; -``` - -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 - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | -| `filter` | `IStatisticsFilter` | Statistics params with duration data | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `IEscrowStatistics` | Escrow statistics data. | - -???+ example "Example" - - ```ts - 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); - ``` - - -*** - -### getWorkerStatistics() - -```ts -static getWorkerStatistics( - networkData: NetworkData, - filter: IStatisticsFilter, -options?: SubgraphOptions): Promise; -``` - -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 - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | -| `filter` | `IStatisticsFilter` | Statistics params with duration data | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `IWorkerStatistics` | Worker statistics data. | - -???+ example "Example" - - ```ts - 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); - ``` - - -*** - -### getPaymentStatistics() - -```ts -static getPaymentStatistics( - networkData: NetworkData, - filter: IStatisticsFilter, -options?: SubgraphOptions): Promise; -``` - -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 - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | -| `filter` | `IStatisticsFilter` | Statistics params with duration data | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `IPaymentStatistics` | Payment statistics data. | - -???+ example "Example" - - ```ts - import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; - - const networkData = NETWORKS[ChainId.POLYGON_AMOY]; - const paymentStats = await StatisticsUtils.getPaymentStatistics(networkData); - console.log( - 'Payment statistics:', - paymentStats.dailyPaymentsData.map((p) => ({ - ...p, - totalAmountPaid: p.totalAmountPaid.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); - ``` - - -*** - -### getHMTStatistics() - -```ts -static getHMTStatistics(networkData: NetworkData, options?: SubgraphOptions): Promise; -``` - -This function returns the statistical data of HMToken. - -```ts -interface IHMTStatistics { - totalTransferAmount: bigint; - totalTransferCount: number; - totalHolders: number; -}; -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `IHMTStatistics` | HMToken statistics data. | - -???+ example "Example" - - ```ts - import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; - - const networkData = NETWORKS[ChainId.POLYGON_AMOY]; - const hmtStats = await StatisticsUtils.getHMTStatistics(networkData); - console.log('HMT statistics:', { - ...hmtStats, - totalTransferAmount: hmtStats.totalTransferAmount.toString(), - }); - ``` - - -*** - -### getHMTHolders() - -```ts -static getHMTHolders( - networkData: NetworkData, - params: IHMTHoldersParams, -options?: SubgraphOptions): Promise; -``` - -This function returns the holders of the HMToken with optional filters and ordering. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | -| `params` | `IHMTHoldersParams` | HMT Holders params with filters and ordering | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `IHMTHolder[]` | List of HMToken holders. | - -???+ example "Example" - - ```ts - import { StatisticsUtils, ChainId, NETWORKS } from '@human-protocol/sdk'; - - 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(), - }))); - ``` - - -*** - -### getHMTDailyData() - -```ts -static getHMTDailyData( - networkData: NetworkData, - filter: IStatisticsFilter, -options?: SubgraphOptions): Promise; -``` - -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 - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `networkData` | [`NetworkData`](../type-aliases/NetworkData.md) | The network information required to connect to the subgraph | -| `filter` | `IStatisticsFilter` | Statistics params with duration data | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `IDailyHMT[]` | Daily HMToken statistics data. | - -???+ example "Example" - - ```ts - 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 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); - ``` - diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/TransactionUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/TransactionUtils.md deleted file mode 100644 index 84138cfa63..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/TransactionUtils.md +++ /dev/null @@ -1,188 +0,0 @@ -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); -``` - -## Methods - -### getTransaction() - -```ts -static getTransaction( - chainId: ChainId, - hash: string, -options?: SubgraphOptions): Promise; -``` - -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 - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `chainId` | `ChainId` | The chain ID. | -| `hash` | `string` | The transaction hash. | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `ITransaction \| null` | Returns the transaction details or null if not found. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorInvalidHashProvided` | If the hash is invalid | -| `ErrorUnsupportedChainID` | If the chain ID is not supported | - -???+ example "Example" - - ```ts - import { TransactionUtils, ChainId } from '@human-protocol/sdk'; - - const transaction = await TransactionUtils.getTransaction( - ChainId.POLYGON_AMOY, - '0x62dD51230A30401C455c8398d06F85e4EaB6309f' - ); - console.log('Transaction:', transaction); - ``` - - -*** - -### getTransactions() - -```ts -static getTransactions(filter: ITransactionsFilter, options?: SubgraphOptions): Promise; -``` - -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[]; -}; -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `filter` | `ITransactionsFilter` | Filter for the transactions. | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `ITransaction[]` | Returns an array with all the transaction details. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorCannotUseDateAndBlockSimultaneously` | If both date and block filters are used | -| `ErrorUnsupportedChainID` | If the chain ID is not supported | - -???+ example "Example" - - ```ts - import { TransactionUtils, ChainId, OrderDirection } from '@human-protocol/sdk'; - - const filter = { - chainId: ChainId.POLYGON_AMOY, - 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); - console.log('Transactions:', transactions.length); - ``` - diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/classes/WorkerUtils.md b/packages/sdk/typescript/human-protocol-sdk/docs/classes/WorkerUtils.md deleted file mode 100644 index 739ecde4b1..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/docs/classes/WorkerUtils.md +++ /dev/null @@ -1,129 +0,0 @@ -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); -``` - -## Methods - -### getWorker() - -```ts -static getWorker( - chainId: ChainId, - address: string, -options?: SubgraphOptions): Promise; -``` - -This function returns the worker data for the given address. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `chainId` | `ChainId` | The chain ID. | -| `address` | `string` | The worker address. | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `IWorker \| null` | Returns the worker details or null if not found. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorUnsupportedChainID` | If the chain ID is not supported | -| `ErrorInvalidAddress` | If the address is invalid | - -???+ example "Example" - - ```ts - import { WorkerUtils, ChainId } from '@human-protocol/sdk'; - - const worker = await WorkerUtils.getWorker( - ChainId.POLYGON_AMOY, - '0x1234567890abcdef1234567890abcdef12345678' - ); - console.log('Worker:', worker); - ``` - - -*** - -### getWorkers() - -```ts -static getWorkers(filter: IWorkersFilter, options?: SubgraphOptions): Promise; -``` - -This function returns all worker details based on the provided filter. - -**Input parameters** - -```ts -interface IWorkersFilter { - chainId: ChainId; // List of chain IDs to query. - address?: string; // (Optional) The worker address to filter by. - orderBy?: string; // (Optional) The field to order by. Default is 'payoutCount'. - orderDirection?: OrderDirection; // (Optional) The direction of the order. Default is 'DESC'. - first?: number; // (Optional) Number of workers per page. Default is 10. - skip?: number; // (Optional) Number of workers to skip. Default is 0. -} -``` - -```ts -type IWorker = { - id: string; - address: string; - totalHMTAmountReceived: bigint; - payoutCount: number; -}; -``` - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `filter` | `IWorkersFilter` | Filter for the workers. | -| `options?` | [`SubgraphOptions`](../interfaces/SubgraphOptions.md) | Optional configuration for subgraph requests. | - - -#### Returns - -| Type | Description | -|------|-------------| -| `IWorker[]` | Returns an array with all the worker details. | - -#### Throws - -| Type | Description | -|------|-------------| -| `ErrorUnsupportedChainID` | If the chain ID is not supported | -| `ErrorInvalidAddress` | If the filter address is invalid | - -???+ example "Example" - - ```ts - import { WorkerUtils, ChainId } from '@human-protocol/sdk'; - - const filter = { - chainId: ChainId.POLYGON_AMOY, - first: 10, - skip: 0, - }; - const workers = await WorkerUtils.getWorkers(filter); - console.log('Workers:', workers.length); - ``` - diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/enumerations/EscrowStatus.md b/packages/sdk/typescript/human-protocol-sdk/docs/enumerations/EscrowStatus.md deleted file mode 100644 index 0dfa358f82..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/docs/enumerations/EscrowStatus.md +++ /dev/null @@ -1,13 +0,0 @@ -Enum for escrow statuses. - -## Enumeration Members - -| Enumeration Member | Value | Description | -| ------ | ------ | ------ | -| `Launched` | `0` | Escrow is launched. | -| `Pending` | `1` | Escrow is funded, and waiting for the results to be submitted. | -| `Partial` | `2` | Escrow is partially paid out. | -| `Paid` | `3` | Escrow is fully paid. | -| `Complete` | `4` | Escrow is finished. | -| `Cancelled` | `5` | Escrow is cancelled. | -| `ToCancel` | `6` | Escrow is cancelled. | diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/interfaces/SubgraphOptions.md b/packages/sdk/typescript/human-protocol-sdk/docs/interfaces/SubgraphOptions.md deleted file mode 100644 index 3674ec4564..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/docs/interfaces/SubgraphOptions.md +++ /dev/null @@ -1,9 +0,0 @@ -Configuration options for subgraph requests with retry logic. - -## Properties - -| Property | Type | Description | -| ------ | ------ | ------ | -| `maxRetries?` | `number` | Maximum number of retry attempts | -| `baseDelay?` | `number` | Base delay between retries in milliseconds | -| `indexerId?` | `string` | Optional indexer identifier. When provided, requests target `{gateway}/deployments/id//indexers/id/`. | diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/MessageDataType.md b/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/MessageDataType.md deleted file mode 100644 index c84d8374d3..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/MessageDataType.md +++ /dev/null @@ -1,6 +0,0 @@ -```ts -type MessageDataType = string | Uint8Array; -``` - -Type representing the data type of a message. -It can be either a string or a Uint8Array. diff --git a/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/NetworkData.md b/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/NetworkData.md deleted file mode 100644 index 194d6a4843..0000000000 --- a/packages/sdk/typescript/human-protocol-sdk/docs/type-aliases/NetworkData.md +++ /dev/null @@ -1,115 +0,0 @@ -```ts -type NetworkData = object; -``` - -Network data - -## Properties - -### chainId - -```ts -chainId: number; -``` - -Network chain id - -*** - -### title - -```ts -title: string; -``` - -Network title - -*** - -### scanUrl - -```ts -scanUrl: string; -``` - -Network scanner URL - -*** - -### hmtAddress - -```ts -hmtAddress: string; -``` - -HMT Token contract address - -*** - -### factoryAddress - -```ts -factoryAddress: string; -``` - -Escrow Factory contract address - -*** - -### stakingAddress - -```ts -stakingAddress: string; -``` - -Staking contract address - -*** - -### kvstoreAddress - -```ts -kvstoreAddress: string; -``` - -KVStore contract address - -*** - -### subgraphUrl - -```ts -subgraphUrl: string; -``` - -Subgraph URL - -*** - -### subgraphUrlApiKey - -```ts -subgraphUrlApiKey: string; -``` - -Subgraph URL API key - -*** - -### oldSubgraphUrl - -```ts -oldSubgraphUrl: string; -``` - -Old subgraph URL - -*** - -### oldFactoryAddress - -```ts -oldFactoryAddress: string; -``` - -Old Escrow Factory contract address From 40a6ba24dde90ac9ca3b0ea5f905c65ff6430cd1 Mon Sep 17 00:00:00 2001 From: portuu3 Date: Tue, 9 Dec 2025 18:49:00 +0100 Subject: [PATCH 10/19] edit index and changes styles --- docs/index.html | 21 +++++++++++++++++++-- docs/overrides/assets/css/custom.css | 1 + docs/overrides/assets/img/python-logo.webp | Bin 0 -> 9414 bytes docs/overrides/assets/img/ts-logo.png | Bin 0 -> 21739 bytes 4 files changed, 20 insertions(+), 2 deletions(-) create mode 100644 docs/overrides/assets/img/python-logo.webp create mode 100644 docs/overrides/assets/img/ts-logo.png diff --git a/docs/index.html b/docs/index.html index 18df3aee24..c61f815b9c 100644 --- a/docs/index.html +++ b/docs/index.html @@ -52,6 +52,9 @@ .sdk-icon { font-size: 2.4rem; margin-bottom: 0.75rem; + display: flex; + align-items: center; + justify-content: center; } .sdk-card h2 { margin: 0 0 0.5rem; @@ -68,6 +71,7 @@ display: flex; gap: 0.4rem; flex-wrap: wrap; + justify-content: center; } .sdk-badge { font-size: 0.7rem; @@ -82,6 +86,8 @@ display: flex; gap: 0.5rem; flex-wrap: wrap; + flex-direction: column; /* stack vertically */ + align-items: center; /* center horizontally */ } .sdk-btn { border-radius: 999px; @@ -128,6 +134,12 @@ .sdk-footer li { margin: 0.25rem 0; } + .sdk-top-logo { + width: 128px; + height: 128px; + display: inline-block; + margin-bottom: 0.75rem; + } @media (max-width: 768px) { .sdk-card { width: 100%; @@ -137,6 +149,7 @@
+

HUMAN Protocol SDKs

Choose your preferred language SDK to integrate with HUMAN Protocol. @@ -147,7 +160,9 @@

HUMAN Protocol SDKs

-
🟦
+
+ TypeScript Logo +
TypeScript Node.js / Browser @@ -169,7 +184,9 @@

TypeScript SDK

-
🐍
+
+ Python Logo +
Python Scripts / Services diff --git a/docs/overrides/assets/css/custom.css b/docs/overrides/assets/css/custom.css index c16b4cd7c4..341aa77833 100644 --- a/docs/overrides/assets/css/custom.css +++ b/docs/overrides/assets/css/custom.css @@ -22,6 +22,7 @@ --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); } diff --git a/docs/overrides/assets/img/python-logo.webp b/docs/overrides/assets/img/python-logo.webp new file mode 100644 index 0000000000000000000000000000000000000000..0a2ac726306fbf836e9fb9174f13502593c85a0b GIT binary patch literal 9414 zcmV;%BstqsNk&G#Bme+cMM6+kP&iDoBme*}|G|F{YH{2)k|Rl#f7Ub8=FC4LCV(HB zq+-7{nvl~e34c@tykpNNif60nok@!fKk$yt!X3PG1FMYsM$HM9swyPl@S%dcte`9) zs>}E>8?Cvij{;B=v?9c$YhNmlMAua7lnIwCTwG9ogw&{w#4 zSh&)IYoRQxdn>!EXDUTy^`P;!Fg4j(8Id(rQ4y$4uV)i1NP3u<*mLp5WIVLR2Ebw! zxOxE^+Co_DK}+ij|1JSvYYpQur_i`^33zG+*xJI@mWDFXCOg0y3k|+rhcvb5UJqgg z+Sa?6HqjeUJ7HFUTEO(|fHN-YDwkD^J&QmuLPL37Xk2VeEw?cid*FK49V)i9J=>EE zCN81A-@Whm{nMzbDkKuk06NH~`*ct^7Bi?0k2FzVr^F-Yro2|%GFZh#kTGsZq&7>Q4lanv!m_czU^- zbz~Fuey)5>08Cq-1ONaGp|Ne-wr$(4+1_%^R<>>1wr$(S;~+tj+_vd)j(-LS5Pov9 zZF}~_bLe&Iz4zXGXY9SVuf2au@4ff7{rR5z2=B}5ASNT14c4sLBLNxASU?6d06S#`E3p){frzwD7LhzvWI|=_HiXdat}D@r$Z(p3(Z_Q7CG_P;Y>o4ZFf0);Q$m`j8{b*i~wQF;FQrso5bahwYFp_nQ!_ITDn*XYg6tG( z7-r`TW%=n31xc^)uXzab$4y*bGoWp-)1wKdKo&K zIHYmOA5?R_d-sGCh_+lVKb-^KDLHQ}#WNl?jOPv0Ys2{0Fv2ik(V_*h8bB;fjaZtR zi&Sh)^;nsjmg;a!g|5_ZI?C}ig*s#$swiw2zhVgf&rUq1#rb0YT z^-J68nYLBCzSU-JSaxoh>x_fStHQq{jp?oN@EpUm+b~|po4O1WuM?{Q&1YhyseWqM zT}@R5u|jlK0e_Zx>%G!Rkm0Umr$q#37^bI&Y0@wuR&)A_hG8kf@EC;g5ynDG+Ywr- zFAZEK;qs?4z@}N)Sc7MJhfQ2;LexaFi-)iYO?3sK1;>_YwK=A$U@E$z>kem=FcV@H-gi z_If>W84jVHaM}9YR_fBqxVWvcdX1-$BEyY(2|0>K+)YTIE#l6EUH3SmI_#MZLJxQrwv z@3vc%X$YTP?|~7Mq-Bj{WLvvsnTGJ`^;AfRO)NnrR5v ztd<@>B;@yYYcmazozepnE$vok8ZDYDIn32z?S`>PTp&D!5Er>w+)SxYEyXCOX$bde zFI}r5gREXeDYQb<0KN&#|GOBa`dT9Z$G78~xTTwwTc(GcbutzE+RyP0x2xxy*2~Zn_7anBFLJ zU|&?;t5>!Dg)8mpgY6srMi=qO*6NXa`vw$*s;QSgkt7?I+2p-`#dVkb@Xn$kt!_cb zXE%Ef&?BFJXsfmk{M!e zTx0hgJ{Z$Gl0c?bkJxJkM3^HF*2Szgg_6&om{P`zC&P2tWa`L!Q-cUfb=SkvF}>=) zf0$P1q#BX>>ko}*^~k-_!~VJRe zxN~?en>+yseS`d^16@^_-jH;*(yw0_(ceB%1P~t*f$?zwcSr|Hy-KY|FhSD&JB;bj z!5Dc05Ler49oe{f2}*HN+qm40QBA2Alcw>$MHP~PlAe=k4NRaa`~D3k_3^!^z$3y0 zpih#4uAZCP=G9(|YhJI4FpbZ=VMn=Oj@*=1?{JdRFJFM-Z{H9nV6#y!P_iMd#X~xb z>~g{cpx1JNlK0ZGPi8^w>z6MeOye^SswovH)t^$2pi|eN4)psE5GS}eLn^j7rW7xw z@uflxbtn6ogfIb{6Eb0^2Ia|=mW>%;b$9c@(-5XU=#5M;E@P6`meoFByZ`u22or!f z%OrwDxx`Tt+z#xC0^94iA3~VM;d$dE6FZ!xb^KTg*xtVX4B~WQiC~UOPwT{q6tI2# z_&MgT3p5otXst|ab&%GRB_e z@#O;Y1Rx?2$jG9!rqoDa)%^e0H-<=_0MsK9%+cj({jdD>3o7N&y*7CQ&@YKVN3Bb% zIdu5~)Q(Ml5(S`Pnb_27pjcOSisj{55D_QMx&@PB_n3J3nb!9w_7**?n97kLPw4Ddhgk{E5gmfm-qF{m)OOd2Az%qtL^TZ1&i40SHiyp z(XXq&eueAX&lDymI4n?5iS>;lIlXC>!z2IsGjTVsCEmRibM1;ale1?>$hxIg56#CC z6B85as-|g29Af|-5m-Fpzhh)(Z8KVU6adT_N!<2Fm#pwuC>kS-8ZBd5qk5)qm(kpm zpxo4cBmO(a(k_Na>6*92+Z>Z_vIW-6>n!t5d(1&=4Ab1X$!4f1lcD%BX)21+R6>-Z z(nSd>F-%YwyBNkP&J3K2XBa6~hJi{|&OqgK6r@f~l^8P#BC)L^F+ zZ>3JD$CWy!k}7pvUFzt_U`Lxu9p#rg&g^-hd_94AvwK)9tP9ni#m`)mXRocZ%#Um{ z+cNVkGlsJm)MPS5{5@-55K%;zI;W2L27)u%;+BC?A&Q(>qqZ%OM zob`oPxZgZAyQk6{l>+kSNu38<1Y2O-^u=WAM)Y(Vc`O1J9XqRVv+Ds%ruozOGqz~@ z+U_VDv{R)8(-<^%sOIVzr@2>^7ER;O*a(4*y{gmVX)Lk`>LU4umV=nz4OFO+y1}K=<0v(L zT#e@%Rn{?$Q)3HMYooFtm4R4gP;G6OnW^k5T8*7mttKijTaH&2)zw4I^p?@^hgQNu zV1Z06C!19^9kmQhtV43@y&SbHxH6Ewx+~n3L1m|{wxj%8bI89smH%8`=zK^7#+#ah z>t|MeVh2@r61&zMva5c`DS8=LQ4xLq1?htQpZH}VoLU&G(epRU@oUY&*OeUe_8DKD zt;aA6$0|vt4$It{kTPpML9z;!RmU+4{#3B;>jSgO;5cUC(q{KC%TuY}avWRhBB}BZ zA)&L`SZ3g-^5e_s48$@E$4gULJlX&>&6MIuI@Wr==Px^=xX!kzdqv9ypb@5wBoNX? zUM1;Imw!6|bPbvdfPOQjB!dtG8%yeB@8JfZex}TxPl$onB}XC9Sx?JcP=WyH6;o!f zCd5F{MW&_bk1MUt5V(QaTxUx0ASGQCT1qE(dpq0!+{%>UHA)PeE=8Yb;tdYk&XnOx zN-nT~v&=!qXX6dbW+99BfHuQ`6elo`gMMxTZ^s*)n_!jk9g!TgC&NgyrDH||iMO=nAZ1JE_54CfK!1ag_yowL3jF^`$c0K9=I zv(FP#Y+cQyXRg(pO-{{(gIJ75WEn<@aRMx+&RH~jdLrz-;C)XS0`BsePI#1Hhw( z>3J>K0Q6urQ);)}Pn88G!ybk;0CV8nShF|z%WxlA#u_lB^9;tlw0yPY<9PA8GiU zi!%sw(TM{%cK4grMdNBx>X!=nJ4S_CeK*Cx6}Cs#%|1Wd?}Yo?@gbvMvKT7b&eto!aTTW zIoA!n<;3^i3^1^E8$B1=3or;zp~cBulM#JSU=CO?w~ad20T@JRFdJ8{*+BR`IlMOq z41nG!ass{}a=Py^QskNx(|9s{Zx)>QUlEmip$j5YXh|O5ZG4~PN$0(pV1bs1zWEPa z5P5xBzPXx?o#TRgbHM^P5#7vQU~NwfM223!if?v!l5%f0bb*(M&Rc-B1w;`d=EZyWUOPOFyf-5($QIH0KC0l7hhRu7_r1GaoRfrmbHacY z*{5@eu=g)uAj*fxg%ocs!}UGF_fr17Sz*AeT=oBzWbeZ6m5oV5|G=RKz*$+QxNGMW z(|D=POMn+n&UkhgI3aW#Ep69^Bx(1r#naredx{0TG=`4{j9?F|&HSn=rF}qRQm5lTKpDcKW6j(+tx9 zHr>U`>x|{=4SY5=MdRfj`U=y#E)nS4`Sltvt)9e^&!}^Ieqp?m;PrUKDtb-W!uWH;R6>?p z3Hu4TrVjG;j>ud>atW}dn6pNoJ>(L`Kak<&)MzN~r(?Ur%eQlRE0@75`EvTs=5rQd zVhR(KF(O3dZ`qlb)V$n({`s770(*bLAVRV!QMN?n&&Am5!abKu&p)3xckGX;gI65VmdlCzoPBpL;pQdI z&OKGm<&<;rUNLfVI$q8fOkCSR*yngbX)hRC&TS~?j!aEWiIS6Z_9Ctja_~>91-*>H z&$TV*=9hD?xw%tQQ&R%v1Wu`&&P*ZX8SN#bD&orq^EKVva4%Tl=3R7ihumCDO-+f_ zZB%Z_5==~x6?sDa<+dj1N_}=$R({a0oSRk7UE}6eyScaByx(pfqW&jd{W;C5_gWkw z4`Qf>bM5VFev4ETg%ql+jU@QaZ6p2^}ve zp<@NbbYejf9m_AGWBG-2a()3FB&<#!=zcxWD=G3cuFUt@@ zG_H3%C6)TRUZq;KA|b5Y7gpY`R{pD2VnwwA356ASzyrc^Bo>yTrb-#2Dy2xQQi6Cv z31S7sNGvEqEWZe`{6Zw>7a+m z{KtYS7L=4iffpAsRcy6X^!W%Q2zm8$+{b2B$wDbB6m)SBRmE1>qUW`IAS-Wh&kc3* zLJi*b6S(Tni58uwvB9Kna!;X}7Ru`4BC?!-kEqSxT%gno@QRV)JT_EmR;Z1I3Kp^D z1ni{Ke9Ht%b>&v7bIzP@r3`g@ctY9_TA{1U2|S?GuO0Y~-Ppebg&I7WOu&8PE136!K2jQWAX@EzyxO- zcc>OwxAzLfkP-cAyo?LxMorLMrOi_AvQStv!6p3c9xS75rnU$}z?!R>d~@-6MCc}G)3 zN1x=#6dg7n+36>?9=%kJ(T9K?@J(Po-1IRcj-B=qsOFg zvQG!S1#bqTXN+ERBt7P;V)hEhprd%RU_eH?2R#<$!W3LS1s&kcz^|iS_3KKdGn5)i zkFf7fB!n;L7m4s$=#pzq_&K*U)YWWMy-IxUnQWPYa$UG!~uGq73arL$~W zDE*u%xZDC<7d@Mw%AT~%1yiD<+n9nDjJM-&F~82H7%i0E$`tfQyme8J3>$Ink zA+}4Hg1(NoQY+8br^Td@RVget*9rd&x8tuXa+mQpQpjxmm^U!_HnXyUDlo=T~7Hcts<3|WGU9o!6rUsjGzqbRW+DJ_{ATm6B-dc6G1TNmtE_4aDD(%*VpR*#bWe$2Ay>WpFOUVFeNMl6fs zq@MKLGhQ8fLODEppnbUAzAE!9jF-CVY-+|Ti*9;WE~zawtB6zvg-d-pFBMTK9HlI} zG>}DVEIIuZrJV3f>U0N{PDCh+wo(hZ)LL?`q*5e4)xHHK`ZO#$S=3ki?sQ%8XOgOP zDKc4vG_dgm`qSlAdL5T6jA~@t0a{^GWnj_59%&+#r9`CHzDpYMB$bZEqpwRty}4jF zsERBa-z{@%;13im<7&vF((Wu;2d=;OrV z#3VrDc6lHQpzUtGMEXMPt*H z_NBhAJa399PC%Uyy+>M^+Ra)umSTw$7oDIjZSB=3CXI<0;=~gt`llA6c5geSZF!

uNQ)>x)(rtCF0PH355SY|Su#Sli8En#KRB#P2xxMK-~3GoSv zNmNioV);cRmS0HNd4;4VFP|jl1xb_}BsIBtBsn*iaOZYOjyJnYl8`5Tqswq#VzW9U zNey;J7!7tp5-N2<9$M;{)K=>FQK{n_rH(sF9W|9YWR^PGJYat-1j2$i zvR2S>{yT0K7+iNUy9>^U|3>^b;=f}U&wv)vFUg`zbU7sQXynn!A(M$I$*O3>OgI|O zRwmiHB3?DV)%q8vT7ODJq}u1Gq1XI6z#^oZK68}GAr)bF6><<7X|e>f zs=Q*?olUmkm^>P+F`E#R%4c+6dzr8b*)XvZQI-;#%Y;(IjmeeCGQqUgn|uZgs93-W z2s$gx0fv-?Ph$mjX~p1JW3*M{M+T{I%Ydb;k}P3ZX$Ulx0ioO_oN8}OczP<{EC!Zh z%PEwHbE=RXQke`gPp*MbxcD;4Rw9DLKFz2yasq@)7!_|4LnT>5<;e~Ze$S{ZY*@dk zJXrxk&}m?db;0=BxM#8bW zF`o*#)Tax1X+)5)(eIScVN(_ktbBSzp2Q0j1-*yOKNN2Y)&-&*J7Zy>ePNTWR0PVW z1&t@@=dtiAKF>RMLHBqx{}wO``W%}Q%tK1C>k&;(e9$m(`N}2(QaetycP4-+_mCG2 z$EsXGN7%gXG}$VgbYzcca?&MmG|+3<)Kn@3rP7@bM4sHj!$33S^S+aiUJ;Nu(>xka z4pYyF1dj@BfY1BR(h*?fkn@N#@Hn`l{q@_#Ah_0u=F}dTXoX5k3BXf=L4{iP3RqF6UCBd1t`!sB+>f zpa_0t3fdW`<4z@6Q0)WZ(Wa>mobjl`xKJW2&X`XgT~5LT7z4l21Z|z!ac6}(sScHj3%{Wy1DRhd$m`B#(&+UB zLP4fa-A1~vJ8gl*8j)hh``-_`u3UT`XM(L9=yj*Pbe1^;1)GBQNqw(7pGlqqjwK(c zSDj2s6nHwUB@p0IZM;->H^HZ%%FqY8RK`m^vzSB>$_A%C(5o(9n!Zdh%7M@Pphs1{ zvB8g=f>NgPL;$y%(~w!I1#X>fuSF@rX>YszU&sYOI$s zcMDtz_)-9WmB?jiz2qf`<-ivLc-8U0gXHq|21!dWD+Ct{U{J**mzzH?u;qYS0en<&Nl&37~znuSE2f3of0LJN|uMKyBa|&8+hN{~TKH*vuX8txPSz zmU>21I6dh*&vD1ied=Y0Hww6I_7bab((60t_nmL};^vN)^Qyd{dj@f{Iz!*ttFJ8Z zRpxjski zKEX`JyS_(cg%?hJr|iDdF$c$;+`JENaL4k^GI?*ajy>zFQmx!stzb3vCvK4E1|Pcl zWq!~ilmCXwZHFog!}2R(#Y9tn;s*I{@O?S|pcjmtQzo0KLT?+YaITb>h2=NGa&B|+ zgWtV;$`39Ig1VV%6n0msQXU(Y?+MGF-k~{8c=;@^px)1480MQ~s?rwK@{q86Q?>j~ zSU%R!y!;tA|B;u!*AFI~Ayb`>*j?dIhGp}@GDcYTGA!dXAg_Sy1>br34PJhpTi|n` z&LuKsYOA3V&uZDy`-Ei=!?NLq;T25!1<&0ArdzPs&3D@>Q?aT=`axNASY95MHdRWW zR!aZO)vNdgzy17segV@jDDd(lo_C^5@hVp+1Z6IjvW!Z}+Dd7CrSxW{^i!pDtgigR zA;0i#P_U!xm#YVMx Mg*wk(la1J$0EqQFX8-^I literal 0 HcmV?d00001 diff --git a/docs/overrides/assets/img/ts-logo.png b/docs/overrides/assets/img/ts-logo.png new file mode 100644 index 0000000000000000000000000000000000000000..77fbb6aec24d581aef15f019ad323dbc56c383de GIT binary patch literal 21739 zcmeFZcU05cw=Wt+0kqbPR3xaf%CN)Cn0fHL^r7FFnpnxKvAT?AG zq$9l-1wto4XrY9=R`mDY8Ry<}-g$qVG437jjXmNf`K~h8T(f@G{I2KPnkuw^u>65Q zAZS%@-ME85P}IT?H6{3ExBql9_}?+x>l)V)h)k%@VSIQ1Uvz) zz)t~l2!y*30R=%i2t;^ zpbyB3;UnXdzwoj|eBWqlhL74E0ekz0<@@h3vN-2VdDjO^ z_hr^U6X?wgS_UFYJ3*wuMCX(uK-cbai*NQ27G_LTTk?LkfP!I`ex{2qxS`vcr z*Vd9-{Mny3#$|RlFGf(Ur9SGjA=nnCjCTX+B9e^FrKN7j-A?Ot@5Xb5&1 zqbmDyC?j`bTE+$y82y?luWpR8PE~eJ+=Rn?uJ2Bv7F($ff-Zi}Z@JGYaLQ-g;LUo} zo0R##q!0)pU;DDlx-on$x7XT*+vPcTmkoI~s3&FIR+$Yr#!?<*G(xhutus9pK+_M# zQt!_3=6}$mnn1OyaG*aSICcf?W|~9=_u}ovk+)yEjQ<2ufVoH$>X;KZW6PNCH%b+i zaU~%5g*1}XF!yrVvV%X$fZJ}(1Bjs4z1>z3#<00o#onpnFYae+wE&dYtK z*!fVnwz?dDXse{-XPuZ)mwX0+uwcC0T32|v`t#1x@k6PY0(y?ZBXamQ#mWoTGos2O zEm(TcrgSb}kMGc}T_xfm1u;$=;osRnpnT7-s9IRM%>gD_F*w(d+Ly7LvUqr~!y4Q@ zEB_=vo}Z7(`pL{rlbt7z?fs_> zs{w1ovr&&8ttt4aUU0k}$&~eqYl{_H(LT^wzo}osOXxEM_l*d*NT_(}~ipB09 ze=IOGh#?t(!pq#6w9@GMcpw}~TKC}E`dg}q<54dX^GOW7rw@=9 zrmT=w#?&f{>tj@_`=aMa3e8iMlc0UQL88g0ou#RWydH!AAEEP}m(v}#mA9bBU)C;T z8K`q@Bc?TD&RAkE=w)`rA28ADnhu8oe&gvt|6N3<>{MZB^v`<*0$?mmf2}gEQ}LjC zqE{Kw3CQaViP7391WL8~*ID16a9^PYs2Zl-?dt37@f45ep zdT(8lM*sbxju$(eiK&I#I&r|5Q9sNpRUlDRk)B?J3$^_Mc zRKMN=2Zex0e|#*Omgdw|weF?2V7DxSxuoV7^Jvr+zh3NqHf z0q!Vw%Vi9EEq5s7dS&~6B-&oB6jBy$Zv|$fHWP>fdF#cQYgJPGhtN?!Rn0DeULH}| zoZgLZ@uP;Ej@c#@WFb2hSN?90w(~4toW(t6M~)9{UJd2n1pGd8KFmJmP@EJBB@}_Z zri4-2^pu^VkY9M1irKZEP<_d31{4k9@l+&H<}mE3Ir=l_tWN4t`9t}WTI$97?E*e2 zz5?U;fqswy0Ba{fYlE4nlq_-J(N|faZ@?GBv`FTVooo&Ad?Nl- z(ZUCMVhriyU91n5ziTOE*#7WV9oB%qbI?wTaLuNA6Ky@`2INN5cfJ-0a1_1G_VxpY zrWX*}8}PWgKjM>Qs{3k5Fd>?Ai++;7ir<_bZc^`yMqFC^A^rzxI@tY~SKSC>#G+mE zF!xa=u=XUKtel8Bejc-}=Tj02y`6sdR07aOp~z=I&k*(+FAKXzk_6=|)AvrNdG$9~ z%Ak!Tm*&QbA#Xe{>*|%dJF#GwL^}u9OZ~@{ZZ5~A;W~eHz5B9Iq{3;5hjU?8{>ETj ztVqMjwi7@%`E$?BsJZG7?L4FKBF)DiIz*k*1rn~^8uG^5tdnzm?-_*@?}WuoFhkHk zw^=6kpB>%#zHLU_VPLlXoBX55%nsMYLGT$5sQ^~0y-o>E@T-z)@g3p-`yZ1$Y3?o# zci1dtVAH6KHWxv!y6t364+L_>Zg-ZOHVaDiW!_M+t7D$KXbukqBd^&53D`Izqm7S4 zAHnI}-*@JY{+0-^6bL09L%l7t)vc#f93la&%YJwbopYDSBV4(2&X2zV%PA9}D>q>R zn$lSJ>6!0KQjk4`;kiWTD{#=yg@cPt17>4eua1lk7ZKf+Q%E#mKTjLH$%$C@+YF?9 zB;If`?-<}q>W$SiMl9Xhyc|25u@{(!b_Z%= z1Y4~fI&0JYCbp{UXlUZ-_E8hp64OX^R3z_@Np72`Y>Ydvm2BTFszM5xR&5^?R~00! z?A27|c?$K}&mX@5d~5BayS!1KxROQgTcIwwi`kAgWvN#m;-ha$+B%|jWrkTq?Z5hU zjSOnj3}FVUAKSyx@@yv`UmG8le?dF4Tj=6|k#MKAvNXW-Bj;PQ^7lyIx&}3pC!mE0 z`X}Sor3m|u&o2Cl3MJw_--@k<2jkRPN0RI;jYY~ciJcMO`-^amdlA~6pXK*sm_EeO zeO=w<_Z#v$EX9wFCif+yId}GO`A3iv&^|4l;@5~>5_P$;l_qteh$p=1!*i~}&NuXl z($(Va;m+xVTjF{l>P&qpCo+?YCSppc4!q?L`aTTzf`NQcosDUu#s27(@$b=R7tw|G zx=6}Y|8Njm1hDHeG;g@%CCV1dQ>i<2l5|Hz(5}W=5q8Z&(l3mojgqe<%FkCT`tH78bU;H^5D?H!wyiol2D!iA?Ny`K^sPy1Zvtm)eZu z@v>i^NzDU?a}&klq4CJ(j2Yt|$w{9FM`)JBA{8GwUJA39I97XVZiT(AAm14I?8okL zhnH+(epYFZCI_z$V$@Hi^rwX=RW4=xW#&5&XY%Q@XgvQ|inT+9?)$eDKLx&jOs?Aa z)Z^N_)D?snJd!K1`N!n_EFjq5+UA?4W+U3C=-85v@d~3W1ZvAaCYN)%zalw`L6Wq4cS9x#G^RS5tXvuh)M2sQTZ;GK;1kn9YblSc9 z>CX^8a9zqW;zu2fjjUsnC2^i=64u0uWy(KmL1w=yE~)RjPqK9Ft~}wrKl;he?$4^; ztlMv!Dyvki$Hz0*`?K+>Kup%L7g-64l1^=#d?hk>jiAPu(>>4JVouHOOn$+`E+UX= z}VgV|P@o%hgGmbHehxj(8t$i%BYX!KDj(>X994H~G_thb6*3n3yYhS$=F z=I^nD(XNzuIS+fY^}%;J7gkFz5F5D@7#HOAiuS9b%aeHbDxJ!|X9q72&#Zm~=xF|tcu4x#ZWW;Vmq`+a^?GQjDaWbwL>Gkkx7O6qr-V(pT`Z)*d)@XHm*ugyd<& zR&IS|_9jkcy}iRrbCle@a|##Hp4d6YqucnI>G#}gnMvy_w)m-)4(Kvp`SSz$Rao7Z zW>##`$cHBS8oRyS`)Pij_O{S->KZ@pn3Ly>1ar04)I6+dOZ<7Nlic;xS>^ThZyK$v zX)>Z3w5RsS>y_#4AALcWBEthDGesByY}YlvVFzCa1yUhJA>Jxmjsj2?AmhG&#Bv=k zI4lTc=p7YY!h*IAcY)XbM&-PnsIE)7Ae_8muExouq@uiQ+C#ez!`Jx4S_iaGq)bO45k% zO1J`ocP68)wC?~TBa=A-$gEyX3T*f_x4G`O&(nkgh0AAD00sycqn(`EWf%N5`-@Ocgo%Y?grn1^C)Bi=W%)#Gzw@3$1_hvpOW`-RhuXR8+ zU7U}HO|IiKnOuKh9&`ymr?Oa%LT2|Cd~0VuafxpdBS=SkpWOtA-4ct+im1%DrIGv89?$FS6Z6OG^m0`V@YkZ=U_Q2O zRoh3sDXmGWD^xc|)l<}Dy?qxI*LWeEHuiI|p2+*VryySjPe4O=(<0buNZ~~+D;hdh z=oD#<_qvDVU$k!@_6?1tYm8797Ta26@B0I<);-?+q9iT|MmU38Sz(-gF)m!m96MW2 zUbZKSWJ#YtjW)dDQgXXZr7&mZL4TR))SugZYZA z_iCLFIXQdA6AaI&SoJ@l zPZYPiaVlXr4S33@!ceo!ipB1(S7u&fe!#T2#L;xu(+wA5y?x-`8I*Q^4PRC6@K-3d z#Aa+zPjMQ4!=czv=g}9f z@$R^|*pWN@PU|WTGJAztMS}68h4Y;mJ0Gi5W>yn3UFXcWL_K$##Kff>jskTQdXrLN z5kepI96AJyd8xvo-@)#OdlQx~*u#FFESPu!KiqcCAEsY1FH75iAfX7U0=)n2(_COH z?T4<5-n3cy?4i{Asoj)<*xcu^9@?;2v^4G4zK=XWQ_m?@!!wgEX&@F&H1Wdm*1wg#L?h{Ns7} z(V$h17_@ccko0uqQ1o=P2}6pX276%PnN+$xr_S8-;F*j|eMlbhtKdq@PizTGX5$83 z9Np;sy-dcdoz>AJ>(ff#X6J*on%Yi0U;-Tb*eZQcu5i`7R6f0Cbp`lnN=q90(t`Pp zWrqsXIC91Rub^~k~mCCjbI7!|}W%=W9 z;)7mDiq|s)M@xkd6=B|dESA%>Tp}>-zSy+o&Pm3xRASN1*>V+)mS{TWbo%zQAkMq* zDT|l%WPKfBx=+fK-$T(68#3I9!*~Pcf8=pZem8CRb1o^-=m0(>7WqFyuZ)d4gvsc{ zH5Yq2lRwgmSWzu`H{Uc=@0+#}bc_pBn#e{=Iws2}=O3cY#nX5DOr;OkLGV6jTv~yq zB1Gp7;CKuQ+Q)&v9nHKnDZC4ORL6w-ug%;H0nxV!Tc<@_T)l;Ohao3wg_9xzij znCWrP2x@pum+-m%(wnX-xrHRYx+4gVx0X1!H>=`=7i-IE2D9zvSmpiofQx+CbrN2% zwMfC$soKB!z1yY_5?D9{={*Qd!HQm8jV{7?*edwct?P}=B-T7wj;r=vXY`ygp*rD zU5aP|I;hlJ)@knLS?%&%9%xH=FfImZ+nJo~v~ZxErdlPLSHQ(&q*C; z0Vl)>3i;x(x9>k=aV5=cvpi0k@$QB8pegCc#%xlzq;~sLNk^e$&{KK%AR>{%f76!x z+SvjHr9A?DXDUZ+1Y#gY4LM?U48|Etf9QUbIclPoUtQl`0KZNO|i9c~-HM~+>V5I}z40{)a)XD? z8yEF7syJu`nxK2E73ktFv%jqtEogTHlIn1DkbV*bM(rBSWYT|scX2DC|JV0;?P4p} zV8rjq2KE8* z$K?!V{#rw-lZ7^7AnEvCr0_4IeGsxoO;8cTwr-8#8*&!pPNN8qV`W>_Ie82)VW9cN z`FG}sfj6^?Hif^46LsG_#qyeRS+Q82U|Y_7j?951=OZRXW`1AXxM0j=VLQ~%72we4 zvKQI>a!=|H8uAV@)Kc8cxsUYQ9e>B*0fWO@O==630EZ#qT-zqf&yz>ur~>drxc1ce z{^u%DKgZDXkRhuNH)!>W`s}`oJ6Sm>btpI;0!PZo0v8_H5|kHlbf6;8HmuE9b9m%5 zWRRCw|H;YoKR!=oO97CUlHJd0h}wirh*R`@%$S%B}CbB>v^Ju+I%k zg~NqF5%;j<2Qc)o2p%i?^o?4n=}lKVaX*)?rR=3fBP6Ew)bUlyBXYfMDc_T{s(qb@ zlUT!!fJFxcvjY*OQw?4c7vc1qKf>I#)M^1|mbh%I0}=Z* zn9{qr=2VALR^Siaa5=t2_h2hml_Fud8>`xJ<0DQ_&O4^7a;?V>a7G!Pk-u;PT0%@u zAsQPd^i_koCrYqp@b3`A5)GHRf%bl2dvCsyc9kuZjj)IyRD;Cr=TSV+pt*J^T59fD{}R1bPTL3$UlBblyM zQ68;-Q*1Aa1xlLGC*QHH596Z_&+cb^dfgNnnVf{Lnpu@2)qeUt>;4ul{3cTt2vpi( zJ~ms0dj*y0G+c^1N3Eoj$QL2cjim_RMUCK@l%B25USWQ6SMBtC!|IF4Sh-VnWqcvi zyulHjbQ8jYNNGD8fc%9)i}9*jFV|Y2yidnsrDs^LnJ-;PUeSBDvU0AB*UovvS`v~k zv!2W;a@)Iz zPy`wQ=s;6RnK}@f;xE7-koGDzK^P8&V>?w&R?&B_QqGd}Rqu%qoagldW9V@qIwu_1 z%(-4^;t&=$3lt^mZFBq#6rrGmWc*Ov$bcK`Kf%@j_p4kqEF#mQ#vv=tmE`Ar3Mx1? zvF@xxSna7qu?lItFYd$s05-C1F|E=7W_9ExZ<#(?u5jC?W%-9)BCATcK-T4^fY&y? z_hQd>2T-Y-aIdwoFaQfx&OeTO>43Cr;^R={SHx`76DQxHL~LD?b)XvbW)TEy2B_ui zK}eY7z`INu>g?h*BRZ*p2`Ts$9K`jlF4+Eo)(qR#^Q0Dqm ztTu=grUv+E>YT;h)z!v#H>wB|wleZ$33lGtyO``cW}1K8W*g;0miV!io*Gw%1bGL5 ze7Sbm?P1YkP?Jp^y4Ly2r{gq&EF$-&#xgN3yDy=7irNCMy8%oS!wEe)jbC%QL4q;sq;llfJY3 z!86h-nzvDzPoPYEq#!MS^DJwOIzJQeZdrPfxTmnn^!8;Q?ak}ZaDMMcE)yIrg5H39 zb-m(@?R2~?TOuTj-DxE^6zIw1`Te;TaS&i+pJ$31HfC9G;Zg6zr25|&Uu!c2GCgz| zs0xBqQK&wCc<^@UW8MT4jUlvh^Oo7TS-ippAO#V!DlnJYSp*?xr=jA#xWdoJm5gRnjYwCrYE*NSIAv_odK^#rh_I8lL%CkJ*B_v3*6LHC>TBWm> z)2nzsvmArwb2M*!G+DF;ZT$W&<1yXfA3EH?^!obmL=d5=6}7A+&qd=9FSy*sC}?I! zy`cDHLP0QF(KcP3X=Y6o+KBs$Fbgs_Ege7ITbvbi0b~*v87tBL(Bg)14q1`2;77V~ z%{8Retx>OS2}|wmBvwA@nS^FyGq5LjwNlb>H=q9lEt0;^UaoiRK-_d1t$d@!y@x=} zlhY(b75xVGOk3e=c3O;wPoMohjTe~nU$XL)>bGQ=`b0Oir z{eDhXU3wV)X|yOq2O;W zz$`BKhETnU4tHmYqOhX>xBV2?HmgVtSZ&dZI)>TF_Izd$R25Ou2vvqSntRH%^dYqP zRl7gVI;>aY`P*w>{SgEacOo)9-az4gMY7d-NMIMh^wT~43H=*e=o^26WPd#_+6Jdq zATI@yB_T3_<0h`HS(R&iYK3{W-I(AV_W6zJGI8<#f@&Y$LXmnPO!?o0q%+W1ZtXAlEq!X{owb{7w>cm@YZ) zdHXXeF>?l~p1Q!~TAnVOfFToKf#TQpPmpJuxZShH zsA1cJPQh~pl9Z#!8eS*j`XXJkLi9~0B_KiCS^!hS`Arxn_0;$oOE@n|QgbKDWL-4( zSw1iQu<_Qf<-qi+iI>wn1wb8*OfU9UP9HoSV2iQbCM0l^SvFMY_ZR2x8oT%6fO9i2 z=9Kpb9l!}EjD^T>IGL8YC}WA4r|A^}ise2|w8SlhAMT80>T5RmT!!+H3i1_PpUK^Two;- z4LD;|Gn2#NU`zraooG&+Find0TM068SINH4Byq`8Y&NzO$_|gziqWbkS;*aa_TO^XY|QhjcM6E$Lp-e<18ruV1Y0?{^R+cX%e0P*N}v zb&-#qK1%@{eF%0=45Yq>ZT^-b9z2PzipZQ(AsnWW`>-n~wA~$I5#6YPd zy_5PCG=AA^^3nsNpDuy`Y@A8F76c3k`$qoU3Nn5q+EIOJ*3?Z)!jqQi>3MwHY)40o zFhBV$Yc(GFRj7eHseT#|Kq>drDAi#qyjdbK4V2xylM0H->f|ovd-C>e>JH36UI~<2 z>$Y?Y(8$B{tr}TyjIbp%0QH2>vR=(Zt0U@1kLbho5KYn32!qzw&+u2Z(lkiqi5vAlR0}=cq~(=bGmq65a|F&qD*- z>O7LNQhnWW$tD8QC#nAd-wbgnt-V!0&qy<$0<4NI8VZj%PlwPGAn^ez_(;!4{~y`; ztq#C?2~^%!qNGga)L8avUeg8XnZDAJO~=V2Kr>8HvvDTi13`ORPGMf?!2zUATc1Yz zDd+;yXSi*@r_@=r(RrF03d)zDyaVC_ULQ9EU^Hk(^6&M}XBjT(@NkGI5Vkn1sex)E zu#L4Ai6@bRFEIPv?cQD41+9_!Cedl6_xA_6#(lfhxuD@3+yudHD&4_OgxtZB!}`#n z*-Llh-LNmt;+Xz9xgWKkelZU1=0P{zT4S1M>pxxHlZga@_T?ps0`$5WfL_Ssgp<5{ zHuw}UmS*nb;pMAAwD0syFSq530}%tK%#Ek9kFnR_x$Y+~V*gdMYFMX$!$%~>0HoqJ zkP)UJ)1Sp4X8$rG!TNv^bqt)LlY+oG#QMB>UQuAc79oU zdFP$<{OSq2oU%~*$c}#w8m)lgFsydQ3VYD20K+gzZv?P0{2{4O4sRJs7<;hFl2eo(>ybAYz*56G>;UM>{b6i89Ph;hYcV3^N8xMHx3?OaugRvI5*->R; zcLQHhRp(Un4hkkxb3>W5(8Rq`0PA~kxU(4o8aWU$`3Bw?@rQq*(3G>Pq=yEsHy%Ji zgx8!CFByFoDoi{^Yyw|!dw+RssVj979_e3`uRtwt!O&(M8n;+hc^SL1WT^^iDosv1 zvcPUGZmUVm#6${qs0iLm%OAfUNMjk9F56FL!-Dal#V-fr>+2#=;SzW~=p7FmH@P^2 z<_v&rX40$OjmLM3jSI7S2!X-L2ic!(_nR*L;*bI~Gh_yWP{yTb?nmb3C}NS^DOEsN ztx!*&Yyt{XEmxp`Zyf#PfxRB|oJ*b#BDl4W+{a9zKhN(p@W*y{SsV$24BPDop}j2$ ztxQ@w97`!SHeogC+)C|@6J8GgwWXD&?kcus`}2#0U}H( zD4hmJCt4HN`u=i%xU%u`CUmsdqGGJqAv_+NULy=n&{*Ddu!&WTk=MVYTl!(4MNI+i zcaDGJL70q)XA%Nh)LL^0p(^^@srr|DRS7SA{o2*etoXhe9^W8#YJj=*p4g7Z0o}C= zllgJ^BOo8aal`OZ`T_o|^deQMt;KhWz~Bl$5P-s<9YKmqH!YIL#>`64%YAK6`HRfp z)fXTww(Qtn>88FsW}R_JdQzrA?PMxH?7Vx zmePOe1P_p(fZ*kU0c2Cn;k2d_jj-~|Hl|szhtNzdy#Pt-CG)jsZ_e93P$?qI(#K4g zSObVflIg+a+?rrq%nrh<~>efum7ygOb&y|NPx-%AinrrT;BWwyI7+( zL@A-KTx}XFuIAw+CMG|ieU9*;{k8PebaSi#IPPmcE$+O3EBo3>pg@y4d*37RP5o&{ zlzKnD%nK)PMr~%XvzmGJh9XC}-pG+r3z)7UmS`pn%VhZax0(J%z@D$FH|gStUz9yr zGj4`Iw7&(A1Zb5I9zo`&HRt&xW&SV;4Y^>4bYUQKM^?Gm2q$|IFMcEZ&sw-agU|gv z+J`}96Rl2Q5`c-Jwg#kvBUcN6KcOBw=wv#O*YXi{;M(QG)%yS;*(60KL@!=&B&GUD z_VocXfDDuQlWGt6AURsqe!BQvt>$C0baZ(3EvMehDF#UKFA9L>ncmD1hHx{PfFWnY zivbQAhp&D~lV&McbcrLU&<+0MA6cVeIAJkxuV={iiP0aw`T8;UXxRXDF#~{4Aqy-9 z2Fu!czZYB8YJ7xt;G@IF1|7@mpbc7T3qa||`hmvE$H&EHQ(Wkc>e< zKr}=byuF8TwiEk1d~kF*$O^2-g6>MlbgWiFT4ar*^RO`+Zzd_s?O2(|(X!kLxL%7+ z^!{T@0)%Ior%V~u{g~yy&`%nDYM_U-YV+aL?OG)#ydG*w4Z7F$stPeQgX%XL9j+Ae z&e*qr(n0d{R9dOg{g=$0g+DKgSNFX;5VwlfeFYC{_Cf^+`i*sE0wK=^XL9pUGc^tJ4GSWABL+{?u z@Pnx6{u7o$AKi4Q7}u83aCp+lsm`vViF8!6?42pG=OWcI8Ue{Ve6t$DVYD_S6P*4?Ii+INl*iW5<$(``fJ@;GKL7X2PZ81BAvFPW;8G0Z~$+3y*I>4H|+fpKc7smOn zVOE-dVxI`n(I2H%?%2ip5n`0&*K_*EDk@~<5AKp3B&ipqu~u~?%fg-fJaT9WTru<0 z8lnHI1gh43TB$C!)RTn_*;(M0<*%gs5=Q~P5R1QR0?{W0ia?InU;HF1cYFD8I9P#n z9vrer)*VIUSVCS=nF;YI9%gf`Zv(t3LgJfZP!TvsonAyr>Fu97e-LPWPH^JEv(&GL zM*t@uH?y~U6MAfLkn7N;4EUE`Y3(n2*YRi_lpNwVIhJ4b4S$w5{!z92-keF+jFywH>11{7KVP=wh}& zLKG0a8E_!q3KD)b+wB0Cpd6TQMcB5reA;tovZNjv7Jb2rAGd)qPHp~2P^PlqQ#3;8 z&+Y_AxiY99w5;pkd=}XJS1v&T5CYxh!N&psCFb^9p{CQ@;8{5u3uMN^0A}wlsBbv% z$wIzLf}j}msra~OKa9lut#r-GEN+{*jrN8)ItkrMEnD5CC3~`^W~ORzI7^z%3NPR2 z*MRuwHT3r-a7@(=YU)IB8n;lHSlNMS{t+tIhQfAolmhzr!=-~_lB}!I#-KikuGG2Z zVyRz z-i`au;YT$JR0G>~t>=~FI{3?R5gi}q8NSNecTAV0c+Ks|9ju;6lz!d!SN#p!?Q8k> zaBC_+YXi<(f}kEi+BY--N*HC;mo*M^ER#}S2WPW#{?>jsZ2j_KS66=mK*y}={4EPD zYJ?L>CTnQnhG|PUIjUuarzY5Px=hgj1hF_wm_S8Eq18+Ykbd!{3@-pR z!Wvyz5_WQHv8hhjh#bGpNQ z1iv@yJ_16}&zv=I6LCOQ9`~r=UhN&OPzxRoh=ZDxLh&*3uJmF7yo<{EY~2x4QnT|3 zoOl;L@Y4cmQF5{IZlQ;oxju4t0*M@~u;py-1%-Ry+^LOeAPE>05kC`$Ef&l~sco2p z20C<>u>QRoKUV-YDge}Ri{9@Ifz`?J83R>C^nN1MiGWPyHrZ+g>~4WP#A*{~_WNs}q_#WREg^bqI88oX za*#3I<0B7qPYWY%?(+K?R`AfnTEcNzk{qk$m~T7IH4k8FTF5c;tLjvA-8wkICew;o z7-*10wgJHx`Q5ncpwD;zpBeIgAU2oPKvEo=?DMb25GuJFDG$q^!K-{gNga^5qKZLYvsQtb136*Ru5mUViv^j>=)d{{^9Atb5?Ct#i+#Gq>f?J=Zw<@4+@Uu{ zyoyNOPR63<^OFBXF$B#Iu{#{US?J!!o(l4U);m60l(4V&Va~lVecgtt?5T>e~C;<{Zz7c!T(4)Y?pUjWc3QLef z&hx3c;&Eob=LVimEGKTn|-VTpujABtU-zA}v}9tPU`* z)mwXaiCb@T!Fvmd)i8=OeQ$KB#=MXhQ)aEJDdpvBMtoui57O#u1$u$izzbALPLx^Q zEpgnw#|22Pb*B3Pt1#h*BD)lxX5;LFHEvld-DewAmBCW2kF~C}dot#0+Lo@uD*7cC zHGPkng9-CEtpitO(u#02;frOql{!|iYVzf9Z(lmzy!z6_ZvA`5MHdPgFvGQWL%`$N z1Kf)5vL_#^`^OnjM#=+gqG>4TdQ8Fl2B}YTVI5so>4Z3W2}uK>kWwq(EE)QJSh$9Y zNJ)S|4yd_irXoe!Cz`mUZT;P5l1$usZhE@I^FNxqphB?|0)Vi@5kO@w-YYuMu1o&x z09DdY_~8VSIGEh|0zXjnz%TOG@lpmT07in9PmGqGw;V}^b(1q-^-YzAnVC55c>0;+kX*5gBF#8}QY;4%J2zCCFK~Ip?`zV&xEzKD2{NC7n)rWu zXzK5}X{3T4;&0&&w+<=1HIK;!_hK+mLU63wZ+-#R?eefm31~?@bc{$4ALfc>>IRt= z3YcXA!C_z~Nmgd6+sq^T0xxT5##P)yui|4PE2#sL}uaibZI2w zRFN;mk|_`tbMUl7S<)GPZbd&E-FTR-0WrHF(RY*kXBb2KFP7t}*M6WQTlNhzQQ&;Sb@KDpXR*694fS_G zl@N$m)=Z5HA>3(HEzT!dff7}^8qn${u7AgwUsqj%3RLw0a=a#Ye{kF7FbsLR8iQ9m z(gL$0+pdca!#AtMBtsrVrIGBRB11=^+*&$afi1}@Le~n>*jXDoJ6#QZP&8t3WQh&F z(E_SH*2;KBK@va@08jna(UJ-}9AzSZZNkEXiKDV78#~cF=^)1^0zB-a5?|+}1!!g3*F) z%d@t`(Krz17UHK%KxNf}u)2~ufHu;?s{ripxpEIH54{E`DL4G&k7d;tmWzqy6gzdP zR7xKp^?^`5;h7$&00FhzK*y{B;@*}dbU~EovkiXluzFxeKl={;I&ifB4dnp^v(2DJ z5VbeFTs}pbTV`FQF$;1(GSQuI+ueoofbI_f4HdZa3Vx}e;k@Q;}Sdx1x zAN?ipkP2ZjOPtb~0({>!z*J`D37@$sZVO`;roI?eb^x&z5=k|Z)-cj3k+j)(_QO4C z6IAvC8o*m)2SdH$FE&9)W}{{fqcgPRwhee+2}~>gBo1f?0FXAM>898|{ApqW16ru>UuGpijve3?KDI87V-aZ&G zkMX?t6d15q3Q85~C5|=tLdDLar}yXcx!-ZC7B_8fffxW>#&GAV|6c*gEkP4W;QoUE zAHBG~P)_Q}!s0dCU$-^5f8IQhYd#z&dV?4LN-x?;0y#u%X51<~wIS>J^4G_wNUeDMa{7*zyV zj8HO6Tqr%nZyzWlB00Jak-VvtU^%rf@+Mr>9S&7Ucuz*m@+`c+XPp~u3?2oX&u&@{ z1y{SI9PW+9*08k3{!BgxXtTI{rL_*ZUyMJ@JtCJ?KC7fk*$!Axt9|DU+bDjkkJEqf z$o@!?=A3E^pE|fW2t2qHpN1j5^P`guh_-t5dS1N;EJ*0h(X!WG-{bg6{ep5o+nz4A zicD#M>vyg#^YshLpzFR;?RB+G?7rMedjK^QokG4-FT#c?p8&2&{==zPVe++8NGy!2-GUiSnFtfqjfpXTZfM0j8Wa z%7z;C&5<}IJ&tz4Y8+Q&RoSf>V>7@>gvZ;A9RHaLRK!7j<}Q=$)R{y~;}>jn+iDbe z_^~H;=DqSPo8m#2e?m*gj!Dw)u;x|IRiYYrxT+l@64>4s#Iq6>S*&|>rzNrzoA>&) z+?X0zW^IRFmhax#Sq`jQ_ScP${ja!m|M`MD3|fRg0lBMlp~X8x8FYePE1G+cKxHbB zl$!l~hPR84!Bekk_rwoIzFYrP6`m0+&08AP`jk@=aV3&JT0xKzOdR>azjgevPApep zG+zAf&`|oUHD1=)TK8pkqsAxjd{9UEz4g%Q66*wdDJk{fH6QjTp=zQ2+d=+SO7qwl zGda-4;}xcLK#Q>#Vv<-dJ4E1K>p;924qLoR{b}O3#0$Osl)jE zNsJzY^pF~0S?$EL9zucqUYV}v8vfH_yW&)LD7@YYDmAGo~4s3+tyKVVFPbVebpDx@lDfDWljZW(#r1g6)a)G zsZ07K?&1u-ss%i&ul5(5NL|B@P)MnsOZD476SdzR3RGW6E|%9HJGXTFq{lYic<9Vw zVQ7cK3bS=0Cwd65F)03mG-hq+q~_q68c%Dj12sW~*)rXbX%j(3pg{+G(G2f=?F|$c z=Fa~_cgie;wVI13tcR)^uEl{lbLw~abtPhAB~1x0Efq_76eBavH6|RUJ>`k(+t0X_ zR3#1?Exh+fv+_0c)V-H#P=;TV(Fw zC|K&(m>G+fb$;>!iy3NE+u4th%n1|du5o6zwLNapsz5l-js5%ue8&`Wziq8_;Agf$ z@2)@jsyLl<1*$sd#x+2j;^AuI+D}x3?AtiSZ|CV_gR8e&zDd%aBIT${kB|HTjnVtU zQIk^=DHS_h-^}h2(igOc-N%_vDw;8PJG6M&fTRk%G?jHVWZifm&2N;?e%WZEf_joW z@vx(n?g|SPMju>oHSPkYLUUh4IxMiREs<}GJHKg2*H<1Xb+8^E7rTIY)AkSvuJ#KU z%gDXlQfj{UW2#1qyU6b$(p(=0FS`mY^wo&EiC2dD``|BNgn$}um%MhZK(SM<`bGGH z3k7G&#tC=M2?~UYc_9IhmclHqQsr8&6*-M1o0r3jsYEso{T7Vb9Q$;Plb zzq|5Jk)~9uhgbLr6MhZo(Az})&eOnldVLo&NiW=e2g$=L5m_egbJQL#e&06tx3a`+ z2CAn0DcJ@FVp0#uWeHsmgO`xugOqV}r3O341$X=j>?oT`Poaj^J2v_+3s54Gnb-Ekg_ptPBjTjE%HG41>t|lYl7 Date: Wed, 10 Dec 2025 09:47:38 +0100 Subject: [PATCH 11/19] update language and version selectors --- docs/overrides/assets/css/custom.css | 171 ++++++++++++++++++++++----- docs/overrides/partials/header.html | 3 - 2 files changed, 139 insertions(+), 35 deletions(-) diff --git a/docs/overrides/assets/css/custom.css b/docs/overrides/assets/css/custom.css index 341aa77833..04f2d6d8b6 100644 --- a/docs/overrides/assets/css/custom.css +++ b/docs/overrides/assets/css/custom.css @@ -79,69 +79,86 @@ h1, h2, h3, h4, h5, h6 { font-weight: 700 !important; } -/* Wrapper in header */ +/* Language switch: match version switch styling */ .md-header__langswitch { position: relative; display: inline-flex; align-items: center; - gap: 0.25rem; - padding: 4px 10px; + gap: 0.4rem; + padding: 6px 12px; border-radius: 999px; - border: 1px solid rgba(255, 255, 255, 0.55); - font-size: 0.78rem; - color: rgba(255, 255, 255, 0.85); + 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; } -/* Label + caret */ +.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__langcaret { - font-size: 0.7rem; - opacity: 0.8; -} -/* Dropdown menu */ .md-header__langmenu { position: absolute; - top: 100%; + top: calc(100% + 14px); right: 0; - margin-top: 0.4rem; - min-width: 140px; - padding: 0.35rem 0; - border-radius: 0.4rem; - background: #201547; /* your header purple */ - box-shadow: 0 6px 18px rgba(0, 0, 0, 0.35); + 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; - z-index: 20; + gap: 2px; + z-index: 40; + } -/* Show on hover/focus */ .md-header__langswitch:hover .md-header__langmenu, .md-header__langswitch:focus-within .md-header__langmenu { display: flex; } -/* Items */ .md-header__langitem { - padding: 0.4rem 0.9rem; - font-size: 0.78rem; + padding: 0.4rem 0.7rem; text-decoration: none; - color: rgba(255, 255, 255, 0.85); - white-space: nowrap; + color: var(--md-primary-fg-color); + border-radius: 8px; + display: flex; + justify-content: space-between; + font-weight: 100; } -.md-header__langitem:hover { - background: rgba(255, 255, 255, 0.12); - color: #ffffff; +.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 { - font-weight: 600; - background: rgba(255, 255, 255, 0.18); + background: rgba(99, 9, 255, 0.12); + color: var(--md-primary-fg-color); } /* Mobile: optionally hide or shrink */ @@ -149,4 +166,94 @@ h1, h2, h3, h4, h5, h6 { .md-header__langswitch { display: none; /* or keep and it will still work */ } -} \ No newline at end of file +} + +/* 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; +} diff --git a/docs/overrides/partials/header.html b/docs/overrides/partials/header.html index 84fcc08d3b..e5a9a46e28 100644 --- a/docs/overrides/partials/header.html +++ b/docs/overrides/partials/header.html @@ -12,9 +12,6 @@