{"id":19740346,"url":"https://github.com/distributive-network/use-dcp-worker","last_synced_at":"2025-04-30T05:32:50.266Z","repository":{"id":92682395,"uuid":"601327975","full_name":"Distributive-Network/use-dcp-worker","owner":"Distributive-Network","description":"A React hook to use a DCP Worker.","archived":false,"fork":false,"pushed_at":"2024-08-28T20:35:06.000Z","size":4730,"stargazers_count":1,"open_issues_count":1,"forks_count":3,"subscribers_count":3,"default_branch":"main","last_synced_at":"2024-11-08T18:17:43.424Z","etag":null,"topics":["dcp","dcp-worker","react","react-hook"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/use-dcp-worker","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Distributive-Network.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-02-13T20:49:08.000Z","updated_at":"2024-08-28T20:35:09.000Z","dependencies_parsed_at":"2024-08-28T22:07:04.696Z","dependency_job_id":null,"html_url":"https://github.com/Distributive-Network/use-dcp-worker","commit_stats":{"total_commits":25,"total_committers":5,"mean_commits":5.0,"dds":"0.31999999999999995","last_synced_commit":"7efb64f0025d94506730923efd0d48c78b9e876f"},"previous_names":["distributive-network/usedcpworker"],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Distributive-Network%2Fuse-dcp-worker","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Distributive-Network%2Fuse-dcp-worker/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Distributive-Network%2Fuse-dcp-worker/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Distributive-Network%2Fuse-dcp-worker/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Distributive-Network","download_url":"https://codeload.github.com/Distributive-Network/use-dcp-worker/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224199294,"owners_count":17272258,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dcp","dcp-worker","react","react-hook"],"created_at":"2024-11-12T01:20:40.395Z","updated_at":"2024-11-12T01:20:40.901Z","avatar_url":"https://github.com/Distributive-Network.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# use-dcp-worker\n\n![npm version][npm-version-badge]\n[![standard-readme compliant][standard-readme-badge]][standard-readme-repo]\n\nA React hook to use a DCP Worker.\n\nThe Distributive Compute Protocol (DCP), is a fast, secure, and powerful parallel computing platform\nbuilt on web technology. DCP breaks large compute workloads into small slices, computes them in\nparallel on different devices, and returns the results to the client.\n\nA DCP Worker performs compute tasks on the network in exchange for DCCs (Distributive Compute\nCredits). This package allows anyone to setup a DCP Worker within their own React projects.\n\nFind out more at \u003chttps://docs.dcp.dev/\u003e.\n\n## Table of Contents\n\n\u003c!--toc:start--\u003e\n\n- [Install](#install)\n- [Usage](#usage)\n- [API](#api)\n- [Maintainers](#maintainers)\n- [Contributing](#contributing)\n- [License](#license)\n\n\u003c!--toc:end--\u003e\n\n## Install\n\n```sh\nnpm add use-dcp-worker\n```\n\n## Usage\n\nLoad `https://scheduler.distributed.computer/dcp-client/dcp-client.js` before the React starts\nhydrating the web app. e.g.,\n\n```html\n\u003cscript src=\"https://scheduler.distributed.computer/dcp-client/dcp-client.js\"\u003e\u003c/script\u003e\n```\n\nThen wrap the part of the app that well use `useDCPWorker` with a `WorkerProvider` component.\n\n```javascript\nimport ReactDOM from 'react-dom/client';\nimport { WorkerProvider } from 'use-dcp-worker';\n\nReactDOM.createRoot(document.getElementById('root')).render(\n  \u003cWorkerProvider\u003e\n    \u003cApp /\u003e\n  \u003c/WorkerProvider\u003e,\n);\n```\n\nFinally, call the hook in the components and start hooking the worker's events into you app.\n\n```javascript\nimport { useDCPWorker } from 'use-dcp-worker';\n\nexport function App() {\n  const { worker, workerState, workerStatistics } = useDCPWorker({\n    workerOptions: {\n      paymentAddress: address,\n    },\n  });\n\n  // ...\n}\n```\n\n## API\n\n### How it works\n\nThe Worker requires an options object for configuration. This hook passes in `dcpConfig.worker`\ndefined in the global scope, with options passed to the hook and those saved in local storage\noverwritten on top, straight to the constructor. The hook was written to handle multiple insances of\nthe hook defined in a React application, ensuring a single instance of a Worker is used/instanciated\n(including between component updates) - achieved using React state management. Once a Worker is\ninstantiated, it is in a global context state that all instances of the hook will reference. The\nstate and statistics the hook provides, `workerState` and `workerStatistics`, is also handled in a\nglobal React state context. Custom handling of state and statistics can always be achieved using the\n`worker` returned with an understanding of the Worker API and Worker events.\n\n### Editing Worker Options\n\nAs part of the [Worker API](https://docs.dcp.dev/specs/worker-api.html), the `worker` has a\n`workerOptions` property that describe the current active options configuring the worker, and\nmutating this object will modify worker options.\n\n**Note:** To achieve desired React component updates regarding changes to certain options that may\nbe featured in a UI, such as _paymentAddress_ - `worker.workerOptions` is a Proxy object with custom\nhandling to handle component updates and writes to local storage.\n\n### Parameters\n\nThe hook accepts a single object with the following parameters:\n\n- `identity?: Keystore`: A Keystore object (`dcp.wallet.Keystore`) which is passed to the Worker\n  constructor and set as the Worker's identity when communicating over the network. If a Keystore is\n  not provided, an arbitrary one will be generated.\n- `useLocalStorage?: boolean = true`: A flag to toggle the use of the browser's local storage. The\n  `workerOptions` object is the entity to be saved to local storage and is updated accordingly when\n  calling `setWorkerOptions`.\n- `workerOptions: object`: The contents of this object will override the default values coming from\n  the worker configuration coming from `dcpConfig`(provided by `dcp-client`, worker node sourced\n  from `dcp-worker`). The only required property of `workerOptions` is `paymentAddress`. The\n  following properties describe the worker options object configuring the DCP Worker:\n\n  - `paymentAddress: string | Address | Keystore`: A string, Address (`dcp.wallet.Address`) or\n    Keystore (`dcp.wallet.Keystore`) identifying a DCP Bank Account to deposit earned DCCs.\n\n    **Note:** Passing an invalid `paymentAddress` will be logged to the console but will not cause\n    the hook to throw an error. The Worker will not be constructed (`worker === undefined`) and the\n    hook will retry construction/initialization on each re-render.\n\n  - `trustComputeGroupOrigins?: boolean = true`: Trust the scheduler to tell client about allowed\n    origins for jobs in a compute group.\n  - `allowOrigins?: object`: Allow list permitting network access beyond DCP messages to services.\n    This list is used only in setting up the DCP Worker. After the worker is constructed/loaded, the\n    `originManager` is responsible for managing origins (see Managing Origins). It's empty by\n    default.\n    - `any: []`: A list of origins that are allowed to communicate with, for all purposes.\n    - `fetchWorkFunctions: []`: A list of origins that are allowed to fetch the work function from.\n    - `fetchArguments: []`: A list of origins that are allowed to fetch work function arguments\n      from.\n    - `fetchData: []`: A list of origins that are allowed to fetch input set data from.\n    - `sendResults: []`: A list of origins that are allowed to send results to.\n  - `minimumWage?: object`: The minimum payout per slice the worker will accept from a job. Will\n    default with the following structure:\n    - `CPU: number = 0`\n    - `GPU: number = 0`\n    - `in: number = 0`\n    - `out: number = 0`\n  - `computeGroups?: []`: List of compute groups the worker is in and the authorization to join\n    them. A compute group is to be described as\n    `{ joinKey: 'exampleGroup', joinSecret: 'password' }`.\n  - `leavePublicGroup?: boolean = false`: A flag that controls if the worker should omit fetching\n    work from the public compute group. If not defined, this flag is evaluated to _false_.\n  - `jobAddresses?: []`: If populated, worker will only fetch slices from jobs corresponding to the\n    job addresses in this list.\n  - `maxWorkingSandboxes?: number | undefined`: Maximum number of sandboxes allowed to do work. If\n    `undefined`, then the Supervisor will determine a safe limit, based off of machine hardware.\n  - `shouldStopWorkerImmediately?: boolean`: If true, when the worker is called to stop, it will\n    terminate all working sandboxes without waiting for them to finish. If false, the worker will\n    wait for all sandboxes to finish computing before terminating.\n\nNote: Learn more about `Keystore` and `Address` in our [Wallet API documentation][wallet-docs].\n\n### Returns\n\nThis hook returns an object with the following properties:\n\n- `worker: Worker`: Refer to the [Worker API documentation][worker-docs].\n- `workerState: object`: Stores status of worker states. Stored globally and preseved between\n  component updates.\n  - `isLoaded: boolean`: True once the worker is properly initialized.\n  - `working: boolean`: True if the worker is doing work, false otherwise.\n  - `willWork: boolean`: True when the worker is starting to do work, false when the worker is\n    stopping.\n  - `fetching: boolean`: True when the worker is fetching for slices to compute, false otherwise.\n  - `submitting: boolean`: True when the worker is submitting results to the scheduler, false\n    otherwise.\n  - `error: Error | boolean`: Set when a worker error has occured, false otherwise.\n  - `workingSandboxes: number`: Number of sandboxes currently doing work.\n- `workerStatistics: object`: Stores a global count of worker statistics for a browser session.\n  Stored globally and preseved between component updates.\n  - `slices: number`: Number of slices completed.\n  - `credits: BigNumber`: Total credits earned.\n  - `computeTime: number`: Total time computed (ms).\n\nNote: Learn more about `Sandbox` in our [Sandbox API][sandbox-docs] \u0026 [Compute API][compute-docs]\ndocs.\n\n### Managing Origins\n\nThe `worker` returned has the `originManager` property, which is an instance of the\n`OriginAccessManager` class responsible for managing the worker's allowed origins. `originManager`\nis `undefined` until the worker is properly initialized.\n\nUpon construction of the worker, the worker options `allowOrigins` property is read into the\nconstruction of the `OriginAccessManager`. Properties of `allowOrigins` translate to a _purpose_ on\nthe OAM, with their values, being a list of origins, are added under that _purpose_ (and `null`\n_key_). The `any` property translates to a `null` _purpose_, which matches any _purpose_. For\nexample, `isAllowed` will return `true` for origins stored under a `null` _purpose_, regardless the\n_purpose_ and _key_ combination queried.\n\n### `OriginAccessManager` Methods\n\n- `add(origin, purpose, key):` Adds (allows) the _origin_ under the _purpose_ and _key_. A `null`\n  _purpose_ and/or _key_ will match any _purpose_ and/or _key_, respectively.\n- `remove(origin, purpose, key):` Removes (un-allows) the _origin_ under the _purpose_ and _key_. A\n  `null` purpose and/or key will **not** match any _purpose_ and/or _key_.\n- `remove_byKey(key):` Removes all origins for all purposes under the _key_. A `null` _key_ is not\n  accepted, must be a string.\n- `getAllowList(purpose, key):` returns a list of origins under the _purpose_ and _key_. A `null`\n  _purpose_ is not accepted, must be a string. Previously added origins under `null` _purpose_\n  and/or _key_ will match any _purpose_ and/or _key_, respectively.\n- `isAllowed(origin, purpose, key):` returns `true` if _origin_ is allowed under the _purpose_ and\n  _key_. A `null` _purpose_ is not accepted, must be a string. Previously added origins under `null`\n  _purpose_ and/or _key_ will match any _purpose_ and/or _key_, respectively.\n\n## Maintainers\n\n[@bryan-hoang](https://github.com/bryan-hoang)\n\n## Contributing\n\nPRs accepted.\n\nSmall note: If editing the README, please conform to the [standard-readme][standard-readme-repo]\nspecification.\n\n## License\n\nMIT © 2024 Distributive Corp.\n\n[npm-version-badge]: https://img.shields.io/npm/v/use-dcp-worker\n[standard-readme-badge]:\n  https://img.shields.io/badge/standard--readme-OK-green.svg?style=flat-square\n[standard-readme-repo]: https://github.com/RichardLitt/standard-readme\n[wallet-docs]: https://docs.dcp.dev/specs/wallet-api.html\n[worker-docs]: https://docs.dcp.dev/specs/worker-api.html\n[sandbox-docs]: https://docs.dcp.dev/specs/worker-api.html#sandbox-api\n[compute-docs]: https://docs.dcp.dev/specs/compute-api.html#definitions\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdistributive-network%2Fuse-dcp-worker","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdistributive-network%2Fuse-dcp-worker","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdistributive-network%2Fuse-dcp-worker/lists"}