From a8cd500b1452825ca31bbde03c328b0b66a733b0 Mon Sep 17 00:00:00 2001 From: Dzeranov Date: Thu, 25 Jul 2024 11:14:02 +0300 Subject: [PATCH 01/89] `hash` is replaced with `txHash` in `TransactionPaginationDto` (#2313) --- .../dashboard/server/src/modules/details/dto/transaction.dto.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/apps/dashboard/server/src/modules/details/dto/transaction.dto.ts b/packages/apps/dashboard/server/src/modules/details/dto/transaction.dto.ts index 25a583cb27..38aebca3c3 100644 --- a/packages/apps/dashboard/server/src/modules/details/dto/transaction.dto.ts +++ b/packages/apps/dashboard/server/src/modules/details/dto/transaction.dto.ts @@ -15,7 +15,7 @@ export class TransactionPaginationDto { }) @IsString() @Expose() - public hash: string; + public txHash: string; @ApiProperty({ example: '0xad1F7e45D83624A0c628F1B03477c6E129EddB78' }) @IsString() From 00f7d909e7b66a3463833b31947ce2cd6beb5dc6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 26 Jul 2024 09:25:03 +0200 Subject: [PATCH 02/89] Bump web-vitals from 3.5.2 to 4.2.2 (#2308) Bumps [web-vitals](https://github.com/GoogleChrome/web-vitals) from 3.5.2 to 4.2.2. - [Changelog](https://github.com/GoogleChrome/web-vitals/blob/main/CHANGELOG.md) - [Commits](https://github.com/GoogleChrome/web-vitals/compare/v3.5.2...v4.2.2) --- updated-dependencies: - dependency-name: web-vitals dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- packages/apps/dashboard/ui/package.json | 2 +- .../apps/job-launcher/client/package.json | 2 +- yarn.lock | 39 +++++++++++++++---- 3 files changed, 34 insertions(+), 9 deletions(-) diff --git a/packages/apps/dashboard/ui/package.json b/packages/apps/dashboard/ui/package.json index 8027914988..ca0149856b 100644 --- a/packages/apps/dashboard/ui/package.json +++ b/packages/apps/dashboard/ui/package.json @@ -38,7 +38,7 @@ "swr": "^2.2.4", "viem": "2.x", "wagmi": "^2.8.5", - "web-vitals": "^3.5.2" + "web-vitals": "^4.2.2" }, "devDependencies": { "@testing-library/jest-dom": "^6.4.2", diff --git a/packages/apps/job-launcher/client/package.json b/packages/apps/job-launcher/client/package.json index f56576cea1..40d68de861 100644 --- a/packages/apps/job-launcher/client/package.json +++ b/packages/apps/job-launcher/client/package.json @@ -30,7 +30,7 @@ "typescript": "^4.9.3", "viem": "2.x", "wagmi": "^2.8.5", - "web-vitals": "^3.5.2", + "web-vitals": "^4.2.2", "xml2js": "^0.6.2", "yup": "^1.2.0" }, diff --git a/yarn.lock b/yarn.lock index 51bf04d9eb..0fe2244bf3 100644 --- a/yarn.lock +++ b/yarn.lock @@ -23393,7 +23393,16 @@ string-natural-compare@^3.0.1: resolved "https://registry.yarnpkg.com/string-natural-compare/-/string-natural-compare-3.0.1.tgz#7a42d58474454963759e8e8b7ae63d71c1e7fdf4" integrity sha512-n3sPwynL1nwKi3WJ6AIsClwBMa0zTi54fn2oLU6ndfTSIO05xaznjSf15PcBZU6FNWbmN5Q6cxT4V5hGvB4taw== -"string-width-cjs@npm:string-width@^4.2.0", "string-width@^1.0.2 || 2 || 3 || 4", string-width@^4.0.0, string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.2, string-width@^4.2.3: +"string-width-cjs@npm:string-width@^4.2.0": + version "4.2.3" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" + integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== + dependencies: + emoji-regex "^8.0.0" + is-fullwidth-code-point "^3.0.0" + strip-ansi "^6.0.1" + +"string-width@^1.0.2 || 2 || 3 || 4", string-width@^4.0.0, string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.2, string-width@^4.2.3: version "4.2.3" resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== @@ -23501,7 +23510,7 @@ string_decoder@~1.1.1: dependencies: safe-buffer "~5.1.0" -"strip-ansi-cjs@npm:strip-ansi@^6.0.1", strip-ansi@^6.0.0, strip-ansi@^6.0.1: +"strip-ansi-cjs@npm:strip-ansi@^6.0.1": version "6.0.1" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== @@ -23522,6 +23531,13 @@ strip-ansi@^5.2.0: dependencies: ansi-regex "^4.1.0" +strip-ansi@^6.0.0, strip-ansi@^6.0.1: + version "6.0.1" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" + integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== + dependencies: + ansi-regex "^5.0.1" + strip-ansi@^7.0.1, strip-ansi@^7.1.0: version "7.1.0" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-7.1.0.tgz#d5b6568ca689d8561370b0707685d22434faff45" @@ -25341,10 +25357,10 @@ web-streams-polyfill@^3.1.1, web-streams-polyfill@^3.2.1: resolved "https://registry.yarnpkg.com/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz#2073b91a2fdb1fbfbd401e7de0ac9f8214cecb4b" integrity sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw== -web-vitals@^3.5.2: - version "3.5.2" - resolved "https://registry.yarnpkg.com/web-vitals/-/web-vitals-3.5.2.tgz#5bb58461bbc173c3f00c2ddff8bfe6e680999ca9" - integrity sha512-c0rhqNcHXRkY/ogGDJQxZ9Im9D19hDihbzSQJrsioex+KnFgmMzBiy57Z1EjkhX/+OjyBpclDCzz2ITtjokFmg== +web-vitals@^4.2.2: + version "4.2.2" + resolved "https://registry.yarnpkg.com/web-vitals/-/web-vitals-4.2.2.tgz#e883245180b95e175eb75a5ca8903b1a11597d7a" + integrity sha512-nYfoOqb4EmElljyXU2qdeE76KsvoHdftQKY4DzA9Aw8DervCg2bG634pHLrJ/d6+B4mE3nWTSJv8Mo7B2mbZkw== web3-core@^4.3.0, web3-core@^4.4.0, web3-core@^4.5.0: version "4.5.0" @@ -25967,7 +25983,7 @@ workerpool@^6.5.1: resolved "https://registry.yarnpkg.com/workerpool/-/workerpool-6.5.1.tgz#060f73b39d0caf97c6db64da004cd01b4c099544" integrity sha512-Fs4dNYcsdpYSAfVxhnl1L5zTksjvOJxtC5hzMNl+1t9B8hTJTdKDyZ5ju7ztgPy+ft9tBFXoOlDNiOT9WUXZlA== -"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0", wrap-ansi@^7.0.0: +"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0": version "7.0.0" resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== @@ -25985,6 +26001,15 @@ wrap-ansi@^6.0.1, wrap-ansi@^6.2.0: string-width "^4.1.0" strip-ansi "^6.0.0" +wrap-ansi@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" + integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== + dependencies: + ansi-styles "^4.0.0" + string-width "^4.1.0" + strip-ansi "^6.0.0" + wrap-ansi@^8.0.1, wrap-ansi@^8.1.0: version "8.1.0" resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-8.1.0.tgz#56dc22368ee570face1b49819975d9b9a5ead214" From 8843cf240c4b4f0291cfd3b5d58240f88ffc1bc3 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 26 Jul 2024 09:26:00 +0200 Subject: [PATCH 03/89] Bump @stripe/stripe-js from 3.5.0 to 4.1.0 (#2305) Bumps [@stripe/stripe-js](https://github.com/stripe/stripe-js) from 3.5.0 to 4.1.0. - [Release notes](https://github.com/stripe/stripe-js/releases) - [Commits](https://github.com/stripe/stripe-js/compare/v3.5.0...v4.1.0) --- updated-dependencies: - dependency-name: "@stripe/stripe-js" dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- packages/apps/job-launcher/client/package.json | 2 +- yarn.lock | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/apps/job-launcher/client/package.json b/packages/apps/job-launcher/client/package.json index 40d68de861..b2429da35b 100644 --- a/packages/apps/job-launcher/client/package.json +++ b/packages/apps/job-launcher/client/package.json @@ -12,7 +12,7 @@ "@mui/x-date-pickers": "^7.5.0", "@reduxjs/toolkit": "^1.9.5", "@stripe/react-stripe-js": "^2.4.0", - "@stripe/stripe-js": "^3.4.1", + "@stripe/stripe-js": "^4.1.0", "@tanstack/query-sync-storage-persister": "^5.38.0", "@tanstack/react-query": "^5.49.2", "@tanstack/react-query-persist-client": "^5.35.4", diff --git a/yarn.lock b/yarn.lock index 0fe2244bf3..c2570ed19a 100644 --- a/yarn.lock +++ b/yarn.lock @@ -6264,10 +6264,10 @@ dependencies: prop-types "^15.7.2" -"@stripe/stripe-js@^3.4.1": - version "3.5.0" - resolved "https://registry.yarnpkg.com/@stripe/stripe-js/-/stripe-js-3.5.0.tgz#7fff3d9d931e972c24dcc8ee25f7481a58879b2b" - integrity sha512-pKS3wZnJoL1iTyGBXAvCwduNNeghJHY6QSRSNNvpYnrrQrLZ6Owsazjyynu0e0ObRgks0i7Rv+pe2M7/MBTZpQ== +"@stripe/stripe-js@^4.1.0": + version "4.1.0" + resolved "https://registry.yarnpkg.com/@stripe/stripe-js/-/stripe-js-4.1.0.tgz#11a54478df28b7a2d146251f645fb26e9efc9bfd" + integrity sha512-HhstGRUz/4JdbZpb26OcOf8Qb/cFR02arvHvgz4sPFLSnI6ZNHC53Jc6JP/FGNwxtrF719YyUnK0gGy4oyhucQ== "@svgr/babel-plugin-add-jsx-attribute@8.0.0": version "8.0.0" From 49e4853fe2703c939a072642e6cd14b6fe9b3c50 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 26 Jul 2024 09:26:39 +0200 Subject: [PATCH 04/89] Bump @tanstack/react-query-persist-client from 5.51.3 to 5.51.11 (#2306) Bumps [@tanstack/react-query-persist-client](https://github.com/TanStack/query/tree/HEAD/packages/react-query-persist-client) from 5.51.3 to 5.51.11. - [Release notes](https://github.com/TanStack/query/releases) - [Commits](https://github.com/TanStack/query/commits/v5.51.11/packages/react-query-persist-client) --- updated-dependencies: - dependency-name: "@tanstack/react-query-persist-client" dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- packages/apps/dashboard/ui/package.json | 2 +- .../exchange-oracle/client/package.json | 2 +- .../apps/job-launcher/client/package.json | 2 +- yarn.lock | 22 ++++++++++++++----- 4 files changed, 20 insertions(+), 8 deletions(-) diff --git a/packages/apps/dashboard/ui/package.json b/packages/apps/dashboard/ui/package.json index ca0149856b..6eecc24256 100644 --- a/packages/apps/dashboard/ui/package.json +++ b/packages/apps/dashboard/ui/package.json @@ -13,7 +13,7 @@ "@reduxjs/toolkit": "^1.9.0", "@tanstack/query-sync-storage-persister": "^5.38.0", "@tanstack/react-query": "^5.49.2", - "@tanstack/react-query-persist-client": "^5.35.4", + "@tanstack/react-query-persist-client": "^5.51.11", "axios": "^1.2.3", "bignumber.js": "^9.1.0", "copy-to-clipboard": "^3.3.3", diff --git a/packages/apps/fortune/exchange-oracle/client/package.json b/packages/apps/fortune/exchange-oracle/client/package.json index b765a1e09e..677822e2ca 100644 --- a/packages/apps/fortune/exchange-oracle/client/package.json +++ b/packages/apps/fortune/exchange-oracle/client/package.json @@ -30,7 +30,7 @@ "@mui/material": "^5.16.0", "@tanstack/query-sync-storage-persister": "^5.38.0", "@tanstack/react-query": "^5.49.2", - "@tanstack/react-query-persist-client": "^5.35.4", + "@tanstack/react-query-persist-client": "^5.51.11", "axios": "^1.7.2", "ethers": "^6.13.1", "react": "^18.3.1", diff --git a/packages/apps/job-launcher/client/package.json b/packages/apps/job-launcher/client/package.json index b2429da35b..01c4e79312 100644 --- a/packages/apps/job-launcher/client/package.json +++ b/packages/apps/job-launcher/client/package.json @@ -15,7 +15,7 @@ "@stripe/stripe-js": "^4.1.0", "@tanstack/query-sync-storage-persister": "^5.38.0", "@tanstack/react-query": "^5.49.2", - "@tanstack/react-query-persist-client": "^5.35.4", + "@tanstack/react-query-persist-client": "^5.51.11", "axios": "^1.1.3", "dayjs": "^1.11.9", "ethers": "^6.12.1", diff --git a/yarn.lock b/yarn.lock index c2570ed19a..6a3d7d17dc 100644 --- a/yarn.lock +++ b/yarn.lock @@ -6471,6 +6471,11 @@ resolved "https://registry.yarnpkg.com/@tanstack/query-core/-/query-core-5.51.3.tgz#0d9ea8d76c54bf40f130c348d8a2d6c954da3d7d" integrity sha512-xgncI1B0OPfSsYcdqKHUxb/OF370GrtK7BxswlllDfyTVw6r3+9VdugJWaVVQT2LiSbkIqEwUteFXR2I0m2iqw== +"@tanstack/query-core@5.51.9": + version "5.51.9" + resolved "https://registry.yarnpkg.com/@tanstack/query-core/-/query-core-5.51.9.tgz#eb2e02c715068d5664680b773e39eb44db6b48d8" + integrity sha512-HsAwaY5J19MD18ykZDS3aVVh+bAt0i7m6uQlFC2b77DLV9djo+xEN7MWQAQQTR8IM+7r/zbozTQ7P0xr0bHuew== + "@tanstack/query-devtools@5.51.1": version "5.51.1" resolved "https://registry.yarnpkg.com/@tanstack/query-devtools/-/query-devtools-5.51.1.tgz#80fb2b16cc11896b808d17b23487c43db38d22a8" @@ -6483,6 +6488,13 @@ dependencies: "@tanstack/query-core" "5.51.3" +"@tanstack/query-persist-client-core@5.51.9": + version "5.51.9" + resolved "https://registry.yarnpkg.com/@tanstack/query-persist-client-core/-/query-persist-client-core-5.51.9.tgz#4d8b2788fcb8122c3ba1ba95e4db2e2c39ee0bb4" + integrity sha512-yKvDozZLf+XkXM+0ynx+JnSufD1QMFFdCgfIKrSHozZJoCeLnuf3kECi1T3KEZqdaxUWtZnSPcII9eb8pLJ9cQ== + dependencies: + "@tanstack/query-core" "5.51.9" + "@tanstack/query-sync-storage-persister@^5.38.0": version "5.51.3" resolved "https://registry.yarnpkg.com/@tanstack/query-sync-storage-persister/-/query-sync-storage-persister-5.51.3.tgz#fcfa19d43abc80230065800aa771e90fe5293972" @@ -6498,12 +6510,12 @@ dependencies: "@tanstack/query-devtools" "5.51.1" -"@tanstack/react-query-persist-client@^5.35.4": - version "5.51.3" - resolved "https://registry.yarnpkg.com/@tanstack/react-query-persist-client/-/react-query-persist-client-5.51.3.tgz#49b707cdb1ab05a0eff0b6abd656bac16d717c23" - integrity sha512-h+laEiW1nsCs0HJtIOPnrTGfVZy57eOzLTx6teF4BVw4y1oVSW0prGr9cDr5Yr3dtaWdza7TQh1zZaYgoWN8oQ== +"@tanstack/react-query-persist-client@^5.51.11": + version "5.51.11" + resolved "https://registry.yarnpkg.com/@tanstack/react-query-persist-client/-/react-query-persist-client-5.51.11.tgz#b75a321813c538ee881f84345853571f2e1f52e2" + integrity sha512-yx8i+QvMKRzdbCrlAjNXj5TwWXrhujiYwea1BG2AEMMAxCa6IIIwsXI96F5xtkoZnN/HYY3B6t9zCJu93yVDmg== dependencies: - "@tanstack/query-persist-client-core" "5.51.3" + "@tanstack/query-persist-client-core" "5.51.9" "@tanstack/react-query@^5.18.1", "@tanstack/react-query@^5.49.2": version "5.51.3" From 06018d928da168c5d94078f556bfe75643c9872a Mon Sep 17 00:00:00 2001 From: portuu3 <61605646+portuu3@users.noreply.github.com> Date: Fri, 26 Jul 2024 15:40:55 +0200 Subject: [PATCH 05/89] [Reputaiton Oracle] Fix error in email verification (#2317) * fix site key nullable * fix sitekeys relation --- .../migrations/1721994760450-nullableSiteKey.ts | 17 +++++++++++++++++ .../server/src/modules/auth/token.repository.ts | 2 +- .../server/src/modules/user/user.entity.ts | 2 +- 3 files changed, 19 insertions(+), 2 deletions(-) create mode 100644 packages/apps/reputation-oracle/server/src/database/migrations/1721994760450-nullableSiteKey.ts diff --git a/packages/apps/reputation-oracle/server/src/database/migrations/1721994760450-nullableSiteKey.ts b/packages/apps/reputation-oracle/server/src/database/migrations/1721994760450-nullableSiteKey.ts new file mode 100644 index 0000000000..74469d5531 --- /dev/null +++ b/packages/apps/reputation-oracle/server/src/database/migrations/1721994760450-nullableSiteKey.ts @@ -0,0 +1,17 @@ +import { MigrationInterface, QueryRunner } from 'typeorm'; + +export class NullableSiteKey1721994760450 implements MigrationInterface { + name = 'NullableSiteKey1721994760450'; + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `DROP INDEX "hmt"."IDX_2dcfd04b329a0fd4be7f376512"`, + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `CREATE UNIQUE INDEX "IDX_2dcfd04b329a0fd4be7f376512" ON "hmt"."site_keys" ("user_id") WHERE (type = 'hcaptcha'::hmt.site_keys_type_enum)`, + ); + } +} diff --git a/packages/apps/reputation-oracle/server/src/modules/auth/token.repository.ts b/packages/apps/reputation-oracle/server/src/modules/auth/token.repository.ts index 82bc5afe87..8157a1c0ad 100644 --- a/packages/apps/reputation-oracle/server/src/modules/auth/token.repository.ts +++ b/packages/apps/reputation-oracle/server/src/modules/auth/token.repository.ts @@ -18,7 +18,7 @@ export class TokenRepository extends BaseRepository { uuid, type, }, - relations: ['user', 'user.kyc', 'user.siteKey'], + relations: ['user', 'user.kyc', 'user.siteKeys'], }); } diff --git a/packages/apps/reputation-oracle/server/src/modules/user/user.entity.ts b/packages/apps/reputation-oracle/server/src/modules/user/user.entity.ts index a43098efa6..30cc009251 100644 --- a/packages/apps/reputation-oracle/server/src/modules/user/user.entity.ts +++ b/packages/apps/reputation-oracle/server/src/modules/user/user.entity.ts @@ -41,7 +41,7 @@ export class UserEntity extends BaseEntity implements IUser { public kyc?: KycEntity; @OneToMany(() => SiteKeyEntity, (siteKey) => siteKey.user) - public siteKeys: SiteKeyEntity[]; + public siteKeys?: SiteKeyEntity[]; @OneToMany( () => UserQualificationEntity, From 0ba2a9646f5e7243ee7021d7b2c5e8a13350c5ad Mon Sep 17 00:00:00 2001 From: Dzeranov Date: Mon, 29 Jul 2024 14:15:23 +0300 Subject: [PATCH 06/89] [Job Launcher] hCaptcha guards are enabled for auth endpoints (#2021) * hCaptcha guards are enabled for auth endpoints * fix after merge --------- Co-authored-by: portuu3 --- .../apps/job-launcher/client/.env.example | 2 - .../components/Auth/ForgotPasswordForm.jsx | 3 - .../src/components/Auth/ResetPasswordForm.jsx | 3 - .../client/src/components/Auth/SignInForm.jsx | 3 - .../client/src/components/Auth/SignUpForm.jsx | 3 - .../job-launcher/client/src/vite-env.d.ts | 2 - .../src/common/config/auth-config.service.ts | 6 +- .../server/src/common/config/env-schema.ts | 6 +- .../server/src/modules/auth/auth.service.ts | 87 ++++++++++--------- 9 files changed, 55 insertions(+), 60 deletions(-) diff --git a/packages/apps/job-launcher/client/.env.example b/packages/apps/job-launcher/client/.env.example index 5ab38ba907..58f0a61399 100644 --- a/packages/apps/job-launcher/client/.env.example +++ b/packages/apps/job-launcher/client/.env.example @@ -2,8 +2,6 @@ VITE_APP_JOB_LAUNCHER_SERVER_URL= VITE_APP_WALLETCONNECT_PROJECT_ID= VITE_APP_STRIPE_PUBLISHABLE_KEY= VITE_APP_HCAPTCHA_SITE_KEY= -VITE_APP_HCAPTCHA_EXCHANGE_URL= -VITE_APP_HCAPTCHA_LABELING_BASE_URL= VITE_APP_ENVIRONMENT= # RPC URLS diff --git a/packages/apps/job-launcher/client/src/components/Auth/ForgotPasswordForm.jsx b/packages/apps/job-launcher/client/src/components/Auth/ForgotPasswordForm.jsx index 13e58d6bc8..6be17a87a7 100644 --- a/packages/apps/job-launcher/client/src/components/Auth/ForgotPasswordForm.jsx +++ b/packages/apps/job-launcher/client/src/components/Auth/ForgotPasswordForm.jsx @@ -121,9 +121,6 @@ export const ForgotPasswordForm = () => { > setFieldValue('hcaptchaToken', token)} ref={captchaRef} /> diff --git a/packages/apps/job-launcher/client/src/components/Auth/ResetPasswordForm.jsx b/packages/apps/job-launcher/client/src/components/Auth/ResetPasswordForm.jsx index ecbf6e008e..1ee62e5ee4 100644 --- a/packages/apps/job-launcher/client/src/components/Auth/ResetPasswordForm.jsx +++ b/packages/apps/job-launcher/client/src/components/Auth/ResetPasswordForm.jsx @@ -89,9 +89,6 @@ export const ResetPasswordForm = () => { > setFieldValue('hcaptchaToken', token)} ref={captchaRef} /> diff --git a/packages/apps/job-launcher/client/src/components/Auth/SignInForm.jsx b/packages/apps/job-launcher/client/src/components/Auth/SignInForm.jsx index 2fd8e9c955..c4e7fe0099 100644 --- a/packages/apps/job-launcher/client/src/components/Auth/SignInForm.jsx +++ b/packages/apps/job-launcher/client/src/components/Auth/SignInForm.jsx @@ -97,9 +97,6 @@ export const SignInForm = () => { handleVerificationToken(token)} ref={captchaRef} /> diff --git a/packages/apps/job-launcher/client/src/components/Auth/SignUpForm.jsx b/packages/apps/job-launcher/client/src/components/Auth/SignUpForm.jsx index 5de00260df..97d01b0208 100644 --- a/packages/apps/job-launcher/client/src/components/Auth/SignUpForm.jsx +++ b/packages/apps/job-launcher/client/src/components/Auth/SignUpForm.jsx @@ -171,9 +171,6 @@ export const SignUpForm = ({ onFinish, setMode, setTabValue }) => { > setFieldValue('hcaptchaToken', token)} ref={captchaRef} /> diff --git a/packages/apps/job-launcher/client/src/vite-env.d.ts b/packages/apps/job-launcher/client/src/vite-env.d.ts index 010189bda9..36339cae4f 100644 --- a/packages/apps/job-launcher/client/src/vite-env.d.ts +++ b/packages/apps/job-launcher/client/src/vite-env.d.ts @@ -5,8 +5,6 @@ interface ImportMetaEnv { readonly VITE_APP_WALLETCONNECT_PROJECT_ID: string; readonly VITE_APP_STRIPE_PUBLISHABLE_KEY: string; readonly VITE_APP_HCAPTCHA_SITE_KEY: string; - readonly VITE_APP_HCAPTCHA_EXCHANGE_URL: string; - readonly VITE_APP_HCAPTCHA_LABELING_BASE_URL: string; readonly VITE_APP_ENVIRONMENT: string; readonly VITE_APP_RPC_URL_MAINNET: string; diff --git a/packages/apps/job-launcher/server/src/common/config/auth-config.service.ts b/packages/apps/job-launcher/server/src/common/config/auth-config.service.ts index c24966fabe..2fb94ee515 100644 --- a/packages/apps/job-launcher/server/src/common/config/auth-config.service.ts +++ b/packages/apps/job-launcher/server/src/common/config/auth-config.service.ts @@ -40,10 +40,10 @@ export class AuthConfigService { get hCaptchaSecret(): string { return this.configService.get('HCAPTCHA_SECRET', ''); } - get hCaptchaExchangeURL(): string { + get hcaptchaProtectionUrl(): string { return this.configService.get( - 'HCAPTCHA_EXCHANGE_URL', - 'https://foundation-exchange.hmt.ai', + 'HCAPTCHA_PROTECTION_URL', + 'https://api.hcaptcha.com', ); } } diff --git a/packages/apps/job-launcher/server/src/common/config/env-schema.ts b/packages/apps/job-launcher/server/src/common/config/env-schema.ts index 1283a329b9..5e3681d8ba 100644 --- a/packages/apps/job-launcher/server/src/common/config/env-schema.ts +++ b/packages/apps/job-launcher/server/src/common/config/env-schema.ts @@ -36,8 +36,10 @@ export const envValidator = Joi.object({ HCAPTCHA_REPUTATION_ORACLE_URI: Joi.string().required(), HCAPTCHA_ORACLE_ADDRESS: Joi.string().required(), HCAPTCHA_SITE_KEY: Joi.string().required(), - // HCAPTCHA_SECRET: Joi.string().required(), - HCAPTCHA_EXCHANGE_URL: Joi.string().description('hcaptcha exchange url'), + HCAPTCHA_SECRET: Joi.string().required(), + HCAPTCHA_PROTECTION_URL: Joi.string().description( + 'Endpoint for validating signin/signup hcaptcha tokens', + ), RPC_URL_SEPOLIA: Joi.string(), RPC_URL_POLYGON: Joi.string(), RPC_URL_POLYGON_AMOY: Joi.string(), diff --git a/packages/apps/job-launcher/server/src/modules/auth/auth.service.ts b/packages/apps/job-launcher/server/src/modules/auth/auth.service.ts index 7ba360c054..57c13bbba0 100644 --- a/packages/apps/job-launcher/server/src/modules/auth/auth.service.ts +++ b/packages/apps/job-launcher/server/src/modules/auth/auth.service.ts @@ -46,19 +46,22 @@ export class AuthService { ) {} public async signin(data: SignInDto, ip?: string): Promise { - // if ( - // !( - // await verifyToken( - // this.authConfigService.hCaptchaExchangeURL, - // this.authConfigService.hCaptchaSiteKey, - // this.authConfigService.hCaptchaSecret, - // data.hCaptchaToken, - // ip, - // ) - // ).success - // ) { - // throw new ControlledError(ErrorAuth.InvalidCaptchaToken, HttpStatus.UNAUTHORIZED); - // } + if ( + !( + await verifyToken( + this.authConfigService.hcaptchaProtectionUrl, + this.authConfigService.hCaptchaSiteKey, + this.authConfigService.hCaptchaSecret, + data.hCaptchaToken, + ip, + ) + ).success + ) { + throw new ControlledError( + ErrorAuth.InvalidCaptchaToken, + HttpStatus.FORBIDDEN, + ); + } const userEntity = await this.userService.getByCredentials( data.email, data.password, @@ -75,19 +78,22 @@ export class AuthService { } public async signup(data: UserCreateDto, ip?: string): Promise { - // if ( - // !( - // await verifyToken( - // this.authConfigService.hCaptchaExchangeURL, - // this.authConfigService.hCaptchaSiteKey, - // this.authConfigService.hCaptchaSecret, - // data.hCaptchaToken, - // ip, - // ) - // ).success - // ) { - // throw new ControlledError(ErrorAuth.InvalidCaptchaToken, HttpStatus.UNAUTHORIZED); - // } + if ( + !( + await verifyToken( + this.authConfigService.hcaptchaProtectionUrl, + this.authConfigService.hCaptchaSiteKey, + this.authConfigService.hCaptchaSecret, + data.hCaptchaToken, + ip, + ) + ).success + ) { + throw new ControlledError( + ErrorAuth.InvalidCaptchaToken, + HttpStatus.FORBIDDEN, + ); + } const storedUser = await this.userRepository.findByEmail(data.email); if (storedUser) { throw new ControlledError( @@ -223,19 +229,22 @@ export class AuthService { data: RestorePasswordDto, ip?: string, ): Promise { - // if ( - // !( - // await verifyToken( - // this.authConfigService.hCaptchaExchangeURL, - // this.authConfigService.hCaptchaSiteKey, - // this.authConfigService.hCaptchaSecret, - // data.hCaptchaToken, - // ip, - // ) - // ).success - // ) { - // throw new ControlledError(ErrorAuth.InvalidCaptchaToken, HttpStatus.UNAUTHORIZED); - // } + if ( + !( + await verifyToken( + this.authConfigService.hcaptchaProtectionUrl, + this.authConfigService.hCaptchaSiteKey, + this.authConfigService.hCaptchaSecret, + data.hCaptchaToken, + ip, + ) + ).success + ) { + throw new ControlledError( + ErrorAuth.InvalidCaptchaToken, + HttpStatus.FORBIDDEN, + ); + } const tokenEntity = await this.tokenRepository.findOneByUuidAndType( data.token, From 28bf1bce4532d141e9aecfab7a7040531d7496c6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Jul 2024 08:12:19 +0200 Subject: [PATCH 07/89] Bump @apollo/client from 3.10.8 to 3.11.1 (#2319) Bumps [@apollo/client](https://github.com/apollographql/apollo-client) from 3.10.8 to 3.11.1. - [Release notes](https://github.com/apollographql/apollo-client/releases) - [Changelog](https://github.com/apollographql/apollo-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/apollographql/apollo-client/compare/v3.10.8...v3.11.1) --- updated-dependencies: - dependency-name: "@apollo/client" dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package.json | 2 +- yarn.lock | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index e55f66b905..fa5898819b 100644 --- a/package.json +++ b/package.json @@ -18,7 +18,7 @@ ] }, "devDependencies": { - "@apollo/client": "^3.7.12", + "@apollo/client": "^3.11.1", "@babel/core": "^7.23.5", "@babel/preset-env": "^7.24.3", "@babel/preset-react": "^7.18.6", diff --git a/yarn.lock b/yarn.lock index 6a3d7d17dc..0647ec70ea 100644 --- a/yarn.lock +++ b/yarn.lock @@ -82,10 +82,10 @@ ora "5.4.1" rxjs "7.8.1" -"@apollo/client@^3.7.12": - version "3.10.8" - resolved "https://registry.yarnpkg.com/@apollo/client/-/client-3.10.8.tgz#96b1548818e45fac752ec2bd318e5466d9ca26b5" - integrity sha512-UaaFEitRrPRWV836wY2L7bd3HRCfbMie1jlYMcmazFAK23MVhz/Uq7VG1nwbotPb5xzFsw5RF4Wnp2G3dWPM3g== +"@apollo/client@^3.11.1": + version "3.11.1" + resolved "https://registry.yarnpkg.com/@apollo/client/-/client-3.11.1.tgz#73a0396a4a5d84d6804288fffa9579e1f3fc3211" + integrity sha512-fVuAi7ufRt2apIEYV18upvykw5JD+CwHAThxZkclby4phWCXtO4LD39Z0sk0+4i+j7oZ+jOofEkO1XGDDomZvQ== dependencies: "@graphql-typed-document-node/core" "^3.1.1" "@wry/caches" "^1.0.0" From 3a149726f14f4ae94a392ef920268bbc428e4221 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Jul 2024 08:13:06 +0200 Subject: [PATCH 08/89] Bump @nestjs/schematics from 9.2.0 to 10.1.3 (#2321) Bumps [@nestjs/schematics](https://github.com/nestjs/schematics) from 9.2.0 to 10.1.3. - [Release notes](https://github.com/nestjs/schematics/releases) - [Changelog](https://github.com/nestjs/schematics/blob/master/.release-it.json) - [Commits](https://github.com/nestjs/schematics/compare/9.2.0...10.1.3) --- updated-dependencies: - dependency-name: "@nestjs/schematics" dependency-type: direct:development update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- packages/apps/dashboard/server/package.json | 2 +- .../exchange-oracle/server/package.json | 2 +- .../fortune/recording-oracle/package.json | 2 +- packages/apps/human-app/server/package.json | 2 +- .../apps/job-launcher/server/package.json | 2 +- .../reputation-oracle/server/package.json | 2 +- yarn.lock | 54 ++----------------- 7 files changed, 11 insertions(+), 55 deletions(-) diff --git a/packages/apps/dashboard/server/package.json b/packages/apps/dashboard/server/package.json index 9cd5455c59..6449ed471b 100644 --- a/packages/apps/dashboard/server/package.json +++ b/packages/apps/dashboard/server/package.json @@ -29,7 +29,7 @@ }, "devDependencies": { "@nestjs/cli": "^10.3.2", - "@nestjs/schematics": "^9.2.0", + "@nestjs/schematics": "^10.1.3", "@nestjs/testing": "^9.4.3", "@types/express": "^4.17.13", "@types/jest": "29.5.1", diff --git a/packages/apps/fortune/exchange-oracle/server/package.json b/packages/apps/fortune/exchange-oracle/server/package.json index 28954b256d..6772002d99 100644 --- a/packages/apps/fortune/exchange-oracle/server/package.json +++ b/packages/apps/fortune/exchange-oracle/server/package.json @@ -38,7 +38,7 @@ "devDependencies": { "@golevelup/ts-jest": "^0.5.0", "@nestjs/cli": "^10.3.2", - "@nestjs/schematics": "^9.2.0", + "@nestjs/schematics": "^10.1.3", "@nestjs/testing": "^10.3.1", "@types/express": "^4.17.13", "@types/jest": "29.5.12", diff --git a/packages/apps/fortune/recording-oracle/package.json b/packages/apps/fortune/recording-oracle/package.json index f2bf353d58..f88b977f41 100644 --- a/packages/apps/fortune/recording-oracle/package.json +++ b/packages/apps/fortune/recording-oracle/package.json @@ -36,7 +36,7 @@ }, "devDependencies": { "@nestjs/cli": "^10.3.2", - "@nestjs/schematics": "^9.2.0", + "@nestjs/schematics": "^10.1.3", "@nestjs/testing": "^10.3.1", "@types/express": "^4.17.13" } diff --git a/packages/apps/human-app/server/package.json b/packages/apps/human-app/server/package.json index 13274afee8..4b041d9047 100644 --- a/packages/apps/human-app/server/package.json +++ b/packages/apps/human-app/server/package.json @@ -47,7 +47,7 @@ }, "devDependencies": { "@nestjs/cli": "^10.3.2", - "@nestjs/schematics": "^9.2.0", + "@nestjs/schematics": "^10.1.3", "@nestjs/testing": "^9.4.3", "@types/express": "^4.17.13", "@types/jest": "29.5.12", diff --git a/packages/apps/job-launcher/server/package.json b/packages/apps/job-launcher/server/package.json index 01031b37b9..e25d67bfd2 100644 --- a/packages/apps/job-launcher/server/package.json +++ b/packages/apps/job-launcher/server/package.json @@ -61,7 +61,7 @@ "devDependencies": { "@golevelup/ts-jest": "^0.5.0", "@nestjs/cli": "^10.3.2", - "@nestjs/schematics": "^9.2.0", + "@nestjs/schematics": "^10.1.3", "@nestjs/testing": "^10.3.1", "@types/bcrypt": "^5.0.2", "@types/express": "^4.17.13", diff --git a/packages/apps/reputation-oracle/server/package.json b/packages/apps/reputation-oracle/server/package.json index 1c3d6a0877..ccda7732b8 100644 --- a/packages/apps/reputation-oracle/server/package.json +++ b/packages/apps/reputation-oracle/server/package.json @@ -60,7 +60,7 @@ "devDependencies": { "@golevelup/ts-jest": "^0.5.0", "@nestjs/cli": "^10.3.2", - "@nestjs/schematics": "^9.2.0", + "@nestjs/schematics": "^10.1.3", "@nestjs/testing": "^10.3.1", "@types/bcrypt": "^5.0.2", "@types/express": "^4.17.13", diff --git a/yarn.lock b/yarn.lock index 0647ec70ea..b1afca71e1 100644 --- a/yarn.lock +++ b/yarn.lock @@ -25,17 +25,6 @@ "@jridgewell/gen-mapping" "^0.3.5" "@jridgewell/trace-mapping" "^0.3.24" -"@angular-devkit/core@16.0.1": - version "16.0.1" - resolved "https://registry.yarnpkg.com/@angular-devkit/core/-/core-16.0.1.tgz#1af4177d503d8d1babdf29c95d8901660a557243" - integrity sha512-2uz98IqkKJlgnHbWQ7VeL4pb+snGAZXIama2KXi+k9GsRntdcw+udX8rL3G9SdUGUF+m6+147Y1oRBMHsO/v4w== - dependencies: - ajv "8.12.0" - ajv-formats "2.1.1" - jsonc-parser "3.2.0" - rxjs "7.8.1" - source-map "0.7.4" - "@angular-devkit/core@17.3.8": version "17.3.8" resolved "https://registry.yarnpkg.com/@angular-devkit/core/-/core-17.3.8.tgz#8679cacf84cf79764f027811020e235ab32016d2" @@ -60,17 +49,6 @@ symbol-observable "4.0.0" yargs-parser "21.1.1" -"@angular-devkit/schematics@16.0.1": - version "16.0.1" - resolved "https://registry.yarnpkg.com/@angular-devkit/schematics/-/schematics-16.0.1.tgz#d49387e9e41c9cce98b155da51b0e193333dd178" - integrity sha512-A9D0LTYmiqiBa90GKcSuWb7hUouGIbm/AHbJbjL85WLLRbQA2PwKl7P5Mpd6nS/ZC0kfG4VQY3VOaDvb3qpI9g== - dependencies: - "@angular-devkit/core" "16.0.1" - jsonc-parser "3.2.0" - magic-string "0.30.0" - ora "5.4.1" - rxjs "7.8.1" - "@angular-devkit/schematics@17.3.8": version "17.3.8" resolved "https://registry.yarnpkg.com/@angular-devkit/schematics/-/schematics-17.3.8.tgz#f853eb21682aadfb6667e090b5b509fc95ce8442" @@ -3262,7 +3240,7 @@ "@jridgewell/gen-mapping" "^0.3.5" "@jridgewell/trace-mapping" "^0.3.25" -"@jridgewell/sourcemap-codec@^1.4.10", "@jridgewell/sourcemap-codec@^1.4.13", "@jridgewell/sourcemap-codec@^1.4.14", "@jridgewell/sourcemap-codec@^1.4.15": +"@jridgewell/sourcemap-codec@^1.4.10", "@jridgewell/sourcemap-codec@^1.4.14", "@jridgewell/sourcemap-codec@^1.4.15": version "1.5.0" resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz#3188bcb273a414b0d215fd22a58540b989b9409a" integrity sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ== @@ -3880,10 +3858,10 @@ cron "3.1.7" uuid "10.0.0" -"@nestjs/schematics@^10.0.1": - version "10.1.2" - resolved "https://registry.yarnpkg.com/@nestjs/schematics/-/schematics-10.1.2.tgz#690e675687ab5b4d63b59e888e20ebdf7231edbc" - integrity sha512-S0bMtZM5U4mAiqkhRyZkXgjmOHBS5P/lp/vEydgMR4F7csOShc3jFeKVs1Eghd9xCFezGKy3SHy7hFT6dpPhWQ== +"@nestjs/schematics@^10.0.1", "@nestjs/schematics@^10.1.3": + version "10.1.3" + resolved "https://registry.yarnpkg.com/@nestjs/schematics/-/schematics-10.1.3.tgz#8bd80ab9fab6a02586524bd2c545b0ea787cf62c" + integrity sha512-aLJ4Nl/K/u6ZlgLa0NjKw5CuBOIgc6vudF42QvmGueu5FaMGM6IJrAuEvB5T2kr0PAfVwYmDFBBHCWdYhTw4Tg== dependencies: "@angular-devkit/core" "17.3.8" "@angular-devkit/schematics" "17.3.8" @@ -3891,16 +3869,6 @@ jsonc-parser "3.3.1" pluralize "8.0.0" -"@nestjs/schematics@^9.2.0": - version "9.2.0" - resolved "https://registry.yarnpkg.com/@nestjs/schematics/-/schematics-9.2.0.tgz#f840054b5ae4b0b4e70aa9f72c09c3cf388f2512" - integrity sha512-wHpNJDPzM6XtZUOB3gW0J6mkFCSJilzCM3XrHI1o0C8vZmFE1snbmkIXNyoi1eV0Nxh1BMymcgz5vIMJgQtTqw== - dependencies: - "@angular-devkit/core" "16.0.1" - "@angular-devkit/schematics" "16.0.1" - jsonc-parser "3.2.0" - pluralize "8.0.0" - "@nestjs/serve-static@^4.0.1": version "4.0.2" resolved "https://registry.yarnpkg.com/@nestjs/serve-static/-/serve-static-4.0.2.tgz#f003bbd90922bdc73d0261edacf001dfef174c96" @@ -17637,11 +17605,6 @@ json5@^2.1.2, json5@^2.2.0, json5@^2.2.2, json5@^2.2.3: resolved "https://registry.yarnpkg.com/json5/-/json5-2.2.3.tgz#78cd6f1a19bdc12b73db5ad0c61efd66c1e29283" integrity sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg== -jsonc-parser@3.2.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/jsonc-parser/-/jsonc-parser-3.2.0.tgz#31ff3f4c2b9793f89c67212627c51c6394f88e76" - integrity sha512-gfFQZrcTc8CnKXp6Y4/CBT3fTc0OVuDofpre4aEeEpSBPV5X5v4+Vmx+8snU7RLPrNHPKSgLxGo9YuQzz20o+w== - jsonc-parser@3.2.1: version "3.2.1" resolved "https://registry.yarnpkg.com/jsonc-parser/-/jsonc-parser-3.2.1.tgz#031904571ccf929d7670ee8c547545081cb37f1a" @@ -18594,13 +18557,6 @@ lz-string@^1.5.0: resolved "https://registry.yarnpkg.com/lz-string/-/lz-string-1.5.0.tgz#c1ab50f77887b712621201ba9fd4e3a6ed099941" integrity sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ== -magic-string@0.30.0: - version "0.30.0" - resolved "https://registry.yarnpkg.com/magic-string/-/magic-string-0.30.0.tgz#fd58a4748c5c4547338a424e90fa5dd17f4de529" - integrity sha512-LA+31JYDJLs82r2ScLrlz1GjSgu66ZV518eyWT+S8VhyQn/JL0u9MeBOvQMGYiPk1DBiSN9DDMOcXvigJZaViQ== - dependencies: - "@jridgewell/sourcemap-codec" "^1.4.13" - magic-string@0.30.8: version "0.30.8" resolved "https://registry.yarnpkg.com/magic-string/-/magic-string-0.30.8.tgz#14e8624246d2bedba70d5462aa99ac9681844613" From 5cb810c99a4a4db95a97b9c2d717a6debe5fca62 Mon Sep 17 00:00:00 2001 From: eugenvoronov <104138627+eugenvoronov@users.noreply.github.com> Date: Tue, 30 Jul 2024 11:26:02 +0300 Subject: [PATCH 09/89] [SDK] ITransaction interface wrong configuration (#2316) * Updated property name * Updated TransactionData * fix error on docs generation * try to fix dependency review --------- Co-authored-by: portuu3 --- ...tocol_sdk.transaction.transaction_utils.md | 4 +- .../base/classes/BaseEthersClient.md | 12 +- .../encryption/classes/Encryption.md | 30 ++-- .../encryption/classes/EncryptionUtils.md | 22 +-- .../typescript/escrow/classes/EscrowClient.md | 154 +++++++----------- .../typescript/escrow/classes/EscrowUtils.md | 12 +- .../kvstore/classes/KVStoreClient.md | 60 +++---- .../kvstore/classes/KVStoreUtils.md | 4 +- .../operator/classes/OperatorUtils.md | 16 +- .../staking/classes/StakingClient.md | 106 +++++------- .../statistics/classes/StatisticsClient.md | 43 +++-- .../storage/classes/StorageClient.md | 44 ++--- .../transaction/classes/TransactionUtils.md | 8 +- .../transaction/transaction_utils.py | 8 +- .../transaction/test_transaction_utils.py | 2 +- .../human-protocol-sdk/package.json | 4 +- .../human-protocol-sdk/src/interfaces.ts | 2 +- yarn.lock | 150 +++++++++-------- 18 files changed, 299 insertions(+), 382 deletions(-) diff --git a/docs/sdk/python/human_protocol_sdk.transaction.transaction_utils.md b/docs/sdk/python/human_protocol_sdk.transaction.transaction_utils.md index b686d67e7a..ce1a533e1d 100644 --- a/docs/sdk/python/human_protocol_sdk.transaction.transaction_utils.md +++ b/docs/sdk/python/human_protocol_sdk.transaction.transaction_utils.md @@ -23,11 +23,11 @@ print( ## Module -### *class* human_protocol_sdk.transaction.transaction_utils.TransactionData(chain_id, block, hash, from_address, to_address, timestamp, value, method) +### *class* human_protocol_sdk.transaction.transaction_utils.TransactionData(chain_id, block, tx_hash, from_address, to_address, timestamp, value, method) Bases: `object` -#### \_\_init_\_(chain_id, block, hash, from_address, to_address, timestamp, value, method) +#### \_\_init_\_(chain_id, block, tx_hash, from_address, to_address, timestamp, value, method) ### *class* human_protocol_sdk.transaction.transaction_utils.TransactionUtils diff --git a/docs/sdk/typescript/base/classes/BaseEthersClient.md b/docs/sdk/typescript/base/classes/BaseEthersClient.md index 5a17968241..1f11c477ad 100644 --- a/docs/sdk/typescript/base/classes/BaseEthersClient.md +++ b/docs/sdk/typescript/base/classes/BaseEthersClient.md @@ -38,9 +38,9 @@ The network information required to connect to the contracts [`BaseEthersClient`](BaseEthersClient.md) -#### Source +#### Defined in -[base.ts:20](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L20) +[base.ts:20](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L20) ## Properties @@ -48,9 +48,9 @@ The network information required to connect to the contracts > **networkData**: `NetworkData` -#### Source +#### Defined in -[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) +[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) *** @@ -58,6 +58,6 @@ The network information required to connect to the contracts > `protected` **runner**: `ContractRunner` -#### Source +#### Defined in -[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) +[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) diff --git a/docs/sdk/typescript/encryption/classes/Encryption.md b/docs/sdk/typescript/encryption/classes/Encryption.md index d59f418d69..995925b3bb 100644 --- a/docs/sdk/typescript/encryption/classes/Encryption.md +++ b/docs/sdk/typescript/encryption/classes/Encryption.md @@ -64,19 +64,9 @@ The private key. [`Encryption`](Encryption.md) -#### Source +#### Defined in -[encryption.ts:53](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L53) - -## Properties - -### privateKey - -> `private` **privateKey**: `PrivateKey` - -#### Source - -[encryption.ts:46](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L46) +[encryption.ts:53](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L53) ## Methods @@ -126,9 +116,9 @@ UYLqAQDfdym4kiUvKO1+REKASt0Gwykndl7hra9txqlUL5DXBQ===Vwgv const resultMessage = await encription.decrypt('message'); ``` -#### Source +#### Defined in -[encryption.ts:180](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L180) +[encryption.ts:180](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L180) *** @@ -162,9 +152,9 @@ const encription = await Encryption.build(privateKey, passphrase); const resultMessage = await encription.sign('message'); ``` -#### Source +#### Defined in -[encryption.ts:217](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L217) +[encryption.ts:217](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L217) *** @@ -227,9 +217,9 @@ const publicKeys = [publicKey1, publicKey2]; const resultMessage = await encription.signAndEncrypt('message', publicKeys); ``` -#### Source +#### Defined in -[encryption.ts:129](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L129) +[encryption.ts:129](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L129) *** @@ -255,6 +245,6 @@ Optional: The passphrase for the private key. - The Encryption instance. -#### Source +#### Defined in -[encryption.ts:64](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L64) +[encryption.ts:64](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L64) diff --git a/docs/sdk/typescript/encryption/classes/EncryptionUtils.md b/docs/sdk/typescript/encryption/classes/EncryptionUtils.md index f7843a2c48..3ee60e2716 100644 --- a/docs/sdk/typescript/encryption/classes/EncryptionUtils.md +++ b/docs/sdk/typescript/encryption/classes/EncryptionUtils.md @@ -95,9 +95,9 @@ const publicKeys = [publicKey1, publicKey2] const result = await EncriptionUtils.encrypt('message', publicKeys); ``` -#### Source +#### Defined in -[encryption.ts:422](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L422) +[encryption.ts:422](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L422) *** @@ -117,7 +117,7 @@ Name for the key pair. Email for the key pair. -• **passphrase**: `string`= `''` +• **passphrase**: `string` = `''` Passphrase to encrypt the private key. Optional. @@ -150,9 +150,9 @@ const passphrase = 'YOUR_PASSPHRASE'; const result = await EncriptionUtils.generateKeyPair(name, email, passphrase); ``` -#### Source +#### Defined in -[encryption.ts:360](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L360) +[encryption.ts:360](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L360) *** @@ -182,9 +182,9 @@ import { EncryptionUtils } from '@human-protocol/sdk'; const signedData = await EncriptionUtils.getSignedData('message'); ``` -#### Source +#### Defined in -[encryption.ts:317](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L317) +[encryption.ts:317](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L317) *** @@ -230,9 +230,9 @@ if (isEncrypted) { } ``` -#### Source +#### Defined in -[encryption.ts:471](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L471) +[encryption.ts:471](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L471) *** @@ -278,6 +278,6 @@ UYLqAQDfdym4kiUvKO1+REKASt0Gwykndl7hra9txqlUL5DXBQ===Vwgv const result = await EncriptionUtils.verify('message', publicKey); ``` -#### Source +#### Defined in -[encryption.ts:284](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L284) +[encryption.ts:284](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L284) diff --git a/docs/sdk/typescript/escrow/classes/EscrowClient.md b/docs/sdk/typescript/escrow/classes/EscrowClient.md index 1456ca96f4..247e140f85 100644 --- a/docs/sdk/typescript/escrow/classes/EscrowClient.md +++ b/docs/sdk/typescript/escrow/classes/EscrowClient.md @@ -102,22 +102,12 @@ The Runner object to interact with the Ethereum network [`BaseEthersClient`](../../base/classes/BaseEthersClient.md).[`constructor`](../../base/classes/BaseEthersClient.md#constructors) -#### Source +#### Defined in -[escrow.ts:129](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L129) +[escrow.ts:129](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L129) ## Properties -### escrowFactoryContract - -> `private` **escrowFactoryContract**: `EscrowFactory` - -#### Source - -[escrow.ts:121](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L121) - -*** - ### networkData > **networkData**: `NetworkData` @@ -126,9 +116,9 @@ The Runner object to interact with the Ethereum network [`BaseEthersClient`](../../base/classes/BaseEthersClient.md).[`networkData`](../../base/classes/BaseEthersClient.md#networkdata) -#### Source +#### Defined in -[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) +[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) *** @@ -140,9 +130,9 @@ The Runner object to interact with the Ethereum network [`BaseEthersClient`](../../base/classes/BaseEthersClient.md).[`runner`](../../base/classes/BaseEthersClient.md#runner) -#### Source +#### Defined in -[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) +[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) ## Methods @@ -158,7 +148,7 @@ This function cancels the specified escrow, sends the balance to the canceler an Address of the escrow. -• **txOptions?**: `Overrides`= `{}` +• **txOptions?**: `Overrides` = `{}` Additional transaction parameters (optional, defaults to an empty object). @@ -186,9 +176,9 @@ const escrowClient = await EscrowClient.build(signer); await escrowClient.abort('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); ``` -#### Source +#### Defined in -[escrow.ts:837](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L837) +[escrow.ts:837](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L837) *** @@ -208,7 +198,7 @@ Address of the escrow. Array of addresses of trusted handlers to add. -• **txOptions?**: `Overrides`= `{}` +• **txOptions?**: `Overrides` = `{}` Additional transaction parameters (optional, defaults to an empty object). @@ -237,9 +227,9 @@ const trustedHandlers = ['0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', '0xf39Fd6 await escrowClient.addTrustedHandlers('0x62dD51230A30401C455c8398d06F85e4EaB6309f', trustedHandlers); ``` -#### Source +#### Defined in -[escrow.ts:885](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L885) +[escrow.ts:885](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L885) *** @@ -271,7 +261,7 @@ Final results file url. Final results file hash. -• **txOptions?**: `Overrides`= `{}` +• **txOptions?**: `Overrides` = `{}` Additional transaction parameters (optional, defaults to an empty object). @@ -304,9 +294,9 @@ const resultsHash'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079'; await escrowClient.bulkPayOut('0x62dD51230A30401C455c8398d06F85e4EaB6309f', recipients, amounts, resultsUrl, resultsHash); ``` -#### Source +#### Defined in -[escrow.ts:650](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L650) +[escrow.ts:650](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L650) *** @@ -322,7 +312,7 @@ This function cancels the specified escrow and sends the balance to the canceler Address of the escrow to cancel. -• **txOptions?**: `Overrides`= `{}` +• **txOptions?**: `Overrides` = `{}` Additional transaction parameters (optional, defaults to an empty object). @@ -350,9 +340,9 @@ const escrowClient = await EscrowClient.build(signer); await escrowClient.cancel('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); ``` -#### Source +#### Defined in -[escrow.ts:753](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L753) +[escrow.ts:753](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L753) *** @@ -368,7 +358,7 @@ This function sets the status of an escrow to completed. Address of the escrow. -• **txOptions?**: `Overrides`= `{}` +• **txOptions?**: `Overrides` = `{}` Additional transaction parameters (optional, defaults to an empty object). @@ -396,9 +386,9 @@ const escrowClient = await EscrowClient.build(signer); await escrowClient.complete('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); ``` -#### Source +#### Defined in -[escrow.ts:592](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L592) +[escrow.ts:592](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L592) *** @@ -463,9 +453,9 @@ const escrowConfig = { const escrowAddress = await escrowClient.createAndSetupEscrow(tokenAddress, trustedHandlers, jobRequesterId, escrowConfig); ``` -#### Source +#### Defined in -[escrow.ts:415](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L415) +[escrow.ts:415](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L415) *** @@ -489,7 +479,7 @@ Array of addresses that can perform actions on the contract. Job Requester Id -• **txOptions?**: `Overrides`= `{}` +• **txOptions?**: `Overrides` = `{}` Additional transaction parameters (optional, defaults to an empty object). @@ -520,9 +510,9 @@ const jobRequesterId = "job-requester-id"; const escrowAddress = await escrowClient.createEscrow(tokenAddress, trustedHandlers, jobRequesterId); ``` -#### Source +#### Defined in -[escrow.ts:209](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L209) +[escrow.ts:209](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L209) *** @@ -542,7 +532,7 @@ Address of the escrow to fund. Amount to be added as funds. -• **txOptions?**: `Overrides`= `{}` +• **txOptions?**: `Overrides` = `{}` Additional transaction parameters (optional, defaults to an empty object). @@ -569,9 +559,9 @@ const amount = ethers.parseUnits(5, 'ether'); //convert from ETH to WEI await escrowClient.fund('0x62dD51230A30401C455c8398d06F85e4EaB6309f', amount); ``` -#### Source +#### Defined in -[escrow.ts:463](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L463) +[escrow.ts:463](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L463) *** @@ -607,31 +597,9 @@ const escrowClient = await EscrowClient.build(signer); const balance = await escrowClient.getBalance('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); ``` -#### Source - -[escrow.ts:940](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L940) - -*** - -### getEscrowContract() - -> `private` **getEscrowContract**(`escrowAddress`): `Escrow` - -Connects to the escrow contract - -#### Parameters - -• **escrowAddress**: `string` - -Escrow address to connect to - -#### Returns - -`Escrow` - -#### Source +#### Defined in -[escrow.ts:169](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L169) +[escrow.ts:940](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L940) *** @@ -667,9 +635,9 @@ const escrowClient = await EscrowClient.build(signer); const oracleAddress = await escrowClient.getExchangeOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); ``` -#### Source +#### Defined in -[escrow.ts:1320](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1320) +[escrow.ts:1320](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1320) *** @@ -705,9 +673,9 @@ const escrowClient = await EscrowClient.build(signer); const factoryAddress = await escrowClient.getFactoryAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); ``` -#### Source +#### Defined in -[escrow.ts:1358](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1358) +[escrow.ts:1358](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1358) *** @@ -743,9 +711,9 @@ const escrowClient = await EscrowClient.build(signer); const intemediateResultsUrl = await escrowClient.getIntermediateResultsUrl('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); ``` -#### Source +#### Defined in -[escrow.ts:1092](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1092) +[escrow.ts:1092](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1092) *** @@ -781,9 +749,9 @@ const escrowClient = await EscrowClient.build(signer); const jobLauncherAddress = await escrowClient.getJobLauncherAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); ``` -#### Source +#### Defined in -[escrow.ts:1244](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1244) +[escrow.ts:1244](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1244) *** @@ -819,9 +787,9 @@ const escrowClient = await EscrowClient.build(signer); const manifestHash = await escrowClient.getManifestHash('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); ``` -#### Source +#### Defined in -[escrow.ts:978](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L978) +[escrow.ts:978](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L978) *** @@ -857,9 +825,9 @@ const escrowClient = await EscrowClient.build(signer); const manifestUrl = await escrowClient.getManifestUrl('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); ``` -#### Source +#### Defined in -[escrow.ts:1016](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1016) +[escrow.ts:1016](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1016) *** @@ -895,9 +863,9 @@ const escrowClient = await EscrowClient.build(signer); const oracleAddress = await escrowClient.getRecordingOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); ``` -#### Source +#### Defined in -[escrow.ts:1206](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1206) +[escrow.ts:1206](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1206) *** @@ -933,9 +901,9 @@ const escrowClient = await EscrowClient.build(signer); const oracleAddress = await escrowClient.getReputationOracleAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); ``` -#### Source +#### Defined in -[escrow.ts:1282](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1282) +[escrow.ts:1282](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1282) *** @@ -971,9 +939,9 @@ const escrowClient = await EscrowClient.build(signer); const resultsUrl = await escrowClient.getResultsUrl('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); ``` -#### Source +#### Defined in -[escrow.ts:1054](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1054) +[escrow.ts:1054](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1054) *** @@ -1009,9 +977,9 @@ const escrowClient = await EscrowClient.build(signer); const status = await escrowClient.getStatus('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); ``` -#### Source +#### Defined in -[escrow.ts:1168](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1168) +[escrow.ts:1168](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1168) *** @@ -1047,9 +1015,9 @@ const escrowClient = await EscrowClient.build(signer); const tokenAddress = await escrowClient.getTokenAddress('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); ``` -#### Source +#### Defined in -[escrow.ts:1130](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1130) +[escrow.ts:1130](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1130) *** @@ -1069,7 +1037,7 @@ Address of the escrow to set up. Escrow configuration parameters. -• **txOptions?**: `Overrides`= `{}` +• **txOptions?**: `Overrides` = `{}` Additional transaction parameters (optional, defaults to an empty object). @@ -1108,9 +1076,9 @@ const escrowConfig = { await escrowClient.setup(escrowAddress, escrowConfig); ``` -#### Source +#### Defined in -[escrow.ts:290](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L290) +[escrow.ts:290](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L290) *** @@ -1134,7 +1102,7 @@ Results file url. Results file hash. -• **txOptions?**: `Overrides`= `{}` +• **txOptions?**: `Overrides` = `{}` Additional transaction parameters (optional, defaults to an empty object). @@ -1162,9 +1130,9 @@ const escrowClient = await EscrowClient.build(signer); await storeResults.storeResults('0x62dD51230A30401C455c8398d06F85e4EaB6309f', 'http://localhost/results.json', 'b5dad76bf6772c0f07fd5e048f6e75a5f86ee079'); ``` -#### Source +#### Defined in -[escrow.ts:528](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L528) +[escrow.ts:528](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L528) *** @@ -1194,6 +1162,6 @@ Thrown if the provider does not exist for the provided Signer Thrown if the network's chainId is not supported -#### Source +#### Defined in -[escrow.ts:147](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L147) +[escrow.ts:147](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L147) diff --git a/docs/sdk/typescript/escrow/classes/EscrowUtils.md b/docs/sdk/typescript/escrow/classes/EscrowUtils.md index 78c2fbba34..e149999dc7 100644 --- a/docs/sdk/typescript/escrow/classes/EscrowUtils.md +++ b/docs/sdk/typescript/escrow/classes/EscrowUtils.md @@ -130,9 +130,9 @@ import { ChainId, EscrowUtils } from '@human-protocol/sdk'; const escrowData = new EscrowUtils.getEscrow(ChainId.POLYGON_AMOY, "0x1234567890123456789012345678901234567890"); ``` -#### Source +#### Defined in -[escrow.ts:1646](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1646) +[escrow.ts:1646](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1646) *** @@ -254,9 +254,9 @@ const filters: IEscrowsFilter = { const escrowDatas = await EscrowUtils.getEscrows(filters); ``` -#### Source +#### Defined in -[escrow.ts:1517](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1517) +[escrow.ts:1517](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1517) *** @@ -367,6 +367,6 @@ import { ChainId, EscrowUtils, EscrowStatus } from '@human-protocol/sdk'; })(); ``` -#### Source +#### Defined in -[escrow.ts:1744](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1744) +[escrow.ts:1744](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1744) diff --git a/docs/sdk/typescript/kvstore/classes/KVStoreClient.md b/docs/sdk/typescript/kvstore/classes/KVStoreClient.md index b15b12abe1..d01ec370f4 100644 --- a/docs/sdk/typescript/kvstore/classes/KVStoreClient.md +++ b/docs/sdk/typescript/kvstore/classes/KVStoreClient.md @@ -102,22 +102,12 @@ The Runner object to interact with the Ethereum network [`BaseEthersClient`](../../base/classes/BaseEthersClient.md).[`constructor`](../../base/classes/BaseEthersClient.md#constructors) -#### Source +#### Defined in -[kvstore.ts:104](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L104) +[kvstore.ts:104](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L104) ## Properties -### contract - -> `private` **contract**: `KVStore` - -#### Source - -[kvstore.ts:96](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L96) - -*** - ### networkData > **networkData**: `NetworkData` @@ -126,9 +116,9 @@ The Runner object to interact with the Ethereum network [`BaseEthersClient`](../../base/classes/BaseEthersClient.md).[`networkData`](../../base/classes/BaseEthersClient.md#networkdata) -#### Source +#### Defined in -[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) +[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) *** @@ -140,9 +130,9 @@ The Runner object to interact with the Ethereum network [`BaseEthersClient`](../../base/classes/BaseEthersClient.md).[`runner`](../../base/classes/BaseEthersClient.md#runner) -#### Source +#### Defined in -[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) +[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) ## Methods @@ -184,9 +174,9 @@ const kvstoreClient = await KVStoreClient.build(provider); const value = await kvstoreClient.get('0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', 'Role'); ``` -#### Source +#### Defined in -[kvstore.ts:305](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L305) +[kvstore.ts:305](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L305) *** @@ -202,7 +192,7 @@ Gets the URL value of the given entity, and verify its hash. Address from which to get the URL value. -• **urlKey**: `string`= `'url'` +• **urlKey**: `string` = `'url'` Configurable URL key. `url` by default. @@ -230,9 +220,9 @@ const linkedinUrl = await kvstoreClient.getFileUrlAndVerifyHash( ); ``` -#### Source +#### Defined in -[kvstore.ts:344](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L344) +[kvstore.ts:344](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L344) *** @@ -268,9 +258,9 @@ const kvstoreClient = await KVStoreClient.build(provider); const publicKey = await kvstoreClient.getPublicKey('0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266'); ``` -#### Source +#### Defined in -[kvstore.ts:402](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L402) +[kvstore.ts:402](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L402) *** @@ -290,7 +280,7 @@ Key of the key-value pair Value of the key-value pair -• **txOptions?**: `Overrides`= `{}` +• **txOptions?**: `Overrides` = `{}` Additional transaction parameters (optional, defaults to an empty object). @@ -318,9 +308,9 @@ const kvstoreClient = await KVStoreClient.build(signer); await kvstoreClient.set('Role', 'RecordingOracle'); ``` -#### Source +#### Defined in -[kvstore.ts:167](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L167) +[kvstore.ts:167](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L167) *** @@ -340,7 +330,7 @@ Array of keys (keys and value must have the same order) Array of values -• **txOptions?**: `Overrides`= `{}` +• **txOptions?**: `Overrides` = `{}` Additional transaction parameters (optional, defaults to an empty object). @@ -370,9 +360,9 @@ const values = ['RecordingOracle', 'http://localhost']; await kvstoreClient.set(keys, values); ``` -#### Source +#### Defined in -[kvstore.ts:210](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L210) +[kvstore.ts:210](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L210) *** @@ -388,11 +378,11 @@ Sets a URL value for the address that submits the transaction, and its hash. URL to set -• **urlKey**: `string`= `'url'` +• **urlKey**: `string` = `'url'` Configurable URL key. `url` by default. -• **txOptions?**: `Overrides`= `{}` +• **txOptions?**: `Overrides` = `{}` Additional transaction parameters (optional, defaults to an empty object). @@ -419,9 +409,9 @@ await kvstoreClient.setFileUrlAndHash('example.com'); await kvstoreClient.setFileUrlAndHash('linkedin.com/example', 'linkedin_url); ``` -#### Source +#### Defined in -[kvstore.ts:253](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L253) +[kvstore.ts:253](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L253) *** @@ -451,6 +441,6 @@ The Runner object to interact with the Ethereum network - Thrown if the network's chainId is not supported -#### Source +#### Defined in -[kvstore.ts:122](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L122) +[kvstore.ts:122](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L122) diff --git a/docs/sdk/typescript/kvstore/classes/KVStoreUtils.md b/docs/sdk/typescript/kvstore/classes/KVStoreUtils.md index d661271870..eb2001fb35 100644 --- a/docs/sdk/typescript/kvstore/classes/KVStoreUtils.md +++ b/docs/sdk/typescript/kvstore/classes/KVStoreUtils.md @@ -111,6 +111,6 @@ const kvStoreData = await KVStoreUtils.getKVStoreData(ChainId.POLYGON_AMOY, "0x1 console.log(kvStoreData); ``` -#### Source +#### Defined in -[kvstore.ts:498](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L498) +[kvstore.ts:498](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L498) diff --git a/docs/sdk/typescript/operator/classes/OperatorUtils.md b/docs/sdk/typescript/operator/classes/OperatorUtils.md index 2642d0f701..52927dc211 100644 --- a/docs/sdk/typescript/operator/classes/OperatorUtils.md +++ b/docs/sdk/typescript/operator/classes/OperatorUtils.md @@ -46,9 +46,9 @@ import { OperatorUtils, ChainId } from '@human-protocol/sdk'; const leader = await OperatorUtils.getLeader(ChainId.POLYGON_AMOY, '0x62dD51230A30401C455c8398d06F85e4EaB6309f'); ``` -#### Source +#### Defined in -[operator.ts:44](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L44) +[operator.ts:44](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L44) *** @@ -81,9 +81,9 @@ const filter: ILeadersFilter = { const leaders = await OperatorUtils.getLeaders(filter); ``` -#### Source +#### Defined in -[operator.ts:99](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L99) +[operator.ts:99](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L99) *** @@ -119,9 +119,9 @@ import { OperatorUtils, ChainId } from '@human-protocol/sdk'; const operators = await OperatorUtils.getReputationNetworkOperators(ChainId.POLYGON_AMOY, '0x62dD51230A30401C455c8398d06F85e4EaB6309f'); ``` -#### Source +#### Defined in -[operator.ts:155](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L155) +[operator.ts:151](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L151) *** @@ -153,6 +153,6 @@ import { OperatorUtils, ChainId } from '@human-protocol/sdk'; const rewards = await OperatorUtils.getRewards(ChainId.POLYGON_AMOY, '0x62dD51230A30401C455c8398d06F85e4EaB6309f'); ``` -#### Source +#### Defined in -[operator.ts:207](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L207) +[operator.ts:199](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L199) diff --git a/docs/sdk/typescript/staking/classes/StakingClient.md b/docs/sdk/typescript/staking/classes/StakingClient.md index 6d0b08f9f7..3180e7b1d1 100644 --- a/docs/sdk/typescript/staking/classes/StakingClient.md +++ b/docs/sdk/typescript/staking/classes/StakingClient.md @@ -102,9 +102,9 @@ The Runner object to interact with the Ethereum network [`BaseEthersClient`](../../base/classes/BaseEthersClient.md).[`constructor`](../../base/classes/BaseEthersClient.md#constructors) -#### Source +#### Defined in -[staking.ts:111](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L111) +[staking.ts:111](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L111) ## Properties @@ -112,9 +112,9 @@ The Runner object to interact with the Ethereum network > **escrowFactoryContract**: `EscrowFactory` -#### Source +#### Defined in -[staking.ts:102](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L102) +[staking.ts:102](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L102) *** @@ -126,9 +126,9 @@ The Runner object to interact with the Ethereum network [`BaseEthersClient`](../../base/classes/BaseEthersClient.md).[`networkData`](../../base/classes/BaseEthersClient.md#networkdata) -#### Source +#### Defined in -[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) +[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) *** @@ -136,9 +136,9 @@ The Runner object to interact with the Ethereum network > **rewardPoolContract**: `RewardPool` -#### Source +#### Defined in -[staking.ts:103](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L103) +[staking.ts:103](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L103) *** @@ -150,9 +150,9 @@ The Runner object to interact with the Ethereum network [`BaseEthersClient`](../../base/classes/BaseEthersClient.md).[`runner`](../../base/classes/BaseEthersClient.md#runner) -#### Source +#### Defined in -[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) +[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) *** @@ -160,9 +160,9 @@ The Runner object to interact with the Ethereum network > **stakingContract**: `Staking` -#### Source +#### Defined in -[staking.ts:101](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L101) +[staking.ts:101](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L101) *** @@ -170,9 +170,9 @@ The Runner object to interact with the Ethereum network > **tokenContract**: `HMToken` -#### Source +#### Defined in -[staking.ts:100](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L100) +[staking.ts:100](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L100) ## Methods @@ -194,7 +194,7 @@ Address of the escrow contract to allocate in. Amount in WEI of tokens to allocate. -• **txOptions?**: `Overrides`= `{}` +• **txOptions?**: `Overrides` = `{}` Additional transaction parameters (optional, defaults to an empty object). @@ -221,9 +221,9 @@ const amount = ethers.parseUnits(5, 'ether'); //convert from ETH to WEI await stakingClient.allocate('0x62dD51230A30401C455c8398d06F85e4EaB6309f', amount); ``` -#### Source +#### Defined in -[staking.ts:458](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L458) +[staking.ts:458](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L458) *** @@ -239,7 +239,7 @@ This function approves the staking contract to transfer a specified amount of to Amount in WEI of tokens to approve for stake. -• **txOptions?**: `Overrides`= `{}` +• **txOptions?**: `Overrides` = `{}` Additional transaction parameters (optional, defaults to an empty object). @@ -266,31 +266,9 @@ const amount = ethers.parseUnits(5, 'ether'); //convert from ETH to WEI await stakingClient.approveStake(amount); ``` -#### Source +#### Defined in -[staking.ts:203](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L203) - -*** - -### checkValidEscrow() - -> `private` **checkValidEscrow**(`escrowAddress`): `Promise`\<`void`\> - -Check if escrow exists - -#### Parameters - -• **escrowAddress**: `string` - -Escrow address to check against - -#### Returns - -`Promise`\<`void`\> - -#### Source - -[staking.ts:167](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L167) +[staking.ts:203](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L203) *** @@ -309,7 +287,7 @@ This function drops the allocation from a specific escrow. Address of the escrow contract to close allocation from. -• **txOptions?**: `Overrides`= `{}` +• **txOptions?**: `Overrides` = `{}` Additional transaction parameters (optional, defaults to an empty object). @@ -335,9 +313,9 @@ const stakingClient = await StakingClient.build(signer); await stakingClient.closeAllocation('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); ``` -#### Source +#### Defined in -[staking.ts:511](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L511) +[staking.ts:511](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L511) *** @@ -355,7 +333,7 @@ This function drops the allocation from a specific escrow. Escrow address from which rewards are distributed. -• **txOptions?**: `Overrides`= `{}` +• **txOptions?**: `Overrides` = `{}` Additional transaction parameters (optional, defaults to an empty object). @@ -381,9 +359,9 @@ const stakingClient = await StakingClient.build(signer); await stakingClient.distributeReward('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); ``` -#### Source +#### Defined in -[staking.ts:554](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L554) +[staking.ts:554](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L554) *** @@ -419,9 +397,9 @@ const stakingClient = await StakingClient.build(provider); const allocationInfo = await stakingClient.getAllocation('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); ``` -#### Source +#### Defined in -[staking.ts:591](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L591) +[staking.ts:591](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L591) *** @@ -449,7 +427,7 @@ Address of the escrow which allocation will be slashed Amount in WEI of tokens to unstake. -• **txOptions?**: `Overrides`= `{}` +• **txOptions?**: `Overrides` = `{}` Additional transaction parameters (optional, defaults to an empty object). @@ -476,9 +454,9 @@ const amount = ethers.parseUnits(5, 'ether'); //convert from ETH to WEI await stakingClient.slash('0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', '0x62dD51230A30401C455c8398d06F85e4EaB6309f', amount); ``` -#### Source +#### Defined in -[staking.ts:387](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L387) +[staking.ts:387](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L387) *** @@ -496,7 +474,7 @@ This function stakes a specified amount of tokens on a specific network. Amount in WEI of tokens to stake. -• **txOptions?**: `Overrides`= `{}` +• **txOptions?**: `Overrides` = `{}` Additional transaction parameters (optional, defaults to an empty object). @@ -524,9 +502,9 @@ await stakingClient.approveStake(amount); // if it was already approved before, await stakingClient.approveStake(amount); ``` -#### Source +#### Defined in -[staking.ts:258](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L258) +[staking.ts:258](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L258) *** @@ -544,7 +522,7 @@ This function unstakes tokens from staking contract. The unstaked tokens stay lo Amount in WEI of tokens to unstake. -• **txOptions?**: `Overrides`= `{}` +• **txOptions?**: `Overrides` = `{}` Additional transaction parameters (optional, defaults to an empty object). @@ -571,9 +549,9 @@ const amount = ethers.parseUnits(5, 'ether'); //convert from ETH to WEI await stakingClient.unstake(amount); ``` -#### Source +#### Defined in -[staking.ts:303](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L303) +[staking.ts:303](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L303) *** @@ -587,7 +565,7 @@ This function withdraws unstaked and non locked tokens form staking contract to #### Parameters -• **txOptions?**: `Overrides`= `{}` +• **txOptions?**: `Overrides` = `{}` Additional transaction parameters (optional, defaults to an empty object). @@ -613,9 +591,9 @@ const stakingClient = await StakingClient.build(signer); await stakingClient.withdraw(); ``` -#### Source +#### Defined in -[staking.ts:349](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L349) +[staking.ts:349](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L349) *** @@ -645,6 +623,6 @@ The Runner object to interact with the Ethereum network - Thrown if the network's chainId is not supported -#### Source +#### Defined in -[staking.ts:145](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L145) +[staking.ts:145](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L145) diff --git a/docs/sdk/typescript/statistics/classes/StatisticsClient.md b/docs/sdk/typescript/statistics/classes/StatisticsClient.md index fd19426ace..3638e58006 100644 --- a/docs/sdk/typescript/statistics/classes/StatisticsClient.md +++ b/docs/sdk/typescript/statistics/classes/StatisticsClient.md @@ -60,9 +60,9 @@ The network information required to connect to the Statistics contract [`StatisticsClient`](StatisticsClient.md) -#### Source +#### Defined in -[statistics.ts:70](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L70) +[statistics.ts:70](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L70) ## Properties @@ -70,9 +70,9 @@ The network information required to connect to the Statistics contract > **networkData**: `NetworkData` -#### Source +#### Defined in -[statistics.ts:62](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L62) +[statistics.ts:62](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L62) *** @@ -80,9 +80,9 @@ The network information required to connect to the Statistics contract > **subgraphUrl**: `string` -#### Source +#### Defined in -[statistics.ts:63](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L63) +[statistics.ts:63](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L63) ## Methods @@ -120,7 +120,7 @@ type EscrowStatistics = { #### Parameters -• **params**: `IStatisticsParams`= `{}` +• **params**: `IStatisticsParams` = `{}` Statistics params with duration data @@ -144,9 +144,9 @@ const escrowStatisticsApril = await statisticsClient.getEscrowStatistics({ }); ``` -#### Source +#### Defined in -[statistics.ts:124](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L124) +[statistics.ts:124](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L124) *** @@ -160,7 +160,7 @@ This function returns the holders of the HMToken with optional filters and order #### Parameters -• **params**: `IHMTHoldersParams`= `{}` +• **params**: `IHMTHoldersParams` = `{}` HMT Holders params with filters and ordering @@ -178,7 +178,6 @@ import { StatisticsClient, ChainId, NETWORKS } from '@human-protocol/sdk'; const statisticsClient = new StatisticsClient(NETWORKS[ChainId.POLYGON_AMOY]); const hmtHolders = await statisticsClient.getHMTHolders({ - orderBy: 'balance', orderDirection: 'asc', }); @@ -188,9 +187,9 @@ console.log('HMT holders:', hmtHolders.map((h) => ({ }))); ``` -#### Source +#### Defined in -[statistics.ts:467](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L467) +[statistics.ts:466](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L466) *** @@ -233,7 +232,7 @@ type HMTStatistics = { #### Parameters -• **params**: `IStatisticsParams`= `{}` +• **params**: `IStatisticsParams` = `{}` Statistics params with duration data @@ -284,9 +283,9 @@ console.log('HMT statistics from 5/8 - 6/8:', { }); ``` -#### Source +#### Defined in -[statistics.ts:397](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L397) +[statistics.ts:397](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L397) *** @@ -321,7 +320,7 @@ type PaymentStatistics = { #### Parameters -• **params**: `IStatisticsParams`= `{}` +• **params**: `IStatisticsParams` = `{}` Statistics params with duration data @@ -366,9 +365,9 @@ console.log( ); ``` -#### Source +#### Defined in -[statistics.ts:288](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L288) +[statistics.ts:288](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L288) *** @@ -401,7 +400,7 @@ type WorkerStatistics = { #### Parameters -• **params**: `IStatisticsParams`= `{}` +• **params**: `IStatisticsParams` = `{}` Statistics params with duration data @@ -425,6 +424,6 @@ const workerStatisticsApril = await statisticsClient.getWorkerStatistics({ }); ``` -#### Source +#### Defined in -[statistics.ts:199](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L199) +[statistics.ts:199](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L199) diff --git a/docs/sdk/typescript/storage/classes/StorageClient.md b/docs/sdk/typescript/storage/classes/StorageClient.md index fc5aed6769..d08fddf1ed 100644 --- a/docs/sdk/typescript/storage/classes/StorageClient.md +++ b/docs/sdk/typescript/storage/classes/StorageClient.md @@ -75,29 +75,9 @@ Optional. Cloud storage access data. If credentials is not provided - use an ano [`StorageClient`](StorageClient.md) -#### Source +#### Defined in -[storage.ts:73](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L73) - -## Properties - -### ~~client~~ - -> `private` **client**: `Client` - -#### Source - -[storage.ts:64](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L64) - -*** - -### ~~clientParams~~ - -> `private` **clientParams**: `StorageParams` - -#### Source - -[storage.ts:65](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L65) +[storage.ts:73](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L73) ## Methods @@ -139,9 +119,9 @@ const storageClient = new StorageClient(params, credentials); const exists = await storageClient.bucketExists('bucket-name'); ``` -#### Source +#### Defined in -[storage.ts:266](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L266) +[storage.ts:266](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L266) *** @@ -185,9 +165,9 @@ const keys = ['file1.json', 'file2.json']; const files = await storageClient.downloadFiles(keys, 'bucket-name'); ``` -#### Source +#### Defined in -[storage.ts:113](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L113) +[storage.ts:113](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L113) *** @@ -229,9 +209,9 @@ const storageClient = new StorageClient(params, credentials); const fileNames = await storageClient.listObjects('bucket-name'); ``` -#### Source +#### Defined in -[storage.ts:297](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L297) +[storage.ts:297](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L297) *** @@ -280,9 +260,9 @@ const files = [file1, file2]; const uploadedFiles = await storageClient.uploadFiles(files, 'bucket-name'); ``` -#### Source +#### Defined in -[storage.ts:201](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L201) +[storage.ts:201](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L201) *** @@ -312,6 +292,6 @@ import { StorageClient } from '@human-protocol/sdk'; const file = await storageClient.downloadFileFromUrl('http://localhost/file.json'); ``` -#### Source +#### Defined in -[storage.ts:148](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L148) +[storage.ts:148](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L148) diff --git a/docs/sdk/typescript/transaction/classes/TransactionUtils.md b/docs/sdk/typescript/transaction/classes/TransactionUtils.md index 0fa5af6f42..c78b72f6bf 100644 --- a/docs/sdk/typescript/transaction/classes/TransactionUtils.md +++ b/docs/sdk/typescript/transaction/classes/TransactionUtils.md @@ -48,9 +48,9 @@ import { TransactionUtils, ChainId } from '@human-protocol/sdk'; const transaction = await TransactionUtils.getTransaction(ChainId.POLYGON, '0x62dD51230A30401C455c8398d06F85e4EaB6309f'); ``` -#### Source +#### Defined in -[transaction.ts:34](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts#L34) +[transaction.ts:34](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts#L34) *** @@ -119,6 +119,6 @@ const filter: ITransactionsFilter = { const transactions = await TransactionUtils.getTransactions(filter); ``` -#### Source +#### Defined in -[transaction.ts:109](https://github.com/humanprotocol/human-protocol/blob/8d975cea1abbae7bc4c000b3bf81cca8faa7415f/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts#L109) +[transaction.ts:109](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts#L109) 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 d8c2f74a98..24c438f567 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 @@ -38,7 +38,7 @@ def __init__( self, chain_id: ChainId, block: int, - hash: str, + tx_hash: str, from_address: str, to_address: str, timestamp: int, @@ -47,7 +47,7 @@ def __init__( ): self.chain_id = chain_id self.block = block - self.hash = hash + self.tx_hash = tx_hash self.from_address = from_address self.to_address = to_address self.timestamp = timestamp @@ -109,7 +109,7 @@ def get_transaction(chain_id: ChainId, hash: str) -> Optional[TransactionData]: return TransactionData( chain_id=chain_id, block=transaction.get("block", 0), - hash=transaction.get("txHash", ""), + tx_hash=transaction.get("txHash", ""), from_address=transaction.get("from", ""), to_address=transaction.get("to", ""), timestamp=transaction.get("timestamp", 0), @@ -181,7 +181,7 @@ def get_transactions(filter: TransactionFilter) -> List[TransactionData]: TransactionData( chain_id=filter.chain_id, block=transaction.get("block", 0), - hash=transaction.get("txHash", ""), + tx_hash=transaction.get("txHash", ""), from_address=transaction.get("from", ""), to_address=transaction.get("to", ""), timestamp=transaction.get("timestamp", 0), diff --git a/packages/sdk/python/human-protocol-sdk/test/human_protocol_sdk/transaction/test_transaction_utils.py b/packages/sdk/python/human-protocol-sdk/test/human_protocol_sdk/transaction/test_transaction_utils.py index 3ada0c488a..5b69d5b463 100644 --- a/packages/sdk/python/human-protocol-sdk/test/human_protocol_sdk/transaction/test_transaction_utils.py +++ b/packages/sdk/python/human-protocol-sdk/test/human_protocol_sdk/transaction/test_transaction_utils.py @@ -155,7 +155,7 @@ def test_get_transaction(self): self.assertIsNotNone(transaction) self.assertEqual(transaction.chain_id, ChainId.POLYGON_AMOY) self.assertEqual(transaction.block, mock_transaction["block"]) - self.assertEqual(transaction.hash, mock_transaction["txHash"]) + self.assertEqual(transaction.tx_hash, mock_transaction["txHash"]) self.assertEqual(transaction.from_address, mock_transaction["from"]) self.assertEqual(transaction.to_address, mock_transaction["to"]) self.assertEqual(transaction.timestamp, mock_transaction["timestamp"]) diff --git a/packages/sdk/typescript/human-protocol-sdk/package.json b/packages/sdk/typescript/human-protocol-sdk/package.json index f4354f71b9..9548e02b30 100644 --- a/packages/sdk/typescript/human-protocol-sdk/package.json +++ b/packages/sdk/typescript/human-protocol-sdk/package.json @@ -52,8 +52,8 @@ "winston": "^3.13.0" }, "devDependencies": { - "typedoc": "^0.25.1", - "typedoc-plugin-markdown": "^4.0.3" + "typedoc": "^0.26.5", + "typedoc-plugin-markdown": "^4.2.3" }, "typedocOptions": { "entryPoints": [ diff --git a/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts b/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts index 778cb99ad3..e4b8bac0fc 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts @@ -121,7 +121,7 @@ export interface IKVStore { export interface ITransaction { block: bigint; - hash: string; + txHash: string; from: string; to: string; timestamp: bigint; diff --git a/yarn.lock b/yarn.lock index b1afca71e1..570ea91c34 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5400,6 +5400,13 @@ "@sentry/types" "6.19.7" tslib "^1.9.3" +"@shikijs/core@1.12.0": + version "1.12.0" + resolved "https://registry.yarnpkg.com/@shikijs/core/-/core-1.12.0.tgz#58ae6d02da7934edd9c10951a989c9cde0cf736b" + integrity sha512-mc1cLbm6UQ8RxLc0dZES7v5rkH+99LxQp/ZvTqV3NLyYsO/fD6JhEflP1H5b2SDq9gI0+0G36AVZWxvounfR9w== + dependencies: + "@types/hast" "^3.0.4" + "@sideway/address@^4.1.5": version "4.1.5" resolved "https://registry.yarnpkg.com/@sideway/address/-/address-4.1.5.tgz#4bc149a0076623ced99ca8208ba780d65a99b9d5" @@ -6927,6 +6934,13 @@ dependencies: "@types/node" "*" +"@types/hast@^3.0.4": + version "3.0.4" + resolved "https://registry.yarnpkg.com/@types/hast/-/hast-3.0.4.tgz#1d6b39993b82cea6ad783945b0508c25903e15aa" + integrity sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ== + dependencies: + "@types/unist" "*" + "@types/history@^4.7.11": version "4.7.11" resolved "https://registry.yarnpkg.com/@types/history/-/history-4.7.11.tgz#56588b17ae8f50c53983a524fc3cc47437969d64" @@ -7378,6 +7392,11 @@ resolved "https://registry.yarnpkg.com/@types/trusted-types/-/trusted-types-2.0.7.tgz#baccb07a970b91707df3a3e8ba6896c57ead2d11" integrity sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw== +"@types/unist@*": + version "3.0.2" + resolved "https://registry.yarnpkg.com/@types/unist/-/unist-3.0.2.tgz#6dd61e43ef60b34086287f83683a5c1b2dc53d20" + integrity sha512-dqId9J8K/vGi5Zr7oo212BGii5m3q5Hxlkwy3WpYuKPklmBEvsbMYYyLxAQpSffdLl/gdW0XUpKWFvYmyoWCoQ== + "@types/use-sync-external-store@^0.0.3": version "0.0.3" resolved "https://registry.yarnpkg.com/@types/use-sync-external-store/-/use-sync-external-store-0.0.3.tgz#b6725d5f4af24ace33b36fafd295136e75509f43" @@ -9040,11 +9059,6 @@ ansi-regex@^6.0.1: resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-6.0.1.tgz#3183e38fae9a65d7cb5e53945cd5897d0260a06a" integrity sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA== -ansi-sequence-parser@^1.1.0: - version "1.1.1" - resolved "https://registry.yarnpkg.com/ansi-sequence-parser/-/ansi-sequence-parser-1.1.1.tgz#e0aa1cdcbc8f8bb0b5bca625aac41f5f056973cf" - integrity sha512-vJXt3yiaUL4UU546s3rPXlsry/RnM730G1+HkpKE012AN0sx1eOrxSu95oKDIonskeLTijMgqWZ3uDEe3NFvyg== - ansi-styles@^2.2.1: version "2.2.1" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-2.2.1.tgz#b432dd3358b634cf75e1e4664368240533c1ddbe" @@ -17610,7 +17624,7 @@ jsonc-parser@3.2.1: resolved "https://registry.yarnpkg.com/jsonc-parser/-/jsonc-parser-3.2.1.tgz#031904571ccf929d7670ee8c547545081cb37f1a" integrity sha512-AilxAyFOAcK5wA1+LeaySVBrHsGQvUFCDWXKpZjzaL0PqW+xfBOttn8GNtWKFWqneyMZj41MWF9Kl6iPWLwgOA== -jsonc-parser@3.3.1, jsonc-parser@^3.2.0: +jsonc-parser@3.3.1: version "3.3.1" resolved "https://registry.yarnpkg.com/jsonc-parser/-/jsonc-parser-3.3.1.tgz#f2a524b4f7fd11e3d791e559977ad60b98b798b4" integrity sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ== @@ -18083,6 +18097,13 @@ linkify-it@^3.0.1: dependencies: uc.micro "^1.0.1" +linkify-it@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/linkify-it/-/linkify-it-5.0.0.tgz#9ef238bfa6dc70bd8e7f9572b52d369af569b421" + integrity sha512-5aHCbzQRADcdP+ATqnDuhhJ/MRIqDkZX5pyjFHRRysS8vZ5AbqGEoFIb6pYHPZ+L/OC2Lc+xT8uHVVR5CAK/wQ== + dependencies: + uc.micro "^2.0.0" + lint-staged@^15.2.1, lint-staged@^15.2.7: version "15.2.7" resolved "https://registry.yarnpkg.com/lint-staged/-/lint-staged-15.2.7.tgz#97867e29ed632820c0fb90be06cd9ed384025649" @@ -18690,6 +18711,18 @@ markdown-it@^12.3.2: mdurl "^1.0.1" uc.micro "^1.0.5" +markdown-it@^14.1.0: + version "14.1.0" + resolved "https://registry.yarnpkg.com/markdown-it/-/markdown-it-14.1.0.tgz#3c3c5992883c633db4714ccb4d7b5935d98b7d45" + integrity sha512-a54IwgWPaeBCAAsv13YgmALOF1elABB08FxO9i+r4VFk5Vl4pKokRPeX8u5TCgSsPi6ec1otfLjdOpVcgbpshg== + dependencies: + argparse "^2.0.1" + entities "^4.4.0" + linkify-it "^5.0.0" + mdurl "^2.0.0" + punycode.js "^2.3.1" + uc.micro "^2.1.0" + markdown-table@2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/markdown-table/-/markdown-table-2.0.0.tgz#194a90ced26d31fe753d8b9434430214c011865b" @@ -18697,11 +18730,6 @@ markdown-table@2.0.0: dependencies: repeat-string "^1.0.0" -marked@^4.3.0: - version "4.3.0" - resolved "https://registry.yarnpkg.com/marked/-/marked-4.3.0.tgz#796362821b019f734054582038b116481b456cf3" - integrity sha512-PRsaiG84bK+AMvxziE/lCFss8juXjNaWzVbN5tXAm4XjeaS9NAHhop+PjQxz2A9h8Q4M/xGmzP8vqNwy6JeK0A== - match-all@^1.2.6: version "1.2.6" resolved "https://registry.yarnpkg.com/match-all/-/match-all-1.2.6.tgz#66d276ad6b49655551e63d3a6ee53e8be0566f8d" @@ -18746,6 +18774,11 @@ mdurl@^1.0.1: resolved "https://registry.yarnpkg.com/mdurl/-/mdurl-1.0.1.tgz#fe85b2ec75a59037f2adfec100fd6c601761152e" integrity sha512-/sKlQJCBYVY9Ers9hqzKou4H6V5UWc/M59TH2dvkt+84itfnq7uFOMLpOiOS4ujvHP4etln18fmIxA5R5fll0g== +mdurl@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/mdurl/-/mdurl-2.0.0.tgz#80676ec0433025dd3e17ee983d0fe8de5a2237e0" + integrity sha512-Lf+9+2r+Tdp5wXDXC4PcIBjTDtq4UKjCPMQhKIuzpJNW0b96kVqSwW0bT7FhRSfmAiFYgP+SCRvdrDozfh0U5w== + media-typer@0.3.0: version "0.3.0" resolved "https://registry.yarnpkg.com/media-typer/-/media-typer-0.3.0.tgz#8710d7af0aa626f8fffa1ce00168545263255748" @@ -18994,7 +19027,7 @@ minimatch@^8.0.2: dependencies: brace-expansion "^2.0.1" -minimatch@^9.0.3, minimatch@^9.0.4: +minimatch@^9.0.4, minimatch@^9.0.5: version "9.0.5" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-9.0.5.tgz#d74f9dd6b57d83d8e98cfb82133b03978bc929e5" integrity sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow== @@ -21113,6 +21146,11 @@ pump@^3.0.0: end-of-stream "^1.1.0" once "^1.3.1" +punycode.js@^2.3.1: + version "2.3.1" + resolved "https://registry.yarnpkg.com/punycode.js/-/punycode.js-2.3.1.tgz#6b53e56ad75588234e79f4affa90972c7dd8cdb7" + integrity sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA== + punycode@1.3.2: version "1.3.2" resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.3.2.tgz#9653a036fb7c1ee42342f2325cceefea3926c48d" @@ -22749,15 +22787,13 @@ shelljs@^0.8.3: interpret "^1.0.0" rechoir "^0.6.2" -shiki@^0.14.7: - version "0.14.7" - resolved "https://registry.yarnpkg.com/shiki/-/shiki-0.14.7.tgz#c3c9e1853e9737845f1d2ef81b31bcfb07056d4e" - integrity sha512-dNPAPrxSc87ua2sKJ3H5dQ/6ZaY8RNnaAqK+t0eG7p0Soi2ydiqbGOTaZCqaYvA/uZYfS1LJnemt3Q+mSfcPCg== +shiki@^1.9.1: + version "1.12.0" + resolved "https://registry.yarnpkg.com/shiki/-/shiki-1.12.0.tgz#fd4900442405760df5c5819b5baa3892ef9612d2" + integrity sha512-BuAxWOm5JhRcbSOl7XCei8wGjgJJonnV0oipUupPY58iULxUGyHhW5CF+9FRMuM1pcJ5cGEJGll1LusX6FwpPA== dependencies: - ansi-sequence-parser "^1.1.0" - jsonc-parser "^3.2.0" - vscode-oniguruma "^1.7.0" - vscode-textmate "^8.0.0" + "@shikijs/core" "1.12.0" + "@types/hast" "^3.0.4" side-channel@^1.0.4, side-channel@^1.0.6: version "1.0.6" @@ -23361,16 +23397,7 @@ string-natural-compare@^3.0.1: resolved "https://registry.yarnpkg.com/string-natural-compare/-/string-natural-compare-3.0.1.tgz#7a42d58474454963759e8e8b7ae63d71c1e7fdf4" integrity sha512-n3sPwynL1nwKi3WJ6AIsClwBMa0zTi54fn2oLU6ndfTSIO05xaznjSf15PcBZU6FNWbmN5Q6cxT4V5hGvB4taw== -"string-width-cjs@npm:string-width@^4.2.0": - version "4.2.3" - resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" - integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== - dependencies: - emoji-regex "^8.0.0" - is-fullwidth-code-point "^3.0.0" - strip-ansi "^6.0.1" - -"string-width@^1.0.2 || 2 || 3 || 4", string-width@^4.0.0, string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.2, string-width@^4.2.3: +"string-width-cjs@npm:string-width@^4.2.0", "string-width@^1.0.2 || 2 || 3 || 4", string-width@^4.0.0, string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.2, string-width@^4.2.3: version "4.2.3" resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== @@ -23478,7 +23505,7 @@ string_decoder@~1.1.1: dependencies: safe-buffer "~5.1.0" -"strip-ansi-cjs@npm:strip-ansi@^6.0.1": +"strip-ansi-cjs@npm:strip-ansi@^6.0.1", strip-ansi@^6.0.0, strip-ansi@^6.0.1: version "6.0.1" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== @@ -23499,13 +23526,6 @@ strip-ansi@^5.2.0: dependencies: ansi-regex "^4.1.0" -strip-ansi@^6.0.0, strip-ansi@^6.0.1: - version "6.0.1" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" - integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== - dependencies: - ansi-regex "^5.0.1" - strip-ansi@^7.0.1, strip-ansi@^7.1.0: version "7.1.0" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-7.1.0.tgz#d5b6568ca689d8561370b0707685d22434faff45" @@ -24590,20 +24610,21 @@ typedarray@^0.0.6: resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777" integrity sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA== -typedoc-plugin-markdown@^4.0.3: - version "4.2.1" - resolved "https://registry.yarnpkg.com/typedoc-plugin-markdown/-/typedoc-plugin-markdown-4.2.1.tgz#b32fddc246c5bfe7e4879834fc3f8b1486de7286" - integrity sha512-7hQt/1WaW/VI4+x3sxwcCGsEylP1E1GvF6OTTELK5sfTEp6AeK+83jkCOgZGp1pI2DiOammMYQMnxxOny9TKsQ== +typedoc-plugin-markdown@^4.2.3: + version "4.2.3" + resolved "https://registry.yarnpkg.com/typedoc-plugin-markdown/-/typedoc-plugin-markdown-4.2.3.tgz#653e12799adacc30136cc500d5e0078ad9b3ca6e" + integrity sha512-esucQj79SFYOv0f5XVha7QWdLUH5C5HRlDf7Z8CXzHedmVPn7jox6Gt7FdoBXN8AFxyHpa3Lbuxu65Dobwt+4Q== -typedoc@^0.25.1: - version "0.25.13" - resolved "https://registry.yarnpkg.com/typedoc/-/typedoc-0.25.13.tgz#9a98819e3b2d155a6d78589b46fa4c03768f0922" - integrity sha512-pQqiwiJ+Z4pigfOnnysObszLiU3mVLWAExSPf+Mu06G/qsc3wzbuM56SZQvONhHLncLUhYzOVkjFFpFfL5AzhQ== +typedoc@^0.26.5: + version "0.26.5" + resolved "https://registry.yarnpkg.com/typedoc/-/typedoc-0.26.5.tgz#08032bd57cac3d56e8ac296a07e3482dc0c645ac" + integrity sha512-Vn9YKdjKtDZqSk+by7beZ+xzkkr8T8CYoiasqyt4TTRFy5+UHzL/mF/o4wGBjRF+rlWQHDb0t6xCpA3JNL5phg== dependencies: lunr "^2.3.9" - marked "^4.3.0" - minimatch "^9.0.3" - shiki "^0.14.7" + markdown-it "^14.1.0" + minimatch "^9.0.5" + shiki "^1.9.1" + yaml "^2.4.5" typeorm-naming-strategies@^4.1.0: version "4.1.0" @@ -24666,6 +24687,11 @@ uc.micro@^1.0.1, uc.micro@^1.0.5: resolved "https://registry.yarnpkg.com/uc.micro/-/uc.micro-1.0.6.tgz#9c411a802a409a91fc6cf74081baba34b24499ac" integrity sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA== +uc.micro@^2.0.0, uc.micro@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/uc.micro/-/uc.micro-2.1.0.tgz#f8d3f7d0ec4c3dea35a7e3c8efa4cb8b45c9e7ee" + integrity sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A== + ufo@^1.4.0, ufo@^1.5.3: version "1.5.4" resolved "https://registry.yarnpkg.com/ufo/-/ufo-1.5.4.tgz#16d6949674ca0c9e0fbbae1fa20a71d7b1ded754" @@ -25246,16 +25272,6 @@ void-elements@3.1.0: resolved "https://registry.yarnpkg.com/void-elements/-/void-elements-3.1.0.tgz#614f7fbf8d801f0bb5f0661f5b2f5785750e4f09" integrity sha512-Dhxzh5HZuiHQhbvTW9AMetFfBHDMYpo23Uo9btPXgdYP+3T5S+p+jgNy7spra+veYhBP2dCSgxR/i2Y02h5/6w== -vscode-oniguruma@^1.7.0: - version "1.7.0" - resolved "https://registry.yarnpkg.com/vscode-oniguruma/-/vscode-oniguruma-1.7.0.tgz#439bfad8fe71abd7798338d1cd3dc53a8beea94b" - integrity sha512-L9WMGRfrjOhgHSdOYgCt/yRMsXzLDJSL7BPrOZt73gU0iWO4mpqzqQzOz5srxqTvMBaR0XZTSrVWo4j55Rc6cA== - -vscode-textmate@^8.0.0: - version "8.0.0" - resolved "https://registry.yarnpkg.com/vscode-textmate/-/vscode-textmate-8.0.0.tgz#2c7a3b1163ef0441097e0b5d6389cd5504b59e5d" - integrity sha512-AFbieoL7a5LMqcnOF04ji+rpXadgOXnZsxQr//r83kLPr7biP7am3g9zbaZIaBGwBRWeSvoMD4mgPdX3e4NWBg== - w3c-keyname@^2.2.4: version "2.2.8" resolved "https://registry.yarnpkg.com/w3c-keyname/-/w3c-keyname-2.2.8.tgz#7b17c8c6883d4e8b86ac8aba79d39e880f8869c5" @@ -25951,7 +25967,7 @@ workerpool@^6.5.1: resolved "https://registry.yarnpkg.com/workerpool/-/workerpool-6.5.1.tgz#060f73b39d0caf97c6db64da004cd01b4c099544" integrity sha512-Fs4dNYcsdpYSAfVxhnl1L5zTksjvOJxtC5hzMNl+1t9B8hTJTdKDyZ5ju7ztgPy+ft9tBFXoOlDNiOT9WUXZlA== -"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0": +"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0", wrap-ansi@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== @@ -25969,15 +25985,6 @@ wrap-ansi@^6.0.1, wrap-ansi@^6.2.0: string-width "^4.1.0" strip-ansi "^6.0.0" -wrap-ansi@^7.0.0: - version "7.0.0" - resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" - integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== - dependencies: - ansi-styles "^4.0.0" - string-width "^4.1.0" - strip-ansi "^6.0.0" - wrap-ansi@^8.0.1, wrap-ansi@^8.1.0: version "8.1.0" resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-8.1.0.tgz#56dc22368ee570face1b49819975d9b9a5ead214" @@ -26147,6 +26154,11 @@ yaml@1.10.2, yaml@^1.10.0, yaml@^1.10.2: resolved "https://registry.yarnpkg.com/yaml/-/yaml-1.10.2.tgz#2301c5ffbf12b467de8da2333a459e29e7920e4b" integrity sha512-r3vXyErRCYJ7wg28yvBY5VSoAF8ZvlcW9/BwUzEtUsjvX/DKs24dIkuwjtuprwJJHsbyUbLApepYTR1BN4uHrg== +yaml@^2.4.5: + version "2.5.0" + resolved "https://registry.yarnpkg.com/yaml/-/yaml-2.5.0.tgz#c6165a721cf8000e91c36490a41d7be25176cf5d" + integrity sha512-2wWLbGbYDiSqqIKoPjar3MPgB94ErzCtrNE1FdqGuaO0pi2JGjmE8aW8TDZwzU7vuxcGRdL/4gPQwQ7hD5AMSw== + yaml@~2.4.2: version "2.4.5" resolved "https://registry.yarnpkg.com/yaml/-/yaml-2.4.5.tgz#60630b206dd6d84df97003d33fc1ddf6296cca5e" From 47174ae1f70e2591b614cbd0337a38b5337feac6 Mon Sep 17 00:00:00 2001 From: portuu3 <61605646+portuu3@users.noreply.github.com> Date: Tue, 30 Jul 2024 11:04:28 +0200 Subject: [PATCH 10/89] fix dependency review (#2325) --- package.json | 3 ++- packages/apps/dashboard/admin/package.json | 3 ++- packages/apps/dashboard/admin/yarn.lock | 8 ++++---- yarn.lock | 8 ++++---- 4 files changed, 12 insertions(+), 10 deletions(-) diff --git a/package.json b/package.json index fa5898819b..9d98c0d6e8 100644 --- a/package.json +++ b/package.json @@ -54,6 +54,7 @@ "qrcode": "^1.5.0", "semver": "^7.5.2", "undici": "^6.11.1", - "ws": "^8.17.1" + "ws": "^8.17.1", + "fast-xml-parser": "4.4.1" } } diff --git a/packages/apps/dashboard/admin/package.json b/packages/apps/dashboard/admin/package.json index 59cd080607..312f3771bd 100644 --- a/packages/apps/dashboard/admin/package.json +++ b/packages/apps/dashboard/admin/package.json @@ -31,7 +31,8 @@ }, "resolutions": { "braces": "^3.0.3", - "tar": "^6.2.1" + "tar": "^6.2.1", + "fast-xml-parser": "4.4.1" }, "author": { "name": "HUMAN Protocol" diff --git a/packages/apps/dashboard/admin/yarn.lock b/packages/apps/dashboard/admin/yarn.lock index 4f2e45a93a..be51158d4c 100644 --- a/packages/apps/dashboard/admin/yarn.lock +++ b/packages/apps/dashboard/admin/yarn.lock @@ -5259,10 +5259,10 @@ fast-safe-stringify@2.1.1: resolved "https://registry.yarnpkg.com/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz#c406a83b6e70d9e35ce3b30a81141df30aeba884" integrity sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA== -fast-xml-parser@^4.2.2: - version "4.4.0" - resolved "https://registry.yarnpkg.com/fast-xml-parser/-/fast-xml-parser-4.4.0.tgz#341cc98de71e9ba9e651a67f41f1752d1441a501" - integrity sha512-kLY3jFlwIYwBNDojclKsNAC12sfD6NwW74QB2CoNGPvtVxjliYehVunB3HYyNi+n4Tt1dAcgwYvmKF/Z18flqg== +fast-xml-parser@4.4.1, fast-xml-parser@^4.2.2: + version "4.4.1" + resolved "https://registry.yarnpkg.com/fast-xml-parser/-/fast-xml-parser-4.4.1.tgz#86dbf3f18edf8739326447bcaac31b4ae7f6514f" + integrity sha512-xkjOecfnKGkSsOwtZ5Pz7Us/T6mrbPQrq0nh+aCO5V9nk5NLWmasAHumTKjiPJPWANe+kAZ84Jc8ooJkzZ88Sw== dependencies: strnum "^1.0.5" diff --git a/yarn.lock b/yarn.lock index 570ea91c34..39b62f6538 100644 --- a/yarn.lock +++ b/yarn.lock @@ -14055,10 +14055,10 @@ fast-url-parser@1.1.3, fast-url-parser@^1.1.3: dependencies: punycode "^1.3.2" -fast-xml-parser@^4.2.2: - version "4.4.0" - resolved "https://registry.yarnpkg.com/fast-xml-parser/-/fast-xml-parser-4.4.0.tgz#341cc98de71e9ba9e651a67f41f1752d1441a501" - integrity sha512-kLY3jFlwIYwBNDojclKsNAC12sfD6NwW74QB2CoNGPvtVxjliYehVunB3HYyNi+n4Tt1dAcgwYvmKF/Z18flqg== +fast-xml-parser@4.4.1, fast-xml-parser@^4.2.2: + version "4.4.1" + resolved "https://registry.yarnpkg.com/fast-xml-parser/-/fast-xml-parser-4.4.1.tgz#86dbf3f18edf8739326447bcaac31b4ae7f6514f" + integrity sha512-xkjOecfnKGkSsOwtZ5Pz7Us/T6mrbPQrq0nh+aCO5V9nk5NLWmasAHumTKjiPJPWANe+kAZ84Jc8ooJkzZ88Sw== dependencies: strnum "^1.0.5" From 8438a98d7921acb5ca2427e797f21d0e944c564e Mon Sep 17 00:00:00 2001 From: Dzeranov Date: Tue, 30 Jul 2024 16:29:48 +0300 Subject: [PATCH 11/89] [Dashboard][Server] Added `/stats/hcaptcha/daily` and `/stats/hcaptcha/general` endpoints (#2296) * Added `/stats/hcaptcha/daily` and `/stats/hcaptcha/general` endpoints * Undo `HmtPriceDto` changes --------- Co-authored-by: portuu3 --- packages/apps/dashboard/server/.env.example | 1 + packages/apps/dashboard/server/package.json | 1 + .../apps/dashboard/server/src/app.module.ts | 5 +- .../src/common/config/env-config.service.ts | 14 ++ .../src/common/config/redis-config.service.ts | 1 + .../src/common/pipes/date-validation.pipe.ts | 15 ++ .../server/src/modules/redis/redis.module.ts | 9 - .../server/src/modules/redis/redis.service.ts | 29 --- .../src/modules/stats/dto/hcaptcha.dto.ts | 28 +++ .../src/modules/stats/stats.controller.ts | 58 ++++- .../server/src/modules/stats/stats.module.ts | 3 +- .../server/src/modules/stats/stats.service.ts | 204 +++++++++++++++++- yarn.lock | 2 +- 13 files changed, 319 insertions(+), 51 deletions(-) create mode 100644 packages/apps/dashboard/server/src/common/pipes/date-validation.pipe.ts delete mode 100644 packages/apps/dashboard/server/src/modules/redis/redis.module.ts delete mode 100644 packages/apps/dashboard/server/src/modules/redis/redis.service.ts create mode 100644 packages/apps/dashboard/server/src/modules/stats/dto/hcaptcha.dto.ts diff --git a/packages/apps/dashboard/server/.env.example b/packages/apps/dashboard/server/.env.example index f92510100f..cdb5837200 100644 --- a/packages/apps/dashboard/server/.env.example +++ b/packages/apps/dashboard/server/.env.example @@ -10,6 +10,7 @@ HMT_PRICE_SOURCE= HMT_PRICE_SOURCE_API_KEY= HMT_PRICE_FROM= HMT_PRICE_TO= +HCAPTCHA_API_KEY= # Redis REDIS_HOST=localhost diff --git a/packages/apps/dashboard/server/package.json b/packages/apps/dashboard/server/package.json index 6449ed471b..f05cc6869d 100644 --- a/packages/apps/dashboard/server/package.json +++ b/packages/apps/dashboard/server/package.json @@ -24,6 +24,7 @@ "@nestjs/mapped-types": "*", "@nestjs/platform-express": "^10.3.10", "cache-manager-redis-store": "^3.0.1", + "dayjs": "^1.11.11", "reflect-metadata": "^0.2.2", "rxjs": "^7.2.0" }, diff --git a/packages/apps/dashboard/server/src/app.module.ts b/packages/apps/dashboard/server/src/app.module.ts index 11b9c393e9..bf04a74240 100644 --- a/packages/apps/dashboard/server/src/app.module.ts +++ b/packages/apps/dashboard/server/src/app.module.ts @@ -1,5 +1,6 @@ import { CacheModule } from '@nestjs/cache-manager'; import { ConfigModule } from '@nestjs/config'; +import { ScheduleModule } from '@nestjs/schedule'; import { Module } from '@nestjs/common'; import * as Joi from 'joi'; @@ -8,7 +9,6 @@ import { AppController } from './app.controller'; import { CacheFactoryConfig } from './common/config/cache-factory.config'; import { CommonConfigModule } from './common/config/config.module'; import { DetailsModule } from './modules/details/details.module'; -import { RedisModule } from './modules/redis/redis.module'; import { StatsModule } from './modules/stats/stats.module'; @Module({ @@ -22,12 +22,13 @@ import { StatsModule } from './modules/stats/stats.module'; HOST: Joi.string().required(), PORT: Joi.number().port().default(3000), SUBGRAPH_API_KEY: Joi.string().required(), + HCAPTCHA_API_KEY: Joi.string().required(), }), }), CacheModule.registerAsync(CacheFactoryConfig), CommonConfigModule, DetailsModule, - RedisModule, + ScheduleModule.forRoot(), StatsModule, ], controllers: [AppController], diff --git a/packages/apps/dashboard/server/src/common/config/env-config.service.ts b/packages/apps/dashboard/server/src/common/config/env-config.service.ts index e5f2a5bd92..aeb66d2816 100644 --- a/packages/apps/dashboard/server/src/common/config/env-config.service.ts +++ b/packages/apps/dashboard/server/src/common/config/env-config.service.ts @@ -8,6 +8,9 @@ const DEFAULT_HMT_PRICE_SOURCE = 'https://api.coingecko.com/api/v3/simple/price?ids=human-protocol&vs_currencies=usd'; const DEFAULT_HMT_PRICE_FROM = 'human-protocol'; const DEFAULT_HMT_PRICE_TO = 'usd'; +const DEFAULT_HCAPTCHA_STATS_SOURCE = + 'https://foundation-accounts.hmt.ai/support/summary-stats'; +export const HCAPTCHA_STATS_START_DATE = '2022-07-01'; @Injectable() export class EnvironmentConfigService { @@ -54,4 +57,15 @@ export class EnvironmentConfigService { get hmtPriceToKey(): string { return this.configService.get('HMT_PRICE_TO', DEFAULT_HMT_PRICE_TO); } + + get hCaptchaApiKey(): string { + return this.configService.getOrThrow('HCAPTCHA_API_KEY'); + } + + get hCaptchaStatsSource(): string { + return this.configService.get( + 'HCAPTCHA_STATS_SOURCE', + DEFAULT_HCAPTCHA_STATS_SOURCE, + ); + } } diff --git a/packages/apps/dashboard/server/src/common/config/redis-config.service.ts b/packages/apps/dashboard/server/src/common/config/redis-config.service.ts index 36024f030c..41fbd6e59b 100644 --- a/packages/apps/dashboard/server/src/common/config/redis-config.service.ts +++ b/packages/apps/dashboard/server/src/common/config/redis-config.service.ts @@ -6,6 +6,7 @@ const DEFAULT_REDIS_PORT = 6379; const DEFAULT_CACHE_HMT_PRICE_TTL = 60; const DEFAULT_CACHE_HMT_GENERAL_STATS_TTL = 2 * 60; const DEFAULT_HMT_PRICE_CACHE_KEY = 'hmt-price'; +export const HCAPTCHA_PREFIX = 'hcaptcha-'; @Injectable() export class RedisConfigService { diff --git a/packages/apps/dashboard/server/src/common/pipes/date-validation.pipe.ts b/packages/apps/dashboard/server/src/common/pipes/date-validation.pipe.ts new file mode 100644 index 0000000000..1f6327ddfc --- /dev/null +++ b/packages/apps/dashboard/server/src/common/pipes/date-validation.pipe.ts @@ -0,0 +1,15 @@ +import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common'; + +@Injectable() +export class DateValidationPipe implements PipeTransform { + private readonly dateRegex = /^\d{4}-\d{2}-\d{2}$/; + + transform(value: string) { + if (typeof value === 'string' && !this.dateRegex.test(value)) { + throw new BadRequestException( + `Validation failed. Value must be in the format YYYY-MM-DD.`, + ); + } + return value; + } +} diff --git a/packages/apps/dashboard/server/src/modules/redis/redis.module.ts b/packages/apps/dashboard/server/src/modules/redis/redis.module.ts deleted file mode 100644 index 28a5cb8435..0000000000 --- a/packages/apps/dashboard/server/src/modules/redis/redis.module.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { RedisService } from './redis.service'; -import { Module } from '@nestjs/common'; - -@Module({ - imports: [], - providers: [RedisService], - exports: [RedisService], -}) -export class RedisModule {} diff --git a/packages/apps/dashboard/server/src/modules/redis/redis.service.ts b/packages/apps/dashboard/server/src/modules/redis/redis.service.ts deleted file mode 100644 index 7219b9345f..0000000000 --- a/packages/apps/dashboard/server/src/modules/redis/redis.service.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { Inject, Injectable, Logger } from '@nestjs/common'; -import { Cache, CACHE_MANAGER } from '@nestjs/cache-manager'; - -import { RedisConfigService } from '../../common/config/redis-config.service'; - -@Injectable() -export class RedisService { - private readonly logger = new Logger(RedisService.name); - constructor( - @Inject(CACHE_MANAGER) private cacheManager: Cache, - private readonly redisConfigService: RedisConfigService, - ) {} - - async getHmtPrice(): Promise { - const cachedHmtPrice: number | undefined = await this.cacheManager.get( - this.redisConfigService.hmtPriceCacheKey, - ); - return cachedHmtPrice; - } - - async setHmtPrice(hmtPrice: number): Promise { - this.logger.log(`Setting a new HMT price: ${hmtPrice}`); - await this.cacheManager.set( - this.redisConfigService.hmtPriceCacheKey, - hmtPrice, - { ttl: this.redisConfigService.cacheHmtPriceTTL } as any, - ); - } -} diff --git a/packages/apps/dashboard/server/src/modules/stats/dto/hcaptcha.dto.ts b/packages/apps/dashboard/server/src/modules/stats/dto/hcaptcha.dto.ts new file mode 100644 index 0000000000..36d9a1a1b7 --- /dev/null +++ b/packages/apps/dashboard/server/src/modules/stats/dto/hcaptcha.dto.ts @@ -0,0 +1,28 @@ +import { IsNumber, IsString } from 'class-validator'; +import { ApiProperty } from '@nestjs/swagger'; + +export class HcaptchaStats { + @ApiProperty({ example: 1000 }) + @IsNumber() + public served: number; + + @ApiProperty({ example: 1000 }) + @IsNumber() + public solved: number; +} + +export class HcaptchaDailyStats extends HcaptchaStats { + @IsString() + public date: string; +} + +export class HcaptchaDailyStatsResponseDto { + @ApiProperty({ example: '2024-05-01' }) + public from: string; + + @ApiProperty({ example: '2024-05-01' }) + public to: string; + + @ApiProperty() + public results: HcaptchaDailyStats[]; +} diff --git a/packages/apps/dashboard/server/src/modules/stats/stats.controller.ts b/packages/apps/dashboard/server/src/modules/stats/stats.controller.ts index 2170c8330c..7568a2feea 100644 --- a/packages/apps/dashboard/server/src/modules/stats/stats.controller.ts +++ b/packages/apps/dashboard/server/src/modules/stats/stats.controller.ts @@ -1,7 +1,13 @@ -import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger'; -import { Controller, Get, HttpCode } from '@nestjs/common'; +import { ApiOperation, ApiResponse, ApiTags, ApiQuery } from '@nestjs/swagger'; +import { Controller, Get, HttpCode, Query } from '@nestjs/common'; + import { StatsService } from './stats.service'; import { HmtPriceDto } from './dto/hmt-price.dto'; +import { + HcaptchaDailyStatsResponseDto, + HcaptchaStats, +} from './dto/hcaptcha.dto'; +import { DateValidationPipe } from '../../common/pipes/date-validation.pipe'; @ApiTags('Stats') @Controller('/stats') @@ -23,4 +29,52 @@ export class StatsController { const hmtPrice = await this.statsService.hmtPrice(); return { hmtPrice }; } + + @Get('/hcaptcha/daily') + @HttpCode(200) + @ApiOperation({ + summary: 'Get Hcaptcha stats', + description: 'Endpoint to return Hcaptcha stats.', + }) + @ApiQuery({ + name: 'from', + type: String, + description: 'Start date in the format YYYY-MM-DD', + required: true, + }) + @ApiQuery({ + name: 'to', + type: String, + description: 'End date in the format YYYY-MM-DD', + required: true, + }) + @ApiResponse({ + status: 200, + description: 'Stats retrieved successfully', + type: HcaptchaDailyStatsResponseDto, + }) + public async hcaptchaDailyStats( + @Query('from', DateValidationPipe) from: string, + @Query('to', DateValidationPipe) to: string, + ): Promise { + const results = await this.statsService.hCaptchaStats(from, to); + return { from, to, results }; + } + + @Get('/hcaptcha/general') + @HttpCode(200) + @ApiOperation({ + summary: 'Get Hcaptcha general stats', + description: 'Endpoint to return Hcaptcha general stats.', + }) + @ApiResponse({ + status: 200, + description: 'Stats retrieved successfully', + type: HcaptchaStats, + }) + public async hcaptchaGeneralStats(): Promise { + const result: HcaptchaStats = + await this.statsService.hCaptchaGeneralStats(); + return result; + } } diff --git a/packages/apps/dashboard/server/src/modules/stats/stats.module.ts b/packages/apps/dashboard/server/src/modules/stats/stats.module.ts index 8924c2b170..1fc3e74d15 100644 --- a/packages/apps/dashboard/server/src/modules/stats/stats.module.ts +++ b/packages/apps/dashboard/server/src/modules/stats/stats.module.ts @@ -1,13 +1,12 @@ import { HttpModule } from '@nestjs/axios'; import { Module } from '@nestjs/common'; -import { RedisService } from '../redis/redis.service'; import { StatsService } from './stats.service'; import { StatsController } from './stats.controller'; @Module({ imports: [HttpModule], controllers: [StatsController], - providers: [RedisService, StatsService], + providers: [StatsService], }) export class StatsModule {} diff --git a/packages/apps/dashboard/server/src/modules/stats/stats.service.ts b/packages/apps/dashboard/server/src/modules/stats/stats.service.ts index bf2af86b4e..3e4cdd6f02 100644 --- a/packages/apps/dashboard/server/src/modules/stats/stats.service.ts +++ b/packages/apps/dashboard/server/src/modules/stats/stats.service.ts @@ -1,20 +1,150 @@ -import { Injectable, Logger } from '@nestjs/common'; +import { Inject, Injectable, Logger, OnModuleInit } from '@nestjs/common'; import { HttpService } from '@nestjs/axios'; import { lastValueFrom } from 'rxjs'; +import * as dayjs from 'dayjs'; +import { Cron } from '@nestjs/schedule'; +import { Cache, CACHE_MANAGER } from '@nestjs/cache-manager'; import { EnvironmentConfigService } from '../../common/config/env-config.service'; -import { RedisService } from '../redis/redis.service'; +import { + HCAPTCHA_PREFIX, + RedisConfigService, +} from '../../common/config/redis-config.service'; +import { HCAPTCHA_STATS_START_DATE } from '../../common/config/env-config.service'; +import { HcaptchaDailyStats, HcaptchaStats } from './dto/hcaptcha.dto'; @Injectable() -export class StatsService { +export class StatsService implements OnModuleInit { private readonly logger = new Logger(StatsService.name); constructor( + @Inject(CACHE_MANAGER) private cacheManager: Cache, + private readonly redisConfigService: RedisConfigService, private readonly envConfigService: EnvironmentConfigService, private readonly httpService: HttpService, - private readonly redisService: RedisService, ) {} + + private async isHistoricalDataFetched(): Promise { + const data = await this.cacheManager.get( + `${HCAPTCHA_PREFIX}${HCAPTCHA_STATS_START_DATE}`, + ); + return !!data; + } + + async onModuleInit() { + this.logger.log('Fetching historical hCaptcha stats.'); + const isFetched = await this.isHistoricalDataFetched(); + if (isFetched) { + return; + } + + let startDate = dayjs(HCAPTCHA_STATS_START_DATE); + const currentDate = dayjs(); + const dates = []; + + while (startDate <= currentDate) { + const from = startDate.startOf('month').format('YYYY-MM-DD'); + const to = startDate.endOf('month').format('YYYY-MM-DD'); + + dates.push({ from, to }); + + startDate = startDate.add(1, 'month'); + } + + const results = []; + for (const range of dates) { + const { data } = await lastValueFrom( + this.httpService.get(this.envConfigService.hCaptchaStatsSource, { + params: { + start_date: range.from, + end_date: range.to, + api_key: this.envConfigService.hCaptchaApiKey, + }, + }), + ); + results.push(data); + } + + for (const monthData of results) { + for (const [date, value] of Object.entries( + monthData, + )) { + const multiplier = date <= '2022-11-30' ? 18 : 9; + value.served *= multiplier; + value.solved *= multiplier; + if (date !== 'total') { + await this.cacheManager.set(`${HCAPTCHA_PREFIX}${date}`, value); + } else { + const dates = Object.keys(monthData).filter((key) => key !== 'total'); + if (dates.length > 0) { + const month = dayjs(dates[0]).format('YYYY-MM'); + await this.cacheManager.set(`${HCAPTCHA_PREFIX}${month}`, value); + } + } + } + } + } + + @Cron('*/15 * * * *') + async fetchTodayHcaptchaStats() { + this.logger.log('Fetching hCaptcha stats for today.'); + const today = dayjs().format('YYYY-MM-DD'); + const from = today; + const to = today; + + const { data } = await lastValueFrom( + this.httpService.get(this.envConfigService.hCaptchaStatsSource, { + params: { + start_date: from, + end_date: to, + api_key: this.envConfigService.hCaptchaApiKey, + }, + }), + ); + + const multiplier = today <= '2022-11-30' ? 18 : 9; + const stats = data[today]; + if (stats) { + stats.served *= multiplier; + stats.solved *= multiplier; + await this.cacheManager.set(`${HCAPTCHA_PREFIX}${today}`, stats); + } + + const currentMonth = dayjs().format('YYYY-MM'); + const daysInMonth = dayjs().daysInMonth(); + + const dates = Array.from( + { length: daysInMonth }, + (_, i) => `${currentMonth}-${String(i + 1).padStart(2, '0')}`, + ); + + const aggregatedStats = await Promise.all( + dates.map(async (date) => { + const dailyStats: HcaptchaDailyStats = await this.cacheManager.get( + `${HCAPTCHA_PREFIX}${date}`, + ); + return dailyStats || { served: 0, solved: 0 }; + }), + ).then((statsArray) => + statsArray.reduce( + (acc, stats) => { + acc.served += stats.served; + acc.solved += stats.solved; + return acc; + }, + { served: 0, solved: 0 }, + ), + ); + + await this.cacheManager.set( + `${HCAPTCHA_PREFIX}${currentMonth}`, + aggregatedStats, + ); + } + public async hmtPrice(): Promise { - const cachedHmtPrice = await this.redisService.getHmtPrice(); + const cachedHmtPrice: number = await this.cacheManager.get( + this.redisConfigService.hmtPriceCacheKey, + ); if (cachedHmtPrice) { return cachedHmtPrice; } @@ -30,7 +160,69 @@ export class StatsService { data[this.envConfigService.hmtPriceFromKey][ this.envConfigService.hmtPriceToKey ]; - await this.redisService.setHmtPrice(hmtPrice); + await this.cacheManager.set( + this.redisConfigService.hmtPriceCacheKey, + hmtPrice, + { ttl: this.redisConfigService.cacheHmtPriceTTL } as any, + ); return hmtPrice; } + + public async hCaptchaStats( + from: string, + to: string, + ): Promise { + let startDate = dayjs(from); + const endDate = dayjs(to); + const dates = []; + + while (startDate <= endDate) { + dates.push(startDate.format('YYYY-MM-DD')); + startDate = startDate.add(1, 'day'); + } + + const stats = await Promise.all( + dates.map(async (date) => { + const stat: HcaptchaDailyStats = await this.cacheManager.get( + `${HCAPTCHA_PREFIX}${date}`, + ); + if (stat) { + stat.date = date; + } + return stat; + }), + ); + + return stats.filter((stat): stat is HcaptchaDailyStats => stat !== null); + } + + public async hCaptchaGeneralStats(): Promise { + let startDate = dayjs(HCAPTCHA_STATS_START_DATE); + const currentDate = dayjs(); + const dates = []; + + while (startDate <= currentDate) { + dates.push(startDate.format('YYYY-MM')); + startDate = startDate.add(1, 'month'); + } + + const stats = await Promise.all( + dates.map(async (date) => { + const stat: HcaptchaStats = await this.cacheManager.get( + `${HCAPTCHA_PREFIX}${date}`, + ); + return stat; + }), + ); + + const aggregatedStats: HcaptchaStats = stats.reduce((acc, stat) => { + if (stat) { + acc.served += stat.served; + acc.solved += stat.solved; + } + return acc; + }); + + return aggregatedStats; + } } diff --git a/yarn.lock b/yarn.lock index 39b62f6538..45a6dfe0dc 100644 --- a/yarn.lock +++ b/yarn.lock @@ -11836,7 +11836,7 @@ dayjs@1.11.10: resolved "https://registry.yarnpkg.com/dayjs/-/dayjs-1.11.10.tgz#68acea85317a6e164457d6d6947564029a6a16a0" integrity sha512-vjAczensTgRcqDERK0SR2XMwsF/tSvnvlv6VcF2GIhg6Sx4yOIt/irsr1RDJsKiIyBzJDpCoXiWWq28MqH2cnQ== -dayjs@^1.11.10, dayjs@^1.11.6, dayjs@^1.11.9: +dayjs@^1.11.10, dayjs@^1.11.11, dayjs@^1.11.6, dayjs@^1.11.9: version "1.11.11" resolved "https://registry.yarnpkg.com/dayjs/-/dayjs-1.11.11.tgz#dfe0e9d54c5f8b68ccf8ca5f72ac603e7e5ed59e" integrity sha512-okzr3f11N6WuqYtZSvm+F776mB41wRZMhKP+hc34YdW+KmtYYK9iqvHSwo2k9FEH3fhGXvOPV6yz2IcSrfRUDg== From 8a3e4df201cc9070b22aab78e7188dc60d5cf425 Mon Sep 17 00:00:00 2001 From: Dzeranov Date: Wed, 31 Jul 2024 12:55:38 +0300 Subject: [PATCH 12/89] Added middleware to forbid all the requests that are being sent not to the allowed host (#2326) --- packages/apps/human-app/server/.env.example | 1 + .../apps/human-app/server/src/app.module.ts | 12 ++++++++++-- .../config/environment-config.service.ts | 4 ++++ .../middleware/host-check.middleware.ts | 19 +++++++++++++++++++ 4 files changed, 34 insertions(+), 2 deletions(-) create mode 100644 packages/apps/human-app/server/src/common/middleware/host-check.middleware.ts diff --git a/packages/apps/human-app/server/.env.example b/packages/apps/human-app/server/.env.example index 3af52d2c98..0cfc8bf1f7 100644 --- a/packages/apps/human-app/server/.env.example +++ b/packages/apps/human-app/server/.env.example @@ -10,6 +10,7 @@ HCAPTCHA_LABELING_STATS_API_URL= # string HCAPTCHA_LABELING_VERIFY_API_URL= # string HCAPTCHA_LABELING_API_KEY= # string IS_AXIOS_REQUEST_LOGGING_ENABLED= #string, true if enabled, disabled otherwise +ALLOWED_HOST= #string, example 'localhost:3000' # CACHE TTL VALUES - in seconds CACHE_TTL_ORACLE_DISCOVERY= # number, example: 43200 CACHE_TTL_ORACLE_STATS= # number, example: 900 diff --git a/packages/apps/human-app/server/src/app.module.ts b/packages/apps/human-app/server/src/app.module.ts index 83856b1177..83b82554a6 100644 --- a/packages/apps/human-app/server/src/app.module.ts +++ b/packages/apps/human-app/server/src/app.module.ts @@ -1,4 +1,4 @@ -import { Module } from '@nestjs/common'; +import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common'; import { AppController } from './app.controller'; import { ConfigModule } from '@nestjs/config'; import { HttpModule } from '@nestjs/axios'; @@ -38,6 +38,8 @@ import { RegisterAddressModule } from './modules/register-address/register-addre import { InterceptorModule } from './common/interceptors/interceptor.module'; import { TokenRefreshModule } from './modules/token-refresh/token-refresh.module'; import { TokenRefreshController } from './modules/token-refresh/token-refresh.controller'; +import { EnvironmentConfigService } from './common/config/environment-config.service'; +import { ForbidUnauthorizedHostMiddleware } from './common/middleware/host-check.middleware'; @Module({ imports: [ @@ -68,6 +70,7 @@ import { TokenRefreshController } from './modules/token-refresh/token-refresh.co return value; }) .required(), + ALLOWED_HOST: Joi.string().required(), }), }), AutomapperModule.forRoot({ @@ -110,5 +113,10 @@ import { TokenRefreshController } from './modules/token-refresh/token-refresh.co TokenRefreshController, ], exports: [HttpModule], + providers: [EnvironmentConfigService], }) -export class AppModule {} +export class AppModule implements NestModule { + configure(consumer: MiddlewareConsumer) { + consumer.apply(ForbidUnauthorizedHostMiddleware).forRoutes('*'); + } +} diff --git a/packages/apps/human-app/server/src/common/config/environment-config.service.ts b/packages/apps/human-app/server/src/common/config/environment-config.service.ts index 80e23c3cfc..04876511ee 100644 --- a/packages/apps/human-app/server/src/common/config/environment-config.service.ts +++ b/packages/apps/human-app/server/src/common/config/environment-config.service.ts @@ -9,6 +9,7 @@ const DEFAULT_CORS_ALLOWED_ORIGIN = 'http://localhost:5173'; const DEFAULT_CORS_ALLOWED_HEADERS = 'Content-Type,Authorization,X-Requested-With,Accept,Origin'; const DEFAULT_CACHE_TTL_EXCHANGE_ORACLE_URL = 24 * 60 * 60; + @Injectable() export class EnvironmentConfigService { constructor(private configService: ConfigService) {} @@ -31,6 +32,9 @@ export class EnvironmentConfigService { this.configService.get('IS_AXIOS_REQUEST_LOGGING_ENABLED') === 'true' ); } + get allowedHost(): string { + return this.configService.getOrThrow('ALLOWED_HOST'); + } get cachePort(): number { return this.configService.getOrThrow('REDIS_PORT'); } diff --git a/packages/apps/human-app/server/src/common/middleware/host-check.middleware.ts b/packages/apps/human-app/server/src/common/middleware/host-check.middleware.ts new file mode 100644 index 0000000000..e12b0a106f --- /dev/null +++ b/packages/apps/human-app/server/src/common/middleware/host-check.middleware.ts @@ -0,0 +1,19 @@ +import { Injectable, NestMiddleware, ForbiddenException } from '@nestjs/common'; +import { Request, Response, NextFunction } from 'express'; +import { EnvironmentConfigService } from '../config/environment-config.service'; + +@Injectable() +export class ForbidUnauthorizedHostMiddleware implements NestMiddleware { + constructor(private readonly envConfigService: EnvironmentConfigService) {} + + use(req: Request, res: Response, next: NextFunction) { + const allowedHost = this.envConfigService.allowedHost; + const requestHost = req.get('host'); + + if (requestHost !== allowedHost) { + throw new ForbiddenException('Forbidden host'); + } + + next(); + } +} From bd0bd0257cb6c4f2b6dcf8c8447515fa782cbd04 Mon Sep 17 00:00:00 2001 From: Eric Lee <98655210+leric7@users.noreply.github.com> Date: Wed, 31 Jul 2024 05:56:09 -0400 Subject: [PATCH 13/89] Optimize subgraph (#2280) * use immutable entity * use bytes as id * add auto pruning and reduce runtime overhead of eth_call * fix big int to bytes * comment eth_calls * remove fees fields * uncomment on chain reads --------- Co-authored-by: portuu3 --- .../human_protocol_sdk.escrow.escrow_utils.md | 7 +- .../base/classes/BaseEthersClient.md | 6 +- .../encryption/classes/Encryption.md | 10 +- .../encryption/classes/EncryptionUtils.md | 10 +- .../typescript/escrow/classes/EscrowClient.md | 52 ++--- .../typescript/escrow/classes/EscrowUtils.md | 12 +- .../kvstore/classes/KVStoreClient.md | 20 +- .../kvstore/classes/KVStoreUtils.md | 2 +- .../operator/classes/OperatorUtils.md | 8 +- .../staking/classes/StakingClient.md | 34 +-- .../statistics/classes/StatisticsClient.md | 16 +- .../storage/classes/StorageClient.md | 12 +- .../transaction/classes/TransactionUtils.md | 4 +- .../human_protocol_sdk/escrow/escrow_utils.py | 39 ---- .../human_protocol_sdk/gql/escrow.py | 3 - .../escrow/test_escrow_utils.py | 6 - .../human-protocol-sdk/src/escrow.ts | 6 - .../src/graphql/queries/escrow.ts | 3 - .../human-protocol-sdk/src/graphql/types.ts | 3 - .../sdk/typescript/subgraph/schema.graphql | 111 +++++----- .../typescript/subgraph/src/mapping/Escrow.ts | 52 +---- .../subgraph/src/mapping/EscrowFactory.ts | 4 +- .../subgraph/src/mapping/HMTokenTemplate.ts | 32 +-- .../subgraph/src/mapping/KVStore.ts | 11 +- .../subgraph/src/mapping/Staking.ts | 7 +- .../subgraph/src/mapping/legacy/Escrow.ts | 14 +- .../src/mapping/legacy/EscrowFactory.ts | 2 +- .../subgraph/src/mapping/utils/dayUpdates.ts | 8 +- .../subgraph/src/mapping/utils/event.ts | 14 +- .../subgraph/src/mapping/utils/string.ts | 5 + .../subgraph/src/mapping/utils/transaction.ts | 2 +- .../sdk/typescript/subgraph/template.yaml | 4 +- .../escrow-factory/escrow-factory.test.ts | 9 +- .../subgraph/tests/escrow/escrow.test.ts | 194 +++--------------- .../typescript/subgraph/tests/hmt/hmt.test.ts | 58 +++--- .../subgraph/tests/kvstore/kvstore.test.ts | 76 +++---- .../escrow-factory/escrow-factory.test.ts | 2 +- .../tests/legacy/escrow/escrow.test.ts | 45 ++-- .../tests/reward-pool/reward-pool.test.ts | 9 +- .../subgraph/tests/staking/staking.test.ts | 65 ++---- 40 files changed, 344 insertions(+), 633 deletions(-) create mode 100644 packages/sdk/typescript/subgraph/src/mapping/utils/string.ts diff --git a/docs/sdk/python/human_protocol_sdk.escrow.escrow_utils.md b/docs/sdk/python/human_protocol_sdk.escrow.escrow_utils.md index c9794f2b4e..9f6320ace2 100644 --- a/docs/sdk/python/human_protocol_sdk.escrow.escrow_utils.md +++ b/docs/sdk/python/human_protocol_sdk.escrow.escrow_utils.md @@ -22,11 +22,11 @@ print( ## Module -### *class* human_protocol_sdk.escrow.escrow_utils.EscrowData(chain_id, id, address, amount_paid, balance, count, factory_address, launcher, status, token, total_funded_amount, created_at, final_results_url=None, intermediate_results_url=None, manifest_hash=None, manifest_url=None, recording_oracle=None, recording_oracle_fee=None, reputation_oracle=None, reputation_oracle_fee=None, exchange_oracle=None, exchange_oracle_fee=None) +### *class* human_protocol_sdk.escrow.escrow_utils.EscrowData(chain_id, id, address, amount_paid, balance, count, factory_address, launcher, status, token, total_funded_amount, created_at, final_results_url=None, intermediate_results_url=None, manifest_hash=None, manifest_url=None, recording_oracle=None, reputation_oracle=None, exchange_oracle=None) Bases: `object` -#### \_\_init_\_(chain_id, id, address, amount_paid, balance, count, factory_address, launcher, status, token, total_funded_amount, created_at, final_results_url=None, intermediate_results_url=None, manifest_hash=None, manifest_url=None, recording_oracle=None, recording_oracle_fee=None, reputation_oracle=None, reputation_oracle_fee=None, exchange_oracle=None, exchange_oracle_fee=None) +#### \_\_init_\_(chain_id, id, address, amount_paid, balance, count, factory_address, launcher, status, token, total_funded_amount, created_at, final_results_url=None, intermediate_results_url=None, manifest_hash=None, manifest_url=None, recording_oracle=None, reputation_oracle=None, exchange_oracle=None) Initializes an EscrowData instance. @@ -48,11 +48,8 @@ Initializes an EscrowData instance. * **manifest_hash** (`Optional`[`str`]) – Manifest hash. * **manifest_url** (`Optional`[`str`]) – Manifest URL. * **recording_oracle** (`Optional`[`str`]) – Recording Oracle address. - * **recording_oracle_fee** (`Optional`[`int`]) – Recording Oracle fee. * **reputation_oracle** (`Optional`[`str`]) – Reputation Oracle address. - * **reputation_oracle_fee** (`Optional`[`int`]) – Reputation Oracle fee. * **exchange_oracle** (`Optional`[`str`]) – Exchange Oracle address. - * **exchange_oracle_fee** (`Optional`[`int`]) – Exchange Oracle fee. ### *class* human_protocol_sdk.escrow.escrow_utils.EscrowUtils diff --git a/docs/sdk/typescript/base/classes/BaseEthersClient.md b/docs/sdk/typescript/base/classes/BaseEthersClient.md index 1f11c477ad..08dd67337d 100644 --- a/docs/sdk/typescript/base/classes/BaseEthersClient.md +++ b/docs/sdk/typescript/base/classes/BaseEthersClient.md @@ -40,7 +40,7 @@ The network information required to connect to the contracts #### Defined in -[base.ts:20](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L20) +[base.ts:20](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L20) ## Properties @@ -50,7 +50,7 @@ The network information required to connect to the contracts #### Defined in -[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) +[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) *** @@ -60,4 +60,4 @@ The network information required to connect to the contracts #### Defined in -[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) +[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) diff --git a/docs/sdk/typescript/encryption/classes/Encryption.md b/docs/sdk/typescript/encryption/classes/Encryption.md index 995925b3bb..fe9f7f7afa 100644 --- a/docs/sdk/typescript/encryption/classes/Encryption.md +++ b/docs/sdk/typescript/encryption/classes/Encryption.md @@ -66,7 +66,7 @@ The private key. #### Defined in -[encryption.ts:53](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L53) +[encryption.ts:53](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L53) ## Methods @@ -118,7 +118,7 @@ const resultMessage = await encription.decrypt('message'); #### Defined in -[encryption.ts:180](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L180) +[encryption.ts:180](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L180) *** @@ -154,7 +154,7 @@ const resultMessage = await encription.sign('message'); #### Defined in -[encryption.ts:217](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L217) +[encryption.ts:217](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L217) *** @@ -219,7 +219,7 @@ const resultMessage = await encription.signAndEncrypt('message', publicKeys); #### Defined in -[encryption.ts:129](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L129) +[encryption.ts:129](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L129) *** @@ -247,4 +247,4 @@ Optional: The passphrase for the private key. #### Defined in -[encryption.ts:64](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L64) +[encryption.ts:64](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L64) diff --git a/docs/sdk/typescript/encryption/classes/EncryptionUtils.md b/docs/sdk/typescript/encryption/classes/EncryptionUtils.md index 3ee60e2716..5e0e22acd3 100644 --- a/docs/sdk/typescript/encryption/classes/EncryptionUtils.md +++ b/docs/sdk/typescript/encryption/classes/EncryptionUtils.md @@ -97,7 +97,7 @@ const result = await EncriptionUtils.encrypt('message', publicKeys); #### Defined in -[encryption.ts:422](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L422) +[encryption.ts:422](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L422) *** @@ -152,7 +152,7 @@ const result = await EncriptionUtils.generateKeyPair(name, email, passphrase); #### Defined in -[encryption.ts:360](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L360) +[encryption.ts:360](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L360) *** @@ -184,7 +184,7 @@ const signedData = await EncriptionUtils.getSignedData('message'); #### Defined in -[encryption.ts:317](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L317) +[encryption.ts:317](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L317) *** @@ -232,7 +232,7 @@ if (isEncrypted) { #### Defined in -[encryption.ts:471](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L471) +[encryption.ts:471](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L471) *** @@ -280,4 +280,4 @@ const result = await EncriptionUtils.verify('message', publicKey); #### Defined in -[encryption.ts:284](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L284) +[encryption.ts:284](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L284) diff --git a/docs/sdk/typescript/escrow/classes/EscrowClient.md b/docs/sdk/typescript/escrow/classes/EscrowClient.md index 247e140f85..d423524323 100644 --- a/docs/sdk/typescript/escrow/classes/EscrowClient.md +++ b/docs/sdk/typescript/escrow/classes/EscrowClient.md @@ -104,7 +104,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[escrow.ts:129](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L129) +[escrow.ts:129](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L129) ## Properties @@ -118,7 +118,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) +[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) *** @@ -132,7 +132,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) +[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) ## Methods @@ -178,7 +178,7 @@ await escrowClient.abort('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); #### Defined in -[escrow.ts:837](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L837) +[escrow.ts:837](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L837) *** @@ -229,7 +229,7 @@ await escrowClient.addTrustedHandlers('0x62dD51230A30401C455c8398d06F85e4EaB6309 #### Defined in -[escrow.ts:885](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L885) +[escrow.ts:885](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L885) *** @@ -296,7 +296,7 @@ await escrowClient.bulkPayOut('0x62dD51230A30401C455c8398d06F85e4EaB6309f', reci #### Defined in -[escrow.ts:650](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L650) +[escrow.ts:650](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L650) *** @@ -342,7 +342,7 @@ await escrowClient.cancel('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); #### Defined in -[escrow.ts:753](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L753) +[escrow.ts:753](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L753) *** @@ -388,7 +388,7 @@ await escrowClient.complete('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); #### Defined in -[escrow.ts:592](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L592) +[escrow.ts:592](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L592) *** @@ -455,7 +455,7 @@ const escrowAddress = await escrowClient.createAndSetupEscrow(tokenAddress, trus #### Defined in -[escrow.ts:415](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L415) +[escrow.ts:415](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L415) *** @@ -512,7 +512,7 @@ const escrowAddress = await escrowClient.createEscrow(tokenAddress, trustedHandl #### Defined in -[escrow.ts:209](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L209) +[escrow.ts:209](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L209) *** @@ -561,7 +561,7 @@ await escrowClient.fund('0x62dD51230A30401C455c8398d06F85e4EaB6309f', amount); #### Defined in -[escrow.ts:463](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L463) +[escrow.ts:463](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L463) *** @@ -599,7 +599,7 @@ const balance = await escrowClient.getBalance('0x62dD51230A30401C455c8398d06F85e #### Defined in -[escrow.ts:940](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L940) +[escrow.ts:940](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L940) *** @@ -637,7 +637,7 @@ const oracleAddress = await escrowClient.getExchangeOracleAddress('0x62dD51230A3 #### Defined in -[escrow.ts:1320](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1320) +[escrow.ts:1320](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1320) *** @@ -675,7 +675,7 @@ const factoryAddress = await escrowClient.getFactoryAddress('0x62dD51230A30401C4 #### Defined in -[escrow.ts:1358](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1358) +[escrow.ts:1358](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1358) *** @@ -713,7 +713,7 @@ const intemediateResultsUrl = await escrowClient.getIntermediateResultsUrl('0x62 #### Defined in -[escrow.ts:1092](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1092) +[escrow.ts:1092](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1092) *** @@ -751,7 +751,7 @@ const jobLauncherAddress = await escrowClient.getJobLauncherAddress('0x62dD51230 #### Defined in -[escrow.ts:1244](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1244) +[escrow.ts:1244](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1244) *** @@ -789,7 +789,7 @@ const manifestHash = await escrowClient.getManifestHash('0x62dD51230A30401C455c8 #### Defined in -[escrow.ts:978](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L978) +[escrow.ts:978](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L978) *** @@ -827,7 +827,7 @@ const manifestUrl = await escrowClient.getManifestUrl('0x62dD51230A30401C455c839 #### Defined in -[escrow.ts:1016](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1016) +[escrow.ts:1016](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1016) *** @@ -865,7 +865,7 @@ const oracleAddress = await escrowClient.getRecordingOracleAddress('0x62dD51230A #### Defined in -[escrow.ts:1206](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1206) +[escrow.ts:1206](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1206) *** @@ -903,7 +903,7 @@ const oracleAddress = await escrowClient.getReputationOracleAddress('0x62dD51230 #### Defined in -[escrow.ts:1282](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1282) +[escrow.ts:1282](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1282) *** @@ -941,7 +941,7 @@ const resultsUrl = await escrowClient.getResultsUrl('0x62dD51230A30401C455c8398d #### Defined in -[escrow.ts:1054](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1054) +[escrow.ts:1054](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1054) *** @@ -979,7 +979,7 @@ const status = await escrowClient.getStatus('0x62dD51230A30401C455c8398d06F85e4E #### Defined in -[escrow.ts:1168](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1168) +[escrow.ts:1168](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1168) *** @@ -1017,7 +1017,7 @@ const tokenAddress = await escrowClient.getTokenAddress('0x62dD51230A30401C455c8 #### Defined in -[escrow.ts:1130](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1130) +[escrow.ts:1130](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1130) *** @@ -1078,7 +1078,7 @@ await escrowClient.setup(escrowAddress, escrowConfig); #### Defined in -[escrow.ts:290](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L290) +[escrow.ts:290](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L290) *** @@ -1132,7 +1132,7 @@ await storeResults.storeResults('0x62dD51230A30401C455c8398d06F85e4EaB6309f', 'h #### Defined in -[escrow.ts:528](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L528) +[escrow.ts:528](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L528) *** @@ -1164,4 +1164,4 @@ Thrown if the network's chainId is not supported #### Defined in -[escrow.ts:147](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L147) +[escrow.ts:147](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L147) diff --git a/docs/sdk/typescript/escrow/classes/EscrowUtils.md b/docs/sdk/typescript/escrow/classes/EscrowUtils.md index e149999dc7..6965d72a22 100644 --- a/docs/sdk/typescript/escrow/classes/EscrowUtils.md +++ b/docs/sdk/typescript/escrow/classes/EscrowUtils.md @@ -94,11 +94,8 @@ type EscrowData = { manifestHash?: string; manifestUrl?: string; recordingOracle?: string; - recordingOracleFee?: string; reputationOracle?: string; - reputationOracleFee?: string; exchangeOracle?: string; - exchangeOracleFee?: string; status: EscrowStatus; token: string; totalFundedAmount: string; @@ -132,7 +129,7 @@ const escrowData = new EscrowUtils.getEscrow(ChainId.POLYGON_AMOY, "0x1234567890 #### Defined in -[escrow.ts:1646](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1646) +[escrow.ts:1640](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1640) *** @@ -216,11 +213,8 @@ type EscrowData = { manifestHash?: string; manifestUrl?: string; recordingOracle?: string; - recordingOracleFee?: string; reputationOracle?: string; - reputationOracleFee?: string; exchangeOracle?: string; - exchangeOracleFee?: string; status: EscrowStatus; token: string; totalFundedAmount: string; @@ -256,7 +250,7 @@ const escrowDatas = await EscrowUtils.getEscrows(filters); #### Defined in -[escrow.ts:1517](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1517) +[escrow.ts:1514](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1514) *** @@ -369,4 +363,4 @@ import { ChainId, EscrowUtils, EscrowStatus } from '@human-protocol/sdk'; #### Defined in -[escrow.ts:1744](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1744) +[escrow.ts:1738](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1738) diff --git a/docs/sdk/typescript/kvstore/classes/KVStoreClient.md b/docs/sdk/typescript/kvstore/classes/KVStoreClient.md index d01ec370f4..606be37521 100644 --- a/docs/sdk/typescript/kvstore/classes/KVStoreClient.md +++ b/docs/sdk/typescript/kvstore/classes/KVStoreClient.md @@ -104,7 +104,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[kvstore.ts:104](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L104) +[kvstore.ts:104](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L104) ## Properties @@ -118,7 +118,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) +[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) *** @@ -132,7 +132,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) +[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) ## Methods @@ -176,7 +176,7 @@ const value = await kvstoreClient.get('0xf39Fd6e51aad88F6F4ce6aB8827279cffFb9226 #### Defined in -[kvstore.ts:305](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L305) +[kvstore.ts:305](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L305) *** @@ -222,7 +222,7 @@ const linkedinUrl = await kvstoreClient.getFileUrlAndVerifyHash( #### Defined in -[kvstore.ts:344](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L344) +[kvstore.ts:344](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L344) *** @@ -260,7 +260,7 @@ const publicKey = await kvstoreClient.getPublicKey('0xf39Fd6e51aad88F6F4ce6aB882 #### Defined in -[kvstore.ts:402](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L402) +[kvstore.ts:402](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L402) *** @@ -310,7 +310,7 @@ await kvstoreClient.set('Role', 'RecordingOracle'); #### Defined in -[kvstore.ts:167](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L167) +[kvstore.ts:167](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L167) *** @@ -362,7 +362,7 @@ await kvstoreClient.set(keys, values); #### Defined in -[kvstore.ts:210](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L210) +[kvstore.ts:210](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L210) *** @@ -411,7 +411,7 @@ await kvstoreClient.setFileUrlAndHash('linkedin.com/example', 'linkedin_url); #### Defined in -[kvstore.ts:253](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L253) +[kvstore.ts:253](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L253) *** @@ -443,4 +443,4 @@ The Runner object to interact with the Ethereum network #### Defined in -[kvstore.ts:122](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L122) +[kvstore.ts:122](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L122) diff --git a/docs/sdk/typescript/kvstore/classes/KVStoreUtils.md b/docs/sdk/typescript/kvstore/classes/KVStoreUtils.md index eb2001fb35..5eb88980c1 100644 --- a/docs/sdk/typescript/kvstore/classes/KVStoreUtils.md +++ b/docs/sdk/typescript/kvstore/classes/KVStoreUtils.md @@ -113,4 +113,4 @@ console.log(kvStoreData); #### Defined in -[kvstore.ts:498](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L498) +[kvstore.ts:498](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L498) diff --git a/docs/sdk/typescript/operator/classes/OperatorUtils.md b/docs/sdk/typescript/operator/classes/OperatorUtils.md index 52927dc211..8508706f6b 100644 --- a/docs/sdk/typescript/operator/classes/OperatorUtils.md +++ b/docs/sdk/typescript/operator/classes/OperatorUtils.md @@ -48,7 +48,7 @@ const leader = await OperatorUtils.getLeader(ChainId.POLYGON_AMOY, '0x62dD51230A #### Defined in -[operator.ts:44](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L44) +[operator.ts:44](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L44) *** @@ -83,7 +83,7 @@ const leaders = await OperatorUtils.getLeaders(filter); #### Defined in -[operator.ts:99](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L99) +[operator.ts:99](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L99) *** @@ -121,7 +121,7 @@ const operators = await OperatorUtils.getReputationNetworkOperators(ChainId.POLY #### Defined in -[operator.ts:151](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L151) +[operator.ts:151](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L151) *** @@ -155,4 +155,4 @@ const rewards = await OperatorUtils.getRewards(ChainId.POLYGON_AMOY, '0x62dD5123 #### Defined in -[operator.ts:199](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L199) +[operator.ts:199](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L199) diff --git a/docs/sdk/typescript/staking/classes/StakingClient.md b/docs/sdk/typescript/staking/classes/StakingClient.md index 3180e7b1d1..363c89e517 100644 --- a/docs/sdk/typescript/staking/classes/StakingClient.md +++ b/docs/sdk/typescript/staking/classes/StakingClient.md @@ -104,7 +104,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[staking.ts:111](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L111) +[staking.ts:111](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L111) ## Properties @@ -114,7 +114,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[staking.ts:102](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L102) +[staking.ts:102](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L102) *** @@ -128,7 +128,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) +[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) *** @@ -138,7 +138,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[staking.ts:103](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L103) +[staking.ts:103](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L103) *** @@ -152,7 +152,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) +[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) *** @@ -162,7 +162,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[staking.ts:101](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L101) +[staking.ts:101](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L101) *** @@ -172,7 +172,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[staking.ts:100](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L100) +[staking.ts:100](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L100) ## Methods @@ -223,7 +223,7 @@ await stakingClient.allocate('0x62dD51230A30401C455c8398d06F85e4EaB6309f', amoun #### Defined in -[staking.ts:458](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L458) +[staking.ts:458](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L458) *** @@ -268,7 +268,7 @@ await stakingClient.approveStake(amount); #### Defined in -[staking.ts:203](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L203) +[staking.ts:203](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L203) *** @@ -315,7 +315,7 @@ await stakingClient.closeAllocation('0x62dD51230A30401C455c8398d06F85e4EaB6309f' #### Defined in -[staking.ts:511](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L511) +[staking.ts:511](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L511) *** @@ -361,7 +361,7 @@ await stakingClient.distributeReward('0x62dD51230A30401C455c8398d06F85e4EaB6309f #### Defined in -[staking.ts:554](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L554) +[staking.ts:554](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L554) *** @@ -399,7 +399,7 @@ const allocationInfo = await stakingClient.getAllocation('0x62dD51230A30401C455c #### Defined in -[staking.ts:591](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L591) +[staking.ts:591](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L591) *** @@ -456,7 +456,7 @@ await stakingClient.slash('0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', '0xf39Fd #### Defined in -[staking.ts:387](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L387) +[staking.ts:387](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L387) *** @@ -504,7 +504,7 @@ await stakingClient.approveStake(amount); #### Defined in -[staking.ts:258](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L258) +[staking.ts:258](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L258) *** @@ -551,7 +551,7 @@ await stakingClient.unstake(amount); #### Defined in -[staking.ts:303](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L303) +[staking.ts:303](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L303) *** @@ -593,7 +593,7 @@ await stakingClient.withdraw(); #### Defined in -[staking.ts:349](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L349) +[staking.ts:349](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L349) *** @@ -625,4 +625,4 @@ The Runner object to interact with the Ethereum network #### Defined in -[staking.ts:145](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L145) +[staking.ts:145](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L145) diff --git a/docs/sdk/typescript/statistics/classes/StatisticsClient.md b/docs/sdk/typescript/statistics/classes/StatisticsClient.md index 3638e58006..a8ef585a3c 100644 --- a/docs/sdk/typescript/statistics/classes/StatisticsClient.md +++ b/docs/sdk/typescript/statistics/classes/StatisticsClient.md @@ -62,7 +62,7 @@ The network information required to connect to the Statistics contract #### Defined in -[statistics.ts:70](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L70) +[statistics.ts:70](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L70) ## Properties @@ -72,7 +72,7 @@ The network information required to connect to the Statistics contract #### Defined in -[statistics.ts:62](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L62) +[statistics.ts:62](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L62) *** @@ -82,7 +82,7 @@ The network information required to connect to the Statistics contract #### Defined in -[statistics.ts:63](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L63) +[statistics.ts:63](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L63) ## Methods @@ -146,7 +146,7 @@ const escrowStatisticsApril = await statisticsClient.getEscrowStatistics({ #### Defined in -[statistics.ts:124](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L124) +[statistics.ts:124](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L124) *** @@ -189,7 +189,7 @@ console.log('HMT holders:', hmtHolders.map((h) => ({ #### Defined in -[statistics.ts:466](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L466) +[statistics.ts:466](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L466) *** @@ -285,7 +285,7 @@ console.log('HMT statistics from 5/8 - 6/8:', { #### Defined in -[statistics.ts:397](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L397) +[statistics.ts:397](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L397) *** @@ -367,7 +367,7 @@ console.log( #### Defined in -[statistics.ts:288](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L288) +[statistics.ts:288](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L288) *** @@ -426,4 +426,4 @@ const workerStatisticsApril = await statisticsClient.getWorkerStatistics({ #### Defined in -[statistics.ts:199](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L199) +[statistics.ts:199](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L199) diff --git a/docs/sdk/typescript/storage/classes/StorageClient.md b/docs/sdk/typescript/storage/classes/StorageClient.md index d08fddf1ed..4ec3c0770c 100644 --- a/docs/sdk/typescript/storage/classes/StorageClient.md +++ b/docs/sdk/typescript/storage/classes/StorageClient.md @@ -77,7 +77,7 @@ Optional. Cloud storage access data. If credentials is not provided - use an ano #### Defined in -[storage.ts:73](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L73) +[storage.ts:73](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L73) ## Methods @@ -121,7 +121,7 @@ const exists = await storageClient.bucketExists('bucket-name'); #### Defined in -[storage.ts:266](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L266) +[storage.ts:266](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L266) *** @@ -167,7 +167,7 @@ const files = await storageClient.downloadFiles(keys, 'bucket-name'); #### Defined in -[storage.ts:113](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L113) +[storage.ts:113](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L113) *** @@ -211,7 +211,7 @@ const fileNames = await storageClient.listObjects('bucket-name'); #### Defined in -[storage.ts:297](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L297) +[storage.ts:297](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L297) *** @@ -262,7 +262,7 @@ const uploadedFiles = await storageClient.uploadFiles(files, 'bucket-name'); #### Defined in -[storage.ts:201](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L201) +[storage.ts:201](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L201) *** @@ -294,4 +294,4 @@ const file = await storageClient.downloadFileFromUrl('http://localhost/file.json #### Defined in -[storage.ts:148](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L148) +[storage.ts:148](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L148) diff --git a/docs/sdk/typescript/transaction/classes/TransactionUtils.md b/docs/sdk/typescript/transaction/classes/TransactionUtils.md index c78b72f6bf..70d8a58597 100644 --- a/docs/sdk/typescript/transaction/classes/TransactionUtils.md +++ b/docs/sdk/typescript/transaction/classes/TransactionUtils.md @@ -50,7 +50,7 @@ const transaction = await TransactionUtils.getTransaction(ChainId.POLYGON, '0x62 #### Defined in -[transaction.ts:34](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts#L34) +[transaction.ts:34](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts#L34) *** @@ -121,4 +121,4 @@ const transactions = await TransactionUtils.getTransactions(filter); #### Defined in -[transaction.ts:109](https://github.com/humanprotocol/human-protocol/blob/be3631cc39e3198133a9145c1c7bd03c2836462a/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts#L109) +[transaction.ts:109](https://github.com/humanprotocol/human-protocol/blob/c4fdb1a29e88dfe9f3982c3b18d5c6939416bda0/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts#L109) 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 346e419cff..fe93113c49 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 @@ -62,11 +62,8 @@ def __init__( manifest_hash: Optional[str] = None, manifest_url: Optional[str] = None, recording_oracle: Optional[str] = None, - recording_oracle_fee: Optional[int] = None, reputation_oracle: Optional[str] = None, - reputation_oracle_fee: Optional[int] = None, exchange_oracle: Optional[str] = None, - exchange_oracle_fee: Optional[int] = None, ): """ Initializes an EscrowData instance. @@ -88,11 +85,8 @@ def __init__( :param manifest_hash: Manifest hash. :param manifest_url: Manifest URL. :param recording_oracle: Recording Oracle address. - :param recording_oracle_fee: Recording Oracle fee. :param reputation_oracle: Reputation Oracle address. - :param reputation_oracle_fee: Reputation Oracle fee. :param exchange_oracle: Exchange Oracle address. - :param exchange_oracle_fee: Exchange Oracle fee. """ self.id = id @@ -107,11 +101,8 @@ def __init__( self.manifest_hash = manifest_hash self.manifest_url = manifest_url self.recording_oracle = recording_oracle - self.recording_oracle_fee = recording_oracle_fee self.reputation_oracle = reputation_oracle - self.reputation_oracle_fee = reputation_oracle_fee self.exchange_oracle = exchange_oracle - self.exchange_oracle_fee = exchange_oracle_fee self.status = status self.token = token self.total_funded_amount = total_funded_amount @@ -234,23 +225,8 @@ def get_escrows( manifest_hash=escrow.get("manifestHash", None), manifest_url=escrow.get("manifestUrl", None), recording_oracle=escrow.get("recordingOracle", None), - recording_oracle_fee=( - int(escrow.get("recordingOracleFee")) - if escrow.get("recordingOracleFee", None) - else None - ), reputation_oracle=escrow.get("reputationOracle", None), - reputation_oracle_fee=( - int(escrow.get("reputationOracleFee")) - if escrow.get("reputationOracleFee", None) - else None - ), exchange_oracle=escrow.get("exchangeOracle", None), - exchange_oracle_fee=( - int(escrow.get("exchangeOracleFee")) - if escrow.get("exchangeOracleFee", None) - else None - ), ) for escrow in escrows_raw ] @@ -331,23 +307,8 @@ def get_escrow( manifest_hash=escrow.get("manifestHash", None), manifest_url=escrow.get("manifestUrl", None), recording_oracle=escrow.get("recordingOracle", None), - recording_oracle_fee=( - int(escrow.get("recordingOracleFee")) - if escrow.get("recordingOracleFee", None) - else None - ), reputation_oracle=escrow.get("reputationOracle", None), - reputation_oracle_fee=( - int(escrow.get("reputationOracleFee")) - if escrow.get("reputationOracleFee", None) - else None - ), exchange_oracle=escrow.get("exchangeOracle", None), - exchange_oracle_fee=( - int(escrow.get("exchangeOracleFee")) - if escrow.get("exchangeOracleFee", None) - else None - ), ) @staticmethod diff --git a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/gql/escrow.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/gql/escrow.py index d7853cef59..b20e2ef397 100644 --- a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/gql/escrow.py +++ b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/gql/escrow.py @@ -16,11 +16,8 @@ manifestHash manifestUrl recordingOracle - recordingOracleFee reputationOracle - reputationOracleFee exchangeOracle - exchangeOracleFee status token totalFundedAmount diff --git a/packages/sdk/python/human-protocol-sdk/test/human_protocol_sdk/escrow/test_escrow_utils.py b/packages/sdk/python/human-protocol-sdk/test/human_protocol_sdk/escrow/test_escrow_utils.py index f0e2e5e8a4..998ee706c8 100644 --- a/packages/sdk/python/human-protocol-sdk/test/human_protocol_sdk/escrow/test_escrow_utils.py +++ b/packages/sdk/python/human-protocol-sdk/test/human_protocol_sdk/escrow/test_escrow_utils.py @@ -32,11 +32,8 @@ def test_get_escrows(self): "manifestHash": "0x1234567890123456789012345678901234567891", "manifestUrl": "https://example.com", "recordingOracle": "0x1234567890123456789012345678901234567891", - "recordingOracleFee": "1000000000000000000", "reputationOracle": "0x1234567890123456789012345678901234567891", - "reputationOracleFee": "1000000000000000000", "exchangeOracle": "0x1234567890123456789012345678901234567891", - "exchangeOracleFee": "1000000000000000000", "status": "Pending", "token": "0x1234567890123456789012345678901234567891", "totalFundedAmount": "1000000000000000000", @@ -119,11 +116,8 @@ def test_get_escrow(self): "manifestHash": "0x1234567890123456789012345678901234567891", "manifestUrl": "https://example.com", "recordingOracle": "0x1234567890123456789012345678901234567891", - "recordingOracleFee": "1000000000000000000", "reputationOracle": "0x1234567890123456789012345678901234567891", - "reputationOracleFee": "1000000000000000000", "exchangeOracle": "0x1234567890123456789012345678901234567891", - "exchangeOracleFee": "1000000000000000000", "status": "Pending", "token": "0x1234567890123456789012345678901234567891", "totalFundedAmount": "1000000000000000000", diff --git a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts b/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts index 394cd3f67a..1addb2d8bf 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts @@ -1484,11 +1484,8 @@ export class EscrowUtils { * manifestHash?: string; * manifestUrl?: string; * recordingOracle?: string; - * recordingOracleFee?: string; * reputationOracle?: string; - * reputationOracleFee?: string; * exchangeOracle?: string; - * exchangeOracleFee?: string; * status: EscrowStatus; * token: string; * totalFundedAmount: string; @@ -1618,11 +1615,8 @@ export class EscrowUtils { * manifestHash?: string; * manifestUrl?: string; * recordingOracle?: string; - * recordingOracleFee?: string; * reputationOracle?: string; - * reputationOracleFee?: string; * exchangeOracle?: string; - * exchangeOracleFee?: string; * status: EscrowStatus; * token: string; * totalFundedAmount: string; diff --git a/packages/sdk/typescript/human-protocol-sdk/src/graphql/queries/escrow.ts b/packages/sdk/typescript/human-protocol-sdk/src/graphql/queries/escrow.ts index 0e938e5bee..92637f37fa 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/graphql/queries/escrow.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/graphql/queries/escrow.ts @@ -16,11 +16,8 @@ const ESCROW_FRAGMENT = gql` manifestHash manifestUrl recordingOracle - recordingOracleFee reputationOracle - reputationOracleFee exchangeOracle - exchangeOracleFee status token totalFundedAmount diff --git a/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts b/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts index b9129f9c6a..d79d608a92 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/graphql/types.ts @@ -13,11 +13,8 @@ export type EscrowData = { manifestHash?: string; manifestUrl?: string; recordingOracle?: string; - recordingOracleFee?: string; reputationOracle?: string; - reputationOracleFee?: string; exchangeOracle?: string; - exchangeOracleFee?: string; status: string; token: string; totalFundedAmount: string; diff --git a/packages/sdk/typescript/subgraph/schema.graphql b/packages/sdk/typescript/subgraph/schema.graphql index 6167b29c39..a5504542f7 100644 --- a/packages/sdk/typescript/subgraph/schema.graphql +++ b/packages/sdk/typescript/subgraph/schema.graphql @@ -3,34 +3,34 @@ ################################################## type Holder @entity { - id: ID! + id: Bytes! address: Bytes! # address balance: BigInt! } type Worker @entity { - id: ID! + id: Bytes! address: Bytes! totalAmountReceived: BigInt! payoutCount: BigInt! } type UniqueSender @entity { - id: ID! + id: Bytes! address: Bytes! transferCount: BigInt! timestamp: BigInt! } type UniqueReceiver @entity { - id: ID! + id: Bytes! address: Bytes! receiveCount: BigInt! timestamp: BigInt! } type Leader @entity { - id: ID! + id: Bytes! address: Bytes! amountStaked: BigInt! amountAllocated: BigInt! @@ -53,20 +53,20 @@ type Leader @entity { } type LeaderURL @entity { - id: ID! + id: Bytes! key: String url: String leader: Leader! } type ReputationNetwork @entity { - id: ID! + id: Bytes! address: Bytes! operators: [Leader!]! @derivedFrom(field: "reputationNetwork") } type Escrow @entity { - id: ID! + id: Bytes! address: Bytes! # address token: Bytes! # address factoryAddress: Bytes! # address @@ -79,27 +79,24 @@ type Escrow @entity { manifestUrl: String # string manifestHash: String # string reputationOracle: Bytes # address - reputationOracleFee: BigInt recordingOracle: Bytes # address - recordingOracleFee: BigInt exchangeOracle: Bytes # address - exchangeOracleFee: BigInt intermediateResultsUrl: String # string finalResultsUrl: String # string jobRequesterId: String # string createdAt: BigInt! } -type Payout @entity { - id: ID! +type Payout @entity(immutable: true) { + id: Bytes! escrowAddress: Bytes! # address recipient: Bytes! # address amount: BigInt! createdAt: BigInt! } -type DailyWorker @entity { - id: ID! +type DailyWorker @entity(immutable: true) { + id: Bytes! timestamp: BigInt! address: Bytes! # address escrowAddress: Bytes! # address @@ -110,8 +107,8 @@ type DailyWorker @entity { ################################################## # HMToken -type HMTTransferEvent @entity { - id: ID! +type HMTTransferEvent @entity(immutable: true) { + id: Bytes! block: BigInt! timestamp: BigInt! txHash: Bytes! @@ -121,8 +118,8 @@ type HMTTransferEvent @entity { amount: BigInt! } -type HMTBulkTransferEvent @entity { - id: ID! +type HMTBulkTransferEvent @entity(immutable: true) { + id: Bytes! block: BigInt! timestamp: BigInt! txHash: Bytes! @@ -131,8 +128,8 @@ type HMTBulkTransferEvent @entity { bulkCount: BigInt! } -type HMTApprovalEvent @entity { - id: ID! +type HMTApprovalEvent @entity(immutable: true) { + id: Bytes! block: BigInt! timestamp: BigInt! txHash: Bytes! @@ -142,8 +139,8 @@ type HMTApprovalEvent @entity { amount: BigInt! } -type HMTBulkApprovalEvent @entity { - id: ID! +type HMTBulkApprovalEvent @entity(immutable: true) { + id: Bytes! block: BigInt! timestamp: BigInt! txHash: Bytes! @@ -153,8 +150,8 @@ type HMTBulkApprovalEvent @entity { } # Escrow -type FundEvent @entity { - id: ID! +type FundEvent @entity(immutable: true) { + id: Bytes! block: BigInt! timestamp: BigInt! txHash: Bytes! @@ -164,8 +161,8 @@ type FundEvent @entity { amount: BigInt! } -type SetupEvent @entity { - id: ID! +type SetupEvent @entity(immutable: true) { + id: Bytes! block: BigInt! timestamp: BigInt! txHash: Bytes! @@ -174,8 +171,8 @@ type SetupEvent @entity { sender: Bytes! # address } -type StoreResultsEvent @entity { - id: ID! +type StoreResultsEvent @entity(immutable: true) { + id: Bytes! block: BigInt! timestamp: BigInt! txHash: Bytes! @@ -185,8 +182,8 @@ type StoreResultsEvent @entity { intermediateResultsUrl: String! # string } -type BulkPayoutEvent @entity { - id: ID! +type BulkPayoutEvent @entity(immutable: true) { + id: Bytes! block: BigInt! timestamp: BigInt! txHash: Bytes! @@ -197,8 +194,8 @@ type BulkPayoutEvent @entity { bulkCount: BigInt! } -type EscrowStatusEvent @entity { - id: ID! +type EscrowStatusEvent @entity(immutable: true) { + id: Bytes! block: BigInt! timestamp: BigInt! txHash: Bytes! @@ -210,8 +207,8 @@ type EscrowStatusEvent @entity { } # KVStore -type KVStoreSetEvent @entity { - id: ID! +type KVStoreSetEvent @entity(immutable: true) { + id: Bytes! block: BigInt! timestamp: BigInt! txHash: Bytes! @@ -221,8 +218,8 @@ type KVStoreSetEvent @entity { value: String! } -type KVStore @entity { - id: ID! +type KVStore @entity(immutable: true) { + id: Bytes! block: BigInt! timestamp: BigInt! address: Bytes! @@ -231,8 +228,8 @@ type KVStore @entity { } # Staking -type StakeDepositedEvent @entity { - id: ID! +type StakeDepositedEvent @entity(immutable: true) { + id: Bytes! block: BigInt! timestamp: BigInt! txHash: Bytes! @@ -241,8 +238,8 @@ type StakeDepositedEvent @entity { amount: BigInt! } -type StakeLockedEvent @entity { - id: ID! +type StakeLockedEvent @entity(immutable: true) { + id: Bytes! block: BigInt! timestamp: BigInt! txHash: Bytes! @@ -252,8 +249,8 @@ type StakeLockedEvent @entity { lockedUntilTimestamp: BigInt! } -type StakeWithdrawnEvent @entity { - id: ID! +type StakeWithdrawnEvent @entity(immutable: true) { + id: Bytes! block: BigInt! timestamp: BigInt! txHash: Bytes! @@ -262,8 +259,8 @@ type StakeWithdrawnEvent @entity { amount: BigInt! } -type StakeSlashedEvent @entity { - id: ID! +type StakeSlashedEvent @entity(immutable: true) { + id: Bytes! block: BigInt! timestamp: BigInt! txHash: Bytes! @@ -274,8 +271,8 @@ type StakeSlashedEvent @entity { amount: BigInt! } -type StakeAllocatedEvent @entity { - id: ID! +type StakeAllocatedEvent @entity(immutable: true) { + id: Bytes! block: BigInt! timestamp: BigInt! txHash: Bytes! @@ -285,8 +282,8 @@ type StakeAllocatedEvent @entity { amount: BigInt! } -type AllocationClosedEvent @entity { - id: ID! +type AllocationClosedEvent @entity(immutable: true) { + id: Bytes! block: BigInt! timestamp: BigInt! txHash: Bytes! @@ -297,8 +294,8 @@ type AllocationClosedEvent @entity { } # RewardPool -type RewardAddedEvent @entity { - id: ID! +type RewardAddedEvent @entity(immutable: true) { + id: Bytes! block: BigInt! timestamp: BigInt! txHash: Bytes! @@ -314,7 +311,7 @@ type RewardAddedEvent @entity { ################################################## type HMTokenStatistics @entity { - id: ID! + id: Bytes! totalTransferEventCount: BigInt! totalBulkTransferEventCount: BigInt! totalApprovalEventCount: BigInt! @@ -324,7 +321,7 @@ type HMTokenStatistics @entity { } type EscrowStatistics @entity { - id: ID! + id: Bytes! fundEventCount: BigInt! setupEventCount: BigInt! storeResultsEventCount: BigInt! @@ -339,7 +336,7 @@ type EscrowStatistics @entity { } type EventDayData @entity { - id: ID! + id: Bytes! timestamp: Int! dailyFundEventCount: BigInt! dailySetupEventCount: BigInt! @@ -362,12 +359,12 @@ type EventDayData @entity { } type LeaderStatistics @entity { - id: ID! + id: Bytes! leaders: BigInt! } -type Transaction @entity { - id: ID! +type Transaction @entity(immutable: true) { + id: Bytes! block: BigInt! timestamp: BigInt! txHash: Bytes! diff --git a/packages/sdk/typescript/subgraph/src/mapping/Escrow.ts b/packages/sdk/typescript/subgraph/src/mapping/Escrow.ts index b13e0cf479..1b77b3f83d 100644 --- a/packages/sdk/typescript/subgraph/src/mapping/Escrow.ts +++ b/packages/sdk/typescript/subgraph/src/mapping/Escrow.ts @@ -21,8 +21,9 @@ import { ZERO_BI, ONE_BI } from './utils/number'; import { toEventId } from './utils/event'; import { getEventDayData } from './utils/dayUpdates'; import { createTransaction } from './utils/transaction'; +import { toBytes } from './utils/string'; -export const STATISTICS_ENTITY_ID = 'escrow-statistics-id'; +export const STATISTICS_ENTITY_ID = toBytes('escrow-statistics-id'); function constructStatsEntity(): EscrowStatistics { const entity = new EscrowStatistics(STATISTICS_ENTITY_ID); @@ -53,10 +54,10 @@ export function createOrLoadEscrowStatistics(): EscrowStatistics { } export function createOrLoadWorker(address: Address): Worker { - let worker = Worker.load(address.toHex()); + let worker = Worker.load(address); if (!worker) { - worker = new Worker(address.toHex()); + worker = new Worker(address); worker.address = address; worker.totalAmountReceived = ZERO_BI; worker.payoutCount = ZERO_BI; @@ -106,7 +107,7 @@ export function handlePending(event: Pending): void { ); // Update escrow entity - const escrowEntity = Escrow.load(dataSource.address().toHex()); + const escrowEntity = Escrow.load(dataSource.address()); if (escrowEntity) { escrowEntity.manifestUrl = event.params.manifest; escrowEntity.manifestHash = event.params.hash; @@ -114,56 +115,21 @@ export function handlePending(event: Pending): void { // Read data on-chain const escrowContract = EscrowContract.bind(event.address); - const legacyEscrowContract = LegacyEscrowContract.bind(event.address); - - // Reputation & Recording Oracle Fee Variable is changed over time - // For old one, it was oracleStake, for new one it is oracleFeePercentage const reputationOracle = escrowContract.try_reputationOracle(); if (!reputationOracle.reverted) { escrowEntity.reputationOracle = reputationOracle.value; } - const reputationOracleFeePercentage = - escrowContract.try_reputationOracleFeePercentage(); - if (!reputationOracleFeePercentage.reverted) { - escrowEntity.reputationOracleFee = BigInt.fromI32( - reputationOracleFeePercentage.value - ); - } - const reputationOracleStake = - legacyEscrowContract.try_reputationOracleStake(); - if (!reputationOracleStake.reverted) { - escrowEntity.reputationOracleFee = reputationOracleStake.value; - } const recordingOracle = escrowContract.try_recordingOracle(); if (!recordingOracle.reverted) { escrowEntity.recordingOracle = recordingOracle.value; } - const recordingOracleFeePercentage = - escrowContract.try_recordingOracleFeePercentage(); - if (!recordingOracleFeePercentage.reverted) { - escrowEntity.recordingOracleFee = BigInt.fromI32( - recordingOracleFeePercentage.value - ); - } - const recordingOracleStake = - legacyEscrowContract.try_recordingOracleStake(); - if (!recordingOracleStake.reverted) { - escrowEntity.recordingOracleFee = recordingOracleStake.value; - } const exchangeOracle = escrowContract.try_exchangeOracle(); if (!exchangeOracle.reverted) { escrowEntity.exchangeOracle = exchangeOracle.value; } - const exchangeOracleFeePercentage = - escrowContract.try_exchangeOracleFeePercentage(); - if (!exchangeOracleFeePercentage.reverted) { - escrowEntity.exchangeOracleFee = BigInt.fromI32( - exchangeOracleFeePercentage.value - ); - } escrowEntity.save(); statusEventEntity.launcher = escrowEntity.launcher; @@ -199,7 +165,7 @@ export function handleIntermediateStorage(event: IntermediateStorage): void { eventDayData.save(); // Update escrow entity - const escrowEntity = Escrow.load(dataSource.address().toHex()); + const escrowEntity = Escrow.load(dataSource.address()); if (escrowEntity) { escrowEntity.intermediateResultsUrl = event.params._url; escrowEntity.save(); @@ -241,7 +207,7 @@ export function handleBulkTransfer(event: BulkTransfer): void { statusEventEntity.sender = event.transaction.from; // Update escrow entity - const escrowEntity = Escrow.load(dataSource.address().toHex()); + const escrowEntity = Escrow.load(dataSource.address()); if (escrowEntity) { escrowEntity.status = event.params._isPartial ? 'Partial' : 'Paid'; @@ -313,7 +279,7 @@ export function handleCancelled(event: Cancelled): void { eventDayData.save(); // Update escrow entity - const escrowEntity = Escrow.load(dataSource.address().toHex()); + const escrowEntity = Escrow.load(dataSource.address()); if (escrowEntity) { escrowEntity.status = 'Cancelled'; escrowEntity.save(); @@ -349,7 +315,7 @@ export function handleCompleted(event: Completed): void { eventDayData.save(); // Update escrow entity - const escrowEntity = Escrow.load(dataSource.address().toHex()); + const escrowEntity = Escrow.load(dataSource.address()); if (escrowEntity) { escrowEntity.status = 'Complete'; escrowEntity.save(); diff --git a/packages/sdk/typescript/subgraph/src/mapping/EscrowFactory.ts b/packages/sdk/typescript/subgraph/src/mapping/EscrowFactory.ts index d20f56c256..a3fb6504e9 100644 --- a/packages/sdk/typescript/subgraph/src/mapping/EscrowFactory.ts +++ b/packages/sdk/typescript/subgraph/src/mapping/EscrowFactory.ts @@ -25,7 +25,7 @@ export function handleLaunched(event: Launched): void { statusEventEntity.save(); // Create Escrow entity - const entity = new Escrow(event.params.escrow.toHex()); + const entity = new Escrow(event.params.escrow); entity.createdAt = event.block.timestamp; entity.address = event.params.escrow; @@ -64,7 +64,7 @@ export function handleLaunched(event: Launched): void { export function handleLaunchedV2(event: LaunchedV2): void { createTransaction(event, 'createEscrow'); // Create Escrow entity - const entity = new Escrow(event.params.escrow.toHex()); + const entity = new Escrow(event.params.escrow); entity.createdAt = event.block.timestamp; entity.address = event.params.escrow; diff --git a/packages/sdk/typescript/subgraph/src/mapping/HMTokenTemplate.ts b/packages/sdk/typescript/subgraph/src/mapping/HMTokenTemplate.ts index 2860e3b4f3..aa44cae521 100644 --- a/packages/sdk/typescript/subgraph/src/mapping/HMTokenTemplate.ts +++ b/packages/sdk/typescript/subgraph/src/mapping/HMTokenTemplate.ts @@ -1,4 +1,4 @@ -import { Address, BigInt } from '@graphprotocol/graph-ts'; +import { Address, BigInt, Bytes } from '@graphprotocol/graph-ts'; import { Approval, @@ -25,8 +25,9 @@ import { ONE_BI, ONE_DAY, ZERO_BI } from './utils/number'; import { createOrLoadEscrowStatistics, createOrLoadWorker } from './Escrow'; import { getEventDayData } from './utils/dayUpdates'; import { createTransaction } from './utils/transaction'; +import { toBytes } from './utils/string'; -export const HMT_STATISTICS_ENTITY_ID = 'hmt-statistics-id'; +export const HMT_STATISTICS_ENTITY_ID = toBytes('hmt-statistics-id'); export const TOTAL_SUPPLY = BigInt.fromString('{{ HMToken.totalSupply }}'); export const CONTRACT_DEPLOYER = '{{ HMToken.contractDeployer }}'; @@ -44,11 +45,11 @@ function constructStatsEntity(): HMTokenStatistics { } export function createOrLoadUniqueSender( - dayStartTimestamp: string, + dayStartTimestamp: BigInt, timestamp: BigInt, address: Address ): UniqueSender { - const id = `${dayStartTimestamp}-${address.toHex()}`; + const id = Bytes.fromI32(dayStartTimestamp.toI32()).concat(address); let uniqueSender = UniqueSender.load(id); if (!uniqueSender) { @@ -63,11 +64,11 @@ export function createOrLoadUniqueSender( } export function createOrLoadUniqueReceiver( - dayStartTimestamp: string, + dayStartTimestamp: BigInt, timestamp: BigInt, address: Address ): UniqueReceiver { - const id = `${dayStartTimestamp}-${address.toHex()}`; + const id = Bytes.fromI32(dayStartTimestamp.toI32()).concat(address); let uniqueReceiver = UniqueReceiver.load(id); if (!uniqueReceiver) { @@ -91,7 +92,7 @@ function updateHolders( ) return ZERO_BI; let count = ZERO_BI; - const id = holderAddress.toHex(); + const id = holderAddress; let holder = Holder.load(id); if (holder == null) { @@ -149,7 +150,7 @@ export function handleTransfer(event: Transfer): void { ); const eventDayData = getEventDayData(event); - const escrow = Escrow.load(event.params._to.toHex()); + const escrow = Escrow.load(event.params._to); if (escrow) { // Create FundEvent entity const fundEventEntity = new FundEvent(toEventId(event)); @@ -205,7 +206,7 @@ export function handleTransfer(event: Transfer): void { // Update unique sender const uniqueSender = createOrLoadUniqueSender( - dayStartTimestamp.toString(), + BigInt.fromI32(dayStartTimestamp), event.block.timestamp, event.params._from ); @@ -220,7 +221,7 @@ export function handleTransfer(event: Transfer): void { // Update unique receiver const uniqueReceiver = createOrLoadUniqueReceiver( - dayStartTimestamp.toString(), + BigInt.fromI32(dayStartTimestamp), event.block.timestamp, event.params._to ); @@ -234,7 +235,7 @@ export function handleTransfer(event: Transfer): void { uniqueReceiver.save(); // Track HMT transfer from Escrow for paidAmount, balance, and payout items - const fromEscrow = Escrow.load(event.params._from.toHex()); + const fromEscrow = Escrow.load(event.params._from); if (fromEscrow) { fromEscrow.amountPaid = fromEscrow.amountPaid.plus(event.params._value); fromEscrow.balance = fromEscrow.balance.minus(event.params._value); @@ -248,7 +249,7 @@ export function handleTransfer(event: Transfer): void { worker.payoutCount = worker.payoutCount.plus(ONE_BI); worker.save(); - const payoutId = `${event.transaction.hash.toHex()}-${event.params._to.toHex()}`; + const payoutId = event.transaction.hash.concat(event.params._to); const payment = new Payout(payoutId); payment.escrowAddress = event.params._from; payment.recipient = event.params._to; @@ -263,11 +264,14 @@ export function handleTransfer(event: Transfer): void { ); const eventDayId = toEventDayId(event); - const dailyWorkerId = `${eventDayId}-${event.params._to.toHex()}`; + const dailyWorkerId = Bytes.fromI32(eventDayId.toI32()).concat( + event.params._to + ); + let dailyWorker = DailyWorker.load(dailyWorkerId); if (!dailyWorker) { dailyWorker = new DailyWorker(dailyWorkerId); - dailyWorker.timestamp = BigInt.fromString(eventDayId); + dailyWorker.timestamp = eventDayId; dailyWorker.address = event.params._to; dailyWorker.escrowAddress = event.params._from; dailyWorker.save(); diff --git a/packages/sdk/typescript/subgraph/src/mapping/KVStore.ts b/packages/sdk/typescript/subgraph/src/mapping/KVStore.ts index da20ec6a88..d7d16f8f0c 100644 --- a/packages/sdk/typescript/subgraph/src/mapping/KVStore.ts +++ b/packages/sdk/typescript/subgraph/src/mapping/KVStore.ts @@ -11,9 +11,10 @@ import { toEventId } from './utils/event'; import { isValidEthAddress } from './utils/ethAdrress'; import { Address, BigInt } from '@graphprotocol/graph-ts'; import { createTransaction } from './utils/transaction'; +import { toBytes } from './utils/string'; export function createOrLoadLeaderURL(leader: Leader, key: string): LeaderURL { - const entityId = `${leader.address.toHex()}-${key}`; + const entityId = leader.address.concat(toBytes(key)); let leaderUrl = LeaderURL.load(entityId); if (!leaderUrl) { @@ -29,10 +30,10 @@ export function createOrLoadLeaderURL(leader: Leader, key: string): LeaderURL { export function createOrLoadReputationNetwork( address: Address ): ReputationNetwork { - let reputationNetwork = ReputationNetwork.load(address.toHex()); + let reputationNetwork = ReputationNetwork.load(address); if (!reputationNetwork) { - reputationNetwork = new ReputationNetwork(address.toHex()); + reputationNetwork = new ReputationNetwork(address); reputationNetwork.address = address; reputationNetwork.save(); } @@ -41,7 +42,7 @@ export function createOrLoadReputationNetwork( } export function createOrUpdateKVStore(event: DataSaved): void { - const kvstoreId = `${event.params.sender.toHex()}-${event.params.key.toString()}`; + const kvstoreId = event.params.sender.concat(toBytes(event.params.key)); let kvstore = KVStore.load(kvstoreId); if (!kvstore) { @@ -104,7 +105,7 @@ export function handleDataSaved(event: DataSaved): void { if (event.params.value == 'ACTIVE') { operator.reputationNetwork = reputationNetwork.id; } else if (event.params.value == 'INACTIVE') { - operator.reputationNetwork = ''; + operator.reputationNetwork = null; } operator.save(); } diff --git a/packages/sdk/typescript/subgraph/src/mapping/Staking.ts b/packages/sdk/typescript/subgraph/src/mapping/Staking.ts index 0da74a8156..312fe18e07 100644 --- a/packages/sdk/typescript/subgraph/src/mapping/Staking.ts +++ b/packages/sdk/typescript/subgraph/src/mapping/Staking.ts @@ -20,8 +20,9 @@ import { Address } from '@graphprotocol/graph-ts'; import { ONE_BI, ZERO_BI } from './utils/number'; import { toEventId } from './utils/event'; import { createTransaction } from './utils/transaction'; +import { toBytes } from './utils/string'; -export const STATISTICS_ENTITY_ID = 'leader-statistics-id'; +export const STATISTICS_ENTITY_ID = toBytes('leader-statistics-id'); function constructStatsEntity(): LeaderStatistics { const entity = new LeaderStatistics(STATISTICS_ENTITY_ID); @@ -42,10 +43,10 @@ export function createOrLoadLeaderStatistics(): LeaderStatistics { } export function createOrLoadLeader(address: Address): Leader { - let leader = Leader.load(address.toHex()); + let leader = Leader.load(address); if (!leader) { - leader = new Leader(address.toHex()); + leader = new Leader(address); leader.address = address; leader.amountStaked = ZERO_BI; diff --git a/packages/sdk/typescript/subgraph/src/mapping/legacy/Escrow.ts b/packages/sdk/typescript/subgraph/src/mapping/legacy/Escrow.ts index b5304e0301..98beb1019e 100644 --- a/packages/sdk/typescript/subgraph/src/mapping/legacy/Escrow.ts +++ b/packages/sdk/typescript/subgraph/src/mapping/legacy/Escrow.ts @@ -59,7 +59,7 @@ export function handlePending(event: Pending): void { ); // Update escrow entity - const escrowEntity = Escrow.load(dataSource.address().toHex()); + const escrowEntity = Escrow.load(dataSource.address()); if (escrowEntity) { escrowEntity.manifestUrl = event.params.manifest; escrowEntity.manifestHash = event.params.hash; @@ -72,19 +72,11 @@ export function handlePending(event: Pending): void { if (!reputationOracle.reverted) { escrowEntity.reputationOracle = reputationOracle.value; } - const reputationOracleStake = escrowContract.try_reputationOracleStake(); - if (!reputationOracleStake.reverted) { - escrowEntity.reputationOracleFee = reputationOracleStake.value; - } const recordingOracle = escrowContract.try_recordingOracle(); if (!recordingOracle.reverted) { escrowEntity.recordingOracle = recordingOracle.value; } - const recordingOracleStake = escrowContract.try_recordingOracleStake(); - if (!recordingOracleStake.reverted) { - escrowEntity.recordingOracleFee = recordingOracleStake.value; - } escrowEntity.save(); } @@ -118,7 +110,7 @@ export function handleIntermediateStorage(event: IntermediateStorage): void { eventDayData.save(); // Update escrow entity - const escrowEntity = Escrow.load(dataSource.address().toHex()); + const escrowEntity = Escrow.load(dataSource.address()); if (escrowEntity) { escrowEntity.intermediateResultsUrl = event.params._url; escrowEntity.save(); @@ -152,7 +144,7 @@ export function handleBulkTransfer(event: BulkTransfer): void { eventDayData.dailyTotalEventCount.plus(ONE_BI); // Update escrow entity - const escrowEntity = Escrow.load(dataSource.address().toHex()); + const escrowEntity = Escrow.load(dataSource.address()); if (escrowEntity) { // Read data on-chain const escrowContract = EscrowContract.bind(event.address); diff --git a/packages/sdk/typescript/subgraph/src/mapping/legacy/EscrowFactory.ts b/packages/sdk/typescript/subgraph/src/mapping/legacy/EscrowFactory.ts index 04b904c7a3..81894eb7cf 100644 --- a/packages/sdk/typescript/subgraph/src/mapping/legacy/EscrowFactory.ts +++ b/packages/sdk/typescript/subgraph/src/mapping/legacy/EscrowFactory.ts @@ -11,7 +11,7 @@ export function handleLaunched(event: Launched): void { createTransaction(event, 'createEscrow'); // Create Escrow entity - const entity = new Escrow(event.params.escrow.toHex()); + const entity = new Escrow(event.params.escrow); entity.createdAt = event.block.timestamp; entity.address = event.params.escrow; diff --git a/packages/sdk/typescript/subgraph/src/mapping/utils/dayUpdates.ts b/packages/sdk/typescript/subgraph/src/mapping/utils/dayUpdates.ts index 9e8e29e817..bb1abb511e 100644 --- a/packages/sdk/typescript/subgraph/src/mapping/utils/dayUpdates.ts +++ b/packages/sdk/typescript/subgraph/src/mapping/utils/dayUpdates.ts @@ -1,4 +1,4 @@ -import { ethereum } from '@graphprotocol/graph-ts'; +import { Bytes, ethereum } from '@graphprotocol/graph-ts'; import { EventDayData } from '../../../generated/schema'; import { ZERO_BI, ONE_DAY } from './number'; @@ -7,9 +7,11 @@ export function getEventDayData(event: ethereum.Event): EventDayData { const dayID = timestamp / ONE_DAY; const dayStartTimestamp = dayID * ONE_DAY; - let eventDayData = EventDayData.load(dayID.toString()); + const eventDayDataID = Bytes.fromI32(dayID); + + let eventDayData = EventDayData.load(eventDayDataID); if (eventDayData === null) { - eventDayData = new EventDayData(dayID.toString()); + eventDayData = new EventDayData(eventDayDataID); eventDayData.timestamp = dayStartTimestamp; eventDayData.dailyFundEventCount = ZERO_BI; eventDayData.dailySetupEventCount = ZERO_BI; diff --git a/packages/sdk/typescript/subgraph/src/mapping/utils/event.ts b/packages/sdk/typescript/subgraph/src/mapping/utils/event.ts index 3a2cf9bdc4..670aac7fa1 100644 --- a/packages/sdk/typescript/subgraph/src/mapping/utils/event.ts +++ b/packages/sdk/typescript/subgraph/src/mapping/utils/event.ts @@ -1,16 +1,16 @@ -import { ethereum } from '@graphprotocol/graph-ts'; +import { BigInt, Bytes, ethereum } from '@graphprotocol/graph-ts'; import { ONE_DAY } from './number'; -export function toEventId(event: ethereum.Event): string { - return `${event.transaction.hash.toHex()}-${event.logIndex.toString()}-${ - event.block.timestamp - }`; +export function toEventId(event: ethereum.Event): Bytes { + return event.transaction.hash + .concatI32(event.logIndex.toI32()) + .concatI32(event.block.timestamp.toI32()); } -export function toEventDayId(event: ethereum.Event): string { +export function toEventDayId(event: ethereum.Event): BigInt { const timestamp = event.block.timestamp.toI32(); const dayID = timestamp / ONE_DAY; const dayStartTimestamp = dayID * ONE_DAY; - return dayStartTimestamp.toString(); + return BigInt.fromI32(dayStartTimestamp); } diff --git a/packages/sdk/typescript/subgraph/src/mapping/utils/string.ts b/packages/sdk/typescript/subgraph/src/mapping/utils/string.ts new file mode 100644 index 0000000000..73d48986b5 --- /dev/null +++ b/packages/sdk/typescript/subgraph/src/mapping/utils/string.ts @@ -0,0 +1,5 @@ +import { Bytes } from '@graphprotocol/graph-ts'; + +export const toBytes = (str: string): Bytes => { + return Bytes.fromUTF8(str); +}; diff --git a/packages/sdk/typescript/subgraph/src/mapping/utils/transaction.ts b/packages/sdk/typescript/subgraph/src/mapping/utils/transaction.ts index a5c0f17692..c7830c2a75 100644 --- a/packages/sdk/typescript/subgraph/src/mapping/utils/transaction.ts +++ b/packages/sdk/typescript/subgraph/src/mapping/utils/transaction.ts @@ -7,7 +7,7 @@ export function createTransaction( to: Address | null = null, value: BigInt | null = null ): void { - const transaction = new Transaction(event.transaction.hash.toHex()); + const transaction = new Transaction(event.transaction.hash); transaction.from = event.transaction.from; transaction.to = to !== null ? to : event.transaction.to; diff --git a/packages/sdk/typescript/subgraph/template.yaml b/packages/sdk/typescript/subgraph/template.yaml index 1c457eb224..24c2c63454 100644 --- a/packages/sdk/typescript/subgraph/template.yaml +++ b/packages/sdk/typescript/subgraph/template.yaml @@ -1,4 +1,4 @@ -specVersion: 0.0.5 +specVersion: 1.0.0 description: '{{ description }}' schema: file: ./schema.graphql @@ -129,7 +129,6 @@ dataSources: - event: RewardAdded(indexed address,indexed address,indexed address,uint256) handler: handleRewardAdded file: ./src/mapping/RewardPool.ts -{{ #LegacyEscrowFactory }} - kind: ethereum name: LegacyEscrowFactory network: '{{ network }}' @@ -150,7 +149,6 @@ dataSources: eventHandlers: - event: Launched(address,address) handler: handleLaunched -{{ /LegacyEscrowFactory }} templates: - name: Escrow kind: ethereum/contract diff --git a/packages/sdk/typescript/subgraph/tests/escrow-factory/escrow-factory.test.ts b/packages/sdk/typescript/subgraph/tests/escrow-factory/escrow-factory.test.ts index 2b185695af..0190690bb9 100644 --- a/packages/sdk/typescript/subgraph/tests/escrow-factory/escrow-factory.test.ts +++ b/packages/sdk/typescript/subgraph/tests/escrow-factory/escrow-factory.test.ts @@ -7,9 +7,10 @@ import { afterAll, } from 'matchstick-as/assembly'; -import { createLaunchedEvent } from './fixtures'; import { STATISTICS_ENTITY_ID } from '../../src/mapping/Escrow'; import { handleLaunched } from '../../src/mapping/EscrowFactory'; +import { toEventId } from '../../src/mapping/utils/event'; +import { createLaunchedEvent } from './fixtures'; const factoryAddressString = '0x92a2eef7ff696bcef98957a0189872680600a958'; const factoryAddress = Address.fromString(factoryAddressString); @@ -121,7 +122,7 @@ describe('EscrowFactory', () => { // Stats Entity assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'totalEscrowCount', '2' ); @@ -135,9 +136,7 @@ describe('EscrowFactory', () => { ); // EscrowStatusEvent - const id1 = `${data1.transaction.hash.toHex()}-${data1.logIndex.toString()}-${ - data1.block.timestamp - }`; + const id1 = toEventId(data1).toHex(); assert.fieldEquals( 'EscrowStatusEvent', diff --git a/packages/sdk/typescript/subgraph/tests/escrow/escrow.test.ts b/packages/sdk/typescript/subgraph/tests/escrow/escrow.test.ts index ba4c8d8998..44a329f6c2 100644 --- a/packages/sdk/typescript/subgraph/tests/escrow/escrow.test.ts +++ b/packages/sdk/typescript/subgraph/tests/escrow/escrow.test.ts @@ -25,6 +25,7 @@ import { handleCancelled, handleCompleted, } from '../../src/mapping/Escrow'; +import { toEventId } from '../../src/mapping/utils/event'; import { ZERO_BI } from '../../src/mapping/utils/number'; import { createISEvent, @@ -80,7 +81,7 @@ describe('Escrow', () => { 'finalResultsUrl():(string)' ).returns([ethereum.Value.fromString('test.com')]); - const escrow = new Escrow(escrowAddress.toHex()); + const escrow = new Escrow(escrowAddress); escrow.address = escrowAddress; escrow.token = Address.zero(); escrow.factoryAddress = Address.zero(); @@ -103,46 +104,17 @@ describe('Escrow', () => { const URL = 'test.com'; const HASH = 'is_hash_1'; - createMockedFunction( - escrowAddress, - 'reputationOracleStake', - 'reputationOracleStake():(uint256)' - ).returns([ethereum.Value.fromI32(10)]); - createMockedFunction( - escrowAddress, - 'reputationOracleFeePercentage', - 'reputationOracleFeePercentage():(uint8)' - ).reverts(); - - createMockedFunction( - escrowAddress, - 'recordingOracleStake', - 'recordingOracleStake():(uint256)' - ).returns([ethereum.Value.fromI32(20)]); - createMockedFunction( - escrowAddress, - 'recordingOracleFeePercentage', - 'recordingOracleFeePercentage():(uint8)' - ).reverts(); - createMockedFunction( escrowAddress, 'exchangeOracle', 'exchangeOracle():(address)' ).reverts(); - createMockedFunction( - escrowAddress, - 'exchangeOracleFeePercentage', - 'exchangeOracleFeePercentage():(uint8)' - ).reverts(); const newPending1 = createPendingEvent(operatorAddress, URL, HASH); handlePending(newPending1); - const id = `${newPending1.transaction.hash.toHex()}-${newPending1.logIndex.toString()}-${ - newPending1.block.timestamp - }`; + const id = toEventId(newPending1).toHex(); // SetupEvent assert.fieldEquals( @@ -215,24 +187,12 @@ describe('Escrow', () => { 'reputationOracle', reputationOracleAddressString ); - assert.fieldEquals( - 'Escrow', - escrowAddress.toHex(), - 'reputationOracleFee', - '10' - ); assert.fieldEquals( 'Escrow', escrowAddress.toHex(), 'recordingOracle', recordingOracleAddressString ); - assert.fieldEquals( - 'Escrow', - escrowAddress.toHex(), - 'recordingOracleFee', - '20' - ); assert.fieldEquals( 'Transaction', newPending1.transaction.hash.toHex(), @@ -269,45 +229,17 @@ describe('Escrow', () => { const URL = 'test.com'; const HASH = 'is_hash_1'; - createMockedFunction( - escrowAddress, - 'reputationOracleStake', - 'reputationOracleStake():(uint256)' - ).reverts(); - createMockedFunction( - escrowAddress, - 'reputationOracleFeePercentage', - 'reputationOracleFeePercentage():(uint8)' - ).returns([ethereum.Value.fromI32(10)]); - createMockedFunction( - escrowAddress, - 'recordingOracleStake', - 'recordingOracleStake():(uint256)' - ).reverts(); - createMockedFunction( - escrowAddress, - 'recordingOracleFeePercentage', - 'recordingOracleFeePercentage():(uint8)' - ).returns([ethereum.Value.fromI32(20)]); - createMockedFunction( escrowAddress, 'exchangeOracle', 'exchangeOracle():(address)' ).reverts(); - createMockedFunction( - escrowAddress, - 'exchangeOracleFeePercentage', - 'exchangeOracleFeePercentage():(uint8)' - ).reverts(); const newPending1 = createPendingEvent(operatorAddress, URL, HASH); handlePending(newPending1); - const id = `${newPending1.transaction.hash.toHex()}-${newPending1.logIndex.toString()}-${ - newPending1.block.timestamp - }`; + const id = toEventId(newPending1).toHex(); // SetupEvent assert.fieldEquals( @@ -380,24 +312,14 @@ describe('Escrow', () => { 'reputationOracle', reputationOracleAddressString ); - assert.fieldEquals( - 'Escrow', - escrowAddress.toHex(), - 'reputationOracleFee', - '10' - ); + assert.fieldEquals( 'Escrow', escrowAddress.toHex(), 'recordingOracle', recordingOracleAddressString ); - assert.fieldEquals( - 'Escrow', - escrowAddress.toHex(), - 'recordingOracleFee', - '20' - ); + assert.fieldEquals( 'Transaction', newPending1.transaction.hash.toHex(), @@ -434,45 +356,17 @@ describe('Escrow', () => { const URL = 'test.com'; const HASH = 'is_hash_1'; - createMockedFunction( - escrowAddress, - 'reputationOracleStake', - 'reputationOracleStake():(uint256)' - ).reverts(); - createMockedFunction( - escrowAddress, - 'reputationOracleFeePercentage', - 'reputationOracleFeePercentage():(uint8)' - ).returns([ethereum.Value.fromI32(10)]); - createMockedFunction( - escrowAddress, - 'recordingOracleStake', - 'recordingOracleStake():(uint256)' - ).reverts(); - createMockedFunction( - escrowAddress, - 'recordingOracleFeePercentage', - 'recordingOracleFeePercentage():(uint8)' - ).returns([ethereum.Value.fromI32(20)]); - createMockedFunction( escrowAddress, 'exchangeOracle', 'exchangeOracle():(address)' ).returns([ethereum.Value.fromAddress(exchangeOracleAddress)]); - createMockedFunction( - escrowAddress, - 'exchangeOracleFeePercentage', - 'exchangeOracleFeePercentage():(uint8)' - ).returns([ethereum.Value.fromI32(30)]); const newPending1 = createPendingEvent(operatorAddress, URL, HASH); handlePending(newPending1); - const id = `${newPending1.transaction.hash.toHex()}-${newPending1.logIndex.toString()}-${ - newPending1.block.timestamp - }`; + const id = toEventId(newPending1).toHex(); // SetupEvent assert.fieldEquals( @@ -545,36 +439,18 @@ describe('Escrow', () => { 'reputationOracle', reputationOracleAddressString ); - assert.fieldEquals( - 'Escrow', - escrowAddress.toHex(), - 'reputationOracleFee', - '10' - ); assert.fieldEquals( 'Escrow', escrowAddress.toHex(), 'recordingOracle', recordingOracleAddressString ); - assert.fieldEquals( - 'Escrow', - escrowAddress.toHex(), - 'recordingOracleFee', - '20' - ); assert.fieldEquals( 'Escrow', escrowAddress.toHex(), 'exchangeOracle', exchangeOracleAddressString ); - assert.fieldEquals( - 'Escrow', - escrowAddress.toHex(), - 'exchangeOracleFee', - '30' - ); assert.fieldEquals( 'Transaction', newPending1.transaction.hash.toHex(), @@ -612,9 +488,7 @@ describe('Escrow', () => { const newIS = createISEvent(workerAddress, URL, 'is_hash_1'); handleIntermediateStorage(newIS); - const id = `${newIS.transaction.hash.toHex()}-${newIS.logIndex.toString()}-${ - newIS.block.timestamp - }`; + const id = toEventId(newIS).toHex(); // StoreResultsEvent assert.fieldEquals( @@ -688,9 +562,7 @@ describe('Escrow', () => { handleBulkTransfer(bulk1); - const id1 = `${bulk1.transaction.hash.toHex()}-${bulk1.logIndex.toString()}-${ - bulk1.block.timestamp - }`; + const id1 = toEventId(bulk1).toHex(); // BulkPayoutEvent assert.fieldEquals( @@ -775,9 +647,7 @@ describe('Escrow', () => { handleBulkTransfer(bulk2); - const id2 = `${bulk2.transaction.hash.toHex()}-${bulk2.logIndex.toString()}-${ - bulk2.block.timestamp - }`; + const id2 = toEventId(bulk2).toHex(); assert.fieldEquals( 'BulkPayoutEvent', @@ -891,9 +761,7 @@ describe('Escrow', () => { handleCancelled(newCancelled); - const id = `${newCancelled.transaction.hash.toHex()}-${newCancelled.logIndex.toString()}-${ - newCancelled.block.timestamp - }`; + const id = toEventId(newCancelled).toHex(); // EscrowStatusEvent assert.fieldEquals( @@ -973,9 +841,7 @@ describe('Escrow', () => { handleCompleted(newCompleted); - const id = `${newCompleted.transaction.hash.toHex()}-${newCompleted.logIndex.toString()}-${ - newCompleted.block.timestamp - }`; + const id = toEventId(newCompleted).toHex(); // EscrowStatusEvent assert.fieldEquals( @@ -1072,13 +938,13 @@ describe('Escrow', () => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'setupEventCount', '2' ); assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'pendingStatusEventCount', '2' ); @@ -1094,7 +960,7 @@ describe('Escrow', () => { ].forEach((field) => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), field, '0' ); @@ -1102,7 +968,7 @@ describe('Escrow', () => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'totalEventCount', '4' ); @@ -1117,7 +983,7 @@ describe('Escrow', () => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'storeResultsEventCount', '2' ); @@ -1134,7 +1000,7 @@ describe('Escrow', () => { ].forEach((field) => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), field, '0' ); @@ -1142,7 +1008,7 @@ describe('Escrow', () => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'totalEventCount', '2' ); @@ -1178,19 +1044,19 @@ describe('Escrow', () => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'bulkPayoutEventCount', '2' ); assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'partialStatusEventCount', '1' ); assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'paidStatusEventCount', '1' ); @@ -1205,7 +1071,7 @@ describe('Escrow', () => { ].forEach((field) => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), field, '0' ); @@ -1213,7 +1079,7 @@ describe('Escrow', () => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'totalEventCount', '4' ); @@ -1228,7 +1094,7 @@ describe('Escrow', () => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'cancelledStatusEventCount', '2' ); @@ -1245,7 +1111,7 @@ describe('Escrow', () => { ].forEach((field) => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), field, '0' ); @@ -1253,7 +1119,7 @@ describe('Escrow', () => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'totalEventCount', '2' ); @@ -1268,7 +1134,7 @@ describe('Escrow', () => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'completedStatusEventCount', '2' ); @@ -1285,7 +1151,7 @@ describe('Escrow', () => { ].forEach((field) => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), field, '0' ); @@ -1293,7 +1159,7 @@ describe('Escrow', () => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'totalEventCount', '2' ); diff --git a/packages/sdk/typescript/subgraph/tests/hmt/hmt.test.ts b/packages/sdk/typescript/subgraph/tests/hmt/hmt.test.ts index 30b89c31ac..235b1bbe8e 100644 --- a/packages/sdk/typescript/subgraph/tests/hmt/hmt.test.ts +++ b/packages/sdk/typescript/subgraph/tests/hmt/hmt.test.ts @@ -19,6 +19,7 @@ import { handleApproval, handleBulkApproval, } from '../../src/mapping/HMToken'; +import { toEventId } from '../../src/mapping/utils/event'; import { ZERO_BI } from '../../src/mapping/utils/number'; import { createTransferEvent, @@ -30,6 +31,7 @@ import { const escrowAddressString = '0xa16081f360e3847006db660bae1c6d1b2e17ec2a'; const escrowAddress = Address.fromString(escrowAddressString); const operatorAddressString = '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266'; +const operatorAddress = Address.fromString(operatorAddressString); const holderAddressString = '0x70997970c51812dc3a010c7d01b50e0d17dc79c8'; const holderAddress = Address.fromString(holderAddressString); const holder1AddressString = '0x92a2eEF7Ff696BCef98957a0189872680600a959'; @@ -43,7 +45,7 @@ describe('HMToken', () => { new DataSourceContext() ); - const escrow = new Escrow(escrowAddress.toHex()); + const escrow = new Escrow(escrowAddress); escrow.address = escrowAddress; escrow.token = Address.zero(); escrow.factoryAddress = Address.zero(); @@ -73,9 +75,7 @@ describe('HMToken', () => { handleTransfer(transfer); - const id = `${transfer.transaction.hash.toHex()}-${transfer.logIndex.toString()}-${ - transfer.block.timestamp - }`; + const id = toEventId(transfer).toHex(); // HMTTransferEvent assert.fieldEquals( @@ -179,9 +179,7 @@ describe('HMToken', () => { handleTransfer(transfer); - const id = `${transfer.transaction.hash.toHex()}-${transfer.logIndex.toString()}-${ - transfer.block.timestamp - }`; + const id = toEventId(transfer).toHex(); // HMTTransferEvent assert.fieldEquals( @@ -229,9 +227,7 @@ describe('HMToken', () => { handleTransfer(transfer); - const id = `${transfer.transaction.hash.toHex()}-${transfer.logIndex.toString()}-${ - transfer.block.timestamp - }`; + const id = toEventId(transfer).toHex(); // HMTTransferEvent assert.fieldEquals( @@ -270,7 +266,9 @@ describe('HMToken', () => { assert.fieldEquals('Worker', operatorAddressString, 'payoutCount', '1'); // Payout - const payoutId = `${transfer.transaction.hash.toHex()}-${operatorAddressString}`; + const payoutId = transfer.transaction.hash + .concat(operatorAddress) + .toHex(); assert.fieldEquals( 'Payout', payoutId, @@ -284,6 +282,8 @@ describe('HMToken', () => { operatorAddressString ); assert.fieldEquals('Payout', payoutId, 'amount', '1'); + + // Transaction assert.fieldEquals( 'Transaction', transfer.transaction.hash.toHex(), @@ -328,9 +328,7 @@ describe('HMToken', () => { handleBulkTransfer(bulkTransfer); - const id = `${bulkTransfer.transaction.hash.toHex()}-${bulkTransfer.logIndex.toString()}-${ - bulkTransfer.block.timestamp - }`; + const id = toEventId(bulkTransfer).toHex(); // HMTBulkTransferEvent assert.fieldEquals( @@ -389,9 +387,7 @@ describe('HMToken', () => { handleApproval(approval); - const id = `${approval.transaction.hash.toHex()}-${approval.logIndex.toString()}-${ - approval.block.timestamp - }`; + const id = toEventId(approval).toHex(); // HMTApprovalEvent assert.fieldEquals( @@ -463,9 +459,7 @@ describe('HMToken', () => { handleBulkApproval(bulkApproval); - const id = `${bulkApproval.transaction.hash.toHex()}-${bulkApproval.logIndex.toString()}-${ - bulkApproval.block.timestamp - }`; + const id = toEventId(bulkApproval).toHex(); // HMTBulkApprovalEvent assert.fieldEquals( @@ -538,13 +532,13 @@ describe('HMToken', () => { assert.fieldEquals( 'HMTokenStatistics', - HMT_STATISTICS_ENTITY_ID, + HMT_STATISTICS_ENTITY_ID.toHex(), 'totalTransferEventCount', '2' ); assert.fieldEquals( 'HMTokenStatistics', - HMT_STATISTICS_ENTITY_ID, + HMT_STATISTICS_ENTITY_ID.toHex(), 'totalValueTransfered', '3' ); @@ -573,7 +567,7 @@ describe('HMToken', () => { assert.fieldEquals( 'HMTokenStatistics', - HMT_STATISTICS_ENTITY_ID, + HMT_STATISTICS_ENTITY_ID.toHex(), 'holders', '1' ); @@ -591,7 +585,7 @@ describe('HMToken', () => { assert.fieldEquals('Holder', holder1Address.toHex(), 'balance', '10'); assert.fieldEquals( 'HMTokenStatistics', - HMT_STATISTICS_ENTITY_ID, + HMT_STATISTICS_ENTITY_ID.toHex(), 'holders', '2' ); @@ -609,7 +603,7 @@ describe('HMToken', () => { assert.fieldEquals('Holder', holder1Address.toHex(), 'balance', '20'); assert.fieldEquals( 'HMTokenStatistics', - HMT_STATISTICS_ENTITY_ID, + HMT_STATISTICS_ENTITY_ID.toHex(), 'holders', '1' ); @@ -624,7 +618,7 @@ describe('HMToken', () => { assert.fieldEquals( 'HMTokenStatistics', - HMT_STATISTICS_ENTITY_ID, + HMT_STATISTICS_ENTITY_ID.toHex(), 'totalBulkTransferEventCount', '2' ); @@ -650,7 +644,7 @@ describe('HMToken', () => { assert.fieldEquals( 'HMTokenStatistics', - HMT_STATISTICS_ENTITY_ID, + HMT_STATISTICS_ENTITY_ID.toHex(), 'totalApprovalEventCount', '2' ); @@ -665,14 +659,14 @@ describe('HMToken', () => { assert.fieldEquals( 'HMTokenStatistics', - HMT_STATISTICS_ENTITY_ID, + HMT_STATISTICS_ENTITY_ID.toHex(), 'totalBulkApprovalEventCount', '2' ); }); test('Should properly calculate FundEvent in statistics, when sending to escrow', () => { - const escrow = new Escrow(escrowAddress.toHex()); + const escrow = new Escrow(escrowAddress); escrow.address = escrowAddress; escrow.token = Address.zero(); escrow.factoryAddress = Address.zero(); @@ -706,7 +700,7 @@ describe('HMToken', () => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'fundEventCount', '2' ); @@ -723,7 +717,7 @@ describe('HMToken', () => { ].forEach((field) => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), field, '0' ); @@ -731,7 +725,7 @@ describe('HMToken', () => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'totalEventCount', '2' ); diff --git a/packages/sdk/typescript/subgraph/tests/kvstore/kvstore.test.ts b/packages/sdk/typescript/subgraph/tests/kvstore/kvstore.test.ts index d33e102832..4c7696adb8 100644 --- a/packages/sdk/typescript/subgraph/tests/kvstore/kvstore.test.ts +++ b/packages/sdk/typescript/subgraph/tests/kvstore/kvstore.test.ts @@ -8,6 +8,8 @@ import { } from 'matchstick-as/assembly'; import { handleDataSaved } from '../../src/mapping/KVStore'; +import { toEventId } from '../../src/mapping/utils/event'; +import { toBytes } from '../../src/mapping/utils/string'; import { createDataSavedEvent } from './fixtures'; describe('KVStore', () => { @@ -32,12 +34,8 @@ describe('KVStore', () => { handleDataSaved(data1); handleDataSaved(data2); - const id1 = `${data1.transaction.hash.toHex()}-${data1.logIndex.toString()}-${ - data1.block.timestamp - }`; - const id2 = `${data2.transaction.hash.toHex()}-${data2.logIndex.toString()}-${ - data2.block.timestamp - }`; + const id1 = toEventId(data1).toHex(); + const id2 = toEventId(data2).toHex(); // Data 1 assert.fieldEquals( @@ -62,7 +60,7 @@ describe('KVStore', () => { 'KVStoreSetEvent', id1, 'leaderAddress', - data1.params.sender.toHexString() + data1.params.sender.toHex() ); assert.fieldEquals('KVStoreSetEvent', id1, 'key', 'role'); assert.fieldEquals('KVStoreSetEvent', id1, 'value', 'Operator'); @@ -90,7 +88,7 @@ describe('KVStore', () => { 'KVStoreSetEvent', id2, 'leaderAddress', - data2.params.sender.toHexString() + data2.params.sender.toHex() ); assert.fieldEquals('KVStoreSetEvent', id2, 'key', 'role'); assert.fieldEquals('KVStoreSetEvent', id2, 'value', 'Validator'); @@ -182,13 +180,13 @@ describe('KVStore', () => { assert.fieldEquals( 'Leader', - data1.params.sender.toHexString(), + data1.params.sender.toHex(), 'role', 'Operator' ); assert.fieldEquals( 'Leader', - data2.params.sender.toHexString(), + data2.params.sender.toHex(), 'role', 'Validator' ); @@ -211,18 +209,8 @@ describe('KVStore', () => { handleDataSaved(data1); handleDataSaved(data2); - assert.fieldEquals( - 'Leader', - data1.params.sender.toHexString(), - 'fee', - '10' - ); - assert.fieldEquals( - 'Leader', - data2.params.sender.toHexString(), - 'fee', - '11' - ); + assert.fieldEquals('Leader', data1.params.sender.toHex(), 'fee', '10'); + assert.fieldEquals('Leader', data2.params.sender.toHex(), 'fee', '11'); }); test("Should properly update leader's public key", () => { @@ -254,7 +242,7 @@ describe('KVStore', () => { assert.fieldEquals( 'Leader', - data1.params.sender.toHexString(), + data1.params.sender.toHex(), 'publicKey', `-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCRxdc9o3XUliS8peqMEwIt8+nE @@ -265,7 +253,7 @@ describe('KVStore', () => { ); assert.fieldEquals( 'Leader', - data2.params.sender.toHexString(), + data2.params.sender.toHex(), 'publicKey', `-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCzcUeZlurLuQuDzc4ZhJMiDete @@ -295,38 +283,38 @@ describe('KVStore', () => { assert.fieldEquals( 'Leader', - data1.params.sender.toHexString(), + data1.params.sender.toHex(), 'webhookUrl', 'https://operator.example.com' ); assert.fieldEquals( 'LeaderURL', - `${data1.params.sender.toHexString()}-webhook_url`, + data1.params.sender.concat(toBytes('webhook_url')).toHex(), 'key', 'webhook_url' ); assert.fieldEquals( 'LeaderURL', - `${data1.params.sender.toHexString()}-webhook_url`, + data1.params.sender.concat(toBytes('webhook_url')).toHex(), 'url', 'https://operator.example.com' ); assert.fieldEquals( 'Leader', - data2.params.sender.toHexString(), + data2.params.sender.toHex(), 'webhookUrl', 'https://validator.example.com' ); assert.fieldEquals( 'LeaderURL', - `${data2.params.sender.toHexString()}-webhook_url`, + data2.params.sender.concat(toBytes('webhook_url')).toHex(), 'key', 'webhook_url' ); assert.fieldEquals( 'LeaderURL', - `${data2.params.sender.toHexString()}-webhook_url`, + data2.params.sender.concat(toBytes('webhook_url')).toHex(), 'url', 'https://validator.example.com' ); @@ -351,38 +339,38 @@ describe('KVStore', () => { assert.fieldEquals( 'Leader', - data1.params.sender.toHexString(), + data1.params.sender.toHex(), 'url', 'https://operator.example.com' ); assert.fieldEquals( 'LeaderURL', - `${data1.params.sender.toHexString()}-url`, + data1.params.sender.concat(toBytes('url')).toHex(), 'key', 'url' ); assert.fieldEquals( 'LeaderURL', - `${data1.params.sender.toHexString()}-url`, + data1.params.sender.concat(toBytes('url')).toHex(), 'url', 'https://operator.example.com' ); assert.fieldEquals( 'Leader', - data2.params.sender.toHexString(), + data2.params.sender.toHex(), 'url', 'https://validator.example.com' ); assert.fieldEquals( 'LeaderURL', - `${data2.params.sender.toHexString()}-url`, + data2.params.sender.concat(toBytes('url')).toHex(), 'key', 'url' ); assert.fieldEquals( 'LeaderURL', - `${data2.params.sender.toHexString()}-url`, + data2.params.sender.concat(toBytes('url')).toHex(), 'url', 'https://validator.example.com' ); @@ -413,21 +401,21 @@ describe('KVStore', () => { assert.fieldEquals( 'Leader', - data1.params.sender.toHexString(), + data1.params.sender.toHex(), 'role', 'Reputation Oracle' ); assert.fieldEquals( 'Leader', - data2.params.sender.toHexString(), + data2.params.sender.toHex(), 'role', 'Job Launcher' ); assert.fieldEquals( 'Leader', - data2.params.sender.toHexString(), + data2.params.sender.toHex(), 'reputationNetwork', - data1.params.sender.toHexString() + data1.params.sender.toHex() ); }); @@ -448,13 +436,13 @@ describe('KVStore', () => { assert.fieldEquals( 'KVStore', - `${data1.params.sender.toHexString()}-${data1.params.key}`, + data1.params.sender.concat(toBytes(data1.params.key)).toHex(), 'key', 'role' ); assert.fieldEquals( 'KVStore', - `${data1.params.sender.toHexString()}-${data1.params.key}`, + data1.params.sender.concat(toBytes(data1.params.key)).toHex(), 'value', 'Reputation Oracle' ); @@ -463,13 +451,13 @@ describe('KVStore', () => { assert.fieldEquals( 'KVStore', - `${data1.params.sender.toHexString()}-${data1.params.key}`, + data1.params.sender.concat(toBytes(data1.params.key)).toHex(), 'key', 'role' ); assert.fieldEquals( 'KVStore', - `${data1.params.sender.toHexString()}-${data1.params.key}`, + data1.params.sender.concat(toBytes(data1.params.key)).toHex(), 'value', 'Job Launcher' ); diff --git a/packages/sdk/typescript/subgraph/tests/legacy/escrow-factory/escrow-factory.test.ts b/packages/sdk/typescript/subgraph/tests/legacy/escrow-factory/escrow-factory.test.ts index b6983be015..4e51f34f60 100644 --- a/packages/sdk/typescript/subgraph/tests/legacy/escrow-factory/escrow-factory.test.ts +++ b/packages/sdk/typescript/subgraph/tests/legacy/escrow-factory/escrow-factory.test.ts @@ -121,7 +121,7 @@ describe('EscrowFactory', () => { // Stats Entity assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'totalEscrowCount', '2' ); diff --git a/packages/sdk/typescript/subgraph/tests/legacy/escrow/escrow.test.ts b/packages/sdk/typescript/subgraph/tests/legacy/escrow/escrow.test.ts index 84d1b59926..b8c339394e 100644 --- a/packages/sdk/typescript/subgraph/tests/legacy/escrow/escrow.test.ts +++ b/packages/sdk/typescript/subgraph/tests/legacy/escrow/escrow.test.ts @@ -23,6 +23,7 @@ import { handlePending, handleBulkTransfer, } from '../../../src/mapping/legacy/Escrow'; +import { toEventId } from '../../../src/mapping/utils/event'; import { ZERO_BI } from '../../../src/mapping/utils/number'; import { createISEvent, @@ -83,7 +84,7 @@ describe('Escrow', () => { 'recordingOracleStake():(uint256)' ).returns([ethereum.Value.fromUnsignedBigInt(BigInt.fromI32(20))]); - const escrow = new Escrow(escrowAddress.toHex()); + const escrow = new Escrow(escrowAddress); escrow.address = escrowAddress; escrow.token = Address.zero(); escrow.factoryAddress = Address.zero(); @@ -110,9 +111,7 @@ describe('Escrow', () => { handlePending(newPending1); - const id = `${newPending1.transaction.hash.toHex()}-${newPending1.logIndex.toString()}-${ - newPending1.block.timestamp - }`; + const id = toEventId(newPending1).toHex(); // SetupEvent assert.fieldEquals( @@ -189,9 +188,7 @@ describe('Escrow', () => { const newIS = createISEvent(workerAddress, URL, 'is_hash_1'); handleIntermediateStorage(newIS); - const id = `${newIS.transaction.hash.toHex()}-${newIS.logIndex.toString()}-${ - newIS.block.timestamp - }`; + const id = toEventId(newIS).toHex(); // StoreResultsEvent assert.fieldEquals( @@ -267,9 +264,7 @@ describe('Escrow', () => { handleBulkTransfer(bulk1); - const id1 = `${bulk1.transaction.hash.toHex()}-${bulk1.logIndex.toString()}-${ - bulk1.block.timestamp - }`; + const id1 = toEventId(bulk1).toHex(); // BulkPayoutEvent assert.fieldEquals( @@ -354,9 +349,7 @@ describe('Escrow', () => { handleBulkTransfer(bulk1); - const id1 = `${bulk1.transaction.hash.toHex()}-${bulk1.logIndex.toString()}-${ - bulk1.block.timestamp - }`; + const id1 = toEventId(bulk1).toHex(); // BulkPayoutEvent assert.fieldEquals( @@ -443,13 +436,13 @@ describe('Escrow', () => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'setupEventCount', '2' ); assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'pendingStatusEventCount', '2' ); @@ -465,7 +458,7 @@ describe('Escrow', () => { ].forEach((field) => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), field, '0' ); @@ -473,7 +466,7 @@ describe('Escrow', () => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'totalEventCount', '4' ); @@ -488,7 +481,7 @@ describe('Escrow', () => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'storeResultsEventCount', '2' ); @@ -505,7 +498,7 @@ describe('Escrow', () => { ].forEach((field) => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), field, '0' ); @@ -513,7 +506,7 @@ describe('Escrow', () => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'totalEventCount', '2' ); @@ -526,7 +519,7 @@ describe('Escrow', () => { new DataSourceContext() ); - const escrow = new Escrow(escrowAddress.toHex()); + const escrow = new Escrow(escrowAddress); escrow.address = escrowAddress; escrow.token = Address.zero(); escrow.factoryAddress = Address.zero(); @@ -558,19 +551,19 @@ describe('Escrow', () => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'bulkPayoutEventCount', '2' ); assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'partialStatusEventCount', '1' ); assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'paidStatusEventCount', '1' ); @@ -585,7 +578,7 @@ describe('Escrow', () => { ].forEach((field) => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), field, '0' ); @@ -593,7 +586,7 @@ describe('Escrow', () => { assert.fieldEquals( 'EscrowStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'totalEventCount', '4' ); diff --git a/packages/sdk/typescript/subgraph/tests/reward-pool/reward-pool.test.ts b/packages/sdk/typescript/subgraph/tests/reward-pool/reward-pool.test.ts index 7fb025b002..fcfa5d4f48 100644 --- a/packages/sdk/typescript/subgraph/tests/reward-pool/reward-pool.test.ts +++ b/packages/sdk/typescript/subgraph/tests/reward-pool/reward-pool.test.ts @@ -8,6 +8,7 @@ import { } from 'matchstick-as/assembly'; import { handleRewardAdded } from '../../src/mapping/RewardPool'; +import { toEventId } from '../../src/mapping/utils/event'; import { createRewardAddedEvent } from './fixtures'; describe('RewardPool', () => { @@ -34,12 +35,8 @@ describe('RewardPool', () => { handleRewardAdded(data1); handleRewardAdded(data2); - const id1 = `${data1.transaction.hash.toHex()}-${data1.logIndex.toString()}-${ - data1.block.timestamp - }`; - const id2 = `${data2.transaction.hash.toHex()}-${data2.logIndex.toString()}-${ - data2.block.timestamp - }`; + const id1 = toEventId(data1).toHex(); + const id2 = toEventId(data2).toHex(); // Data 1 assert.fieldEquals( diff --git a/packages/sdk/typescript/subgraph/tests/staking/staking.test.ts b/packages/sdk/typescript/subgraph/tests/staking/staking.test.ts index af58fce820..c5864da246 100644 --- a/packages/sdk/typescript/subgraph/tests/staking/staking.test.ts +++ b/packages/sdk/typescript/subgraph/tests/staking/staking.test.ts @@ -18,6 +18,7 @@ import { handleStakeWithdrawn, STATISTICS_ENTITY_ID, } from '../../src/mapping/Staking'; +import { toEventId } from '../../src/mapping/utils/event'; import { ZERO_BI } from '../../src/mapping/utils/number'; import { createAllocationClosedEvent, @@ -35,7 +36,7 @@ const escrow2Address = Address.fromString(escrow2AddressString); describe('Staking', () => { beforeAll(() => { - const escrow1 = new Escrow(escrow1Address.toHex()); + const escrow1 = new Escrow(escrow1Address); escrow1.address = escrow1Address; escrow1.token = Address.zero(); escrow1.factoryAddress = Address.zero(); @@ -48,7 +49,7 @@ describe('Staking', () => { escrow1.createdAt = BigInt.fromI32(0); escrow1.save(); - const escrow2 = new Escrow(escrow2Address.toHex()); + const escrow2 = new Escrow(escrow2Address); escrow2.address = escrow2Address; escrow2.token = Address.zero(); escrow2.factoryAddress = Address.zero(); @@ -81,12 +82,8 @@ describe('Staking', () => { handleStakeDeposited(data1); handleStakeDeposited(data2); - const id1 = `${data1.transaction.hash.toHex()}-${data1.logIndex.toString()}-${ - data1.block.timestamp - }`; - const id2 = `${data2.transaction.hash.toHex()}-${data2.logIndex.toString()}-${ - data2.block.timestamp - }`; + const id1 = toEventId(data1).toHex(); + const id2 = toEventId(data2).toHex(); // Data 1 assert.fieldEquals( @@ -145,7 +142,7 @@ describe('Staking', () => { // Leader statistics assert.fieldEquals( 'LeaderStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'leaders', '2' ); @@ -214,12 +211,8 @@ describe('Staking', () => { handleStakeLocked(data1); handleStakeLocked(data2); - const id1 = `${data1.transaction.hash.toHex()}-${data1.logIndex.toString()}-${ - data1.block.timestamp - }`; - const id2 = `${data2.transaction.hash.toHex()}-${data2.logIndex.toString()}-${ - data2.block.timestamp - }`; + const id1 = toEventId(data1).toHex(); + const id2 = toEventId(data2).toHex(); // Data 1 assert.fieldEquals( @@ -280,7 +273,7 @@ describe('Staking', () => { // Leader statistics assert.fieldEquals( 'LeaderStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'leaders', '2' ); @@ -372,12 +365,8 @@ describe('Staking', () => { handleStakeWithdrawn(data1); handleStakeWithdrawn(data2); - const id1 = `${data1.transaction.hash.toHex()}-${data1.logIndex.toString()}-${ - data1.block.timestamp - }`; - const id2 = `${data2.transaction.hash.toHex()}-${data2.logIndex.toString()}-${ - data2.block.timestamp - }`; + const id1 = toEventId(data1).toHex(); + const id2 = toEventId(data2).toHex(); // Data 1 assert.fieldEquals( @@ -436,7 +425,7 @@ describe('Staking', () => { // Leader statistics assert.fieldEquals( 'LeaderStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'leaders', '2' ); @@ -544,12 +533,8 @@ describe('Staking', () => { handleStakeAllocated(data1); handleStakeAllocated(data2); - const id1 = `${data1.transaction.hash.toHex()}-${data1.logIndex.toString()}-${ - data1.block.timestamp - }`; - const id2 = `${data2.transaction.hash.toHex()}-${data2.logIndex.toString()}-${ - data2.block.timestamp - }`; + const id1 = toEventId(data1).toHex(); + const id2 = toEventId(data2).toHex(); // Data 1 assert.fieldEquals( @@ -620,7 +605,7 @@ describe('Staking', () => { // Leader statistics assert.fieldEquals( 'LeaderStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'leaders', '2' ); @@ -740,12 +725,8 @@ describe('Staking', () => { handleStakeSlashed(data1); handleStakeSlashed(data2); - const id1 = `${data1.transaction.hash.toHex()}-${data1.logIndex.toString()}-${ - data1.block.timestamp - }`; - const id2 = `${data2.transaction.hash.toHex()}-${data2.logIndex.toString()}-${ - data2.block.timestamp - }`; + const id1 = toEventId(data1).toHex(); + const id2 = toEventId(data2).toHex(); // Data 1 assert.fieldEquals( @@ -828,7 +809,7 @@ describe('Staking', () => { // Leader statistics assert.fieldEquals( 'LeaderStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'leaders', '2' ); @@ -960,12 +941,8 @@ describe('Staking', () => { handleAllocationClosed(data1); handleAllocationClosed(data2); - const id1 = `${data1.transaction.hash.toHex()}-${data1.logIndex.toString()}-${ - data1.block.timestamp - }`; - const id2 = `${data2.transaction.hash.toHex()}-${data2.logIndex.toString()}-${ - data2.block.timestamp - }`; + const id1 = toEventId(data1).toHex(); + const id2 = toEventId(data2).toHex(); // Data 1 assert.fieldEquals( @@ -1036,7 +1013,7 @@ describe('Staking', () => { // Leader statistics assert.fieldEquals( 'LeaderStatistics', - STATISTICS_ENTITY_ID, + STATISTICS_ENTITY_ID.toHex(), 'leaders', '2' ); From 8641d5e5efc014769fc8e0ebc5a28158d1429b13 Mon Sep 17 00:00:00 2001 From: portuu3 <61605646+portuu3@users.noreply.github.com> Date: Wed, 31 Jul 2024 13:44:46 +0200 Subject: [PATCH 14/89] Fix subgraph deployment (#2328) --- packages/sdk/typescript/subgraph/template.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/sdk/typescript/subgraph/template.yaml b/packages/sdk/typescript/subgraph/template.yaml index 24c2c63454..475c12ebe0 100644 --- a/packages/sdk/typescript/subgraph/template.yaml +++ b/packages/sdk/typescript/subgraph/template.yaml @@ -129,6 +129,7 @@ dataSources: - event: RewardAdded(indexed address,indexed address,indexed address,uint256) handler: handleRewardAdded file: ./src/mapping/RewardPool.ts +{{ #LegacyEscrowFactory }} - kind: ethereum name: LegacyEscrowFactory network: '{{ network }}' @@ -149,6 +150,7 @@ dataSources: eventHandlers: - event: Launched(address,address) handler: handleLaunched +{{ /LegacyEscrowFactory }} templates: - name: Escrow kind: ethereum/contract From 0d25ae828a08495c3d17d3840cf13f6e90149232 Mon Sep 17 00:00:00 2001 From: eugenvoronov <104138627+eugenvoronov@users.noreply.github.com> Date: Mon, 5 Aug 2024 13:05:11 +0300 Subject: [PATCH 15/89] Fixed labels type (#2336) --- .../server/src/modules/job/job.dto.ts | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/packages/apps/job-launcher/server/src/modules/job/job.dto.ts b/packages/apps/job-launcher/server/src/modules/job/job.dto.ts index 9832df8e38..22162ec5e6 100644 --- a/packages/apps/job-launcher/server/src/modules/job/job.dto.ts +++ b/packages/apps/job-launcher/server/src/modules/job/job.dto.ts @@ -129,6 +129,22 @@ export class CvatDataDto { public boxes?: StorageDataDto; } +export class Label { + @ApiProperty() + @IsString() + public name: string; + + @ApiPropertyOptional() + @IsArray() + @IsOptional() + public nodes?: string[]; + + @ApiPropertyOptional() + @IsArray() + @IsOptional() + public joints?: string[]; +} + export class JobCvatDto extends JobDto { @ApiProperty({ name: 'requester_description' }) @IsString() @@ -138,7 +154,7 @@ export class JobCvatDto extends JobDto { @IsObject() public data: CvatDataDto; - @ApiProperty() + @ApiProperty({ type: [Label] }) @IsArray() @ArrayMinSize(1) public labels: Label[]; @@ -376,22 +392,6 @@ export class CvatData { public boxes_url?: string; } -export class Label { - @ApiProperty() - @IsString() - public name: string; - - @ApiPropertyOptional() - @IsArray() - @IsOptional() - public nodes?: string[]; - - @ApiPropertyOptional() - @IsArray() - @IsOptional() - public joints?: string[]; -} - export class Annotation { @IsArray() public labels: Label[]; From 8d3a9a37a2904359029b15aa9c4435fa92ce9e31 Mon Sep 17 00:00:00 2001 From: eugenvoronov <104138627+eugenvoronov@users.noreply.github.com> Date: Mon, 5 Aug 2024 13:28:49 +0300 Subject: [PATCH 16/89] Updated description (#2337) --- packages/apps/job-launcher/client/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/apps/job-launcher/client/index.html b/packages/apps/job-launcher/client/index.html index abbdee95ff..f5c6685d78 100644 --- a/packages/apps/job-launcher/client/index.html +++ b/packages/apps/job-launcher/client/index.html @@ -5,7 +5,7 @@ - + - -# 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) - * [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) - * [`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) - * [`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) - * [`StatisticsFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.StatisticsFilter) - * [`TransactionFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.TransactionFilter) - * [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) - * [`get_contract_interface()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_contract_interface) - * [`get_data_from_subgraph()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_data_from_subgraph) - * [`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_reward_pool_interface()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_reward_pool_interface) - * [`get_staking_interface()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_staking_interface) - * [`handle_transaction()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.handle_transaction) - * [`parse_transfer_transaction()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.parse_transfer_transaction) - * [`validate_url()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.validate_url) - * [`with_retry()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.with_retry) diff --git a/docs/sdk/typescript/base/classes/BaseEthersClient.md b/docs/sdk/typescript/base/classes/BaseEthersClient.md index 032938cf82..63a79f4422 100644 --- a/docs/sdk/typescript/base/classes/BaseEthersClient.md +++ b/docs/sdk/typescript/base/classes/BaseEthersClient.md @@ -40,7 +40,7 @@ The network information required to connect to the contracts #### Defined in -[base.ts:20](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L20) +[base.ts:20](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L20) ## Properties @@ -50,7 +50,7 @@ The network information required to connect to the contracts #### Defined in -[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) +[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) *** @@ -60,4 +60,4 @@ The network information required to connect to the contracts #### Defined in -[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) +[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) diff --git a/docs/sdk/typescript/encryption/classes/Encryption.md b/docs/sdk/typescript/encryption/classes/Encryption.md index 37e9d6a8c1..6ff4b83171 100644 --- a/docs/sdk/typescript/encryption/classes/Encryption.md +++ b/docs/sdk/typescript/encryption/classes/Encryption.md @@ -66,7 +66,7 @@ The private key. #### Defined in -[encryption.ts:53](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L53) +[encryption.ts:53](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L53) ## Methods @@ -118,7 +118,7 @@ const resultMessage = await encription.decrypt('message'); #### Defined in -[encryption.ts:180](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L180) +[encryption.ts:180](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L180) *** @@ -154,7 +154,7 @@ const resultMessage = await encription.sign('message'); #### Defined in -[encryption.ts:217](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L217) +[encryption.ts:217](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L217) *** @@ -219,7 +219,7 @@ const resultMessage = await encription.signAndEncrypt('message', publicKeys); #### Defined in -[encryption.ts:129](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L129) +[encryption.ts:129](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L129) *** @@ -247,4 +247,4 @@ Optional: The passphrase for the private key. #### Defined in -[encryption.ts:64](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L64) +[encryption.ts:64](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L64) diff --git a/docs/sdk/typescript/encryption/classes/EncryptionUtils.md b/docs/sdk/typescript/encryption/classes/EncryptionUtils.md index c7602663c4..a21bf6fe89 100644 --- a/docs/sdk/typescript/encryption/classes/EncryptionUtils.md +++ b/docs/sdk/typescript/encryption/classes/EncryptionUtils.md @@ -97,7 +97,7 @@ const result = await EncriptionUtils.encrypt('message', publicKeys); #### Defined in -[encryption.ts:422](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L422) +[encryption.ts:422](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L422) *** @@ -152,7 +152,7 @@ const result = await EncriptionUtils.generateKeyPair(name, email, passphrase); #### Defined in -[encryption.ts:360](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L360) +[encryption.ts:360](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L360) *** @@ -184,7 +184,7 @@ const signedData = await EncriptionUtils.getSignedData('message'); #### Defined in -[encryption.ts:317](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L317) +[encryption.ts:317](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L317) *** @@ -232,7 +232,7 @@ if (isEncrypted) { #### Defined in -[encryption.ts:471](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L471) +[encryption.ts:471](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L471) *** @@ -280,4 +280,4 @@ const result = await EncriptionUtils.verify('message', publicKey); #### Defined in -[encryption.ts:284](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L284) +[encryption.ts:284](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L284) diff --git a/docs/sdk/typescript/escrow/classes/EscrowClient.md b/docs/sdk/typescript/escrow/classes/EscrowClient.md index e8f27b7ba1..326d1beab4 100644 --- a/docs/sdk/typescript/escrow/classes/EscrowClient.md +++ b/docs/sdk/typescript/escrow/classes/EscrowClient.md @@ -104,7 +104,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[escrow.ts:129](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L129) +[escrow.ts:129](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L129) ## Properties @@ -118,7 +118,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) +[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) *** @@ -132,7 +132,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) +[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) ## Methods @@ -178,7 +178,7 @@ await escrowClient.abort('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); #### Defined in -[escrow.ts:837](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L837) +[escrow.ts:837](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L837) *** @@ -229,7 +229,7 @@ await escrowClient.addTrustedHandlers('0x62dD51230A30401C455c8398d06F85e4EaB6309 #### Defined in -[escrow.ts:885](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L885) +[escrow.ts:885](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L885) *** @@ -296,7 +296,7 @@ await escrowClient.bulkPayOut('0x62dD51230A30401C455c8398d06F85e4EaB6309f', reci #### Defined in -[escrow.ts:650](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L650) +[escrow.ts:650](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L650) *** @@ -342,7 +342,7 @@ await escrowClient.cancel('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); #### Defined in -[escrow.ts:753](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L753) +[escrow.ts:753](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L753) *** @@ -388,7 +388,7 @@ await escrowClient.complete('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); #### Defined in -[escrow.ts:592](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L592) +[escrow.ts:592](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L592) *** @@ -455,7 +455,7 @@ const escrowAddress = await escrowClient.createAndSetupEscrow(tokenAddress, trus #### Defined in -[escrow.ts:415](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L415) +[escrow.ts:415](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L415) *** @@ -512,7 +512,7 @@ const escrowAddress = await escrowClient.createEscrow(tokenAddress, trustedHandl #### Defined in -[escrow.ts:209](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L209) +[escrow.ts:209](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L209) *** @@ -561,7 +561,7 @@ await escrowClient.fund('0x62dD51230A30401C455c8398d06F85e4EaB6309f', amount); #### Defined in -[escrow.ts:463](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L463) +[escrow.ts:463](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L463) *** @@ -599,7 +599,7 @@ const balance = await escrowClient.getBalance('0x62dD51230A30401C455c8398d06F85e #### Defined in -[escrow.ts:940](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L940) +[escrow.ts:940](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L940) *** @@ -637,7 +637,7 @@ const oracleAddress = await escrowClient.getExchangeOracleAddress('0x62dD51230A3 #### Defined in -[escrow.ts:1320](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1320) +[escrow.ts:1320](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1320) *** @@ -675,7 +675,7 @@ const factoryAddress = await escrowClient.getFactoryAddress('0x62dD51230A30401C4 #### Defined in -[escrow.ts:1358](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1358) +[escrow.ts:1358](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1358) *** @@ -713,7 +713,7 @@ const intemediateResultsUrl = await escrowClient.getIntermediateResultsUrl('0x62 #### Defined in -[escrow.ts:1092](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1092) +[escrow.ts:1092](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1092) *** @@ -751,7 +751,7 @@ const jobLauncherAddress = await escrowClient.getJobLauncherAddress('0x62dD51230 #### Defined in -[escrow.ts:1244](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1244) +[escrow.ts:1244](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1244) *** @@ -789,7 +789,7 @@ const manifestHash = await escrowClient.getManifestHash('0x62dD51230A30401C455c8 #### Defined in -[escrow.ts:978](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L978) +[escrow.ts:978](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L978) *** @@ -827,7 +827,7 @@ const manifestUrl = await escrowClient.getManifestUrl('0x62dD51230A30401C455c839 #### Defined in -[escrow.ts:1016](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1016) +[escrow.ts:1016](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1016) *** @@ -865,7 +865,7 @@ const oracleAddress = await escrowClient.getRecordingOracleAddress('0x62dD51230A #### Defined in -[escrow.ts:1206](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1206) +[escrow.ts:1206](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1206) *** @@ -903,7 +903,7 @@ const oracleAddress = await escrowClient.getReputationOracleAddress('0x62dD51230 #### Defined in -[escrow.ts:1282](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1282) +[escrow.ts:1282](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1282) *** @@ -941,7 +941,7 @@ const resultsUrl = await escrowClient.getResultsUrl('0x62dD51230A30401C455c8398d #### Defined in -[escrow.ts:1054](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1054) +[escrow.ts:1054](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1054) *** @@ -979,7 +979,7 @@ const status = await escrowClient.getStatus('0x62dD51230A30401C455c8398d06F85e4E #### Defined in -[escrow.ts:1168](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1168) +[escrow.ts:1168](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1168) *** @@ -1017,7 +1017,7 @@ const tokenAddress = await escrowClient.getTokenAddress('0x62dD51230A30401C455c8 #### Defined in -[escrow.ts:1130](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1130) +[escrow.ts:1130](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1130) *** @@ -1078,7 +1078,7 @@ await escrowClient.setup(escrowAddress, escrowConfig); #### Defined in -[escrow.ts:290](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L290) +[escrow.ts:290](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L290) *** @@ -1132,7 +1132,7 @@ await storeResults.storeResults('0x62dD51230A30401C455c8398d06F85e4EaB6309f', 'h #### Defined in -[escrow.ts:528](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L528) +[escrow.ts:528](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L528) *** @@ -1164,4 +1164,4 @@ Thrown if the network's chainId is not supported #### Defined in -[escrow.ts:147](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L147) +[escrow.ts:147](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L147) diff --git a/docs/sdk/typescript/escrow/classes/EscrowUtils.md b/docs/sdk/typescript/escrow/classes/EscrowUtils.md index 20ae594e71..388aae4932 100644 --- a/docs/sdk/typescript/escrow/classes/EscrowUtils.md +++ b/docs/sdk/typescript/escrow/classes/EscrowUtils.md @@ -129,7 +129,7 @@ const escrowData = new EscrowUtils.getEscrow(ChainId.POLYGON_AMOY, "0x1234567890 #### Defined in -[escrow.ts:1640](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1640) +[escrow.ts:1640](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1640) *** @@ -250,7 +250,7 @@ const escrowDatas = await EscrowUtils.getEscrows(filters); #### Defined in -[escrow.ts:1514](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1514) +[escrow.ts:1514](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1514) *** @@ -363,4 +363,4 @@ import { ChainId, EscrowUtils, EscrowStatus } from '@human-protocol/sdk'; #### Defined in -[escrow.ts:1738](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1738) +[escrow.ts:1738](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1738) diff --git a/docs/sdk/typescript/kvstore/classes/KVStoreClient.md b/docs/sdk/typescript/kvstore/classes/KVStoreClient.md index 7d9ca73d2b..4a1e27446f 100644 --- a/docs/sdk/typescript/kvstore/classes/KVStoreClient.md +++ b/docs/sdk/typescript/kvstore/classes/KVStoreClient.md @@ -104,7 +104,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[kvstore.ts:107](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L107) +[kvstore.ts:107](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L107) ## Properties @@ -118,7 +118,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) +[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) *** @@ -132,7 +132,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) +[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) ## Methods @@ -182,7 +182,7 @@ await kvstoreClient.set('Role', 'RecordingOracle'); #### Defined in -[kvstore.ts:170](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L170) +[kvstore.ts:170](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L170) *** @@ -234,7 +234,7 @@ await kvstoreClient.set(keys, values); #### Defined in -[kvstore.ts:213](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L213) +[kvstore.ts:213](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L213) *** @@ -283,7 +283,7 @@ await kvstoreClient.setFileUrlAndHash('linkedin.com/example', 'linkedin_url); #### Defined in -[kvstore.ts:256](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L256) +[kvstore.ts:256](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L256) *** @@ -315,4 +315,4 @@ The Runner object to interact with the Ethereum network #### Defined in -[kvstore.ts:125](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L125) +[kvstore.ts:125](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L125) diff --git a/docs/sdk/typescript/kvstore/classes/KVStoreUtils.md b/docs/sdk/typescript/kvstore/classes/KVStoreUtils.md index 0529bf7a36..bef9b7a8c5 100644 --- a/docs/sdk/typescript/kvstore/classes/KVStoreUtils.md +++ b/docs/sdk/typescript/kvstore/classes/KVStoreUtils.md @@ -102,7 +102,7 @@ console.log(value); #### Defined in -[kvstore.ts:388](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L388) +[kvstore.ts:388](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L388) *** @@ -146,7 +146,7 @@ console.log(url); #### Defined in -[kvstore.ts:437](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L437) +[kvstore.ts:435](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L435) *** @@ -191,7 +191,7 @@ console.log(kvStoreData); #### Defined in -[kvstore.ts:336](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L336) +[kvstore.ts:336](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L336) *** @@ -231,4 +231,4 @@ console.log(publicKey); #### Defined in -[kvstore.ts:494](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L494) +[kvstore.ts:492](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L492) diff --git a/docs/sdk/typescript/operator/classes/OperatorUtils.md b/docs/sdk/typescript/operator/classes/OperatorUtils.md index 0f502beaac..e192a2d37a 100644 --- a/docs/sdk/typescript/operator/classes/OperatorUtils.md +++ b/docs/sdk/typescript/operator/classes/OperatorUtils.md @@ -48,7 +48,7 @@ const leader = await OperatorUtils.getLeader(ChainId.POLYGON_AMOY, '0x62dD51230A #### Defined in -[operator.ts:44](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L44) +[operator.ts:44](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L44) *** @@ -83,7 +83,7 @@ const leaders = await OperatorUtils.getLeaders(filter); #### Defined in -[operator.ts:99](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L99) +[operator.ts:99](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L99) *** @@ -121,7 +121,7 @@ const operators = await OperatorUtils.getReputationNetworkOperators(ChainId.POLY #### Defined in -[operator.ts:151](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L151) +[operator.ts:151](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L151) *** @@ -155,4 +155,4 @@ const rewards = await OperatorUtils.getRewards(ChainId.POLYGON_AMOY, '0x62dD5123 #### Defined in -[operator.ts:201](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L201) +[operator.ts:201](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L201) diff --git a/docs/sdk/typescript/staking/classes/StakingClient.md b/docs/sdk/typescript/staking/classes/StakingClient.md index 293520b0b2..1d333b58a4 100644 --- a/docs/sdk/typescript/staking/classes/StakingClient.md +++ b/docs/sdk/typescript/staking/classes/StakingClient.md @@ -104,7 +104,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[staking.ts:111](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L111) +[staking.ts:111](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L111) ## Properties @@ -114,7 +114,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[staking.ts:102](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L102) +[staking.ts:102](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L102) *** @@ -128,7 +128,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) +[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) *** @@ -138,7 +138,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[staking.ts:103](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L103) +[staking.ts:103](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L103) *** @@ -152,7 +152,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) +[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) *** @@ -162,7 +162,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[staking.ts:101](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L101) +[staking.ts:101](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L101) *** @@ -172,7 +172,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[staking.ts:100](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L100) +[staking.ts:100](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L100) ## Methods @@ -223,7 +223,7 @@ await stakingClient.allocate('0x62dD51230A30401C455c8398d06F85e4EaB6309f', amoun #### Defined in -[staking.ts:458](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L458) +[staking.ts:458](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L458) *** @@ -268,7 +268,7 @@ await stakingClient.approveStake(amount); #### Defined in -[staking.ts:203](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L203) +[staking.ts:203](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L203) *** @@ -315,7 +315,7 @@ await stakingClient.closeAllocation('0x62dD51230A30401C455c8398d06F85e4EaB6309f' #### Defined in -[staking.ts:511](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L511) +[staking.ts:511](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L511) *** @@ -361,7 +361,7 @@ await stakingClient.distributeReward('0x62dD51230A30401C455c8398d06F85e4EaB6309f #### Defined in -[staking.ts:554](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L554) +[staking.ts:554](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L554) *** @@ -399,7 +399,7 @@ const allocationInfo = await stakingClient.getAllocation('0x62dD51230A30401C455c #### Defined in -[staking.ts:591](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L591) +[staking.ts:591](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L591) *** @@ -456,7 +456,7 @@ await stakingClient.slash('0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', '0xf39Fd #### Defined in -[staking.ts:387](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L387) +[staking.ts:387](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L387) *** @@ -504,7 +504,7 @@ await stakingClient.approveStake(amount); #### Defined in -[staking.ts:258](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L258) +[staking.ts:258](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L258) *** @@ -551,7 +551,7 @@ await stakingClient.unstake(amount); #### Defined in -[staking.ts:303](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L303) +[staking.ts:303](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L303) *** @@ -593,7 +593,7 @@ await stakingClient.withdraw(); #### Defined in -[staking.ts:349](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L349) +[staking.ts:349](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L349) *** @@ -625,4 +625,4 @@ The Runner object to interact with the Ethereum network #### Defined in -[staking.ts:145](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L145) +[staking.ts:145](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L145) diff --git a/docs/sdk/typescript/statistics/classes/StatisticsClient.md b/docs/sdk/typescript/statistics/classes/StatisticsClient.md index 26517f9f92..5401f81f42 100644 --- a/docs/sdk/typescript/statistics/classes/StatisticsClient.md +++ b/docs/sdk/typescript/statistics/classes/StatisticsClient.md @@ -62,7 +62,7 @@ The network information required to connect to the Statistics contract #### Defined in -[statistics.ts:72](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L72) +[statistics.ts:72](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L72) ## Properties @@ -72,7 +72,7 @@ The network information required to connect to the Statistics contract #### Defined in -[statistics.ts:64](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L64) +[statistics.ts:64](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L64) *** @@ -82,7 +82,7 @@ The network information required to connect to the Statistics contract #### Defined in -[statistics.ts:65](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L65) +[statistics.ts:65](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L65) ## Methods @@ -148,7 +148,7 @@ const escrowStatisticsApril = await statisticsClient.getEscrowStatistics({ #### Defined in -[statistics.ts:128](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L128) +[statistics.ts:128](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L128) *** @@ -213,7 +213,7 @@ console.log('HMT statistics from 5/8 - 6/8:', hmtStatisticsRange); #### Defined in -[statistics.ts:495](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L495) +[statistics.ts:495](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L495) *** @@ -256,7 +256,7 @@ console.log('HMT holders:', hmtHolders.map((h) => ({ #### Defined in -[statistics.ts:421](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L421) +[statistics.ts:421](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L421) *** @@ -296,7 +296,7 @@ console.log('HMT statistics:', { #### Defined in -[statistics.ts:378](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L378) +[statistics.ts:378](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L378) *** @@ -380,7 +380,7 @@ console.log( #### Defined in -[statistics.ts:312](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L312) +[statistics.ts:312](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L312) *** @@ -441,4 +441,4 @@ const workerStatisticsApril = await statisticsClient.getWorkerStatistics({ #### Defined in -[statistics.ts:213](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L213) +[statistics.ts:213](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L213) diff --git a/docs/sdk/typescript/storage/classes/StorageClient.md b/docs/sdk/typescript/storage/classes/StorageClient.md index c98f3a539e..17c38875f1 100644 --- a/docs/sdk/typescript/storage/classes/StorageClient.md +++ b/docs/sdk/typescript/storage/classes/StorageClient.md @@ -77,7 +77,7 @@ Optional. Cloud storage access data. If credentials is not provided - use an ano #### Defined in -[storage.ts:73](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L73) +[storage.ts:73](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L73) ## Methods @@ -121,7 +121,7 @@ const exists = await storageClient.bucketExists('bucket-name'); #### Defined in -[storage.ts:266](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L266) +[storage.ts:266](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L266) *** @@ -167,7 +167,7 @@ const files = await storageClient.downloadFiles(keys, 'bucket-name'); #### Defined in -[storage.ts:113](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L113) +[storage.ts:113](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L113) *** @@ -211,7 +211,7 @@ const fileNames = await storageClient.listObjects('bucket-name'); #### Defined in -[storage.ts:297](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L297) +[storage.ts:297](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L297) *** @@ -262,7 +262,7 @@ const uploadedFiles = await storageClient.uploadFiles(files, 'bucket-name'); #### Defined in -[storage.ts:201](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L201) +[storage.ts:201](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L201) *** @@ -294,4 +294,4 @@ const file = await storageClient.downloadFileFromUrl('http://localhost/file.json #### Defined in -[storage.ts:148](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L148) +[storage.ts:148](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L148) diff --git a/docs/sdk/typescript/transaction/classes/TransactionUtils.md b/docs/sdk/typescript/transaction/classes/TransactionUtils.md index 5634aa4eea..0ff1419ec8 100644 --- a/docs/sdk/typescript/transaction/classes/TransactionUtils.md +++ b/docs/sdk/typescript/transaction/classes/TransactionUtils.md @@ -50,7 +50,7 @@ const transaction = await TransactionUtils.getTransaction(ChainId.POLYGON, '0x62 #### Defined in -[transaction.ts:34](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts#L34) +[transaction.ts:34](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts#L34) *** @@ -121,4 +121,4 @@ const transactions = await TransactionUtils.getTransactions(filter); #### Defined in -[transaction.ts:109](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts#L109) +[transaction.ts:109](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts#L109) diff --git a/packages/sdk/python/human-protocol-sdk/docs/Makefile b/packages/sdk/python/human-protocol-sdk/docs/Makefile deleted file mode 100644 index a2d36df643..0000000000 --- a/packages/sdk/python/human-protocol-sdk/docs/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -# Minimal makefile for Sphinx documentation -# - -# You can set these variables from the command line, and also -# from the environment for the first two. -SPHINXOPTS ?= -SPHINXBUILD ?= pipenv run sphinx-build -SOURCEDIR = . -BUILDDIR = _build - -# Put it first so that "make" without argument is like "make help". -help: - @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) - -.PHONY: help Makefile - -# Catch-all target: route all unknown targets to Sphinx using the new -# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). -%: Makefile - @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/packages/sdk/python/human-protocol-sdk/docs/conf.py b/packages/sdk/python/human-protocol-sdk/docs/conf.py deleted file mode 100644 index 2cd74782ba..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 = "2023, Author" -author = "Author" - -# -- 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/human_protocol_sdk.kvstore.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.kvstore.rst index 41f1c65865..19b2b74847 100644 --- 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 @@ -13,3 +13,4 @@ Submodules :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.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.rst index 0c60c4d8bd..1e3d3d47bb 100644 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.rst +++ b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.rst @@ -20,6 +20,7 @@ Subpackages human_protocol_sdk.staking human_protocol_sdk.statistics human_protocol_sdk.storage + human_protocol_sdk.transaction Submodules ---------- 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/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/human_protocol_sdk/gql/operator.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/gql/operator.py index 137c0d7ba1..676c7f4b61 100644 --- a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/gql/operator.py +++ b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/gql/operator.py @@ -12,7 +12,6 @@ lockedUntilTimestamp amountWithdrawn amountSlashed - reputation reward amountJobsProcessed role 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 ae8df6a880..e51aef656e 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 @@ -71,7 +71,6 @@ def __init__( locked_until_timestamp: int, amount_withdrawn: int, amount_slashed: int, - reputation: int, reward: int, amount_jobs_processed: int, role: Optional[str] = None, @@ -95,7 +94,6 @@ def __init__( :param locked_until_timestamp: Locked until timestamp :param amount_withdrawn: Amount withdrawn :param amount_slashed: Amount slashed - :param reputation: Reputation :param reward: Reward :param amount_jobs_processed: Amount of jobs launched :param role: Role @@ -115,7 +113,6 @@ def __init__( self.locked_until_timestamp = locked_until_timestamp self.amount_withdrawn = amount_withdrawn self.amount_slashed = amount_slashed - self.reputation = reputation self.reward = reward self.amount_jobs_processed = amount_jobs_processed self.role = role @@ -229,7 +226,6 @@ def get_leaders(filter: LeaderFilter) -> List[LeaderData]: locked_until_timestamp=int(leader.get("lockedUntilTimestamp", 0)), amount_withdrawn=int(leader.get("amountWithdrawn", 0)), amount_slashed=int(leader.get("amountSlashed", 0)), - reputation=int(leader.get("reputation", 0)), reward=int(leader.get("reward", 0)), amount_jobs_processed=int(leader.get("amountJobsProcessed", 0)), role=leader.get("role", None), @@ -317,7 +313,6 @@ def get_leader( locked_until_timestamp=int(leader.get("lockedUntilTimestamp", 0)), amount_withdrawn=int(leader.get("amountWithdrawn", 0)), amount_slashed=int(leader.get("amountSlashed", 0)), - reputation=int(leader.get("reputation", 0)), reward=int(leader.get("reward", 0)), amount_jobs_processed=int(leader.get("amountJobsProcessed", 0)), role=leader.get("role", None), diff --git a/packages/sdk/python/human-protocol-sdk/test/human_protocol_sdk/operator/test_operator_utils.py b/packages/sdk/python/human-protocol-sdk/test/human_protocol_sdk/operator/test_operator_utils.py index 03a0010fde..2d25a10851 100644 --- a/packages/sdk/python/human-protocol-sdk/test/human_protocol_sdk/operator/test_operator_utils.py +++ b/packages/sdk/python/human-protocol-sdk/test/human_protocol_sdk/operator/test_operator_utils.py @@ -33,7 +33,6 @@ def test_get_leaders(self): "lockedUntilTimestamp": "0", "amountWithdrawn": "25", "amountSlashed": "25", - "reputation": "25", "reward": "25", "amountJobsProcessed": "25", "role": "role", @@ -67,7 +66,6 @@ def test_get_leaders(self): self.assertEqual(leaders[0].locked_until_timestamp, 0) self.assertEqual(leaders[0].amount_withdrawn, 25) self.assertEqual(leaders[0].amount_slashed, 25) - self.assertEqual(leaders[0].reputation, 25) self.assertEqual(leaders[0].reward, 25) self.assertEqual(leaders[0].amount_jobs_processed, 25) self.assertEqual(leaders[0].role, "role") @@ -99,7 +97,6 @@ def test_get_leaders_when_job_types_is_none(self): "lockedUntilTimestamp": "0", "amountWithdrawn": "25", "amountSlashed": "25", - "reputation": "25", "reward": "25", "amountJobsProcessed": "25", "role": "role", @@ -131,7 +128,6 @@ def test_get_leaders_when_job_types_is_none(self): self.assertEqual(leaders[0].locked_until_timestamp, 0) self.assertEqual(leaders[0].amount_withdrawn, 25) self.assertEqual(leaders[0].amount_slashed, 25) - self.assertEqual(leaders[0].reputation, 25) self.assertEqual(leaders[0].reward, 25) self.assertEqual(leaders[0].amount_jobs_processed, 25) self.assertEqual(leaders[0].role, "role") @@ -164,7 +160,6 @@ def test_get_leaders_when_job_types_is_array(self): "lockedUntilTimestamp": "0", "amountWithdrawn": "25", "amountSlashed": "25", - "reputation": "25", "reward": "25", "amountJobsProcessed": "25", "role": "role", @@ -196,7 +191,6 @@ def test_get_leaders_when_job_types_is_array(self): self.assertEqual(leaders[0].locked_until_timestamp, 0) self.assertEqual(leaders[0].amount_withdrawn, 25) self.assertEqual(leaders[0].amount_slashed, 25) - self.assertEqual(leaders[0].reputation, 25) self.assertEqual(leaders[0].reward, 25) self.assertEqual(leaders[0].amount_jobs_processed, 25) self.assertEqual(leaders[0].role, "role") @@ -253,7 +247,6 @@ def test_get_leader(self): "lockedUntilTimestamp": "0", "amountWithdrawn": "25", "amountSlashed": "25", - "reputation": "25", "reward": "25", "amountJobsProcessed": "25", "role": "role", @@ -286,7 +279,6 @@ def test_get_leader(self): self.assertEqual(leader.locked_until_timestamp, 0) self.assertEqual(leader.amount_withdrawn, 25) self.assertEqual(leader.amount_slashed, 25) - self.assertEqual(leader.reputation, 25) self.assertEqual(leader.reward, 25) self.assertEqual(leader.amount_jobs_processed, 25) self.assertEqual(leader.role, "role") @@ -318,7 +310,6 @@ def test_get_leader_when_job_types_is_none(self): "lockedUntilTimestamp": "0", "amountWithdrawn": "25", "amountSlashed": "25", - "reputation": "25", "reward": "25", "amountJobsProcessed": "25", "role": "role", @@ -349,7 +340,6 @@ def test_get_leader_when_job_types_is_none(self): self.assertEqual(leader.locked_until_timestamp, 0) self.assertEqual(leader.amount_withdrawn, 25) self.assertEqual(leader.amount_slashed, 25) - self.assertEqual(leader.reputation, 25) self.assertEqual(leader.reward, 25) self.assertEqual(leader.amount_jobs_processed, 25) self.assertEqual(leader.role, "role") @@ -381,7 +371,6 @@ def test_get_leader_when_job_types_is_array(self): "lockedUntilTimestamp": "0", "amountWithdrawn": "25", "amountSlashed": "25", - "reputation": "25", "reward": "25", "amountJobsProcessed": "25", "role": "role", @@ -412,7 +401,6 @@ def test_get_leader_when_job_types_is_array(self): self.assertEqual(leader.locked_until_timestamp, 0) self.assertEqual(leader.amount_withdrawn, 25) self.assertEqual(leader.amount_slashed, 25) - self.assertEqual(leader.reputation, 25) self.assertEqual(leader.reward, 25) self.assertEqual(leader.amount_jobs_processed, 25) self.assertEqual(leader.role, "role") diff --git a/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts b/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts index 100b038ca9..fb05fb390a 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts @@ -24,7 +24,6 @@ export interface ILeader { lockedUntilTimestamp: bigint; amountWithdrawn: bigint; amountSlashed: bigint; - reputation: bigint; reward: bigint; amountJobsProcessed: bigint; role?: string; diff --git a/packages/sdk/typescript/human-protocol-sdk/test/operator.test.ts b/packages/sdk/typescript/human-protocol-sdk/test/operator.test.ts index c76016fde6..26f236008a 100644 --- a/packages/sdk/typescript/human-protocol-sdk/test/operator.test.ts +++ b/packages/sdk/typescript/human-protocol-sdk/test/operator.test.ts @@ -44,7 +44,6 @@ describe('OperatorUtils', () => { lockedUntilTimestamp: ethers.toBigInt(0), amountWithdrawn: ethers.parseEther('25'), amountSlashed: ethers.parseEther('25'), - reputation: ethers.parseEther('25'), reward: ethers.parseEther('25'), amountJobsProcessed: ethers.parseEther('25'), jobTypes: 'type1,type2', @@ -180,7 +179,6 @@ describe('OperatorUtils', () => { lockedUntilTimestamp: ethers.toBigInt(0), amountWithdrawn: ethers.parseEther('25'), amountSlashed: ethers.parseEther('25'), - reputation: ethers.parseEther('25'), reward: ethers.parseEther('25'), amountJobsProcessed: ethers.parseEther('25'), jobTypes: 'type1,type2', diff --git a/packages/sdk/typescript/subgraph/schema.graphql b/packages/sdk/typescript/subgraph/schema.graphql index 4198c463f9..5e6d931c1f 100644 --- a/packages/sdk/typescript/subgraph/schema.graphql +++ b/packages/sdk/typescript/subgraph/schema.graphql @@ -38,7 +38,6 @@ type Leader @entity { lockedUntilTimestamp: BigInt! amountWithdrawn: BigInt! amountSlashed: BigInt! - reputation: BigInt! reward: BigInt! amountJobsProcessed: BigInt! diff --git a/packages/sdk/typescript/subgraph/src/mapping/Staking.ts b/packages/sdk/typescript/subgraph/src/mapping/Staking.ts index 63507d03d7..500d3219d9 100644 --- a/packages/sdk/typescript/subgraph/src/mapping/Staking.ts +++ b/packages/sdk/typescript/subgraph/src/mapping/Staking.ts @@ -56,7 +56,6 @@ export function createOrLoadLeader(address: Address): Leader { leader.amountSlashed = ZERO_BI; leader.amountWithdrawn = ZERO_BI; leader.reward = ZERO_BI; - leader.reputation = ZERO_BI; leader.amountJobsProcessed = ZERO_BI; } From 5a7ffcc840fb61c1260fa9141080317abaa1c169 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 26 Aug 2024 16:19:23 +0200 Subject: [PATCH 77/89] Bump matchstick-as from 0.5.2 to 0.6.0 (#2443) Bumps matchstick-as from 0.5.2 to 0.6.0. --- updated-dependencies: - dependency-name: matchstick-as dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- packages/sdk/typescript/subgraph/package.json | 2 +- yarn.lock | 39 +++++++++++++++---- 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/packages/sdk/typescript/subgraph/package.json b/packages/sdk/typescript/subgraph/package.json index a0334c4f68..59ca899a8c 100644 --- a/packages/sdk/typescript/subgraph/package.json +++ b/packages/sdk/typescript/subgraph/package.json @@ -39,7 +39,7 @@ "@graphql-eslint/eslint-plugin": "^3.19.1", "@human-protocol/core": "*", "graphql": "^16.6.0", - "matchstick-as": "^0.5.2", + "matchstick-as": "^0.6.0", "mustache": "^4.2.0" }, "lint-staged": { diff --git a/yarn.lock b/yarn.lock index e4d28eee10..3736708635 100644 --- a/yarn.lock +++ b/yarn.lock @@ -18901,10 +18901,10 @@ match-sorter@^6.0.2: "@babel/runtime" "^7.23.8" remove-accents "0.5.0" -matchstick-as@^0.5.2: - version "0.5.2" - resolved "https://registry.yarnpkg.com/matchstick-as/-/matchstick-as-0.5.2.tgz#6a6dde02d1d939c32458bd67bac688891a07a34c" - integrity sha512-fb1OVphDKEvJY06Ue02Eh1CNncuW95vp6b8tNAP7UIqplICSLoU/zgN6U7ge7R0upsoO78C7CRi4EyK/7Jxz7g== +matchstick-as@^0.6.0: + version "0.6.0" + resolved "https://registry.yarnpkg.com/matchstick-as/-/matchstick-as-0.6.0.tgz#c65296b1f51b1014d605c52067d9b5321ea630e8" + integrity sha512-E36fWsC1AbCkBFt05VsDDRoFvGSdcZg6oZJrtIe/YDBbuFh8SKbR5FcoqDhNWqSN+F7bN/iS2u8Md0SM+4pUpw== dependencies: wabt "1.0.24" @@ -23578,7 +23578,16 @@ string-natural-compare@^3.0.1: resolved "https://registry.yarnpkg.com/string-natural-compare/-/string-natural-compare-3.0.1.tgz#7a42d58474454963759e8e8b7ae63d71c1e7fdf4" integrity sha512-n3sPwynL1nwKi3WJ6AIsClwBMa0zTi54fn2oLU6ndfTSIO05xaznjSf15PcBZU6FNWbmN5Q6cxT4V5hGvB4taw== -"string-width-cjs@npm:string-width@^4.2.0", "string-width@^1.0.2 || 2 || 3 || 4", string-width@^4.0.0, string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.2, string-width@^4.2.3: +"string-width-cjs@npm:string-width@^4.2.0": + version "4.2.3" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" + integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== + dependencies: + emoji-regex "^8.0.0" + is-fullwidth-code-point "^3.0.0" + strip-ansi "^6.0.1" + +"string-width@^1.0.2 || 2 || 3 || 4", string-width@^4.0.0, string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.2, string-width@^4.2.3: version "4.2.3" resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== @@ -23686,7 +23695,7 @@ string_decoder@~1.1.1: dependencies: safe-buffer "~5.1.0" -"strip-ansi-cjs@npm:strip-ansi@^6.0.1", strip-ansi@^6.0.0, strip-ansi@^6.0.1: +"strip-ansi-cjs@npm:strip-ansi@^6.0.1": version "6.0.1" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== @@ -23707,6 +23716,13 @@ strip-ansi@^5.2.0: dependencies: ansi-regex "^4.1.0" +strip-ansi@^6.0.0, strip-ansi@^6.0.1: + version "6.0.1" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" + integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== + dependencies: + ansi-regex "^5.0.1" + strip-ansi@^7.0.1, strip-ansi@^7.1.0: version "7.1.0" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-7.1.0.tgz#d5b6568ca689d8561370b0707685d22434faff45" @@ -26144,7 +26160,7 @@ workerpool@^6.5.1: resolved "https://registry.yarnpkg.com/workerpool/-/workerpool-6.5.1.tgz#060f73b39d0caf97c6db64da004cd01b4c099544" integrity sha512-Fs4dNYcsdpYSAfVxhnl1L5zTksjvOJxtC5hzMNl+1t9B8hTJTdKDyZ5ju7ztgPy+ft9tBFXoOlDNiOT9WUXZlA== -"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0", wrap-ansi@^7.0.0: +"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0": version "7.0.0" resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== @@ -26162,6 +26178,15 @@ wrap-ansi@^6.0.1, wrap-ansi@^6.2.0: string-width "^4.1.0" strip-ansi "^6.0.0" +wrap-ansi@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" + integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== + dependencies: + ansi-styles "^4.0.0" + string-width "^4.1.0" + strip-ansi "^6.0.0" + wrap-ansi@^8.0.1, wrap-ansi@^8.1.0: version "8.1.0" resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-8.1.0.tgz#56dc22368ee570face1b49819975d9b9a5ead214" From 40cb31814b929b230fe7ac5a7b779053d0cc8762 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 26 Aug 2024 16:20:16 +0200 Subject: [PATCH 78/89] Bump eslint-plugin-prettier from 4.2.1 to 5.2.1 (#2445) Bumps [eslint-plugin-prettier](https://github.com/prettier/eslint-plugin-prettier) from 4.2.1 to 5.2.1. - [Release notes](https://github.com/prettier/eslint-plugin-prettier/releases) - [Changelog](https://github.com/prettier/eslint-plugin-prettier/blob/master/CHANGELOG.md) - [Commits](https://github.com/prettier/eslint-plugin-prettier/compare/v4.2.1...v5.2.1) --- updated-dependencies: - dependency-name: eslint-plugin-prettier dependency-type: direct:development update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package.json | 2 +- packages/apps/dashboard/server/package.json | 2 +- .../apps/fortune/exchange-oracle/server/package.json | 2 +- packages/apps/human-app/frontend/package.json | 2 +- packages/apps/human-app/server/package.json | 2 +- packages/apps/job-launcher/server/package.json | 2 +- packages/apps/reputation-oracle/server/package.json | 2 +- yarn.lock | 9 +-------- 8 files changed, 8 insertions(+), 15 deletions(-) diff --git a/package.json b/package.json index 9d98c0d6e8..703b592345 100644 --- a/package.json +++ b/package.json @@ -34,7 +34,7 @@ "eslint": "^8.55.0", "eslint-config-prettier": "^9.1.0", "eslint-plugin-jest": "^28.6.0", - "eslint-plugin-prettier": "^5.1.3", + "eslint-plugin-prettier": "^5.2.1", "ethers": "^6.12.1", "husky": "^9.0.11", "jest": "^29.7.0", diff --git a/packages/apps/dashboard/server/package.json b/packages/apps/dashboard/server/package.json index 99120f3e44..d88acc9102 100644 --- a/packages/apps/dashboard/server/package.json +++ b/packages/apps/dashboard/server/package.json @@ -40,7 +40,7 @@ "@typescript-eslint/parser": "^5.0.0", "eslint": "^8.0.1", "eslint-config-prettier": "^8.3.0", - "eslint-plugin-prettier": "^4.0.0", + "eslint-plugin-prettier": "^5.2.1", "jest": "29.5.0", "prettier": "^2.3.2", "source-map-support": "^0.5.20", diff --git a/packages/apps/fortune/exchange-oracle/server/package.json b/packages/apps/fortune/exchange-oracle/server/package.json index 6772002d99..032909c335 100644 --- a/packages/apps/fortune/exchange-oracle/server/package.json +++ b/packages/apps/fortune/exchange-oracle/server/package.json @@ -48,7 +48,7 @@ "@typescript-eslint/parser": "^5.0.0", "eslint": "^8.55.0", "eslint-config-prettier": "^9.1.0", - "eslint-plugin-prettier": "^5.1.3", + "eslint-plugin-prettier": "^5.2.1", "jest": "29.7.0", "prettier": "^3.2.5", "source-map-support": "^0.5.20", diff --git a/packages/apps/human-app/frontend/package.json b/packages/apps/human-app/frontend/package.json index 32f33a12e4..b18be9c1a4 100644 --- a/packages/apps/human-app/frontend/package.json +++ b/packages/apps/human-app/frontend/package.json @@ -64,7 +64,7 @@ "@vitest/ui": "^1.4.0", "eslint": "^8.55.0", "eslint-config-prettier": "^9.1.0", - "eslint-plugin-prettier": "^5.1.3", + "eslint-plugin-prettier": "^5.2.1", "eslint-plugin-react-refresh": "^0.4.9", "husky": "^9.0.10", "jsdom": "^24.1.1", diff --git a/packages/apps/human-app/server/package.json b/packages/apps/human-app/server/package.json index 4b041d9047..056b427ced 100644 --- a/packages/apps/human-app/server/package.json +++ b/packages/apps/human-app/server/package.json @@ -58,7 +58,7 @@ "@typescript-eslint/parser": "^5.0.0", "eslint": "^8.55.0", "eslint-config-prettier": "^9.1.0", - "eslint-plugin-prettier": "^5.1.3", + "eslint-plugin-prettier": "^5.2.1", "jest": "29.7.0", "nock": "^13.5.1", "prettier": "^3.1.1", diff --git a/packages/apps/job-launcher/server/package.json b/packages/apps/job-launcher/server/package.json index af51383399..a1ff8ac488 100644 --- a/packages/apps/job-launcher/server/package.json +++ b/packages/apps/job-launcher/server/package.json @@ -77,7 +77,7 @@ "@vercel/node": "^3.0.26", "eslint": "^8.55.0", "eslint-config-prettier": "^9.1.0", - "eslint-plugin-prettier": "^5.1.3", + "eslint-plugin-prettier": "^5.2.1", "jest": "29.7.0", "prettier": "^3.2.5", "source-map-support": "^0.5.20", diff --git a/packages/apps/reputation-oracle/server/package.json b/packages/apps/reputation-oracle/server/package.json index ccda7732b8..514670c947 100644 --- a/packages/apps/reputation-oracle/server/package.json +++ b/packages/apps/reputation-oracle/server/package.json @@ -73,7 +73,7 @@ "@typescript-eslint/parser": "^5.0.0", "eslint": "^8.55.0", "eslint-config-prettier": "^9.1.0", - "eslint-plugin-prettier": "^5.1.3", + "eslint-plugin-prettier": "^5.2.1", "jest": "29.7.0", "prettier": "^3.2.5", "source-map-support": "^0.5.20", diff --git a/yarn.lock b/yarn.lock index 3736708635..618eaffbb3 100644 --- a/yarn.lock +++ b/yarn.lock @@ -13459,14 +13459,7 @@ eslint-plugin-playwright@^0.16.0: resolved "https://registry.yarnpkg.com/eslint-plugin-playwright/-/eslint-plugin-playwright-0.16.0.tgz#083c601a0704a7615509e63ac475bf7f0052d226" integrity sha512-DcHpF0SLbNeh9MT4pMzUGuUSnJ7q5MWbP8sSEFIMS6j7Ggnduq8ghNlfhURgty4c1YFny7Ge9xYTO1FSAoV2Vw== -eslint-plugin-prettier@^4.0.0: - version "4.2.1" - resolved "https://registry.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-4.2.1.tgz#651cbb88b1dab98bfd42f017a12fa6b2d993f94b" - integrity sha512-f/0rXLXUt0oFYs8ra4w49wYZBG5GKZpAYsJSm6rnYL5uVDjd+zowwMwVZHnAjf4edNrKpCDYfXDgmRE/Ak7QyQ== - dependencies: - prettier-linter-helpers "^1.0.0" - -eslint-plugin-prettier@^5.1.3: +eslint-plugin-prettier@^5.2.1: version "5.2.1" resolved "https://registry.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-5.2.1.tgz#d1c8f972d8f60e414c25465c163d16f209411f95" integrity sha512-gH3iR3g4JfF+yYPaJYkN7jEl9QbweL/YfkoRlNnuIEHEz1vHVlCmWOS+eGGiRuzHQXdJFCOTxRgvju9b8VUmrw== From 8e33cf2db037efd4cff5d2122753d7d508376556 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 26 Aug 2024 16:20:42 +0200 Subject: [PATCH 79/89] Bump @types/uuid from 9.0.8 to 10.0.0 (#2446) Bumps [@types/uuid](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/uuid) from 9.0.8 to 10.0.0. - [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases) - [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/uuid) --- updated-dependencies: - dependency-name: "@types/uuid" dependency-type: direct:development update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- packages/apps/reputation-oracle/server/package.json | 2 +- yarn.lock | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/apps/reputation-oracle/server/package.json b/packages/apps/reputation-oracle/server/package.json index 514670c947..29f69c52c0 100644 --- a/packages/apps/reputation-oracle/server/package.json +++ b/packages/apps/reputation-oracle/server/package.json @@ -67,7 +67,7 @@ "@types/jest": "29.5.12", "@types/node": "20.12.12", "@types/supertest": "^6.0.2", - "@types/uuid": "^9.0.6", + "@types/uuid": "^10.0.0", "@types/zxcvbn": "4.4.4", "@typescript-eslint/eslint-plugin": "^5.0.0", "@typescript-eslint/parser": "^5.0.0", diff --git a/yarn.lock b/yarn.lock index 618eaffbb3..79016e6b5a 100644 --- a/yarn.lock +++ b/yarn.lock @@ -7487,10 +7487,10 @@ resolved "https://registry.yarnpkg.com/@types/use-sync-external-store/-/use-sync-external-store-0.0.3.tgz#b6725d5f4af24ace33b36fafd295136e75509f43" integrity sha512-EwmlvuaxPNej9+T4v5AuBPJa2x2UOJVdjCtDHgcDqitUeOtjnJKJ+apYjVcAoBEMjKW1VVFGZLUb5+qqa09XFA== -"@types/uuid@^9.0.6": - version "9.0.8" - resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-9.0.8.tgz#7545ba4fc3c003d6c756f651f3bf163d8f0f29ba" - integrity sha512-jg+97EGIcY9AGHJJRaaPVgetKDsrTgbRjQ5Msgjh/DQKEFl0DtyRr/VCOyD1T2R1MNeWPK/u7JoGhlDZnKBAfA== +"@types/uuid@^10.0.0": + version "10.0.0" + resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-10.0.0.tgz#e9c07fe50da0f53dc24970cca94d619ff03f6f6d" + integrity sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ== "@types/validator@^13.11.8": version "13.12.0" From 06209dfa8bc14538f516634faa85daa8530b7c74 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 26 Aug 2024 16:21:15 +0200 Subject: [PATCH 80/89] Bump @reduxjs/toolkit from 1.9.7 to 2.2.7 (#2447) Bumps [@reduxjs/toolkit](https://github.com/reduxjs/redux-toolkit) from 1.9.7 to 2.2.7. - [Release notes](https://github.com/reduxjs/redux-toolkit/releases) - [Commits](https://github.com/reduxjs/redux-toolkit/compare/v1.9.7...v2.2.7) --- updated-dependencies: - dependency-name: "@reduxjs/toolkit" dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- packages/apps/dashboard/ui/package.json | 2 +- .../apps/job-launcher/client/package.json | 2 +- yarn.lock | 32 ++++++++++++++++++- 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/packages/apps/dashboard/ui/package.json b/packages/apps/dashboard/ui/package.json index 76502db888..ac010fcd38 100644 --- a/packages/apps/dashboard/ui/package.json +++ b/packages/apps/dashboard/ui/package.json @@ -10,7 +10,7 @@ "@human-protocol/sdk": "*", "@mui/icons-material": "^5.15.11", "@mui/material": "^5.16.7", - "@reduxjs/toolkit": "^1.9.0", + "@reduxjs/toolkit": "^2.2.7", "@tanstack/query-sync-storage-persister": "^5.38.0", "@tanstack/react-query": "^5.49.2", "@tanstack/react-query-persist-client": "^5.51.11", diff --git a/packages/apps/job-launcher/client/package.json b/packages/apps/job-launcher/client/package.json index 669b37bfe3..c2e8b2bd63 100644 --- a/packages/apps/job-launcher/client/package.json +++ b/packages/apps/job-launcher/client/package.json @@ -10,7 +10,7 @@ "@mui/lab": "^5.0.0-alpha.141", "@mui/material": "^5.16.7", "@mui/x-date-pickers": "^7.5.0", - "@reduxjs/toolkit": "^1.9.5", + "@reduxjs/toolkit": "^2.2.7", "@stripe/react-stripe-js": "^2.4.0", "@stripe/stripe-js": "^4.2.0", "@tanstack/query-sync-storage-persister": "^5.38.0", diff --git a/yarn.lock b/yarn.lock index 79016e6b5a..711b9bd89d 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5105,7 +5105,7 @@ resolved "https://registry.yarnpkg.com/@redis/time-series/-/time-series-1.1.0.tgz#cba454c05ec201bd5547aaf55286d44682ac8eb5" integrity sha512-c1Q99M5ljsIuc4YdaCwfUEXsofakb9c8+Zse2qxTadu8TalLXuAESzLvFAvNVbkmSlvlzIQOLpBCmWI9wTOt+g== -"@reduxjs/toolkit@1.9.7", "@reduxjs/toolkit@^1.9.0", "@reduxjs/toolkit@^1.9.5": +"@reduxjs/toolkit@1.9.7": version "1.9.7" resolved "https://registry.yarnpkg.com/@reduxjs/toolkit/-/toolkit-1.9.7.tgz#7fc07c0b0ebec52043f8cb43510cf346405f78a6" integrity sha512-t7v8ZPxhhKgOKtU+uyJT13lu4vL7az5aFi4IdoDs/eS548edn2M8Ik9h8fxgvMjGoAUVFSt6ZC1P5cWmQ014QQ== @@ -5115,6 +5115,16 @@ redux-thunk "^2.4.2" reselect "^4.1.8" +"@reduxjs/toolkit@^2.2.7": + version "2.2.7" + resolved "https://registry.yarnpkg.com/@reduxjs/toolkit/-/toolkit-2.2.7.tgz#199e3d10ccb39267cb5aee92c0262fd9da7fdfb2" + integrity sha512-faI3cZbSdFb8yv9dhDTmGwclW0vk0z5o1cia+kf7gCbaCwHI5e+7tP57mJUv22pNcNbeA62GSrPpfrUfdXcQ6g== + dependencies: + immer "^10.0.3" + redux "^5.0.1" + redux-thunk "^3.1.0" + reselect "^5.1.0" + "@remix-run/router@1.19.1": version "1.19.1" resolved "https://registry.yarnpkg.com/@remix-run/router/-/router-1.19.1.tgz#984771bfd1de2715f42394c87fb716c1349e014f" @@ -15922,6 +15932,11 @@ immer@9.0.19: resolved "https://registry.yarnpkg.com/immer/-/immer-9.0.19.tgz#67fb97310555690b5f9cd8380d38fc0aabb6b38b" integrity sha512-eY+Y0qcsB4TZKwgQzLaE/lqYMlKhv5J9dyd2RhhtGhNo2njPXDqU9XPfcNfa3MIDsdtZt5KlkIsirlo4dHsWdQ== +immer@^10.0.3: + version "10.1.1" + resolved "https://registry.yarnpkg.com/immer/-/immer-10.1.1.tgz#206f344ea372d8ea176891545ee53ccc062db7bc" + integrity sha512-s2MPrmjovJcoMaHtx6K11Ra7oD05NT97w1IC5zpMkT6Atjr7H8LjaDd81iIxUYpMKSRRNMJE703M1Fhr/TctHw== + immer@^9.0.21, immer@^9.0.6: version "9.0.21" resolved "https://registry.yarnpkg.com/immer/-/immer-9.0.21.tgz#1e025ea31a40f24fb064f1fef23e931496330176" @@ -22081,6 +22096,11 @@ redux-thunk@^2.4.2: resolved "https://registry.yarnpkg.com/redux-thunk/-/redux-thunk-2.4.2.tgz#b9d05d11994b99f7a91ea223e8b04cf0afa5ef3b" integrity sha512-+P3TjtnP0k/FEjcBL5FZpoovtvrTNT/UXd4/sluaSyrURlSlhLSzEdfsTBW7WsKB6yPvgd7q/iZPICFjW4o57Q== +redux-thunk@^3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/redux-thunk/-/redux-thunk-3.1.0.tgz#94aa6e04977c30e14e892eae84978c1af6058ff3" + integrity sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw== + redux@^4.2.0, redux@^4.2.1: version "4.2.1" resolved "https://registry.yarnpkg.com/redux/-/redux-4.2.1.tgz#c08f4306826c49b5e9dc901dee0452ea8fce6197" @@ -22088,6 +22108,11 @@ redux@^4.2.0, redux@^4.2.1: dependencies: "@babel/runtime" "^7.9.2" +redux@^5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/redux/-/redux-5.0.1.tgz#97fa26881ce5746500125585d5642c77b6e9447b" + integrity sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w== + reflect-metadata@^0.1.13: version "0.1.14" resolved "https://registry.yarnpkg.com/reflect-metadata/-/reflect-metadata-0.1.14.tgz#24cf721fe60677146bb77eeb0e1f9dece3d65859" @@ -22316,6 +22341,11 @@ reselect@^4.1.8: resolved "https://registry.yarnpkg.com/reselect/-/reselect-4.1.8.tgz#3f5dc671ea168dccdeb3e141236f69f02eaec524" integrity sha512-ab9EmR80F/zQTMNeneUr4cv+jSwPJgIlvEmVwLerwrWVbpLlBuls9XHzIeTFy4cegU2NHBp3va0LKOzU5qFEYQ== +reselect@^5.1.0: + version "5.1.1" + resolved "https://registry.yarnpkg.com/reselect/-/reselect-5.1.1.tgz#c766b1eb5d558291e5e550298adb0becc24bb72e" + integrity sha512-K/BG6eIky/SBpzfHZv/dd+9JBFiS4SWV7FIujVyJRux6e45+73RaUHXLmIR1f7WOMaQ0U1km6qwklRQxpJJY0w== + resize-observer-polyfill@^1.5.1: version "1.5.1" resolved "https://registry.yarnpkg.com/resize-observer-polyfill/-/resize-observer-polyfill-1.5.1.tgz#0e9020dd3d21024458d4ebd27e23e40269810464" From ef0e21f52d6174b410fbd358efd22b4ede91861b Mon Sep 17 00:00:00 2001 From: portuu3 <61605646+portuu3@users.noreply.github.com> Date: Tue, 27 Aug 2024 09:31:15 +0200 Subject: [PATCH 81/89] Revert "Removed reputation from leader entity (#2420)" (#2448) This reverts commit 4d623dc8cea9b273d531e8f8663b69e5bc7b7b8f. --- .../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 | 107 +++ ...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 | 907 ++++++++++++++++++ .../human_protocol_sdk.escrow.escrow_utils.md | 162 ++++ docs/sdk/python/human_protocol_sdk.escrow.md | 50 + docs/sdk/python/human_protocol_sdk.filter.md | 88 ++ ...man_protocol_sdk.kvstore.kvstore_client.md | 183 ++++ ...uman_protocol_sdk.kvstore.kvstore_utils.md | 132 +++ docs/sdk/python/human_protocol_sdk.kvstore.md | 15 + .../human_protocol_sdk.legacy_encryption.md | 162 ++++ docs/sdk/python/human_protocol_sdk.md | 187 ++++ .../sdk/python/human_protocol_sdk.operator.md | 24 + ...an_protocol_sdk.operator.operator_utils.md | 187 ++++ docs/sdk/python/human_protocol_sdk.staking.md | 24 + ...man_protocol_sdk.staking.staking_client.md | 437 +++++++++ .../python/human_protocol_sdk.statistics.md | 38 + ...otocol_sdk.statistics.statistics_client.md | 342 +++++++ 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 | 16 + ...tocol_sdk.transaction.transaction_utils.md | 94 ++ docs/sdk/python/human_protocol_sdk.utils.md | 119 +++ docs/sdk/python/index.md | 73 ++ .../base/classes/BaseEthersClient.md | 6 +- .../encryption/classes/Encryption.md | 10 +- .../encryption/classes/EncryptionUtils.md | 10 +- .../typescript/escrow/classes/EscrowClient.md | 52 +- .../typescript/escrow/classes/EscrowUtils.md | 6 +- .../kvstore/classes/KVStoreClient.md | 14 +- .../kvstore/classes/KVStoreUtils.md | 8 +- .../operator/classes/OperatorUtils.md | 8 +- .../staking/classes/StakingClient.md | 34 +- .../statistics/classes/StatisticsClient.md | 18 +- .../storage/classes/StorageClient.md | 12 +- .../transaction/classes/TransactionUtils.md | 4 +- .../python/human-protocol-sdk/docs/Makefile | 20 + .../python/human-protocol-sdk/docs/conf.py | 54 ++ .../docs/human_protocol_sdk.kvstore.rst | 1 - .../docs/human_protocol_sdk.rst | 1 - .../python/human-protocol-sdk/docs/index.rst | 28 + .../python/human-protocol-sdk/docs/make.bat | 35 + .../human_protocol_sdk/gql/operator.py | 1 + .../operator/operator_utils.py | 5 + .../operator/test_operator_utils.py | 12 + .../human-protocol-sdk/src/interfaces.ts | 1 + .../human-protocol-sdk/test/operator.test.ts | 2 + .../sdk/typescript/subgraph/schema.graphql | 1 + .../subgraph/src/mapping/Staking.ts | 1 + 55 files changed, 4945 insertions(+), 93 deletions(-) create mode 100644 docs/sdk/python/human_protocol_sdk.agreement.bootstrap.md create mode 100644 docs/sdk/python/human_protocol_sdk.agreement.md create mode 100644 docs/sdk/python/human_protocol_sdk.agreement.measures.md create mode 100644 docs/sdk/python/human_protocol_sdk.agreement.utils.md create mode 100644 docs/sdk/python/human_protocol_sdk.constants.md create mode 100644 docs/sdk/python/human_protocol_sdk.encryption.encryption.md create mode 100644 docs/sdk/python/human_protocol_sdk.encryption.encryption_utils.md create mode 100644 docs/sdk/python/human_protocol_sdk.encryption.md create mode 100644 docs/sdk/python/human_protocol_sdk.escrow.escrow_client.md create mode 100644 docs/sdk/python/human_protocol_sdk.escrow.escrow_utils.md create mode 100644 docs/sdk/python/human_protocol_sdk.escrow.md create mode 100644 docs/sdk/python/human_protocol_sdk.filter.md create mode 100644 docs/sdk/python/human_protocol_sdk.kvstore.kvstore_client.md create mode 100644 docs/sdk/python/human_protocol_sdk.kvstore.kvstore_utils.md create mode 100644 docs/sdk/python/human_protocol_sdk.kvstore.md create mode 100644 docs/sdk/python/human_protocol_sdk.legacy_encryption.md create mode 100644 docs/sdk/python/human_protocol_sdk.md create mode 100644 docs/sdk/python/human_protocol_sdk.operator.md create mode 100644 docs/sdk/python/human_protocol_sdk.operator.operator_utils.md create mode 100644 docs/sdk/python/human_protocol_sdk.staking.md create mode 100644 docs/sdk/python/human_protocol_sdk.staking.staking_client.md create mode 100644 docs/sdk/python/human_protocol_sdk.statistics.md create mode 100644 docs/sdk/python/human_protocol_sdk.statistics.statistics_client.md create mode 100644 docs/sdk/python/human_protocol_sdk.storage.md create mode 100644 docs/sdk/python/human_protocol_sdk.storage.storage_client.md create mode 100644 docs/sdk/python/human_protocol_sdk.storage.storage_utils.md create mode 100644 docs/sdk/python/human_protocol_sdk.transaction.md create mode 100644 docs/sdk/python/human_protocol_sdk.transaction.transaction_utils.md create mode 100644 docs/sdk/python/human_protocol_sdk.utils.md create mode 100644 docs/sdk/python/index.md create mode 100644 packages/sdk/python/human-protocol-sdk/docs/Makefile create mode 100644 packages/sdk/python/human-protocol-sdk/docs/conf.py create mode 100644 packages/sdk/python/human-protocol-sdk/docs/index.rst create mode 100644 packages/sdk/python/human-protocol-sdk/docs/make.bat diff --git a/docs/sdk/python/human_protocol_sdk.agreement.bootstrap.md b/docs/sdk/python/human_protocol_sdk.agreement.bootstrap.md new file mode 100644 index 0000000000..d1659f6ba2 --- /dev/null +++ b/docs/sdk/python/human_protocol_sdk.agreement.bootstrap.md @@ -0,0 +1,41 @@ +# 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 new file mode 100644 index 0000000000..aaa48cd386 --- /dev/null +++ b/docs/sdk/python/human_protocol_sdk.agreement.md @@ -0,0 +1,105 @@ +# 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 new file mode 100644 index 0000000000..8aac0ff6ea --- /dev/null +++ b/docs/sdk/python/human_protocol_sdk.md @@ -0,0 +1,187 @@ +# 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) + * [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) + * [`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) + * [`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.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) + * [`LeaderData`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.LeaderData) + * [`LeaderFilter`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.LeaderFilter) + * [`Operator`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.Operator) + * [`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) + * [`AllocationData`](human_protocol_sdk.staking.staking_client.md#human_protocol_sdk.staking.staking_client.AllocationData) + * [`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.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) + +## Submodules + +* [human_protocol_sdk.constants module](human_protocol_sdk.constants.md) + * [`ChainId`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId) + * [`ChainId.AVALANCHE`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId.AVALANCHE) + * [`ChainId.AVALANCHE_TESTNET`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId.AVALANCHE_TESTNET) + * [`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.CELO`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId.CELO) + * [`ChainId.CELO_ALFAJORES`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId.CELO_ALFAJORES) + * [`ChainId.GOERLI`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId.GOERLI) + * [`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.MOONBASE_ALPHA`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId.MOONBASE_ALPHA) + * [`ChainId.MOONBEAM`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId.MOONBEAM) + * [`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.POLYGON_MUMBAI`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId.POLYGON_MUMBAI) + * [`ChainId.RINKEBY`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId.RINKEBY) + * [`ChainId.SEPOLIA`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId.SEPOLIA) + * [`ChainId.XLAYER`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId.XLAYER) + * [`ChainId.XLAYER_TESTNET`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId.XLAYER_TESTNET) + * [`KVStoreKeys`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.KVStoreKeys) + * [`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.public_key`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.KVStoreKeys.public_key) + * [`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) + * [`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) + * [`Role.validator`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.Role.validator) + * [`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) +* [human_protocol_sdk.filter module](human_protocol_sdk.filter.md) + * [`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__) + * [`StatisticsFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.StatisticsFilter) + * [`StatisticsFilter.__init__()`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.StatisticsFilter.__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__) +* [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) + * [`get_contract_interface()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_contract_interface) + * [`get_data_from_subgraph()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_data_from_subgraph) + * [`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_reward_pool_interface()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_reward_pool_interface) + * [`get_staking_interface()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_staking_interface) + * [`handle_transaction()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.handle_transaction) + * [`parse_transfer_transaction()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.parse_transfer_transaction) + * [`validate_url()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.validate_url) + * [`with_retry()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.with_retry) diff --git a/docs/sdk/python/human_protocol_sdk.operator.md b/docs/sdk/python/human_protocol_sdk.operator.md new file mode 100644 index 0000000000..221784ef4c --- /dev/null +++ b/docs/sdk/python/human_protocol_sdk.operator.md @@ -0,0 +1,24 @@ +# 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) + * [`LeaderData`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.LeaderData) + * [`LeaderData.__init__()`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.LeaderData.__init__) + * [`LeaderFilter`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.LeaderFilter) + * [`LeaderFilter.__init__()`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.LeaderFilter.__init__) + * [`Operator`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.Operator) + * [`Operator.__init__()`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.Operator.__init__) + * [`OperatorUtils`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.OperatorUtils) + * [`OperatorUtils.get_leader()`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.OperatorUtils.get_leader) + * [`OperatorUtils.get_leaders()`](human_protocol_sdk.operator.operator_utils.md#human_protocol_sdk.operator.operator_utils.OperatorUtils.get_leaders) + * [`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 new file mode 100644 index 0000000000..14f6d7d430 --- /dev/null +++ b/docs/sdk/python/human_protocol_sdk.operator.operator_utils.md @@ -0,0 +1,187 @@ +# 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, LeaderFilter + +print( + OperatorUtils.get_leaders( + LeaderFilter(networks=[ChainId.POLYGON_AMOY], role="Job Launcher") + ) +) +``` + +## Module + +### *class* human_protocol_sdk.operator.operator_utils.LeaderData(chain_id, id, address, amount_staked, amount_allocated, amount_locked, locked_until_timestamp, amount_withdrawn, amount_slashed, reputation, reward, amount_jobs_processed, role=None, fee=None, public_key=None, webhook_url=None, url=None, job_types=None) + +Bases: `object` + +#### \_\_init_\_(chain_id, id, address, amount_staked, amount_allocated, amount_locked, locked_until_timestamp, amount_withdrawn, amount_slashed, reputation, reward, amount_jobs_processed, role=None, fee=None, public_key=None, webhook_url=None, url=None, job_types=None) + +Initializes an LeaderData instance. + +* **Parameters:** + * **chain_id** ([`ChainId`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId)) – Chain Identifier + * **id** (`str`) – Identifier + * **address** (`str`) – Address + * **amount_staked** (`int`) – Amount staked + * **amount_allocated** (`int`) – Amount allocated + * **amount_locked** (`int`) – Amount locked + * **locked_until_timestamp** (`int`) – Locked until timestamp + * **amount_withdrawn** (`int`) – Amount withdrawn + * **amount_slashed** (`int`) – Amount slashed + * **reputation** (`int`) – Reputation + * **reward** (`int`) – Reward + * **amount_jobs_processed** (`int`) – Amount of jobs launched + * **role** (`Optional`[`str`]) – Role + * **fee** (`Optional`[`int`]) – Fee + * **public_key** (`Optional`[`str`]) – Public key + * **webhook_url** (`Optional`[`str`]) – Webhook url + * **url** (`Optional`[`str`]) – Url + * **job_types** (`Optional`[`List`[`str`]]) – Job types + +### *class* human_protocol_sdk.operator.operator_utils.LeaderFilter(chain_id, role=None) + +Bases: `object` + +A class used to filter leaders. + +#### \_\_init_\_(chain_id, role=None) + +Initializes a LeaderFilter instance. + +* **Parameters:** + * **chain_id** ([`ChainId`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId)) – Chain Id to request data + * **role** (`Optional`[`str`]) – Leader role + +### *class* human_protocol_sdk.operator.operator_utils.Operator(address, role, url='', job_types=[]) + +Bases: `object` + +#### \_\_init_\_(address, role, url='', job_types=[]) + +Initializes an Operator instance. + +* **Parameters:** + * **address** (`str`) – Operator address + * **role** (`str`) – Role of the operator + +### *class* human_protocol_sdk.operator.operator_utils.OperatorUtils + +Bases: `object` + +A utility class that provides additional operator-related functionalities. + +#### *static* get_leader(chain_id, leader_address) + +Get the leader details. + +* **Parameters:** + * **chain_id** ([`ChainId`](human_protocol_sdk.constants.md#human_protocol_sdk.constants.ChainId)) – Network in which the leader exists + * **leader_address** (`str`) – Address of the leader +* **Return type:** + `Optional`[[`LeaderData`](#human_protocol_sdk.operator.operator_utils.LeaderData)] +* **Returns:** + Leader data if exists, otherwise None +* **Example:** + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.operator import OperatorUtils + + leader = OperatorUtils.get_leader( + ChainId.POLYGON_AMOY, + '0x62dD51230A30401C455c8398d06F85e4EaB6309f' + ) + ``` + +#### *static* get_leaders(filter) + +Get leaders data of the protocol + +* **Parameters:** + **filter** ([`LeaderFilter`](#human_protocol_sdk.operator.operator_utils.LeaderFilter)) – Leader filter +* **Return type:** + `List`[[`LeaderData`](#human_protocol_sdk.operator.operator_utils.LeaderData)] +* **Returns:** + List of leaders data +* **Example:** + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.operator import OperatorUtils, LeaderFilter + + print( + OperatorUtils.get_leaders( + LeaderFilter(chain_id=ChainId.POLYGON_AMOY) + ) + ) + ``` + +#### *static* get_reputation_network_operators(chain_id, address, role=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 +* **Parem job_types:** + (Optional) Job types of the operator +* **Return type:** + `List`[[`Operator`](#human_protocol_sdk.operator.operator_utils.Operator)] +* **Returns:** + Returns an array of operator details +* **Example:** + ```python + from human_protocol_sdk.constants import ChainId + from human_protocol_sdk.operator import OperatorUtils + + leader = OperatorUtils.get_reputation_network_operators( + ChainId.POLYGON_AMOY, + '0x62dD51230A30401C455c8398d06F85e4EaB6309f' + ) + ``` + +#### *static* get_rewards_info(chain_id, slasher) + +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 +* **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' + ) + ``` + +### *exception* human_protocol_sdk.operator.operator_utils.OperatorUtilsError + +Bases: `Exception` + +Raises when some error happens when interacting with 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 new file mode 100644 index 0000000000..80244a941c --- /dev/null +++ b/docs/sdk/python/human_protocol_sdk.staking.md @@ -0,0 +1,24 @@ +# 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) + * [`AllocationData`](human_protocol_sdk.staking.staking_client.md#human_protocol_sdk.staking.staking_client.AllocationData) + * [`AllocationData.__init__()`](human_protocol_sdk.staking.staking_client.md#human_protocol_sdk.staking.staking_client.AllocationData.__init__) + * [`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.allocate()`](human_protocol_sdk.staking.staking_client.md#human_protocol_sdk.staking.staking_client.StakingClient.allocate) + * [`StakingClient.approve_stake()`](human_protocol_sdk.staking.staking_client.md#human_protocol_sdk.staking.staking_client.StakingClient.approve_stake) + * [`StakingClient.close_allocation()`](human_protocol_sdk.staking.staking_client.md#human_protocol_sdk.staking.staking_client.StakingClient.close_allocation) + * [`StakingClient.distribute_reward()`](human_protocol_sdk.staking.staking_client.md#human_protocol_sdk.staking.staking_client.StakingClient.distribute_reward) + * [`StakingClient.get_allocation()`](human_protocol_sdk.staking.staking_client.md#human_protocol_sdk.staking.staking_client.StakingClient.get_allocation) + * [`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) diff --git a/docs/sdk/python/human_protocol_sdk.staking.staking_client.md b/docs/sdk/python/human_protocol_sdk.staking.staking_client.md new file mode 100644 index 0000000000..ffe8e02e37 --- /dev/null +++ b/docs/sdk/python/human_protocol_sdk.staking.staking_client.md @@ -0,0 +1,437 @@ +# human_protocol_sdk.staking.staking_client module + +This client enables to perform actions on staking contracts and +obtain 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 Web3 instance, and configure 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 construct_sign_and_send_raw_middleware +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.add( + construct_sign_and_send_raw_middleware(gas_payer), + "construct_sign_and_send_raw_middleware", + ) + 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.AllocationData(escrow_address, staker, tokens, created_at, closed_at) + +Bases: `object` + +#### \_\_init_\_(escrow_address, staker, tokens, created_at, closed_at) + +Initializes an AllocationData instance. + +* **Parameters:** + * **escrow_address** (`str`) – Escrow address + * **staker** (`str`) – Staker address + * **tokens** (`str`) – Amount allocated + * **created_at** (`str`) – Creation date + * **closed_at** (`str`) – Closing date + +### *class* human_protocol_sdk.staking.staking_client.StakingClient(w3) + +Bases: `object` + +A class used to manage staking, and allocation on the HUMAN network. + +#### \_\_init_\_(w3) + +Initializes a Staking instance + +* **Parameters:** + **w3** (`Web3`) – Web3 instance + +#### allocate(escrow_address, amount, tx_options=None) + +Allocates HMT token to the escrow. + +* **Parameters:** + * **escrow_address** (`str`) – Address of the escrow + * **amount** (`Decimal`) – Amount to allocate + * **tx_options** (`Optional`[`TxParams`]) – (Optional) Additional transaction parameters +* **Return type:** + `None` +* **Returns:** + None +* **Validate:** + - Amount must be greater than 0 + - Escrow address must be valid + - Amount must be less than or equal to the staked amount (on-chain) +* **Example:** + ```python + from eth_typing import URI + from web3 import Web3 + from web3.middleware import construct_sign_and_send_raw_middleware + 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.add( + construct_sign_and_send_raw_middleware(gas_payer), + "construct_sign_and_send_raw_middleware", + ) + 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.allocate('0x62dD51230A30401C455c8398d06F85e4EaB6309f', amount) + ``` + +#### approve_stake(amount, tx_options=None) + +Approves HMT token for Staking. + +* **Parameters:** + * **amount** (`Decimal`) – Amount to approve + * **tx_options** (`Optional`[`TxParams`]) – (Optional) Additional transaction parameters +* **Return type:** + `None` +* **Returns:** + None +* **Validate:** + Amount must be greater than 0 +* **Example:** + ```python + from eth_typing import URI + from web3 import Web3 + from web3.middleware import construct_sign_and_send_raw_middleware + 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.add( + construct_sign_and_send_raw_middleware(gas_payer), + "construct_sign_and_send_raw_middleware", + ) + 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.approve_stake(amount) + ``` + +#### close_allocation(escrow_address, tx_options=None) + +Closes allocated HMT token from the escrow. + +* **Parameters:** + * **escrow_address** (`str`) – Address of the escrow + * **tx_options** (`Optional`[`TxParams`]) – (Optional) Additional transaction parameters +* **Return type:** + `None` +* **Returns:** + None +* **Validate:** + - Escrow address must be valid + - Escrow should be cancelled / completed (on-chain) +* **Example:** + ```python + from eth_typing import URI + from web3 import Web3 + from web3.middleware import construct_sign_and_send_raw_middleware + 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.add( + construct_sign_and_send_raw_middleware(gas_payer), + "construct_sign_and_send_raw_middleware", + ) + return (w3, gas_payer) + + (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') + staking_client = StakingClient(w3) + + staking_client.close_allocation('0x62dD51230A30401C455c8398d06F85e4EaB6309f') + ``` + +#### distribute_reward(escrow_address, tx_options=None) + +Pays out rewards to the slashers for the specified escrow address. + +* **Parameters:** + * **escrow_address** (`str`) – Address of the escrow + * **tx_options** (`Optional`[`TxParams`]) – (Optional) Additional transaction parameters +* **Return type:** + `None` +* **Returns:** + None +* **Validate:** + - Escrow address must be valid +* **Example:** + ```python + from eth_typing import URI + from web3 import Web3 + from web3.middleware import construct_sign_and_send_raw_middleware + 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.add( + construct_sign_and_send_raw_middleware(gas_payer), + "construct_sign_and_send_raw_middleware", + ) + return (w3, gas_payer) + + (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') + staking_client = StakingClient(w3) + + staking_client.distribute_reward('0x62dD51230A30401C455c8398d06F85e4EaB6309f') + ``` + +#### get_allocation(escrow_address) + +Gets the allocation info for the specified escrow. + +* **Parameters:** + **escrow_address** (`str`) – Address of the escrow +* **Return type:** + `Optional`[[`AllocationData`](#human_protocol_sdk.staking.staking_client.AllocationData)] +* **Returns:** + Allocation info if escrow exists, otherwise None +* **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) + + allocation = staking_client.get_allocation( + '0x62dD51230A30401C455c8398d06F85e4EaB6309f' + ) + ``` + +#### slash(slasher, staker, escrow_address, amount, tx_options=None) + +Slashes HMT token. + +* **Parameters:** + * **slasher** (`str`) – Address of the slasher + * **staker** (`str`) – Address of the staker + * **escrow_address** (`str`) – Address of the escrow + * **amount** (`Decimal`) – Amount to slash + * **tx_options** (`Optional`[`TxParams`]) – (Optional) Additional transaction parameters +* **Return type:** + `None` +* **Returns:** + 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:** + ```python + from eth_typing import URI + from web3 import Web3 + from web3.middleware import construct_sign_and_send_raw_middleware + 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.add( + construct_sign_and_send_raw_middleware(gas_payer), + "construct_sign_and_send_raw_middleware", + ) + 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 + ) + ``` + +#### stake(amount, tx_options=None) + +Stakes HMT token. + +* **Parameters:** + * **amount** (`Decimal`) – Amount to stake + * **tx_options** (`Optional`[`TxParams`]) – (Optional) Additional transaction parameters +* **Return type:** + `None` +* **Returns:** + 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:** + ```python + from eth_typing import URI + from web3 import Web3 + from web3.middleware import construct_sign_and_send_raw_middleware + 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.add( + construct_sign_and_send_raw_middleware(gas_payer), + "construct_sign_and_send_raw_middleware", + ) + 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.approve_stake(amount) + # if it was already approved before, this is not necessary + staking_client.stake(amount) + ``` + +#### unstake(amount, tx_options=None) + +Unstakes HMT token. + +* **Parameters:** + * **amount** (`Decimal`) – Amount to unstake + * **tx_options** (`Optional`[`TxParams`]) – (Optional) Additional transaction parameters +* **Return type:** + `None` +* **Returns:** + 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) +* **Example:** + ```python + from eth_typing import URI + from web3 import Web3 + from web3.middleware import construct_sign_and_send_raw_middleware + 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.add( + construct_sign_and_send_raw_middleware(gas_payer), + "construct_sign_and_send_raw_middleware", + ) + 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) + ``` + +#### withdraw(tx_options=None) + +Withdraws HMT token. + +* **Parameters:** + **tx_options** (`Optional`[`TxParams`]) – (Optional) Additional transaction parameters +* **Return type:** + `None` +* **Returns:** + None +* **Validate:** + - There must be unstaked tokens which is unlocked (on-chain) +* **Example:** + ```python + from eth_typing import URI + from web3 import Web3 + from web3.middleware import construct_sign_and_send_raw_middleware + 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.add( + construct_sign_and_send_raw_middleware(gas_payer), + "construct_sign_and_send_raw_middleware", + ) + return (w3, gas_payer) + + (w3, gas_payer) = get_w3_with_priv_key('YOUR_PRIVATE_KEY') + staking_client = StakingClient(w3) + + staking_client.withdraw() + ``` + +### *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.statistics.md b/docs/sdk/python/human_protocol_sdk.statistics.md new file mode 100644 index 0000000000..ee37413d17 --- /dev/null +++ b/docs/sdk/python/human_protocol_sdk.statistics.md @@ -0,0 +1,38 @@ +# 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 new file mode 100644 index 0000000000..763afb78fd --- /dev/null +++ b/docs/sdk/python/human_protocol_sdk.statistics.statistics_client.md @@ -0,0 +1,342 @@ +# 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=) + +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 +* **Return type:** + [`EscrowStatistics`](#human_protocol_sdk.statistics.statistics_client.EscrowStatistics) +* **Returns:** + Escrow statistics data +* **Example:** + ```python + from human_protocol_sdk.contants 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=) + +Get HMT dailt 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 +* **Return type:** + `List`[[`DailyHMTData`](#human_protocol_sdk.statistics.statistics_client.DailyHMTData)] +* **Returns:** + HMT statistics data +* **Example:** + ```python + from human_protocol_sdk.contants 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=) + +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 +* **Return type:** + `List`[[`HMTHolder`](#human_protocol_sdk.statistics.statistics_client.HMTHolder)] +* **Returns:** + List of HMT holders +* **Example:** + ```python + from human_protocol_sdk.contants 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() + +Get HMT statistics data. + +* **Return type:** + [`HMTStatistics`](#human_protocol_sdk.statistics.statistics_client.HMTStatistics) +* **Returns:** + HMT statistics data +* **Example:** + ```python + from human_protocol_sdk.contants 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=) + +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 +* **Return type:** + [`PaymentStatistics`](#human_protocol_sdk.statistics.statistics_client.PaymentStatistics) +* **Returns:** + Payment statistics data +* **Example:** + ```python + from human_protocol_sdk.contants 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=) + +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 +* **Return type:** + [`WorkerStatistics`](#human_protocol_sdk.statistics.statistics_client.WorkerStatistics) +* **Returns:** + Worker statistics data +* **Example:** + ```python + from human_protocol_sdk.contants 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 new file mode 100644 index 0000000000..039bef73dd --- /dev/null +++ b/docs/sdk/python/human_protocol_sdk.storage.md @@ -0,0 +1,22 @@ +# 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 new file mode 100644 index 0000000000..497becc3a2 --- /dev/null +++ b/docs/sdk/python/human_protocol_sdk.storage.storage_client.md @@ -0,0 +1,246 @@ +# 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 content"], + 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 new file mode 100644 index 0000000000..d45551b0ee --- /dev/null +++ b/docs/sdk/python/human_protocol_sdk.storage.storage_utils.md @@ -0,0 +1,30 @@ +# 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 StorageClient + + result = StorageClient.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 new file mode 100644 index 0000000000..58fb7d7b25 --- /dev/null +++ b/docs/sdk/python/human_protocol_sdk.transaction.md @@ -0,0 +1,16 @@ +# 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) + * [`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 new file mode 100644 index 0000000000..ce1a533e1d --- /dev/null +++ b/docs/sdk/python/human_protocol_sdk.transaction.transaction_utils.md @@ -0,0 +1,94 @@ +# 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( + networks=[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.TransactionData(chain_id, block, tx_hash, from_address, to_address, timestamp, value, method) + +Bases: `object` + +#### \_\_init_\_(chain_id, block, tx_hash, from_address, to_address, timestamp, value, method) + +### *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) + +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 +* **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) + +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 +* **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", + 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 new file mode 100644 index 0000000000..adc9d4cc71 --- /dev/null +++ b/docs/sdk/python/human_protocol_sdk.utils.md @@ -0,0 +1,119 @@ +# human_protocol_sdk.utils module + +### 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_data_from_subgraph(network, query, params=None) + +### 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:** + Decimal with HMT balance + +### human_protocol_sdk.utils.get_kvstore_interface() + +Retrieve the KVStore interface. + +* **Returns:** + The KVStore interface of smart contract. + +### human_protocol_sdk.utils.get_reward_pool_interface() + +Retrieve the RewardPool interface. + +* **Returns:** + The RewardPool 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_transaction(w3, tx_name, tx, exception, tx_options) + +Executes the transaction and waits for the receipt. + +* **Parameters:** + * **w3** (`Web3`) – Web3 instance + * **tx_name** (`str`) – Name of the transaction + * **tx** – Transaction object + * **exception** (`Exception`) – Exception class to raise in case of error + * **tx_options** (`Optional`[`TxParams`]) – (Optional) Additional transaction parameters + - If provided, can include values like ‘gas’, ‘gas_price’, ‘nonce’, etc + - If ‘gas’ is not specified or is None, it will be estimated using tx.estimate_gas() +* **Returns:** + The transaction receipt +* **Validate:** + - There must be a default account + +### human_protocol_sdk.utils.parse_transfer_transaction(hmtoken_contract, tx_receipt) + +* **Return type:** + `Tuple`[`bool`, `Optional`[`int`]] + +### human_protocol_sdk.utils.validate_url(url) + +Gets the url string. + +* **Parameters:** + **url** (`str`) – Public or private url address +* **Return type:** + `bool` +* **Returns:** + True if url is valid +* **Raises:** + **ValidationFailure** – If the url is invalid + +### human_protocol_sdk.utils.with_retry(fn, retries=3, delay=5, backoff=2) + +Retry a function + +Mainly used with handle_transaction to retry on case of failure. +Uses expnential backoff. + +* **Parameters:** + * **fn** – to run with retry logic. + * **retries** – number of times to retry the transaction + * **delay** – time to wait (exponentially) + * **backoff** – defines the rate of grow for the exponential wait. +* **Returns:** + False if transaction never succeeded, + otherwise the return of the function +* **Note:** + If the partial returns a Boolean and it happens to be False, + we would not know if the tx succeeded and it will retry. diff --git a/docs/sdk/python/index.md b/docs/sdk/python/index.md new file mode 100644 index 0000000000..fbc414248c --- /dev/null +++ b/docs/sdk/python/index.md @@ -0,0 +1,73 @@ + + +# 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) + * [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) + * [`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) + * [`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) + * [`StatisticsFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.StatisticsFilter) + * [`TransactionFilter`](human_protocol_sdk.filter.md#human_protocol_sdk.filter.TransactionFilter) + * [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) + * [`get_contract_interface()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_contract_interface) + * [`get_data_from_subgraph()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_data_from_subgraph) + * [`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_reward_pool_interface()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_reward_pool_interface) + * [`get_staking_interface()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.get_staking_interface) + * [`handle_transaction()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.handle_transaction) + * [`parse_transfer_transaction()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.parse_transfer_transaction) + * [`validate_url()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.validate_url) + * [`with_retry()`](human_protocol_sdk.utils.md#human_protocol_sdk.utils.with_retry) diff --git a/docs/sdk/typescript/base/classes/BaseEthersClient.md b/docs/sdk/typescript/base/classes/BaseEthersClient.md index 63a79f4422..032938cf82 100644 --- a/docs/sdk/typescript/base/classes/BaseEthersClient.md +++ b/docs/sdk/typescript/base/classes/BaseEthersClient.md @@ -40,7 +40,7 @@ The network information required to connect to the contracts #### Defined in -[base.ts:20](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L20) +[base.ts:20](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L20) ## Properties @@ -50,7 +50,7 @@ The network information required to connect to the contracts #### Defined in -[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) +[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) *** @@ -60,4 +60,4 @@ The network information required to connect to the contracts #### Defined in -[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) +[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) diff --git a/docs/sdk/typescript/encryption/classes/Encryption.md b/docs/sdk/typescript/encryption/classes/Encryption.md index 6ff4b83171..37e9d6a8c1 100644 --- a/docs/sdk/typescript/encryption/classes/Encryption.md +++ b/docs/sdk/typescript/encryption/classes/Encryption.md @@ -66,7 +66,7 @@ The private key. #### Defined in -[encryption.ts:53](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L53) +[encryption.ts:53](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L53) ## Methods @@ -118,7 +118,7 @@ const resultMessage = await encription.decrypt('message'); #### Defined in -[encryption.ts:180](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L180) +[encryption.ts:180](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L180) *** @@ -154,7 +154,7 @@ const resultMessage = await encription.sign('message'); #### Defined in -[encryption.ts:217](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L217) +[encryption.ts:217](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L217) *** @@ -219,7 +219,7 @@ const resultMessage = await encription.signAndEncrypt('message', publicKeys); #### Defined in -[encryption.ts:129](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L129) +[encryption.ts:129](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L129) *** @@ -247,4 +247,4 @@ Optional: The passphrase for the private key. #### Defined in -[encryption.ts:64](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L64) +[encryption.ts:64](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L64) diff --git a/docs/sdk/typescript/encryption/classes/EncryptionUtils.md b/docs/sdk/typescript/encryption/classes/EncryptionUtils.md index a21bf6fe89..c7602663c4 100644 --- a/docs/sdk/typescript/encryption/classes/EncryptionUtils.md +++ b/docs/sdk/typescript/encryption/classes/EncryptionUtils.md @@ -97,7 +97,7 @@ const result = await EncriptionUtils.encrypt('message', publicKeys); #### Defined in -[encryption.ts:422](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L422) +[encryption.ts:422](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L422) *** @@ -152,7 +152,7 @@ const result = await EncriptionUtils.generateKeyPair(name, email, passphrase); #### Defined in -[encryption.ts:360](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L360) +[encryption.ts:360](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L360) *** @@ -184,7 +184,7 @@ const signedData = await EncriptionUtils.getSignedData('message'); #### Defined in -[encryption.ts:317](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L317) +[encryption.ts:317](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L317) *** @@ -232,7 +232,7 @@ if (isEncrypted) { #### Defined in -[encryption.ts:471](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L471) +[encryption.ts:471](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L471) *** @@ -280,4 +280,4 @@ const result = await EncriptionUtils.verify('message', publicKey); #### Defined in -[encryption.ts:284](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L284) +[encryption.ts:284](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/encryption.ts#L284) diff --git a/docs/sdk/typescript/escrow/classes/EscrowClient.md b/docs/sdk/typescript/escrow/classes/EscrowClient.md index 326d1beab4..e8f27b7ba1 100644 --- a/docs/sdk/typescript/escrow/classes/EscrowClient.md +++ b/docs/sdk/typescript/escrow/classes/EscrowClient.md @@ -104,7 +104,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[escrow.ts:129](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L129) +[escrow.ts:129](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L129) ## Properties @@ -118,7 +118,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) +[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) *** @@ -132,7 +132,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) +[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) ## Methods @@ -178,7 +178,7 @@ await escrowClient.abort('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); #### Defined in -[escrow.ts:837](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L837) +[escrow.ts:837](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L837) *** @@ -229,7 +229,7 @@ await escrowClient.addTrustedHandlers('0x62dD51230A30401C455c8398d06F85e4EaB6309 #### Defined in -[escrow.ts:885](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L885) +[escrow.ts:885](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L885) *** @@ -296,7 +296,7 @@ await escrowClient.bulkPayOut('0x62dD51230A30401C455c8398d06F85e4EaB6309f', reci #### Defined in -[escrow.ts:650](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L650) +[escrow.ts:650](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L650) *** @@ -342,7 +342,7 @@ await escrowClient.cancel('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); #### Defined in -[escrow.ts:753](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L753) +[escrow.ts:753](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L753) *** @@ -388,7 +388,7 @@ await escrowClient.complete('0x62dD51230A30401C455c8398d06F85e4EaB6309f'); #### Defined in -[escrow.ts:592](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L592) +[escrow.ts:592](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L592) *** @@ -455,7 +455,7 @@ const escrowAddress = await escrowClient.createAndSetupEscrow(tokenAddress, trus #### Defined in -[escrow.ts:415](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L415) +[escrow.ts:415](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L415) *** @@ -512,7 +512,7 @@ const escrowAddress = await escrowClient.createEscrow(tokenAddress, trustedHandl #### Defined in -[escrow.ts:209](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L209) +[escrow.ts:209](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L209) *** @@ -561,7 +561,7 @@ await escrowClient.fund('0x62dD51230A30401C455c8398d06F85e4EaB6309f', amount); #### Defined in -[escrow.ts:463](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L463) +[escrow.ts:463](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L463) *** @@ -599,7 +599,7 @@ const balance = await escrowClient.getBalance('0x62dD51230A30401C455c8398d06F85e #### Defined in -[escrow.ts:940](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L940) +[escrow.ts:940](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L940) *** @@ -637,7 +637,7 @@ const oracleAddress = await escrowClient.getExchangeOracleAddress('0x62dD51230A3 #### Defined in -[escrow.ts:1320](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1320) +[escrow.ts:1320](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1320) *** @@ -675,7 +675,7 @@ const factoryAddress = await escrowClient.getFactoryAddress('0x62dD51230A30401C4 #### Defined in -[escrow.ts:1358](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1358) +[escrow.ts:1358](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1358) *** @@ -713,7 +713,7 @@ const intemediateResultsUrl = await escrowClient.getIntermediateResultsUrl('0x62 #### Defined in -[escrow.ts:1092](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1092) +[escrow.ts:1092](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1092) *** @@ -751,7 +751,7 @@ const jobLauncherAddress = await escrowClient.getJobLauncherAddress('0x62dD51230 #### Defined in -[escrow.ts:1244](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1244) +[escrow.ts:1244](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1244) *** @@ -789,7 +789,7 @@ const manifestHash = await escrowClient.getManifestHash('0x62dD51230A30401C455c8 #### Defined in -[escrow.ts:978](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L978) +[escrow.ts:978](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L978) *** @@ -827,7 +827,7 @@ const manifestUrl = await escrowClient.getManifestUrl('0x62dD51230A30401C455c839 #### Defined in -[escrow.ts:1016](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1016) +[escrow.ts:1016](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1016) *** @@ -865,7 +865,7 @@ const oracleAddress = await escrowClient.getRecordingOracleAddress('0x62dD51230A #### Defined in -[escrow.ts:1206](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1206) +[escrow.ts:1206](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1206) *** @@ -903,7 +903,7 @@ const oracleAddress = await escrowClient.getReputationOracleAddress('0x62dD51230 #### Defined in -[escrow.ts:1282](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1282) +[escrow.ts:1282](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1282) *** @@ -941,7 +941,7 @@ const resultsUrl = await escrowClient.getResultsUrl('0x62dD51230A30401C455c8398d #### Defined in -[escrow.ts:1054](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1054) +[escrow.ts:1054](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1054) *** @@ -979,7 +979,7 @@ const status = await escrowClient.getStatus('0x62dD51230A30401C455c8398d06F85e4E #### Defined in -[escrow.ts:1168](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1168) +[escrow.ts:1168](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1168) *** @@ -1017,7 +1017,7 @@ const tokenAddress = await escrowClient.getTokenAddress('0x62dD51230A30401C455c8 #### Defined in -[escrow.ts:1130](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1130) +[escrow.ts:1130](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1130) *** @@ -1078,7 +1078,7 @@ await escrowClient.setup(escrowAddress, escrowConfig); #### Defined in -[escrow.ts:290](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L290) +[escrow.ts:290](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L290) *** @@ -1132,7 +1132,7 @@ await storeResults.storeResults('0x62dD51230A30401C455c8398d06F85e4EaB6309f', 'h #### Defined in -[escrow.ts:528](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L528) +[escrow.ts:528](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L528) *** @@ -1164,4 +1164,4 @@ Thrown if the network's chainId is not supported #### Defined in -[escrow.ts:147](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L147) +[escrow.ts:147](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L147) diff --git a/docs/sdk/typescript/escrow/classes/EscrowUtils.md b/docs/sdk/typescript/escrow/classes/EscrowUtils.md index 388aae4932..20ae594e71 100644 --- a/docs/sdk/typescript/escrow/classes/EscrowUtils.md +++ b/docs/sdk/typescript/escrow/classes/EscrowUtils.md @@ -129,7 +129,7 @@ const escrowData = new EscrowUtils.getEscrow(ChainId.POLYGON_AMOY, "0x1234567890 #### Defined in -[escrow.ts:1640](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1640) +[escrow.ts:1640](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1640) *** @@ -250,7 +250,7 @@ const escrowDatas = await EscrowUtils.getEscrows(filters); #### Defined in -[escrow.ts:1514](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1514) +[escrow.ts:1514](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1514) *** @@ -363,4 +363,4 @@ import { ChainId, EscrowUtils, EscrowStatus } from '@human-protocol/sdk'; #### Defined in -[escrow.ts:1738](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1738) +[escrow.ts:1738](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/escrow.ts#L1738) diff --git a/docs/sdk/typescript/kvstore/classes/KVStoreClient.md b/docs/sdk/typescript/kvstore/classes/KVStoreClient.md index 4a1e27446f..7d9ca73d2b 100644 --- a/docs/sdk/typescript/kvstore/classes/KVStoreClient.md +++ b/docs/sdk/typescript/kvstore/classes/KVStoreClient.md @@ -104,7 +104,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[kvstore.ts:107](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L107) +[kvstore.ts:107](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L107) ## Properties @@ -118,7 +118,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) +[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) *** @@ -132,7 +132,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) +[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) ## Methods @@ -182,7 +182,7 @@ await kvstoreClient.set('Role', 'RecordingOracle'); #### Defined in -[kvstore.ts:170](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L170) +[kvstore.ts:170](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L170) *** @@ -234,7 +234,7 @@ await kvstoreClient.set(keys, values); #### Defined in -[kvstore.ts:213](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L213) +[kvstore.ts:213](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L213) *** @@ -283,7 +283,7 @@ await kvstoreClient.setFileUrlAndHash('linkedin.com/example', 'linkedin_url); #### Defined in -[kvstore.ts:256](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L256) +[kvstore.ts:256](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L256) *** @@ -315,4 +315,4 @@ The Runner object to interact with the Ethereum network #### Defined in -[kvstore.ts:125](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L125) +[kvstore.ts:125](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L125) diff --git a/docs/sdk/typescript/kvstore/classes/KVStoreUtils.md b/docs/sdk/typescript/kvstore/classes/KVStoreUtils.md index bef9b7a8c5..0529bf7a36 100644 --- a/docs/sdk/typescript/kvstore/classes/KVStoreUtils.md +++ b/docs/sdk/typescript/kvstore/classes/KVStoreUtils.md @@ -102,7 +102,7 @@ console.log(value); #### Defined in -[kvstore.ts:388](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L388) +[kvstore.ts:388](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L388) *** @@ -146,7 +146,7 @@ console.log(url); #### Defined in -[kvstore.ts:435](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L435) +[kvstore.ts:437](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L437) *** @@ -191,7 +191,7 @@ console.log(kvStoreData); #### Defined in -[kvstore.ts:336](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L336) +[kvstore.ts:336](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L336) *** @@ -231,4 +231,4 @@ console.log(publicKey); #### Defined in -[kvstore.ts:492](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L492) +[kvstore.ts:494](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts#L494) diff --git a/docs/sdk/typescript/operator/classes/OperatorUtils.md b/docs/sdk/typescript/operator/classes/OperatorUtils.md index e192a2d37a..0f502beaac 100644 --- a/docs/sdk/typescript/operator/classes/OperatorUtils.md +++ b/docs/sdk/typescript/operator/classes/OperatorUtils.md @@ -48,7 +48,7 @@ const leader = await OperatorUtils.getLeader(ChainId.POLYGON_AMOY, '0x62dD51230A #### Defined in -[operator.ts:44](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L44) +[operator.ts:44](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L44) *** @@ -83,7 +83,7 @@ const leaders = await OperatorUtils.getLeaders(filter); #### Defined in -[operator.ts:99](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L99) +[operator.ts:99](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L99) *** @@ -121,7 +121,7 @@ const operators = await OperatorUtils.getReputationNetworkOperators(ChainId.POLY #### Defined in -[operator.ts:151](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L151) +[operator.ts:151](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L151) *** @@ -155,4 +155,4 @@ const rewards = await OperatorUtils.getRewards(ChainId.POLYGON_AMOY, '0x62dD5123 #### Defined in -[operator.ts:201](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L201) +[operator.ts:201](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/operator.ts#L201) diff --git a/docs/sdk/typescript/staking/classes/StakingClient.md b/docs/sdk/typescript/staking/classes/StakingClient.md index 1d333b58a4..293520b0b2 100644 --- a/docs/sdk/typescript/staking/classes/StakingClient.md +++ b/docs/sdk/typescript/staking/classes/StakingClient.md @@ -104,7 +104,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[staking.ts:111](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L111) +[staking.ts:111](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L111) ## Properties @@ -114,7 +114,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[staking.ts:102](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L102) +[staking.ts:102](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L102) *** @@ -128,7 +128,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) +[base.ts:12](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L12) *** @@ -138,7 +138,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[staking.ts:103](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L103) +[staking.ts:103](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L103) *** @@ -152,7 +152,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) +[base.ts:11](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/base.ts#L11) *** @@ -162,7 +162,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[staking.ts:101](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L101) +[staking.ts:101](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L101) *** @@ -172,7 +172,7 @@ The Runner object to interact with the Ethereum network #### Defined in -[staking.ts:100](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L100) +[staking.ts:100](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L100) ## Methods @@ -223,7 +223,7 @@ await stakingClient.allocate('0x62dD51230A30401C455c8398d06F85e4EaB6309f', amoun #### Defined in -[staking.ts:458](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L458) +[staking.ts:458](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L458) *** @@ -268,7 +268,7 @@ await stakingClient.approveStake(amount); #### Defined in -[staking.ts:203](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L203) +[staking.ts:203](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L203) *** @@ -315,7 +315,7 @@ await stakingClient.closeAllocation('0x62dD51230A30401C455c8398d06F85e4EaB6309f' #### Defined in -[staking.ts:511](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L511) +[staking.ts:511](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L511) *** @@ -361,7 +361,7 @@ await stakingClient.distributeReward('0x62dD51230A30401C455c8398d06F85e4EaB6309f #### Defined in -[staking.ts:554](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L554) +[staking.ts:554](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L554) *** @@ -399,7 +399,7 @@ const allocationInfo = await stakingClient.getAllocation('0x62dD51230A30401C455c #### Defined in -[staking.ts:591](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L591) +[staking.ts:591](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L591) *** @@ -456,7 +456,7 @@ await stakingClient.slash('0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', '0xf39Fd #### Defined in -[staking.ts:387](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L387) +[staking.ts:387](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L387) *** @@ -504,7 +504,7 @@ await stakingClient.approveStake(amount); #### Defined in -[staking.ts:258](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L258) +[staking.ts:258](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L258) *** @@ -551,7 +551,7 @@ await stakingClient.unstake(amount); #### Defined in -[staking.ts:303](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L303) +[staking.ts:303](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L303) *** @@ -593,7 +593,7 @@ await stakingClient.withdraw(); #### Defined in -[staking.ts:349](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L349) +[staking.ts:349](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L349) *** @@ -625,4 +625,4 @@ The Runner object to interact with the Ethereum network #### Defined in -[staking.ts:145](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L145) +[staking.ts:145](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/staking.ts#L145) diff --git a/docs/sdk/typescript/statistics/classes/StatisticsClient.md b/docs/sdk/typescript/statistics/classes/StatisticsClient.md index 5401f81f42..26517f9f92 100644 --- a/docs/sdk/typescript/statistics/classes/StatisticsClient.md +++ b/docs/sdk/typescript/statistics/classes/StatisticsClient.md @@ -62,7 +62,7 @@ The network information required to connect to the Statistics contract #### Defined in -[statistics.ts:72](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L72) +[statistics.ts:72](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L72) ## Properties @@ -72,7 +72,7 @@ The network information required to connect to the Statistics contract #### Defined in -[statistics.ts:64](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L64) +[statistics.ts:64](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L64) *** @@ -82,7 +82,7 @@ The network information required to connect to the Statistics contract #### Defined in -[statistics.ts:65](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L65) +[statistics.ts:65](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L65) ## Methods @@ -148,7 +148,7 @@ const escrowStatisticsApril = await statisticsClient.getEscrowStatistics({ #### Defined in -[statistics.ts:128](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L128) +[statistics.ts:128](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L128) *** @@ -213,7 +213,7 @@ console.log('HMT statistics from 5/8 - 6/8:', hmtStatisticsRange); #### Defined in -[statistics.ts:495](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L495) +[statistics.ts:495](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L495) *** @@ -256,7 +256,7 @@ console.log('HMT holders:', hmtHolders.map((h) => ({ #### Defined in -[statistics.ts:421](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L421) +[statistics.ts:421](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L421) *** @@ -296,7 +296,7 @@ console.log('HMT statistics:', { #### Defined in -[statistics.ts:378](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L378) +[statistics.ts:378](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L378) *** @@ -380,7 +380,7 @@ console.log( #### Defined in -[statistics.ts:312](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L312) +[statistics.ts:312](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L312) *** @@ -441,4 +441,4 @@ const workerStatisticsApril = await statisticsClient.getWorkerStatistics({ #### Defined in -[statistics.ts:213](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L213) +[statistics.ts:213](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/statistics.ts#L213) diff --git a/docs/sdk/typescript/storage/classes/StorageClient.md b/docs/sdk/typescript/storage/classes/StorageClient.md index 17c38875f1..c98f3a539e 100644 --- a/docs/sdk/typescript/storage/classes/StorageClient.md +++ b/docs/sdk/typescript/storage/classes/StorageClient.md @@ -77,7 +77,7 @@ Optional. Cloud storage access data. If credentials is not provided - use an ano #### Defined in -[storage.ts:73](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L73) +[storage.ts:73](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L73) ## Methods @@ -121,7 +121,7 @@ const exists = await storageClient.bucketExists('bucket-name'); #### Defined in -[storage.ts:266](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L266) +[storage.ts:266](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L266) *** @@ -167,7 +167,7 @@ const files = await storageClient.downloadFiles(keys, 'bucket-name'); #### Defined in -[storage.ts:113](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L113) +[storage.ts:113](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L113) *** @@ -211,7 +211,7 @@ const fileNames = await storageClient.listObjects('bucket-name'); #### Defined in -[storage.ts:297](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L297) +[storage.ts:297](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L297) *** @@ -262,7 +262,7 @@ const uploadedFiles = await storageClient.uploadFiles(files, 'bucket-name'); #### Defined in -[storage.ts:201](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L201) +[storage.ts:201](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L201) *** @@ -294,4 +294,4 @@ const file = await storageClient.downloadFileFromUrl('http://localhost/file.json #### Defined in -[storage.ts:148](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L148) +[storage.ts:148](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/storage.ts#L148) diff --git a/docs/sdk/typescript/transaction/classes/TransactionUtils.md b/docs/sdk/typescript/transaction/classes/TransactionUtils.md index 0ff1419ec8..5634aa4eea 100644 --- a/docs/sdk/typescript/transaction/classes/TransactionUtils.md +++ b/docs/sdk/typescript/transaction/classes/TransactionUtils.md @@ -50,7 +50,7 @@ const transaction = await TransactionUtils.getTransaction(ChainId.POLYGON, '0x62 #### Defined in -[transaction.ts:34](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts#L34) +[transaction.ts:34](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts#L34) *** @@ -121,4 +121,4 @@ const transactions = await TransactionUtils.getTransactions(filter); #### Defined in -[transaction.ts:109](https://github.com/humanprotocol/human-protocol/blob/26306326c85fb8c7501973952d670f809ecb43c6/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts#L109) +[transaction.ts:109](https://github.com/humanprotocol/human-protocol/blob/0b3839952b697011b6b5a2ed2d456d3d85ce02c7/packages/sdk/typescript/human-protocol-sdk/src/transaction.ts#L109) diff --git a/packages/sdk/python/human-protocol-sdk/docs/Makefile b/packages/sdk/python/human-protocol-sdk/docs/Makefile new file mode 100644 index 0000000000..a2d36df643 --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line, and also +# from the environment for the first two. +SPHINXOPTS ?= +SPHINXBUILD ?= pipenv run sphinx-build +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/packages/sdk/python/human-protocol-sdk/docs/conf.py b/packages/sdk/python/human-protocol-sdk/docs/conf.py new file mode 100644 index 0000000000..2cd74782ba --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/conf.py @@ -0,0 +1,54 @@ +# 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 = "2023, Author" +author = "Author" + +# -- 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/human_protocol_sdk.kvstore.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.kvstore.rst index 19b2b74847..41f1c65865 100644 --- 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 @@ -13,4 +13,3 @@ Submodules :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.rst b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.rst index 1e3d3d47bb..0c60c4d8bd 100644 --- a/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.rst +++ b/packages/sdk/python/human-protocol-sdk/docs/human_protocol_sdk.rst @@ -20,7 +20,6 @@ Subpackages human_protocol_sdk.staking human_protocol_sdk.statistics human_protocol_sdk.storage - human_protocol_sdk.transaction Submodules ---------- diff --git a/packages/sdk/python/human-protocol-sdk/docs/index.rst b/packages/sdk/python/human-protocol-sdk/docs/index.rst new file mode 100644 index 0000000000..69f27a5333 --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/index.rst @@ -0,0 +1,28 @@ +.. 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/make.bat b/packages/sdk/python/human-protocol-sdk/docs/make.bat new file mode 100644 index 0000000000..32bb24529f --- /dev/null +++ b/packages/sdk/python/human-protocol-sdk/docs/make.bat @@ -0,0 +1,35 @@ +@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/human_protocol_sdk/gql/operator.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/gql/operator.py index 676c7f4b61..137c0d7ba1 100644 --- a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/gql/operator.py +++ b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/gql/operator.py @@ -12,6 +12,7 @@ lockedUntilTimestamp amountWithdrawn amountSlashed + reputation reward amountJobsProcessed role 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 e51aef656e..ae8df6a880 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 @@ -71,6 +71,7 @@ def __init__( locked_until_timestamp: int, amount_withdrawn: int, amount_slashed: int, + reputation: int, reward: int, amount_jobs_processed: int, role: Optional[str] = None, @@ -94,6 +95,7 @@ def __init__( :param locked_until_timestamp: Locked until timestamp :param amount_withdrawn: Amount withdrawn :param amount_slashed: Amount slashed + :param reputation: Reputation :param reward: Reward :param amount_jobs_processed: Amount of jobs launched :param role: Role @@ -113,6 +115,7 @@ def __init__( self.locked_until_timestamp = locked_until_timestamp self.amount_withdrawn = amount_withdrawn self.amount_slashed = amount_slashed + self.reputation = reputation self.reward = reward self.amount_jobs_processed = amount_jobs_processed self.role = role @@ -226,6 +229,7 @@ def get_leaders(filter: LeaderFilter) -> List[LeaderData]: locked_until_timestamp=int(leader.get("lockedUntilTimestamp", 0)), amount_withdrawn=int(leader.get("amountWithdrawn", 0)), amount_slashed=int(leader.get("amountSlashed", 0)), + reputation=int(leader.get("reputation", 0)), reward=int(leader.get("reward", 0)), amount_jobs_processed=int(leader.get("amountJobsProcessed", 0)), role=leader.get("role", None), @@ -313,6 +317,7 @@ def get_leader( locked_until_timestamp=int(leader.get("lockedUntilTimestamp", 0)), amount_withdrawn=int(leader.get("amountWithdrawn", 0)), amount_slashed=int(leader.get("amountSlashed", 0)), + reputation=int(leader.get("reputation", 0)), reward=int(leader.get("reward", 0)), amount_jobs_processed=int(leader.get("amountJobsProcessed", 0)), role=leader.get("role", None), diff --git a/packages/sdk/python/human-protocol-sdk/test/human_protocol_sdk/operator/test_operator_utils.py b/packages/sdk/python/human-protocol-sdk/test/human_protocol_sdk/operator/test_operator_utils.py index 2d25a10851..03a0010fde 100644 --- a/packages/sdk/python/human-protocol-sdk/test/human_protocol_sdk/operator/test_operator_utils.py +++ b/packages/sdk/python/human-protocol-sdk/test/human_protocol_sdk/operator/test_operator_utils.py @@ -33,6 +33,7 @@ def test_get_leaders(self): "lockedUntilTimestamp": "0", "amountWithdrawn": "25", "amountSlashed": "25", + "reputation": "25", "reward": "25", "amountJobsProcessed": "25", "role": "role", @@ -66,6 +67,7 @@ def test_get_leaders(self): self.assertEqual(leaders[0].locked_until_timestamp, 0) self.assertEqual(leaders[0].amount_withdrawn, 25) self.assertEqual(leaders[0].amount_slashed, 25) + self.assertEqual(leaders[0].reputation, 25) self.assertEqual(leaders[0].reward, 25) self.assertEqual(leaders[0].amount_jobs_processed, 25) self.assertEqual(leaders[0].role, "role") @@ -97,6 +99,7 @@ def test_get_leaders_when_job_types_is_none(self): "lockedUntilTimestamp": "0", "amountWithdrawn": "25", "amountSlashed": "25", + "reputation": "25", "reward": "25", "amountJobsProcessed": "25", "role": "role", @@ -128,6 +131,7 @@ def test_get_leaders_when_job_types_is_none(self): self.assertEqual(leaders[0].locked_until_timestamp, 0) self.assertEqual(leaders[0].amount_withdrawn, 25) self.assertEqual(leaders[0].amount_slashed, 25) + self.assertEqual(leaders[0].reputation, 25) self.assertEqual(leaders[0].reward, 25) self.assertEqual(leaders[0].amount_jobs_processed, 25) self.assertEqual(leaders[0].role, "role") @@ -160,6 +164,7 @@ def test_get_leaders_when_job_types_is_array(self): "lockedUntilTimestamp": "0", "amountWithdrawn": "25", "amountSlashed": "25", + "reputation": "25", "reward": "25", "amountJobsProcessed": "25", "role": "role", @@ -191,6 +196,7 @@ def test_get_leaders_when_job_types_is_array(self): self.assertEqual(leaders[0].locked_until_timestamp, 0) self.assertEqual(leaders[0].amount_withdrawn, 25) self.assertEqual(leaders[0].amount_slashed, 25) + self.assertEqual(leaders[0].reputation, 25) self.assertEqual(leaders[0].reward, 25) self.assertEqual(leaders[0].amount_jobs_processed, 25) self.assertEqual(leaders[0].role, "role") @@ -247,6 +253,7 @@ def test_get_leader(self): "lockedUntilTimestamp": "0", "amountWithdrawn": "25", "amountSlashed": "25", + "reputation": "25", "reward": "25", "amountJobsProcessed": "25", "role": "role", @@ -279,6 +286,7 @@ def test_get_leader(self): self.assertEqual(leader.locked_until_timestamp, 0) self.assertEqual(leader.amount_withdrawn, 25) self.assertEqual(leader.amount_slashed, 25) + self.assertEqual(leader.reputation, 25) self.assertEqual(leader.reward, 25) self.assertEqual(leader.amount_jobs_processed, 25) self.assertEqual(leader.role, "role") @@ -310,6 +318,7 @@ def test_get_leader_when_job_types_is_none(self): "lockedUntilTimestamp": "0", "amountWithdrawn": "25", "amountSlashed": "25", + "reputation": "25", "reward": "25", "amountJobsProcessed": "25", "role": "role", @@ -340,6 +349,7 @@ def test_get_leader_when_job_types_is_none(self): self.assertEqual(leader.locked_until_timestamp, 0) self.assertEqual(leader.amount_withdrawn, 25) self.assertEqual(leader.amount_slashed, 25) + self.assertEqual(leader.reputation, 25) self.assertEqual(leader.reward, 25) self.assertEqual(leader.amount_jobs_processed, 25) self.assertEqual(leader.role, "role") @@ -371,6 +381,7 @@ def test_get_leader_when_job_types_is_array(self): "lockedUntilTimestamp": "0", "amountWithdrawn": "25", "amountSlashed": "25", + "reputation": "25", "reward": "25", "amountJobsProcessed": "25", "role": "role", @@ -401,6 +412,7 @@ def test_get_leader_when_job_types_is_array(self): self.assertEqual(leader.locked_until_timestamp, 0) self.assertEqual(leader.amount_withdrawn, 25) self.assertEqual(leader.amount_slashed, 25) + self.assertEqual(leader.reputation, 25) self.assertEqual(leader.reward, 25) self.assertEqual(leader.amount_jobs_processed, 25) self.assertEqual(leader.role, "role") diff --git a/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts b/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts index fb05fb390a..100b038ca9 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts @@ -24,6 +24,7 @@ export interface ILeader { lockedUntilTimestamp: bigint; amountWithdrawn: bigint; amountSlashed: bigint; + reputation: bigint; reward: bigint; amountJobsProcessed: bigint; role?: string; diff --git a/packages/sdk/typescript/human-protocol-sdk/test/operator.test.ts b/packages/sdk/typescript/human-protocol-sdk/test/operator.test.ts index 26f236008a..c76016fde6 100644 --- a/packages/sdk/typescript/human-protocol-sdk/test/operator.test.ts +++ b/packages/sdk/typescript/human-protocol-sdk/test/operator.test.ts @@ -44,6 +44,7 @@ describe('OperatorUtils', () => { lockedUntilTimestamp: ethers.toBigInt(0), amountWithdrawn: ethers.parseEther('25'), amountSlashed: ethers.parseEther('25'), + reputation: ethers.parseEther('25'), reward: ethers.parseEther('25'), amountJobsProcessed: ethers.parseEther('25'), jobTypes: 'type1,type2', @@ -179,6 +180,7 @@ describe('OperatorUtils', () => { lockedUntilTimestamp: ethers.toBigInt(0), amountWithdrawn: ethers.parseEther('25'), amountSlashed: ethers.parseEther('25'), + reputation: ethers.parseEther('25'), reward: ethers.parseEther('25'), amountJobsProcessed: ethers.parseEther('25'), jobTypes: 'type1,type2', diff --git a/packages/sdk/typescript/subgraph/schema.graphql b/packages/sdk/typescript/subgraph/schema.graphql index 5e6d931c1f..4198c463f9 100644 --- a/packages/sdk/typescript/subgraph/schema.graphql +++ b/packages/sdk/typescript/subgraph/schema.graphql @@ -38,6 +38,7 @@ type Leader @entity { lockedUntilTimestamp: BigInt! amountWithdrawn: BigInt! amountSlashed: BigInt! + reputation: BigInt! reward: BigInt! amountJobsProcessed: BigInt! diff --git a/packages/sdk/typescript/subgraph/src/mapping/Staking.ts b/packages/sdk/typescript/subgraph/src/mapping/Staking.ts index 500d3219d9..63507d03d7 100644 --- a/packages/sdk/typescript/subgraph/src/mapping/Staking.ts +++ b/packages/sdk/typescript/subgraph/src/mapping/Staking.ts @@ -56,6 +56,7 @@ export function createOrLoadLeader(address: Address): Leader { leader.amountSlashed = ZERO_BI; leader.amountWithdrawn = ZERO_BI; leader.reward = ZERO_BI; + leader.reputation = ZERO_BI; leader.amountJobsProcessed = ZERO_BI; } From 205c7f016f53435dafb521a142cea04146294121 Mon Sep 17 00:00:00 2001 From: portuu3 <61605646+portuu3@users.noreply.github.com> Date: Tue, 27 Aug 2024 09:41:55 +0200 Subject: [PATCH 82/89] Revert "Add registration data to leaders entity (#2414)" (#2449) This reverts commit 003f8fb254c504f1c90e3f46a369c0ad2f1c6635. --- .../human_protocol_sdk/constants.py | 1 - .../human_protocol_sdk/gql/operator.py | 4 +- .../operator/operator_utils.py | 10 --- .../operator/test_operator_utils.py | 12 ---- .../human-protocol-sdk/src/constants.ts | 1 - .../src/graphql/queries/operator.ts | 2 - .../human-protocol-sdk/src/interfaces.ts | 2 - .../human-protocol-sdk/test/operator.test.ts | 4 -- .../sdk/typescript/subgraph/schema.graphql | 2 - .../subgraph/src/mapping/KVStore.ts | 4 -- .../subgraph/tests/kvstore/kvstore.test.ts | 64 ------------------- 11 files changed, 1 insertion(+), 105 deletions(-) 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 3bf7086af9..1e25465d90 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 @@ -368,4 +368,3 @@ class KVStoreKeys(Enum): url = "url" job_types = "job_types" registration_needed = "registration_needed" - registration_instructions = "registration_instructions" diff --git a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/gql/operator.py b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/gql/operator.py index 137c0d7ba1..b955b24bdd 100644 --- a/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/gql/operator.py +++ b/packages/sdk/python/human-protocol-sdk/human_protocol_sdk/gql/operator.py @@ -19,10 +19,8 @@ fee publicKey webhookUrl - url + url, jobTypes - registrationNeeded - registrationInstructions } """ 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 ae8df6a880..8c4e878275 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 @@ -80,8 +80,6 @@ def __init__( webhook_url: Optional[str] = None, url: Optional[str] = None, job_types: Optional[List[str]] = None, - registration_needed: Optional[bool] = None, - registration_instructions: Optional[str] = None, ): """ Initializes an LeaderData instance. @@ -124,8 +122,6 @@ def __init__( self.webhook_url = webhook_url self.url = url self.job_types = job_types - self.registration_needed = registration_needed - self.registration_instructions = registration_instructions class RewardData: @@ -246,10 +242,6 @@ def get_leaders(filter: LeaderFilter) -> List[LeaderData]: else [] ) ), - registration_needed=leader.get("registrationNeeded", None), - registration_instructions=leader.get( - "registrationInstructions", None - ), ) for leader in leaders_raw ] @@ -334,8 +326,6 @@ def get_leader( else [] ) ), - registration_needed=leader.get("registrationNeeded", None), - registration_instructions=leader.get("registrationInstructions", None), ) @staticmethod diff --git a/packages/sdk/python/human-protocol-sdk/test/human_protocol_sdk/operator/test_operator_utils.py b/packages/sdk/python/human-protocol-sdk/test/human_protocol_sdk/operator/test_operator_utils.py index 03a0010fde..9f31ce53b5 100644 --- a/packages/sdk/python/human-protocol-sdk/test/human_protocol_sdk/operator/test_operator_utils.py +++ b/packages/sdk/python/human-protocol-sdk/test/human_protocol_sdk/operator/test_operator_utils.py @@ -42,8 +42,6 @@ def test_get_leaders(self): "webhookUrl": None, "url": None, "jobTypes": "type1,type2", - "registrationNeeded": True, - "registrationInstructions": "www.google.com", } ], } @@ -76,8 +74,6 @@ def test_get_leaders(self): self.assertEqual(leaders[0].webhook_url, None) self.assertEqual(leaders[0].url, None) self.assertEqual(leaders[0].job_types, ["type1", "type2"]) - self.assertEqual(leaders[0].registration_needed, True) - self.assertEqual(leaders[0].registration_instructions, "www.google.com") def test_get_leaders_when_job_types_is_none(self): filter = LeaderFilter(chain_id=ChainId.POLYGON, role="role") @@ -139,8 +135,6 @@ def test_get_leaders_when_job_types_is_none(self): self.assertEqual(leaders[0].public_key, None) self.assertEqual(leaders[0].webhook_url, None) self.assertEqual(leaders[0].url, None) - self.assertEqual(leaders[0].registration_needed, None) - self.assertEqual(leaders[0].registration_instructions, None) # Should rerutn empty array self.assertEqual(leaders[0].job_types, []) @@ -262,8 +256,6 @@ def test_get_leader(self): "webhookUrl": None, "url": None, "jobTypes": "type1,type2", - "registrationNeeded": True, - "registrationInstructions": "www.google.com", } } } @@ -295,8 +287,6 @@ def test_get_leader(self): self.assertEqual(leader.webhook_url, None) self.assertEqual(leader.url, None) self.assertEqual(leader.job_types, ["type1", "type2"]) - self.assertEqual(leader.registration_needed, True) - self.assertEqual(leader.registration_instructions, "www.google.com") def test_get_leader_when_job_types_is_none(self): staker_address = "0x1234567890123456789012345678901234567891" @@ -358,8 +348,6 @@ def test_get_leader_when_job_types_is_none(self): self.assertEqual(leader.webhook_url, None) self.assertEqual(leader.url, None) self.assertEqual(leader.job_types, []) - self.assertEqual(leader.registration_needed, None) - self.assertEqual(leader.registration_instructions, None) def test_get_leader_when_job_types_is_array(self): staker_address = "0x1234567890123456789012345678901234567891" diff --git a/packages/sdk/typescript/human-protocol-sdk/src/constants.ts b/packages/sdk/typescript/human-protocol-sdk/src/constants.ts index e9131eed01..bd7e821475 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/constants.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/constants.ts @@ -350,7 +350,6 @@ export const KVStoreKeys = { url: 'url', jobTypes: 'job_types', registrationNeeded: 'registration_needed', - registrationInstructions: 'registration_instructions', }; export const Role = { diff --git a/packages/sdk/typescript/human-protocol-sdk/src/graphql/queries/operator.ts b/packages/sdk/typescript/human-protocol-sdk/src/graphql/queries/operator.ts index f75bcc4c39..e63a451947 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/graphql/queries/operator.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/graphql/queries/operator.ts @@ -20,8 +20,6 @@ const LEADER_FRAGMENT = gql` webhookUrl url jobTypes - registrationNeeded - registrationInstructions } `; diff --git a/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts b/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts index 100b038ca9..6922e51cca 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/interfaces.ts @@ -33,8 +33,6 @@ export interface ILeader { webhookUrl?: string; url?: string; jobTypes?: string[]; - registrationNeeded?: boolean; - registrationInstructions?: string; } export interface ILeaderSubgraph extends Omit { diff --git a/packages/sdk/typescript/human-protocol-sdk/test/operator.test.ts b/packages/sdk/typescript/human-protocol-sdk/test/operator.test.ts index c76016fde6..dfbee6e0b6 100644 --- a/packages/sdk/typescript/human-protocol-sdk/test/operator.test.ts +++ b/packages/sdk/typescript/human-protocol-sdk/test/operator.test.ts @@ -48,8 +48,6 @@ describe('OperatorUtils', () => { reward: ethers.parseEther('25'), amountJobsProcessed: ethers.parseEther('25'), jobTypes: 'type1,type2', - registrationNeeded: true, - registrationInstructions: 'www.google.com', }; const mockLeader: ILeader = { @@ -184,8 +182,6 @@ describe('OperatorUtils', () => { reward: ethers.parseEther('25'), amountJobsProcessed: ethers.parseEther('25'), jobTypes: 'type1,type2', - registrationNeeded: true, - registrationInstructions: 'www.google.com', }; const mockLeader: ILeader = { diff --git a/packages/sdk/typescript/subgraph/schema.graphql b/packages/sdk/typescript/subgraph/schema.graphql index 4198c463f9..712164b149 100644 --- a/packages/sdk/typescript/subgraph/schema.graphql +++ b/packages/sdk/typescript/subgraph/schema.graphql @@ -50,8 +50,6 @@ type Leader @entity { url: String urls: [LeaderURL!]! @derivedFrom(field: "leader") reputationNetwork: ReputationNetwork - registrationNeeded: Boolean - registrationInstructions: String } type LeaderURL @entity { diff --git a/packages/sdk/typescript/subgraph/src/mapping/KVStore.ts b/packages/sdk/typescript/subgraph/src/mapping/KVStore.ts index 2a893382b2..d7d16f8f0c 100644 --- a/packages/sdk/typescript/subgraph/src/mapping/KVStore.ts +++ b/packages/sdk/typescript/subgraph/src/mapping/KVStore.ts @@ -108,10 +108,6 @@ export function handleDataSaved(event: DataSaved): void { operator.reputationNetwork = null; } operator.save(); - } else if (key == 'registration_needed') { - leader.registrationNeeded = event.params.value === 'true'; - } else if (key == 'registration_instructions') { - leader.registrationInstructions = event.params.value; } if (key.indexOf('url') > -1) { diff --git a/packages/sdk/typescript/subgraph/tests/kvstore/kvstore.test.ts b/packages/sdk/typescript/subgraph/tests/kvstore/kvstore.test.ts index bb604896ca..4c7696adb8 100644 --- a/packages/sdk/typescript/subgraph/tests/kvstore/kvstore.test.ts +++ b/packages/sdk/typescript/subgraph/tests/kvstore/kvstore.test.ts @@ -462,68 +462,4 @@ describe('KVStore', () => { 'Job Launcher' ); }); - - test("Should properly update leader's registration needed", () => { - const data1 = createDataSavedEvent( - '0xD979105297fB0eee83F7433fC09279cb5B94fFC6', - 'registration_needed', - 'true', - BigInt.fromI32(10) - ); - const data2 = createDataSavedEvent( - '0x92a2eEF7Ff696BCef98957a0189872680600a959', - 'registration_needed', - 'false', - BigInt.fromI32(11) - ); - - handleDataSaved(data1); - handleDataSaved(data2); - - assert.fieldEquals( - 'Leader', - data1.params.sender.toHex(), - 'registrationNeeded', - 'true' - ); - - assert.fieldEquals( - 'Leader', - data2.params.sender.toHex(), - 'registrationNeeded', - 'false' - ); - }); - - test("Should properly update leader's registration instructions", () => { - const data1 = createDataSavedEvent( - '0xD979105297fB0eee83F7433fC09279cb5B94fFC6', - 'registration_instructions', - 'https://validator.example.com', - BigInt.fromI32(10) - ); - const data2 = createDataSavedEvent( - '0x92a2eEF7Ff696BCef98957a0189872680600a959', - 'registration_instructions', - 'https://validator.example.com', - BigInt.fromI32(11) - ); - - handleDataSaved(data1); - handleDataSaved(data2); - - assert.fieldEquals( - 'Leader', - data1.params.sender.toHex(), - 'registrationInstructions', - 'https://validator.example.com' - ); - - assert.fieldEquals( - 'Leader', - data2.params.sender.toHex(), - 'registrationInstructions', - 'https://validator.example.com' - ); - }); }); From e9ad17660a38864a73b28c4a5b610dedb5d767b4 Mon Sep 17 00:00:00 2001 From: Arseny Boykov <36469655+Bobronium@users.noreply.github.com> Date: Tue, 27 Aug 2024 11:53:58 +0200 Subject: [PATCH 83/89] [Exchange Oracle] Add ruff (#2395) Establish automatic code linting and formatting with ruff in CVAT Exchange Oracle --- .../ci-lint-cvat-exchange-oracle.yaml | 33 ++ .../exchange-oracle/.pre-commit-config.yaml | 24 +- .../examples/cvat/exchange-oracle/alembic.ini | 14 +- .../cvat/exchange-oracle/alembic/env.py | 4 +- ...3fb7bfcbcf_add_escrow_creation_tracking.py | 42 +- .../alembic/versions/16ecc586d685_init.py | 6 +- .../alembic/versions/__init__.py | 0 .../c1e74c227cfe_non_unique_escrows.py | 12 +- .../examples/cvat/exchange-oracle/poetry.lock | 135 +++--- .../cvat/exchange-oracle/pyproject.toml | 122 ++++- packages/examples/cvat/exchange-oracle/run.py | 2 +- .../exchange-oracle/src/chain/__init__.py | 0 .../cvat/exchange-oracle/src/chain/escrow.py | 12 +- .../cvat/exchange-oracle/src/chain/web3.py | 4 +- .../cvat/exchange-oracle/src/core/__init__.py | 0 .../src/core/annotation_meta.py | 3 +- .../cvat/exchange-oracle/src/core/config.py | 49 +- .../cvat/exchange-oracle/src/core/manifest.py | 22 +- .../exchange-oracle/src/core/oracle_events.py | 18 +- .../src/core/tasks/boxes_from_points.py | 6 +- .../src/core/tasks/skeletons_from_boxes.py | 8 +- .../crons/process_job_launcher_webhooks.py | 69 ++- .../process_recording_oracle_webhooks.py | 8 +- .../src/crons/state_trackers.py | 8 +- .../cvat/exchange-oracle/src/cvat/__init__.py | 0 .../exchange-oracle/src/cvat/api_calls.py | 48 +- .../cvat/exchange-oracle/src/db/__init__.py | 2 +- .../cvat/exchange-oracle/src/db/errors.py | 2 + .../cvat/exchange-oracle/src/db/utils.py | 9 +- .../exchange-oracle/src/endpoints/__init__.py | 13 +- .../exchange-oracle/src/endpoints/exchange.py | 9 +- .../src/endpoints/middleware.py | 9 +- .../exchange-oracle/src/endpoints/webhook.py | 4 +- .../exchange-oracle/src/handlers/__init__.py | 0 .../src/handlers/completed_escrows.py | 28 +- .../src/handlers/cvat_events.py | 4 +- .../src/handlers/error_handlers.py | 3 +- .../src/handlers/job_creation.py | 160 ++++--- .../src/handlers/job_export.py | 29 +- .../examples/cvat/exchange-oracle/src/log.py | 3 +- .../exchange-oracle/src/models/__init__.py | 0 .../cvat/exchange-oracle/src/models/cvat.py | 52 +-- .../exchange-oracle/src/models/webhook.py | 2 +- .../exchange-oracle/src/schemas/__init__.py | 10 +- .../cvat/exchange-oracle/src/schemas/cvat.py | 8 +- .../exchange-oracle/src/schemas/exchange.py | 3 +- .../exchange-oracle/src/schemas/webhook.py | 5 +- .../exchange-oracle/src/services/__init__.py | 0 .../src/services/cloud/client.py | 22 +- .../exchange-oracle/src/services/cloud/gcs.py | 17 +- .../exchange-oracle/src/services/cloud/s3.py | 30 +- .../src/services/cloud/types.py | 24 +- .../src/services/cloud/utils.py | 4 +- .../cvat/exchange-oracle/src/services/cvat.py | 187 ++++---- .../exchange-oracle/src/services/exchange.py | 14 +- .../exchange-oracle/src/services/webhook.py | 20 +- .../exchange-oracle/src/utils/__init__.py | 0 .../exchange-oracle/src/utils/annotations.py | 30 +- .../cvat/exchange-oracle/src/utils/enums.py | 2 +- .../cvat/exchange-oracle/src/utils/logging.py | 4 +- .../cvat/exchange-oracle/src/utils/net.py | 2 +- .../exchange-oracle/src/utils/requests.py | 6 +- .../exchange-oracle/src/utils/webhooks.py | 13 +- .../src/validators/__init__.py | 0 .../src/validators/validation.py | 4 +- .../exchange-oracle/tests/api/__init__.py | 0 .../tests/api/test_exchange_api.py | 4 +- .../exchange-oracle/tests/api/test_greet.py | 2 +- .../cvat/exchange-oracle/tests/conftest.py | 2 +- .../tests/integration/chain/__init__.py | 0 .../tests/integration/chain/test_escrow.py | 67 ++- .../tests/integration/chain/test_kvstore.py | 67 +-- .../tests/integration/chain/test_web3.py | 53 +-- .../tests/integration/cron/__init__.py | 0 .../cron/state_trackers/__init__.py | 0 .../state_trackers/test_track_assignments.py | 157 ++++--- .../test_track_completed_escrows.py | 53 +-- .../test_track_completed_projects.py | 4 +- .../test_track_completed_tasks.py | 4 +- .../test_track_escrow_creation.py | 8 +- .../test_track_task_creation.py | 16 +- .../test_process_job_launcher_webhooks.py | 66 +-- .../test_process_recording_oracle_webhooks.py | 38 +- .../tests/integration/services/__init__.py | 0 .../tests/integration/services/test_cvat.py | 427 +++++++++--------- .../integration/services/test_exchange.py | 117 ++--- .../integration/services/test_webhook.py | 141 +++--- .../exchange-oracle/tests/unit/__init__.py | 0 .../tests/unit/helpers/__init__.py | 0 .../exchange-oracle/tests/utils/constants.py | 10 +- .../exchange-oracle/tests/utils/setup_cvat.py | 4 +- 91 files changed, 1337 insertions(+), 1286 deletions(-) create mode 100644 .github/workflows/ci-lint-cvat-exchange-oracle.yaml create mode 100644 packages/examples/cvat/exchange-oracle/alembic/versions/__init__.py create mode 100644 packages/examples/cvat/exchange-oracle/src/chain/__init__.py create mode 100644 packages/examples/cvat/exchange-oracle/src/core/__init__.py create mode 100644 packages/examples/cvat/exchange-oracle/src/cvat/__init__.py create mode 100644 packages/examples/cvat/exchange-oracle/src/handlers/__init__.py create mode 100644 packages/examples/cvat/exchange-oracle/src/models/__init__.py create mode 100644 packages/examples/cvat/exchange-oracle/src/services/__init__.py create mode 100644 packages/examples/cvat/exchange-oracle/src/utils/__init__.py create mode 100644 packages/examples/cvat/exchange-oracle/src/validators/__init__.py create mode 100644 packages/examples/cvat/exchange-oracle/tests/api/__init__.py create mode 100644 packages/examples/cvat/exchange-oracle/tests/integration/chain/__init__.py create mode 100644 packages/examples/cvat/exchange-oracle/tests/integration/cron/__init__.py create mode 100644 packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/__init__.py create mode 100644 packages/examples/cvat/exchange-oracle/tests/integration/services/__init__.py create mode 100644 packages/examples/cvat/exchange-oracle/tests/unit/__init__.py create mode 100644 packages/examples/cvat/exchange-oracle/tests/unit/helpers/__init__.py diff --git a/.github/workflows/ci-lint-cvat-exchange-oracle.yaml b/.github/workflows/ci-lint-cvat-exchange-oracle.yaml new file mode 100644 index 0000000000..cb43ed75d4 --- /dev/null +++ b/.github/workflows/ci-lint-cvat-exchange-oracle.yaml @@ -0,0 +1,33 @@ +name: CVAT Exchange Oracle Lint + +on: + push: + paths: + - 'packages/examples/cvat/exchange-oracle/**' + - '.github/workflows/ci-lint-cvat-exchange-oracle.yaml' + +env: + WORKING_DIR: ./packages/examples/cvat/exchange-oracle + +defaults: + run: + working-directory: ./packages/examples/cvat/exchange-oracle + +jobs: + cvat-exo-lint: + name: CVAT Exchange Oracle Lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + cache: 'pip' + cache-dependency-path: ${{ env.WORKING_DIR }}/poetry.lock + - run: python -m pip install poetry + - uses: actions/setup-python@v5 + with: + python-version: '3.10' + cache: 'poetry' + cache-dependency-path: ${{ env.WORKING_DIR }}/poetry.lock + - run: poetry install --no-root --only dev + - run: poetry run pre-commit run --all-files \ No newline at end of file diff --git a/packages/examples/cvat/exchange-oracle/.pre-commit-config.yaml b/packages/examples/cvat/exchange-oracle/.pre-commit-config.yaml index 08cd8c4879..75cdc64287 100644 --- a/packages/examples/cvat/exchange-oracle/.pre-commit-config.yaml +++ b/packages/examples/cvat/exchange-oracle/.pre-commit-config.yaml @@ -1,11 +1,17 @@ repos: - - repo: https://github.com/psf/black - rev: 22.6.0 + - repo: local hooks: - - id: black - language_version: python3.11 - - repo: https://github.com/PyCQA/isort - rev: 5.12.0 - hooks: - - id: isort - language_version: python3.11 \ No newline at end of file + - id: lint + name: lint + entry: ruff check --fix --unsafe-fixes --show-fixes + language: system + require_serial: true + files: "^packages/examples/cvat/exchange-oracle/.*" + types: [python] + - id: format + name: format + entry: ruff format + require_serial: true + language: system + files: "^packages/examples/cvat/exchange-oracle/.*" + types: [python] diff --git a/packages/examples/cvat/exchange-oracle/alembic.ini b/packages/examples/cvat/exchange-oracle/alembic.ini index 86d1800182..12c6610f1b 100644 --- a/packages/examples/cvat/exchange-oracle/alembic.ini +++ b/packages/examples/cvat/exchange-oracle/alembic.ini @@ -63,11 +63,15 @@ sqlalchemy.url = # on newly generated revision scripts. See the documentation for further # detail and examples -# format using "black" - use the console_scripts runner, against the "black" entrypoint -# hooks = black -# black.type = console_scripts -# black.entrypoint = black -# black.options = -l 79 REVISION_SCRIPT_FILENAME +hooks=ruff, ruff_format, types_update + +ruff.type = exec +ruff.executable = ruff +ruff.options = check --fix --unsafe-fixes REVISION_SCRIPT_FILENAME + +ruff_format.type = exec +ruff_format.executable = ruff +ruff_format.options = format REVISION_SCRIPT_FILENAME # Logging configuration [loggers] diff --git a/packages/examples/cvat/exchange-oracle/alembic/env.py b/packages/examples/cvat/exchange-oracle/alembic/env.py index 5ecaa3c3f2..1328f73712 100644 --- a/packages/examples/cvat/exchange-oracle/alembic/env.py +++ b/packages/examples/cvat/exchange-oracle/alembic/env.py @@ -21,9 +21,7 @@ # from myapp import mymodel # target_metadata = mymodel.Base.metadata -from src.db import Base -from src.models.cvat import Job, Task -from src.models.webhook import Webhook +from src.db import Base # noqa: E402 target_metadata = Base.metadata diff --git a/packages/examples/cvat/exchange-oracle/alembic/versions/0f3fb7bfcbcf_add_escrow_creation_tracking.py b/packages/examples/cvat/exchange-oracle/alembic/versions/0f3fb7bfcbcf_add_escrow_creation_tracking.py index 11c6800a5d..b89bf427c6 100644 --- a/packages/examples/cvat/exchange-oracle/alembic/versions/0f3fb7bfcbcf_add_escrow_creation_tracking.py +++ b/packages/examples/cvat/exchange-oracle/alembic/versions/0f3fb7bfcbcf_add_escrow_creation_tracking.py @@ -5,37 +5,45 @@ Create Date: 2024-04-12 18:51:51.504971 """ -from alembic import op + import sqlalchemy as sa -import sqlalchemy_utils +from alembic import op # revision identifiers, used by Alembic. -revision = '0f3fb7bfcbcf' -down_revision = 'c1e74c227cfe' +revision = "0f3fb7bfcbcf" +down_revision = "c1e74c227cfe" branch_labels = None depends_on = None def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### - op.create_table('escrow_creations', - sa.Column('id', sa.String(), nullable=False), - sa.Column('escrow_address', sa.String(length=42), nullable=False), - sa.Column('chain_id', sa.Integer(), nullable=False), - sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True), - sa.Column('finished_at', sa.DateTime(timezone=True), nullable=True), - sa.Column('total_jobs', sa.Integer(), nullable=False), - sa.PrimaryKeyConstraint('id') + op.create_table( + "escrow_creations", + sa.Column("id", sa.String(), nullable=False), + sa.Column("escrow_address", sa.String(length=42), nullable=False), + sa.Column("chain_id", sa.Integer(), nullable=False), + sa.Column( + "created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=True + ), + sa.Column("finished_at", sa.DateTime(timezone=True), nullable=True), + sa.Column("total_jobs", sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint("id"), + ) + op.create_index( + op.f("ix_escrow_creations_escrow_address"), + "escrow_creations", + ["escrow_address"], + unique=False, ) - op.create_index(op.f('ix_escrow_creations_escrow_address'), 'escrow_creations', ['escrow_address'], unique=False) - op.create_index(op.f('ix_escrow_creations_id'), 'escrow_creations', ['id'], unique=False) + op.create_index(op.f("ix_escrow_creations_id"), "escrow_creations", ["id"], unique=False) # ### end Alembic commands ### def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### - op.drop_index(op.f('ix_escrow_creations_id'), table_name='escrow_creations') - op.drop_index(op.f('ix_escrow_creations_escrow_address'), table_name='escrow_creations') - op.drop_table('escrow_creations') + op.drop_index(op.f("ix_escrow_creations_id"), table_name="escrow_creations") + op.drop_index(op.f("ix_escrow_creations_escrow_address"), table_name="escrow_creations") + op.drop_table("escrow_creations") # ### end Alembic commands ### diff --git a/packages/examples/cvat/exchange-oracle/alembic/versions/16ecc586d685_init.py b/packages/examples/cvat/exchange-oracle/alembic/versions/16ecc586d685_init.py index 6ff8ca49b5..1aca7bcaaf 100644 --- a/packages/examples/cvat/exchange-oracle/alembic/versions/16ecc586d685_init.py +++ b/packages/examples/cvat/exchange-oracle/alembic/versions/16ecc586d685_init.py @@ -1,14 +1,14 @@ """init Revision ID: 16ecc586d685 -Revises: +Revises: Create Date: 2023-10-05 13:56:16.966151 """ -from alembic import op + import sqlalchemy as sa -import sqlalchemy_utils +from alembic import op # revision identifiers, used by Alembic. revision = "16ecc586d685" diff --git a/packages/examples/cvat/exchange-oracle/alembic/versions/__init__.py b/packages/examples/cvat/exchange-oracle/alembic/versions/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/examples/cvat/exchange-oracle/alembic/versions/c1e74c227cfe_non_unique_escrows.py b/packages/examples/cvat/exchange-oracle/alembic/versions/c1e74c227cfe_non_unique_escrows.py index f2ea93a456..bc20bbb497 100644 --- a/packages/examples/cvat/exchange-oracle/alembic/versions/c1e74c227cfe_non_unique_escrows.py +++ b/packages/examples/cvat/exchange-oracle/alembic/versions/c1e74c227cfe_non_unique_escrows.py @@ -5,25 +5,23 @@ Create Date: 2024-02-05 22:54:42.478270 """ -from alembic import op -import sqlalchemy as sa -import sqlalchemy_utils +from alembic import op # revision identifiers, used by Alembic. -revision = 'c1e74c227cfe' -down_revision = '16ecc586d685' +revision = "c1e74c227cfe" +down_revision = "16ecc586d685" branch_labels = None depends_on = None def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### - op.drop_constraint('projects_escrow_address_key', 'projects', type_='unique') + op.drop_constraint("projects_escrow_address_key", "projects", type_="unique") # ### end Alembic commands ### def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### - op.create_unique_constraint('projects_escrow_address_key', 'projects', ['escrow_address']) + op.create_unique_constraint("projects_escrow_address_key", "projects", ["escrow_address"]) # ### end Alembic commands ### diff --git a/packages/examples/cvat/exchange-oracle/poetry.lock b/packages/examples/cvat/exchange-oracle/poetry.lock index b301689e1a..136c82ed69 100644 --- a/packages/examples/cvat/exchange-oracle/poetry.lock +++ b/packages/examples/cvat/exchange-oracle/poetry.lock @@ -1,4 +1,4 @@ -# This file is automatically @generated by Poetry 1.7.1 and should not be changed by hand. +# This file is automatically @generated by Poetry 1.8.3 and should not be changed by hand. [[package]] name = "aiohttp" @@ -397,52 +397,6 @@ files = [ {file = "bitarray-2.9.2.tar.gz", hash = "sha256:a8f286a51a32323715d77755ed959f94bef13972e9a2fe71b609e40e6d27957e"}, ] -[[package]] -name = "black" -version = "23.12.1" -description = "The uncompromising code formatter." -optional = false -python-versions = ">=3.8" -files = [ - {file = "black-23.12.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:e0aaf6041986767a5e0ce663c7a2f0e9eaf21e6ff87a5f95cbf3675bfd4c41d2"}, - {file = "black-23.12.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:c88b3711d12905b74206227109272673edce0cb29f27e1385f33b0163c414bba"}, - {file = "black-23.12.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a920b569dc6b3472513ba6ddea21f440d4b4c699494d2e972a1753cdc25df7b0"}, - {file = "black-23.12.1-cp310-cp310-win_amd64.whl", hash = "sha256:3fa4be75ef2a6b96ea8d92b1587dd8cb3a35c7e3d51f0738ced0781c3aa3a5a3"}, - {file = "black-23.12.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:8d4df77958a622f9b5a4c96edb4b8c0034f8434032ab11077ec6c56ae9f384ba"}, - {file = "black-23.12.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:602cfb1196dc692424c70b6507593a2b29aac0547c1be9a1d1365f0d964c353b"}, - {file = "black-23.12.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9c4352800f14be5b4864016882cdba10755bd50805c95f728011bcb47a4afd59"}, - {file = "black-23.12.1-cp311-cp311-win_amd64.whl", hash = "sha256:0808494f2b2df923ffc5723ed3c7b096bd76341f6213989759287611e9837d50"}, - {file = "black-23.12.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:25e57fd232a6d6ff3f4478a6fd0580838e47c93c83eaf1ccc92d4faf27112c4e"}, - {file = "black-23.12.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:2d9e13db441c509a3763a7a3d9a49ccc1b4e974a47be4e08ade2a228876500ec"}, - {file = "black-23.12.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6d1bd9c210f8b109b1762ec9fd36592fdd528485aadb3f5849b2740ef17e674e"}, - {file = "black-23.12.1-cp312-cp312-win_amd64.whl", hash = "sha256:ae76c22bde5cbb6bfd211ec343ded2163bba7883c7bc77f6b756a1049436fbb9"}, - {file = "black-23.12.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:1fa88a0f74e50e4487477bc0bb900c6781dbddfdfa32691e780bf854c3b4a47f"}, - {file = "black-23.12.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:a4d6a9668e45ad99d2f8ec70d5c8c04ef4f32f648ef39048d010b0689832ec6d"}, - {file = "black-23.12.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b18fb2ae6c4bb63eebe5be6bd869ba2f14fd0259bda7d18a46b764d8fb86298a"}, - {file = "black-23.12.1-cp38-cp38-win_amd64.whl", hash = "sha256:c04b6d9d20e9c13f43eee8ea87d44156b8505ca8a3c878773f68b4e4812a421e"}, - {file = "black-23.12.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:3e1b38b3135fd4c025c28c55ddfc236b05af657828a8a6abe5deec419a0b7055"}, - {file = "black-23.12.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:4f0031eaa7b921db76decd73636ef3a12c942ed367d8c3841a0739412b260a54"}, - {file = "black-23.12.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:97e56155c6b737854e60a9ab1c598ff2533d57e7506d97af5481141671abf3ea"}, - {file = "black-23.12.1-cp39-cp39-win_amd64.whl", hash = "sha256:dd15245c8b68fe2b6bd0f32c1556509d11bb33aec9b5d0866dd8e2ed3dba09c2"}, - {file = "black-23.12.1-py3-none-any.whl", hash = "sha256:78baad24af0f033958cad29731e27363183e140962595def56423e626f4bee3e"}, - {file = "black-23.12.1.tar.gz", hash = "sha256:4ce3ef14ebe8d9509188014d96af1c456a910d5b5cbf434a09fef7e024b3d0d5"}, -] - -[package.dependencies] -click = ">=8.0.0" -mypy-extensions = ">=0.4.3" -packaging = ">=22.0" -pathspec = ">=0.9.0" -platformdirs = ">=2" -tomli = {version = ">=1.1.0", markers = "python_version < \"3.11\""} -typing-extensions = {version = ">=4.0.1", markers = "python_version < \"3.11\""} - -[package.extras] -colorama = ["colorama (>=0.4.3)"] -d = ["aiohttp (>=3.7.4)", "aiohttp (>=3.7.4,!=3.9.0)"] -jupyter = ["ipython (>=7.8.0)", "tokenize-rt (>=3.2.0)"] -uvloop = ["uvloop (>=0.15.2)"] - [[package]] name = "boto3" version = "1.34.30" @@ -1874,20 +1828,6 @@ files = [ {file = "iniconfig-2.0.0.tar.gz", hash = "sha256:2d91e135bf72d31a410b17c16da610a82cb55f6b0477d1a902134b24a455b8b3"}, ] -[[package]] -name = "isort" -version = "5.13.2" -description = "A Python utility / library to sort Python imports." -optional = false -python-versions = ">=3.8.0" -files = [ - {file = "isort-5.13.2-py3-none-any.whl", hash = "sha256:8ca5e72a8d85860d5a3fa69b8745237f2939afe12dbf656afbcb47fe72d947a6"}, - {file = "isort-5.13.2.tar.gz", hash = "sha256:48fdfcb9face5d58a4f6dde2e72a1fb8dcaf8ab26f95ab49fab84c2ddefb0109"}, -] - -[package.extras] -colors = ["colorama (>=0.4.6)"] - [[package]] name = "jmespath" version = "1.0.1" @@ -2470,17 +2410,6 @@ files = [ {file = "multidict-6.0.4.tar.gz", hash = "sha256:3666906492efb76453c0e7b97f2cf459b0682e7402c0489a95484965dbc1da49"}, ] -[[package]] -name = "mypy-extensions" -version = "1.0.0" -description = "Type system extensions for programs checked with the mypy type checker." -optional = false -python-versions = ">=3.5" -files = [ - {file = "mypy_extensions-1.0.0-py3-none-any.whl", hash = "sha256:4392f6c0eb8a5668a69e23d168ffa70f0be9ccfd32b5cc2d26a34ae5b844552d"}, - {file = "mypy_extensions-1.0.0.tar.gz", hash = "sha256:75dbf8955dc00442a438fc4d0666508a9a97b6bd41aa2f0ffe9d2f2725af0782"}, -] - [[package]] name = "networkx" version = "3.2.1" @@ -2766,17 +2695,6 @@ files = [ [package.dependencies] regex = ">=2022.3.15" -[[package]] -name = "pathspec" -version = "0.12.1" -description = "Utility library for gitignore style pattern matching of file paths." -optional = false -python-versions = ">=3.8" -files = [ - {file = "pathspec-0.12.1-py3-none-any.whl", hash = "sha256:a0d503e138a4c123b27490a4f7beda6a01c6f288df0e4a8b79c7eb0dc7b4cc08"}, - {file = "pathspec-0.12.1.tar.gz", hash = "sha256:a482d51503a1ab33b1c67a6c3813a26953dbdc71c31dacaef9a838c4e29f5712"}, -] - [[package]] name = "pgpy" version = "0.6.0" @@ -2955,6 +2873,8 @@ files = [ {file = "psycopg2-2.9.9-cp310-cp310-win_amd64.whl", hash = "sha256:426f9f29bde126913a20a96ff8ce7d73fd8a216cfb323b1f04da402d452853c3"}, {file = "psycopg2-2.9.9-cp311-cp311-win32.whl", hash = "sha256:ade01303ccf7ae12c356a5e10911c9e1c51136003a9a1d92f7aa9d010fb98372"}, {file = "psycopg2-2.9.9-cp311-cp311-win_amd64.whl", hash = "sha256:121081ea2e76729acfb0673ff33755e8703d45e926e416cb59bae3a86c6a4981"}, + {file = "psycopg2-2.9.9-cp312-cp312-win32.whl", hash = "sha256:d735786acc7dd25815e89cc4ad529a43af779db2e25aa7c626de864127e5a024"}, + {file = "psycopg2-2.9.9-cp312-cp312-win_amd64.whl", hash = "sha256:a7653d00b732afb6fc597e29c50ad28087dcb4fbfb28e86092277a559ae4e693"}, {file = "psycopg2-2.9.9-cp37-cp37m-win32.whl", hash = "sha256:5e0d98cade4f0e0304d7d6f25bbfbc5bd186e07b38eac65379309c4ca3193efa"}, {file = "psycopg2-2.9.9-cp37-cp37m-win_amd64.whl", hash = "sha256:7e2dacf8b009a1c1e843b5213a87f7c544b2b042476ed7755be813eaf4e8347a"}, {file = "psycopg2-2.9.9-cp38-cp38-win32.whl", hash = "sha256:ff432630e510709564c01dafdbe996cb552e0b9f3f065eb89bdce5bd31fabf4c"}, @@ -3677,35 +3597,82 @@ files = [ {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:b42169467c42b692c19cf539c38d4602069d8c1505e97b86387fcf7afb766e1d"}, {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-macosx_13_0_arm64.whl", hash = "sha256:07238db9cbdf8fc1e9de2489a4f68474e70dffcb32232db7c08fa61ca0c7c462"}, {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:fff3573c2db359f091e1589c3d7c5fc2f86f5bdb6f24252c2d8e539d4e45f412"}, + {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-manylinux_2_24_aarch64.whl", hash = "sha256:aa2267c6a303eb483de8d02db2871afb5c5fc15618d894300b88958f729ad74f"}, + {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:840f0c7f194986a63d2c2465ca63af8ccbbc90ab1c6001b1978f05119b5e7334"}, + {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:024cfe1fc7c7f4e1aff4a81e718109e13409767e4f871443cbff3dba3578203d"}, {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-win32.whl", hash = "sha256:c69212f63169ec1cfc9bb44723bf2917cbbd8f6191a00ef3410f5a7fe300722d"}, {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-win_amd64.whl", hash = "sha256:cabddb8d8ead485e255fe80429f833172b4cadf99274db39abc080e068cbcc31"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:bef08cd86169d9eafb3ccb0a39edb11d8e25f3dae2b28f5c52fd997521133069"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-macosx_13_0_arm64.whl", hash = "sha256:b16420e621d26fdfa949a8b4b47ade8810c56002f5389970db4ddda51dbff248"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:25c515e350e5b739842fc3228d662413ef28f295791af5e5110b543cf0b57d9b"}, + {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-manylinux_2_24_aarch64.whl", hash = "sha256:1707814f0d9791df063f8c19bb51b0d1278b8e9a2353abbb676c2f685dee6afe"}, + {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:46d378daaac94f454b3a0e3d8d78cafd78a026b1d71443f4966c696b48a6d899"}, + {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:09b055c05697b38ecacb7ac50bdab2240bfca1a0c4872b0fd309bb07dc9aa3a9"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-win32.whl", hash = "sha256:53a300ed9cea38cf5a2a9b069058137c2ca1ce658a874b79baceb8f892f915a7"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-win_amd64.whl", hash = "sha256:c2a72e9109ea74e511e29032f3b670835f8a59bbdc9ce692c5b4ed91ccf1eedb"}, {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:ebc06178e8821efc9692ea7544aa5644217358490145629914d8020042c24aa1"}, {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-macosx_13_0_arm64.whl", hash = "sha256:edaef1c1200c4b4cb914583150dcaa3bc30e592e907c01117c08b13a07255ec2"}, {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d176b57452ab5b7028ac47e7b3cf644bcfdc8cacfecf7e71759f7f51a59e5c92"}, + {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-manylinux_2_24_aarch64.whl", hash = "sha256:1dc67314e7e1086c9fdf2680b7b6c2be1c0d8e3a8279f2e993ca2a7545fecf62"}, + {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:3213ece08ea033eb159ac52ae052a4899b56ecc124bb80020d9bbceeb50258e9"}, + {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:aab7fd643f71d7946f2ee58cc88c9b7bfc97debd71dcc93e03e2d174628e7e2d"}, + {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-win32.whl", hash = "sha256:5c365d91c88390c8d0a8545df0b5857172824b1c604e867161e6b3d59a827eaa"}, + {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-win_amd64.whl", hash = "sha256:1758ce7d8e1a29d23de54a16ae867abd370f01b5a69e1a3ba75223eaa3ca1a1b"}, {file = "ruamel.yaml.clib-0.2.8-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:a5aa27bad2bb83670b71683aae140a1f52b0857a2deff56ad3f6c13a017a26ed"}, {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:c58ecd827313af6864893e7af0a3bb85fd529f862b6adbefe14643947cfe2942"}, {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-macosx_12_0_arm64.whl", hash = "sha256:f481f16baec5290e45aebdc2a5168ebc6d35189ae6fea7a58787613a25f6e875"}, + {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-manylinux_2_24_aarch64.whl", hash = "sha256:77159f5d5b5c14f7c34073862a6b7d34944075d9f93e681638f6d753606c6ce6"}, {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:7f67a1ee819dc4562d444bbafb135832b0b909f81cc90f7aa00260968c9ca1b3"}, + {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:4ecbf9c3e19f9562c7fdd462e8d18dd902a47ca046a2e64dba80699f0b6c09b7"}, + {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:87ea5ff66d8064301a154b3933ae406b0863402a799b16e4a1d24d9fbbcbe0d3"}, {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-win32.whl", hash = "sha256:75e1ed13e1f9de23c5607fe6bd1aeaae21e523b32d83bb33918245361e9cc51b"}, {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-win_amd64.whl", hash = "sha256:3f215c5daf6a9d7bbed4a0a4f760f3113b10e82ff4c5c44bec20a68c8014f675"}, {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:1b617618914cb00bf5c34d4357c37aa15183fa229b24767259657746c9077615"}, {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-macosx_12_0_arm64.whl", hash = "sha256:a6a9ffd280b71ad062eae53ac1659ad86a17f59a0fdc7699fd9be40525153337"}, + {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-manylinux_2_24_aarch64.whl", hash = "sha256:305889baa4043a09e5b76f8e2a51d4ffba44259f6b4c72dec8ca56207d9c6fe1"}, {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:700e4ebb569e59e16a976857c8798aee258dceac7c7d6b50cab63e080058df91"}, + {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:e2b4c44b60eadec492926a7270abb100ef9f72798e18743939bdbf037aab8c28"}, + {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:e79e5db08739731b0ce4850bed599235d601701d5694c36570a99a0c5ca41a9d"}, {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-win32.whl", hash = "sha256:955eae71ac26c1ab35924203fda6220f84dce57d6d7884f189743e2abe3a9fbe"}, {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-win_amd64.whl", hash = "sha256:56f4252222c067b4ce51ae12cbac231bce32aee1d33fbfc9d17e5b8d6966c312"}, {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:03d1162b6d1df1caa3a4bd27aa51ce17c9afc2046c31b0ad60a0a96ec22f8001"}, {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-macosx_12_0_arm64.whl", hash = "sha256:bba64af9fa9cebe325a62fa398760f5c7206b215201b0ec825005f1b18b9bccf"}, + {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-manylinux_2_24_aarch64.whl", hash = "sha256:a1a45e0bb052edf6a1d3a93baef85319733a888363938e1fc9924cb00c8df24c"}, {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:da09ad1c359a728e112d60116f626cc9f29730ff3e0e7db72b9a2dbc2e4beed5"}, + {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:184565012b60405d93838167f425713180b949e9d8dd0bbc7b49f074407c5a8b"}, + {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:a75879bacf2c987c003368cf14bed0ffe99e8e85acfa6c0bfffc21a090f16880"}, {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-win32.whl", hash = "sha256:84b554931e932c46f94ab306913ad7e11bba988104c5cff26d90d03f68258cd5"}, {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-win_amd64.whl", hash = "sha256:25ac8c08322002b06fa1d49d1646181f0b2c72f5cbc15a85e80b4c30a544bb15"}, {file = "ruamel.yaml.clib-0.2.8.tar.gz", hash = "sha256:beb2e0404003de9a4cab9753a8805a8fe9320ee6673136ed7f04255fe60bb512"}, ] +[[package]] +name = "ruff" +version = "0.6.0" +description = "An extremely fast Python linter and code formatter, written in Rust." +optional = false +python-versions = ">=3.7" +files = [ + {file = "ruff-0.6.0-py3-none-linux_armv6l.whl", hash = "sha256:92dcce923e5df265781e5fc76f9a1edad52201a7aafe56e586b90988d5239013"}, + {file = "ruff-0.6.0-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:31b90ff9dc79ed476c04e957ba7e2b95c3fceb76148f2079d0d68a908d2cfae7"}, + {file = "ruff-0.6.0-py3-none-macosx_11_0_arm64.whl", hash = "sha256:6d834a9ec9f8287dd6c3297058b3a265ed6b59233db22593379ee38ebc4b9768"}, + {file = "ruff-0.6.0-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f2089267692696aba342179471831a085043f218706e642564812145df8b8d0d"}, + {file = "ruff-0.6.0-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:aa62b423ee4bbd8765f2c1dbe8f6aac203e0583993a91453dc0a449d465c84da"}, + {file = "ruff-0.6.0-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7344e1a964b16b1137ea361d6516ce4ee61a0403fa94252a1913ecc1311adcae"}, + {file = "ruff-0.6.0-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:487f3a35c3f33bf82be212ce15dc6278ea854e35573a3f809442f73bec8b2760"}, + {file = "ruff-0.6.0-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:75db409984077a793cf344d499165298a6f65449e905747ac65983b12e3e64b1"}, + {file = "ruff-0.6.0-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:84908bd603533ecf1db456d8fc2665d1f4335d722e84bc871d3bbd2d1116c272"}, + {file = "ruff-0.6.0-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0f1749a0aef3ec41ed91a0e2127a6ae97d2e2853af16dbd4f3c00d7a3af726c5"}, + {file = "ruff-0.6.0-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:016fea751e2bcfbbd2f8cb19b97b37b3fd33148e4df45b526e87096f4e17354f"}, + {file = "ruff-0.6.0-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:6ae80f141b53b2e36e230017e64f5ea2def18fac14334ffceaae1b780d70c4f7"}, + {file = "ruff-0.6.0-py3-none-musllinux_1_2_i686.whl", hash = "sha256:eaaaf33ea4b3f63fd264d6a6f4a73fa224bbfda4b438ffea59a5340f4afa2bb5"}, + {file = "ruff-0.6.0-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:7667ddd1fc688150a7ca4137140867584c63309695a30016880caf20831503a0"}, + {file = "ruff-0.6.0-py3-none-win32.whl", hash = "sha256:ae48365aae60d40865a412356f8c6f2c0be1c928591168111eaf07eaefa6bea3"}, + {file = "ruff-0.6.0-py3-none-win_amd64.whl", hash = "sha256:774032b507c96f0c803c8237ce7d2ef3934df208a09c40fa809c2931f957fe5e"}, + {file = "ruff-0.6.0-py3-none-win_arm64.whl", hash = "sha256:a5366e8c3ae6b2dc32821749b532606c42e609a99b0ae1472cf601da931a048c"}, + {file = "ruff-0.6.0.tar.gz", hash = "sha256:272a81830f68f9bd19d49eaf7fa01a5545c5a2e86f32a9935bb0e4bb9a1db5b8"}, +] + [[package]] name = "s3transfer" version = "0.10.0" @@ -4370,4 +4337,4 @@ multidict = ">=4.0" [metadata] lock-version = "2.0" python-versions = "^3.10,<3.13" -content-hash = "9c5912834d202daf5607eebb1405e9f13c15bf5770fb5f58567ffd4331698b56" +content-hash = "cca3e02a568c585382d045430da0c2d18234634f2a86bb81a12b6cad52ef226e" diff --git a/packages/examples/cvat/exchange-oracle/pyproject.toml b/packages/examples/cvat/exchange-oracle/pyproject.toml index 2bca744724..bcca6ac50b 100644 --- a/packages/examples/cvat/exchange-oracle/pyproject.toml +++ b/packages/examples/cvat/exchange-oracle/pyproject.toml @@ -28,19 +28,121 @@ pyinstrument = "^4.6.2" [tool.poetry.group.dev.dependencies] -black = "^23.1.0" pre-commit = "^3.0.4" -isort = "^5.12.0" +ruff = "^0.6.0" -[tool.isort] -profile = "black" -forced_separate = ["tests"] -line_length = 100 -skip_gitignore = true # align tool behavior with Black - -[tool.black] +[tool.ruff] line-length = 100 -target-version = ['py310'] +target-version = "py310" + + +[tool.ruff.lint] +select = ["ALL"] +unfixable = [ + "RUF005", # messes up concantenation with numpy structures +] +ignore = [ + "W191", # Rules conflicting with ruff format (https://docs.astral.sh/ruff/formatter/#conflicting-lint-rules) + "E111", # | + "E114", # | + "E117", # | + "D206", # | + "D300", # | + "Q000", # | + "Q001", # | + "Q002", # | + "Q003", # | + "COM812", # | + "COM819", # | + "ISC001", # | + "ISC002", # | + "ANN101", # Method args annotations (mypy will take care of that) + "ANN001", # | + "ANN202", # | + "ANN201", # | + "ANN401", # | + "ANN102", # | + "RUF001", # Allow cyrillic letters in comments + + "B904", # Raise from: modern pythons preserve previous exceptions + "EM", # Forbids using literal strings in exceptions. + # Sujested way of dealing with exceptions increases verbosity + # while giving little to no benefit in readability + "TRY003", # | + "G004", # Forbids using f-strings in logging. This project doesn't rely on lazy % formatting when using logging. + "A003", # Class attribute `id` is shadowing a Python builtin — it's ok in class body + "FIX001", # Forbids using TODOs, but TODOs are useful + "FIX002", # | + "TD001", # | + "TD002", # | + "TD003", # | + "E711", # Allow == None comparisons for sqlalchemy queries + "E712", # Allow == True comparisons for sqlalchemy queries + "PERF203", # Noisy microoptimisation + # Want to resolve eventually, but not now: + "S101", # Allow asserts (there are too many of them right now to fix) + "TRY401", # Checks for excesive logging of exception objects + "G001", # Forbid str.format for logging + "PTH123", # Checks for uses of `os.path.splitext` + "D", # Docstrings + "N806", # Variable in function should be lowercase + "RUF012", # Mutable class attributes should be annotated with `typing.ClassVar` + "SLF001", # Private member accessed + "F811", # Redefinition of unused + "RUF005", # Consider iterable unpacking instead of concatenation + "A002", # Argument is shadowing a Python builtin + "N818", # Exception name should be named with an Error suffix + "TRY002", # Create your own exception + "ANN003", # Missing type annotation for `**kwargs` + "ANN204", # Missing return type annotation for special method + "ERA001", # Found commented-out code + "N801", # Class name should use CapWords convention + "PLR0915", # Too many statements + "F401", # Imported but unused + "PLR2004", # Magic value used in comparison, consider replacing with a constant variable + "ANN002", # Missing type annotation for `*args` + "TRY300", # Consider moving this statement to an `else` block + "C901", # Function is too complex + "PLW2901", # Variable overwritten by assignment target + "PTH118", # Prefer pathlib instead of os.path + "PTH119", # `os.path.basename()` should be replaced by `Path.name` + "PTH122", # `os.path.splitext()` should be replaced by `Path.suffix`, `Path.stem`, and `Path.parent` + "PTH207", # Replace `glob` with `Path.glob` or `Path.rglob` + "UP032", # Upgrades .format() to f-strings. Disabling until it ignores line-length + "C401", # set comprehensions are apparently can be hard to distinguish from dict comprehensions + "RET505", # Unnecessary elif/else statements after/before raise/return. +] + + +[tool.ruff.lint.per-file-ignores] +"tests/*" = [ + "PLR0913", # Annotations and args + "ANN202", # | + "ANN201", # | + "ANN001", # | + "ANN003", # | + "ARG001", # | + "SLF001", # Allow private attrs access + "PLR2004", # Allow magic values + "S", # security + "DTZ005", # allow datetimes without timezones +] +# alembic is not a package in a traditional sense, so putting __init__.py there doesn't make sense +"alembic/*" = ["INP001"] + +[tool.ruff.lint.pep8-naming] +classmethod-decorators = [ + "pydantic.validator", +] + +[tool.ruff.lint.pylint] +max-args = 9 # Lower number might be beneficial to reduce cognitive load. Consider using data containers. + +[tool.ruff.lint.isort] +forced-separate = ["tests"] + +[tool.ruff.lint.flake8-tidy-imports] +ban-relative-imports = "all" [build-system] requires = ["poetry-core"] diff --git a/packages/examples/cvat/exchange-oracle/run.py b/packages/examples/cvat/exchange-oracle/run.py index 8e313c1bf1..92b0fc8a8c 100644 --- a/packages/examples/cvat/exchange-oracle/run.py +++ b/packages/examples/cvat/exchange-oracle/run.py @@ -10,7 +10,7 @@ uvicorn.run( app="src:app", - host="0.0.0.0", + host="0.0.0.0", # noqa: S104 port=int(Config.port), workers=Config.workers_amount, # reload=is_dev, diff --git a/packages/examples/cvat/exchange-oracle/src/chain/__init__.py b/packages/examples/cvat/exchange-oracle/src/chain/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/examples/cvat/exchange-oracle/src/chain/escrow.py b/packages/examples/cvat/exchange-oracle/src/chain/escrow.py index 6b85ebe7c7..1d76214f59 100644 --- a/packages/examples/cvat/exchange-oracle/src/chain/escrow.py +++ b/packages/examples/cvat/exchange-oracle/src/chain/escrow.py @@ -1,8 +1,7 @@ import json -from typing import List from human_protocol_sdk.constants import ChainId, Status -from human_protocol_sdk.encryption import Encryption, EncryptionUtils +from human_protocol_sdk.encryption import Encryption from human_protocol_sdk.escrow import EscrowData, EscrowUtils from human_protocol_sdk.storage import StorageUtils @@ -21,9 +20,11 @@ def validate_escrow( chain_id: int, escrow_address: str, *, - accepted_states: List[Status] = [Status.Pending], + accepted_states: list[Status] | None = None, allow_no_funds: bool = False, ) -> None: + if accepted_states is None: + accepted_states = [Status.Pending] assert accepted_states escrow = get_escrow(chain_id, escrow_address) @@ -36,9 +37,8 @@ def validate_escrow( ) ) - if status == Status.Pending and not allow_no_funds: - if int(escrow.balance) == 0: - raise ValueError("Escrow doesn't have funds") + if status == Status.Pending and not allow_no_funds and int(escrow.balance) == 0: + raise ValueError("Escrow doesn't have funds") def get_escrow_manifest(chain_id: int, escrow_address: str) -> dict: diff --git a/packages/examples/cvat/exchange-oracle/src/chain/web3.py b/packages/examples/cvat/exchange-oracle/src/chain/web3.py index cc427c96b9..e76f77bf95 100644 --- a/packages/examples/cvat/exchange-oracle/src/chain/web3.py +++ b/packages/examples/cvat/exchange-oracle/src/chain/web3.py @@ -71,9 +71,7 @@ def sign_message(chain_id: Networks, message) -> str: def recover_signer(chain_id: Networks, message, signature: str) -> str: w3 = get_web3(chain_id) message_hash = encode_defunct(text=serialize_message(message)) - signer = w3.eth.account.recover_message(message_hash, signature=signature) - - return signer + return w3.eth.account.recover_message(message_hash, signature=signature) def validate_address(escrow_address: str) -> str: diff --git a/packages/examples/cvat/exchange-oracle/src/core/__init__.py b/packages/examples/cvat/exchange-oracle/src/core/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/examples/cvat/exchange-oracle/src/core/annotation_meta.py b/packages/examples/cvat/exchange-oracle/src/core/annotation_meta.py index e19a77efd5..d539787315 100644 --- a/packages/examples/cvat/exchange-oracle/src/core/annotation_meta.py +++ b/packages/examples/cvat/exchange-oracle/src/core/annotation_meta.py @@ -1,5 +1,4 @@ from pathlib import Path -from typing import List from pydantic import BaseModel @@ -15,4 +14,4 @@ class JobMeta(BaseModel): class AnnotationMeta(BaseModel): - jobs: List[JobMeta] + jobs: list[JobMeta] diff --git a/packages/examples/cvat/exchange-oracle/src/core/config.py b/packages/examples/cvat/exchange-oracle/src/core/config.py index 91669459bc..7a6481574b 100644 --- a/packages/examples/cvat/exchange-oracle/src/core/config.py +++ b/packages/examples/cvat/exchange-oracle/src/core/config.py @@ -1,8 +1,10 @@ # pylint: disable=too-few-public-methods,missing-class-docstring -""" Project configuration from env vars """ +"""Project configuration from env vars""" + import inspect import os -from typing import ClassVar, Iterable, Optional +from collections.abc import Iterable +from typing import ClassVar from attrs.converters import to_bool from dotenv import load_dotenv @@ -14,7 +16,7 @@ from src.utils.net import is_ipv4 dotenv_path = os.getenv("DOTENV_PATH", None) -if dotenv_path and not os.path.exists(dotenv_path): +if dotenv_path and not os.path.exists(dotenv_path): # noqa: PTH110 raise FileNotFoundError(dotenv_path) load_dotenv(dotenv_path) @@ -28,22 +30,22 @@ def validate(cls) -> None: class PostgresConfig: port = os.environ.get("PG_PORT", "5432") - host = os.environ.get("PG_HOST", "0.0.0.0") + host = os.environ.get("PG_HOST", "0.0.0.0") # noqa: S104 user = os.environ.get("PG_USER", "admin") password = os.environ.get("PG_PASSWORD", "admin") database = os.environ.get("PG_DB", "exchange_oracle") lock_timeout = int(os.environ.get("PG_LOCK_TIMEOUT", "3000")) # milliseconds @classmethod - def connection_url(cls): + def connection_url(cls) -> str: return f"postgresql://{cls.user}:{cls.password}@{cls.host}:{cls.port}/{cls.database}" class _NetworkConfig: chain_id: ClassVar[int] - rpc_api: ClassVar[Optional[str]] - private_key: ClassVar[Optional[str]] - addr: ClassVar[Optional[str]] + rpc_api: ClassVar[str | None] + private_key: ClassVar[str | None] + addr: ClassVar[str | None] @classmethod def is_configured(cls) -> bool: @@ -154,27 +156,27 @@ class StorageConfig: endpoint_url: ClassVar[str] = os.environ[ "STORAGE_ENDPOINT_URL" ] # TODO: probably should be optional - region: ClassVar[Optional[str]] = os.environ.get("STORAGE_REGION") + region: ClassVar[str | None] = os.environ.get("STORAGE_REGION") results_dir_suffix: ClassVar[str] = os.environ.get("STORAGE_RESULTS_DIR_SUFFIX", "-results") secure: ClassVar[bool] = to_bool(os.environ.get("STORAGE_USE_SSL", "true")) # S3 specific attributes - access_key: ClassVar[Optional[str]] = os.environ.get("STORAGE_ACCESS_KEY") - secret_key: ClassVar[Optional[str]] = os.environ.get("STORAGE_SECRET_KEY") + access_key: ClassVar[str | None] = os.environ.get("STORAGE_ACCESS_KEY") + secret_key: ClassVar[str | None] = os.environ.get("STORAGE_SECRET_KEY") # GCS specific attributes - key_file_path: ClassVar[Optional[str]] = os.environ.get("STORAGE_KEY_FILE_PATH") + key_file_path: ClassVar[str | None] = os.environ.get("STORAGE_KEY_FILE_PATH") @classmethod def get_scheme(cls) -> str: return "https://" if cls.secure else "http://" @classmethod - def provider_endpoint_url(cls): + def provider_endpoint_url(cls) -> str: return f"{cls.get_scheme()}{cls.endpoint_url}" @classmethod - def bucket_url(cls): + def bucket_url(cls) -> str: if is_ipv4(cls.endpoint_url): return f"{cls.get_scheme()}{cls.endpoint_url}/{cls.data_bucket_name}/" else: @@ -188,10 +190,10 @@ class FeaturesConfig: default_export_timeout = int(os.environ.get("DEFAULT_EXPORT_TIMEOUT", 60)) "Timeout, in seconds, for annotations or dataset export waiting" - request_logging_enabled = to_bool(os.getenv("REQUEST_LOGGING_ENABLED", False)) + request_logging_enabled = to_bool(os.getenv("REQUEST_LOGGING_ENABLED", "0")) "Allow to log request details for each request" - profiling_enabled = to_bool(os.getenv("PROFILING_ENABLED", False)) + profiling_enabled = to_bool(os.getenv("PROFILING_ENABLED", "0")) "Allow to profile specific requests" @@ -222,12 +224,12 @@ def validate(cls) -> None: ex_prefix = "Wrong server configuration." if (cls.pgp_public_key_url or cls.pgp_passphrase) and not cls.pgp_private_key: - raise Exception(" ".join([ex_prefix, "The PGP_PRIVATE_KEY environment is not set."])) + raise Exception(f"{ex_prefix} The PGP_PRIVATE_KEY environment is not set.") if cls.pgp_private_key: try: Encryption(cls.pgp_private_key, passphrase=cls.pgp_passphrase) - except Exception as ex: + except Exception as ex: # noqa: BLE001 # Possible reasons: # - private key is invalid # - private key is locked but no passphrase is provided @@ -264,9 +266,12 @@ def validate(cls) -> None: attr_or_method.validate() @classmethod - def get_network_configs(cls, only_configured: bool = True) -> Iterable[_NetworkConfig]: + def get_network_configs(cls, *, only_configured: bool = True) -> Iterable[_NetworkConfig]: for attr_or_method in cls.__dict__: attr_or_method = getattr(cls, attr_or_method) - if inspect.isclass(attr_or_method) and issubclass(attr_or_method, _NetworkConfig): - if not only_configured or attr_or_method.is_configured(): - yield attr_or_method + if ( + inspect.isclass(attr_or_method) + and issubclass(attr_or_method, _NetworkConfig) + and (not only_configured or attr_or_method.is_configured()) + ): + yield attr_or_method diff --git a/packages/examples/cvat/exchange-oracle/src/core/manifest.py b/packages/examples/cvat/exchange-oracle/src/core/manifest.py index c8a4c2260d..c70c1ed91a 100644 --- a/packages/examples/cvat/exchange-oracle/src/core/manifest.py +++ b/packages/examples/cvat/exchange-oracle/src/core/manifest.py @@ -1,6 +1,6 @@ from decimal import Decimal from enum import Enum -from typing import Annotated, Any, Dict, List, Literal, Optional, Tuple, Union +from typing import Annotated, Any, Literal from pydantic import AnyUrl, BaseModel, Field, root_validator @@ -28,22 +28,22 @@ class AwsBucketUrl(BucketUrlBase, BaseModel): class GcsBucketUrl(BucketUrlBase, BaseModel): provider: Literal[BucketProviders.gcs] - service_account_key: Dict[str, Any] = {} # (optional) Contents of GCS key file + service_account_key: dict[str, Any] = {} # (optional) Contents of GCS key file -BucketUrl = Annotated[Union[AwsBucketUrl, GcsBucketUrl], Field(discriminator="provider")] +BucketUrl = Annotated[AwsBucketUrl | GcsBucketUrl, Field(discriminator="provider")] class DataInfo(BaseModel): - data_url: Union[AnyUrl, BucketUrl] + data_url: AnyUrl | BucketUrl "Bucket URL, AWS S3 | GCS, virtual-hosted-style access" # https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-bucket-intro.html - points_url: Optional[Union[AnyUrl, BucketUrl]] = None + points_url: AnyUrl | BucketUrl | None = None "A path to an archive with a set of points in COCO Keypoints format, " "which provides information about all objects on images" - boxes_url: Optional[Union[AnyUrl, BucketUrl]] = None + boxes_url: AnyUrl | BucketUrl | None = None "A path to an archive with a set of boxes in COCO Instances format, " "which provides information about all objects on images" @@ -67,7 +67,7 @@ class PlainLabelInfo(LabelInfoBase): class SkeletonLabelInfo(LabelInfoBase): type: Literal[LabelTypes.skeleton] - nodes: List[str] = Field(min_items=1) + nodes: list[str] = Field(min_items=1) """ A list of node label names (only points are supposed to be nodes). Example: @@ -76,7 +76,7 @@ class SkeletonLabelInfo(LabelInfoBase): ] """ - joints: Optional[List[Tuple[int, int]]] = Field(default_factory=list) + joints: list[tuple[int, int]] | None = Field(default_factory=list) "A list of node adjacency, e.g. [[0, 1], [1, 2], [1, 3]]" @root_validator @@ -114,7 +114,7 @@ def validate_type(cls, values: dict) -> dict: return values -LabelInfo = Annotated[Union[PlainLabelInfo, SkeletonLabelInfo], Field(discriminator="type")] +LabelInfo = Annotated[PlainLabelInfo | SkeletonLabelInfo, Field(discriminator="type")] class AnnotationInfo(BaseModel): @@ -132,7 +132,7 @@ class AnnotationInfo(BaseModel): job_size: int = 10 "Frames per job, validation frames are not included" - max_time: Optional[int] = None # deprecated, TODO: mark deprecated with pydantic 2.7+ + max_time: int | None = None # deprecated, TODO: mark deprecated with pydantic 2.7+ "Maximum time per job (assignment) for an annotator, in seconds" @root_validator(pre=True) @@ -161,7 +161,7 @@ class ValidationInfo(BaseModel): val_size: int = Field(default=2, gt=0) "Validation frames per job" - gt_url: Union[AnyUrl, BucketUrl] + gt_url: AnyUrl | BucketUrl "URL to the archive with Ground Truth annotations, the format is COCO keypoints" diff --git a/packages/examples/cvat/exchange-oracle/src/core/oracle_events.py b/packages/examples/cvat/exchange-oracle/src/core/oracle_events.py index 334fd2ee80..6188d598f0 100644 --- a/packages/examples/cvat/exchange-oracle/src/core/oracle_events.py +++ b/packages/examples/cvat/exchange-oracle/src/core/oracle_events.py @@ -1,4 +1,4 @@ -from typing import Optional, Type, Union +from typing import Union from pydantic import BaseModel @@ -9,11 +9,7 @@ RecordingOracleEventTypes, ) -EventTypeTag = Union[ - ExchangeOracleEventTypes, - JobLauncherEventTypes, - RecordingOracleEventTypes, -] +EventTypeTag = ExchangeOracleEventTypes | JobLauncherEventTypes | RecordingOracleEventTypes class OracleEvent(BaseModel): @@ -58,7 +54,7 @@ class ExchangeOracleEvent_TaskFinished(OracleEvent): } -def get_class_for_event_type(event_type: str) -> Type[OracleEvent]: +def get_class_for_event_type(event_type: str) -> type[OracleEvent]: event_class = next((v for k, v in _event_type_map.items() if k == event_type), None) if not event_class: @@ -68,7 +64,7 @@ def get_class_for_event_type(event_type: str) -> Type[OracleEvent]: def get_type_tag_for_event_class( - event_class: Type[OracleEvent], + event_class: type[OracleEvent], ) -> EventTypeTag: event_type = next((k for k, v in _event_type_map.items() if v == event_class), None) @@ -81,7 +77,7 @@ def get_type_tag_for_event_class( def parse_event( sender: OracleWebhookTypes, event_type: str, - event_data: Optional[dict] = None, + event_data: dict | None = None, ) -> OracleEvent: sender_events_mapping = { OracleWebhookTypes.job_launcher: JobLauncherEventTypes, @@ -91,10 +87,10 @@ def parse_event( sender_events = sender_events_mapping.get(sender) if sender_events is not None: - if not event_type in sender_events: + if event_type not in sender_events: raise ValueError(f"Unknown event '{sender}.{event_type}'") else: - assert False, f"Unknown event sender type '{sender}'" + raise AssertionError(f"Unknown event sender type '{sender}'") event_class = get_class_for_event_type(event_type) return event_class.parse_obj(event_data or {}) diff --git a/packages/examples/cvat/exchange-oracle/src/core/tasks/boxes_from_points.py b/packages/examples/cvat/exchange-oracle/src/core/tasks/boxes_from_points.py index c9320473b6..bd26aacc14 100644 --- a/packages/examples/cvat/exchange-oracle/src/core/tasks/boxes_from_points.py +++ b/packages/examples/cvat/exchange-oracle/src/core/tasks/boxes_from_points.py @@ -1,14 +1,14 @@ import os +from collections.abc import Sequence from pathlib import Path from tempfile import TemporaryDirectory -from typing import Dict, Sequence import attrs import datumaro as dm from attrs import frozen from datumaro.util import dump_json, parse_json -BboxPointMapping = Dict[int, int] +BboxPointMapping = dict[int, int] @frozen @@ -28,7 +28,7 @@ def asdict(self) -> dict: RoiInfos = Sequence[RoiInfo] -RoiFilenames = Dict[int, str] +RoiFilenames = dict[int, str] class TaskMetaLayout: diff --git a/packages/examples/cvat/exchange-oracle/src/core/tasks/skeletons_from_boxes.py b/packages/examples/cvat/exchange-oracle/src/core/tasks/skeletons_from_boxes.py index 404e3b06ea..dc70d33a91 100644 --- a/packages/examples/cvat/exchange-oracle/src/core/tasks/skeletons_from_boxes.py +++ b/packages/examples/cvat/exchange-oracle/src/core/tasks/skeletons_from_boxes.py @@ -1,7 +1,7 @@ import os +from collections.abc import Sequence from pathlib import Path from tempfile import TemporaryDirectory -from typing import Dict, Sequence, Tuple import attrs import datumaro as dm @@ -12,7 +12,7 @@ DEFAULT_ASSIGNMENT_SIZE_MULTIPLIER = Config.core_config.skeleton_assignment_size_mult -SkeletonBboxMapping = Dict[int, int] +SkeletonBboxMapping = dict[int, int] @frozen(kw_only=True) @@ -37,9 +37,9 @@ def asdict(self) -> dict: RoiInfos = Sequence[RoiInfo] -RoiFilenames = Dict[int, str] +RoiFilenames = dict[int, str] -PointLabelsMapping = Dict[Tuple[str, str], str] +PointLabelsMapping = dict[tuple[str, str], str] "(skeleton, point) -> job point name" diff --git a/packages/examples/cvat/exchange-oracle/src/crons/process_job_launcher_webhooks.py b/packages/examples/cvat/exchange-oracle/src/crons/process_job_launcher_webhooks.py index 00e873f8e4..2682f6ff95 100644 --- a/packages/examples/cvat/exchange-oracle/src/crons/process_job_launcher_webhooks.py +++ b/packages/examples/cvat/exchange-oracle/src/crons/process_job_launcher_webhooks.py @@ -109,53 +109,48 @@ def handle_job_launcher_event(webhook: Webhook, *, db_session: Session, logger: raise case JobLauncherEventTypes.escrow_canceled: - try: - validate_escrow( - webhook.chain_id, - webhook.escrow_address, - accepted_states=[EscrowStatus.Pending, EscrowStatus.Cancelled], - ) + validate_escrow( + webhook.chain_id, + webhook.escrow_address, + accepted_states=[EscrowStatus.Pending, EscrowStatus.Cancelled], + ) - projects = cvat_db_service.get_projects_by_escrow_address( - db_session, webhook.escrow_address, for_update=True, limit=None + projects = cvat_db_service.get_projects_by_escrow_address( + db_session, webhook.escrow_address, for_update=True, limit=None + ) + if not projects: + logger.error( + "Received escrow cancel event " + f"(escrow_address={webhook.escrow_address}). " + "The project doesn't exist, ignoring" ) - if not projects: + return + + for project in projects: + if project.status in [ + ProjectStatuses.canceled, + ProjectStatuses.recorded, + ]: logger.error( "Received escrow cancel event " f"(escrow_address={webhook.escrow_address}). " - "The project doesn't exist, ignoring" - ) - return - - for project in projects: - if project.status in [ - ProjectStatuses.canceled, - ProjectStatuses.recorded, - ]: - logger.error( - "Received escrow cancel event " - f"(escrow_address={webhook.escrow_address}). " - "The project is already finished, ignoring" - ) - continue - - logger.info( - f"Received escrow cancel event (escrow_address={webhook.escrow_address}). " - "Canceling the project" - ) - cvat_db_service.update_project_status( - db_session, project.id, ProjectStatuses.canceled + "The project is already finished, ignoring" ) + continue - cvat_db_service.finish_escrow_creations_by_escrow_address( - db_session, escrow_address=webhook.escrow_address, chain_id=webhook.chain_id + logger.info( + f"Received escrow cancel event (escrow_address={webhook.escrow_address}). " + "Canceling the project" + ) + cvat_db_service.update_project_status( + db_session, project.id, ProjectStatuses.canceled ) - except Exception as ex: - raise - + cvat_db_service.finish_escrow_creations_by_escrow_address( + db_session, escrow_address=webhook.escrow_address, chain_id=webhook.chain_id + ) case _: - assert False, f"Unknown job launcher event {webhook.event_type}" + raise AssertionError(f"Unknown job launcher event {webhook.event_type}") def process_outgoing_job_launcher_webhooks(): diff --git a/packages/examples/cvat/exchange-oracle/src/crons/process_recording_oracle_webhooks.py b/packages/examples/cvat/exchange-oracle/src/crons/process_recording_oracle_webhooks.py index b0293a89be..c49fac60b9 100644 --- a/packages/examples/cvat/exchange-oracle/src/crons/process_recording_oracle_webhooks.py +++ b/packages/examples/cvat/exchange-oracle/src/crons/process_recording_oracle_webhooks.py @@ -68,10 +68,8 @@ def handle_recording_oracle_event(webhook: Webhook, *, db_session: Session, logg ) if not project_ids: logger.error( - "Unexpected event {} received for an unknown project, " - "ignoring (escrow_address={})".format( - webhook.event_type, webhook.escrow_address - ) + f"Unexpected event {webhook.event_type} received for an unknown project, " + f"ignoring (escrow_address={webhook.escrow_address})" ) return @@ -148,7 +146,7 @@ def handle_recording_oracle_event(webhook: Webhook, *, db_session: Session, logg cvat_db_service.update_project_status(db_session, project.id, new_status) case _: - assert False, f"Unknown recording oracle event {webhook.event_type}" + raise AssertionError(f"Unknown recording oracle event {webhook.event_type}") def process_outgoing_recording_oracle_webhooks(): diff --git a/packages/examples/cvat/exchange-oracle/src/crons/state_trackers.py b/packages/examples/cvat/exchange-oracle/src/crons/state_trackers.py index 09745773e1..868569b522 100644 --- a/packages/examples/cvat/exchange-oracle/src/crons/state_trackers.py +++ b/packages/examples/cvat/exchange-oracle/src/crons/state_trackers.py @@ -1,5 +1,3 @@ -from typing import List - from sqlalchemy import exc as sa_errors import src.cvat.api_calls as cvat_api @@ -221,8 +219,8 @@ def track_task_creation() -> None: ) ) - completed: List[cvat_models.DataUpload] = [] - failed: List[cvat_models.DataUpload] = [] + completed: list[cvat_models.DataUpload] = [] + failed: list[cvat_models.DataUpload] = [] for upload in uploads: status, reason = cvat_api.get_task_upload_status(upload.task_id) project = upload.task.project @@ -313,7 +311,7 @@ def track_escrow_creation() -> None: ) ) - finished: List[cvat_models.EscrowCreation] = [] + finished: list[cvat_models.EscrowCreation] = [] for creation in creations: created_jobs_count = cvat_service.count_jobs_by_escrow_address( session, diff --git a/packages/examples/cvat/exchange-oracle/src/cvat/__init__.py b/packages/examples/cvat/exchange-oracle/src/cvat/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/examples/cvat/exchange-oracle/src/cvat/api_calls.py b/packages/examples/cvat/exchange-oracle/src/cvat/api_calls.py index 3b5a7b4a8a..75c4ad5f31 100644 --- a/packages/examples/cvat/exchange-oracle/src/cvat/api_calls.py +++ b/packages/examples/cvat/exchange-oracle/src/cvat/api_calls.py @@ -2,6 +2,7 @@ import json import logging import zipfile +from collections.abc import Generator from contextlib import contextmanager from contextvars import ContextVar from datetime import timedelta @@ -9,7 +10,7 @@ from http import HTTPStatus from io import BytesIO from time import sleep -from typing import Any, Dict, Generator, List, Optional, Tuple +from typing import Any from cvat_sdk.api_client import ApiClient, Configuration, exceptions, models from cvat_sdk.api_client.api_client import Endpoint @@ -50,7 +51,7 @@ def _get_annotations( cvat_id: int, format_name: str, attempt_interval: int = 5, - timeout: Optional[int] = _NOTSET, + timeout: int | None = _NOTSET, ) -> io.RawIOBase: """ Downloads annotations. @@ -125,13 +126,13 @@ def create_cloudstorage( provider: str, bucket_name: str, *, - credentials: Optional[Dict[str, Any]] = None, - bucket_host: Optional[str] = None, + credentials: dict[str, Any] | None = None, + bucket_host: str | None = None, ) -> models.CloudStorageRead: # credentials: access_key | secret_key | service_account_key # CVAT credentials: key | secret_key | key_file - def _to_cvat_credentials(credentials: Dict[str, Any]) -> Dict: - cvat_credentials = dict() + def _to_cvat_credentials(credentials: dict[str, Any]) -> dict: + cvat_credentials = {} for cvat_field, field in { "key": "access_key", "secret_key": "secret_key", @@ -147,7 +148,7 @@ def _to_cvat_credentials(credentials: Dict[str, Any]) -> Dict: cvat_credentials[cvat_field] = value return cvat_credentials - request_kwargs = dict() + request_kwargs = {} if credentials: request_kwargs.update(_to_cvat_credentials(credentials)) @@ -186,7 +187,7 @@ def _to_cvat_credentials(credentials: Dict[str, Any]) -> Dict: def create_project( - name: str, *, labels: Optional[list] = None, user_guide: str = "" + name: str, *, labels: list | None = None, user_guide: str = "" ) -> models.ProjectRead: logger = logging.getLogger("app") with get_api_client() as api_client: @@ -239,7 +240,7 @@ def request_project_annotations(cvat_id: int, format_name: str) -> bool: def get_project_annotations( - cvat_id: int, format_name: str, *, timeout: Optional[int] = _NOTSET + cvat_id: int, format_name: str, *, timeout: int | None = _NOTSET ) -> io.RawIOBase: """ Downloads annotations. @@ -314,7 +315,7 @@ def create_task(project_id: int, name: str) -> models.TaskRead: raise -def get_cloudstorage_contents(cloudstorage_id: int) -> List[str]: +def get_cloudstorage_contents(cloudstorage_id: int) -> list[str]: logger = logging.getLogger("app") with get_api_client() as api_client: try: @@ -332,7 +333,7 @@ def put_task_data( task_id: int, cloudstorage_id: int, *, - filenames: Optional[list[str]] = None, + filenames: list[str] | None = None, sort_images: bool = True, ) -> None: logger = logging.getLogger("app") @@ -355,7 +356,7 @@ def put_task_data( ) try: (_, response) = api_client.tasks_api.create_data(task_id, data_request=data_request) - return None + return except exceptions.ApiException as e: logger.exception(f"Exception when calling ProjectsApi.put_task_data: {e}\n") @@ -388,7 +389,7 @@ def request_task_annotations(cvat_id: int, format_name: str) -> bool: def get_task_annotations( - cvat_id: int, format_name: str, *, timeout: Optional[int] = _NOTSET + cvat_id: int, format_name: str, *, timeout: int | None = _NOTSET ) -> io.RawIOBase: """ Downloads annotations. @@ -418,16 +419,15 @@ def get_task_annotations( raise -def fetch_task_jobs(task_id: int) -> List[models.JobRead]: +def fetch_task_jobs(task_id: int) -> list[models.JobRead]: logger = logging.getLogger("app") with get_api_client() as api_client: try: - data = get_paginated_collection( + return get_paginated_collection( api_client.jobs_api.list_endpoint, task_id=task_id, type="annotation", ) - return data except exceptions.ApiException as e: logger.exception(f"Exception when calling JobsApi.list: {e}\n") raise @@ -459,7 +459,7 @@ def request_job_annotations(cvat_id: int, format_name: str) -> bool: def get_job_annotations( - cvat_id: int, format_name: str, *, timeout: Optional[int] = _NOTSET + cvat_id: int, format_name: str, *, timeout: int | None = _NOTSET ) -> io.RawIOBase: """ Downloads annotations. @@ -509,13 +509,13 @@ def delete_cloudstorage(cvat_id: int) -> None: raise -def fetch_projects(assignee: str = "") -> List[models.ProjectRead]: +def fetch_projects(assignee: str = "") -> list[models.ProjectRead]: logger = logging.getLogger("app") with get_api_client() as api_client: try: return get_paginated_collection( api_client.projects_api.list_endpoint, - **(dict(assignee=assignee) if assignee else {}), + **({"assignee": assignee} if assignee else {}), ) except exceptions.ApiException as e: logger.exception(f"Exception when calling ProjectsApi.list(): {e}\n") @@ -529,7 +529,7 @@ class UploadStatus(str, Enum, metaclass=BetterEnumMeta): FAILED = "Failed" -def get_task_upload_status(cvat_id: int) -> Tuple[Optional[UploadStatus], str]: +def get_task_upload_status(cvat_id: int) -> tuple[UploadStatus | None, str]: logger = logging.getLogger("app") with get_api_client() as api_client: @@ -557,13 +557,13 @@ def clear_job_annotations(job_id: int) -> None: ) except exceptions.ApiException as e: if e.status == 404: - return None + return logger.exception(f"Exception when calling JobsApi.partial_update_annotations(): {e}\n") raise -def update_job_assignee(id: str, assignee_id: Optional[int]): +def update_job_assignee(id: str, assignee_id: int | None): logger = logging.getLogger("app") with get_api_client() as api_client: @@ -577,7 +577,7 @@ def update_job_assignee(id: str, assignee_id: Optional[int]): raise -def restart_job(id: str, *, assignee_id: Optional[int] = None): +def restart_job(id: str, *, assignee_id: int | None = None): logger = logging.getLogger("app") with get_api_client() as api_client: @@ -615,7 +615,7 @@ def remove_user_from_org(user_id: int): with get_api_client() as api_client: try: (page, _) = api_client.users_api.list( - filter='{"==":[{"var":"id"},"%s"]}' % (user_id,), + filter='{"==":[{"var":"id"},"%s"]}' % user_id, # noqa: UP031 org=Config.cvat_config.cvat_org_slug, ) if not page.results: diff --git a/packages/examples/cvat/exchange-oracle/src/db/__init__.py b/packages/examples/cvat/exchange-oracle/src/db/__init__.py index 6e9c85cded..68068770e3 100644 --- a/packages/examples/cvat/exchange-oracle/src/db/__init__.py +++ b/packages/examples/cvat/exchange-oracle/src/db/__init__.py @@ -8,7 +8,7 @@ engine = sqlalchemy.create_engine( DATABASE_URL, echo="debug" if Config.loglevel <= src.utils.logging.TRACE else False, - connect_args={"options": "-c lock_timeout={:d}".format(Config.postgres_config.lock_timeout)}, + connect_args={"options": f"-c lock_timeout={Config.postgres_config.lock_timeout:d}"}, ) SessionLocal = sessionmaker(autocommit=False, bind=engine) diff --git a/packages/examples/cvat/exchange-oracle/src/db/errors.py b/packages/examples/cvat/exchange-oracle/src/db/errors.py index 9eeb655405..fbd7606bca 100644 --- a/packages/examples/cvat/exchange-oracle/src/db/errors.py +++ b/packages/examples/cvat/exchange-oracle/src/db/errors.py @@ -3,6 +3,8 @@ if db_engine.driver != "psycopg2": raise NotImplementedError +__all__ = ["LockNotAvailable"] + from psycopg2.errors import LockNotAvailable # These errors can be found, e.g., in the .orig field of sqlalchemy errors diff --git a/packages/examples/cvat/exchange-oracle/src/db/utils.py b/packages/examples/cvat/exchange-oracle/src/db/utils.py index 24dfb41561..77651fa42a 100644 --- a/packages/examples/cvat/exchange-oracle/src/db/utils.py +++ b/packages/examples/cvat/exchange-oracle/src/db/utils.py @@ -1,5 +1,5 @@ from dataclasses import dataclass -from typing import TypeVar, Union +from typing import TypeVar from sqlalchemy import Select from sqlalchemy.orm import Query @@ -14,14 +14,11 @@ class ForUpdateParams: T = TypeVar("T", Query, Select) -def maybe_for_update(query: T, enable: Union[bool, ForUpdateParams]) -> T: +def maybe_for_update(query: T, enable: bool | ForUpdateParams) -> T: if not enable: return query - if isinstance(enable, ForUpdateParams): - params = enable - else: - params = ForUpdateParams() + params = enable if isinstance(enable, ForUpdateParams) else ForUpdateParams() return query.with_for_update( skip_locked=params.skip_locked, diff --git a/packages/examples/cvat/exchange-oracle/src/endpoints/__init__.py b/packages/examples/cvat/exchange-oracle/src/endpoints/__init__.py index b4466bee8b..8845a4b52c 100644 --- a/packages/examples/cvat/exchange-oracle/src/endpoints/__init__.py +++ b/packages/examples/cvat/exchange-oracle/src/endpoints/__init__.py @@ -1,4 +1,5 @@ -""" API endpoints """ +"""API endpoints""" + from fastapi import APIRouter, FastAPI from src.core.config import Config @@ -24,11 +25,11 @@ def meta_route() -> MetaResponse: ] return MetaResponse.parse_obj( - dict( - message="Exchange Oracle API", - version="0.1.0", - supported_networks=networks_info, - ) + { + "message": "Exchange Oracle API", + "version": "0.1.0", + "supported_networks": networks_info, + } ) diff --git a/packages/examples/cvat/exchange-oracle/src/endpoints/exchange.py b/packages/examples/cvat/exchange-oracle/src/endpoints/exchange.py index fabeb3543f..0d3f3ab087 100644 --- a/packages/examples/cvat/exchange-oracle/src/endpoints/exchange.py +++ b/packages/examples/cvat/exchange-oracle/src/endpoints/exchange.py @@ -1,6 +1,5 @@ from contextlib import suppress from http import HTTPStatus -from typing import Optional from fastapi import APIRouter, Header, HTTPException, Path, Query @@ -16,7 +15,7 @@ @router.get("/tasks", description="Lists available tasks") async def list_tasks( - wallet_address: Optional[str] = Query(default=None), + wallet_address: str | None = Query(default=None), signature: str = Header(description="Calling service signature"), ) -> list[TaskResponse]: await validate_human_app_signature(signature) @@ -57,7 +56,7 @@ async def register( status_code=HTTPStatus.NOT_FOUND, detail="User with this email not found" ) from e - elif ( + if ( e.status == HTTPStatus.BAD_REQUEST and "The user is a member of the organization already." in e.body ): @@ -67,9 +66,7 @@ async def register( status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail="User already exists" ) - elif ( - e.status == HTTPStatus.BAD_REQUEST and "Enter a valid email address." in e.body - ): + if e.status == HTTPStatus.BAD_REQUEST and "Enter a valid email address." in e.body: raise HTTPException( status_code=HTTPStatus.BAD_REQUEST, detail="Invalid email address" ) diff --git a/packages/examples/cvat/exchange-oracle/src/endpoints/middleware.py b/packages/examples/cvat/exchange-oracle/src/endpoints/middleware.py index a346eddcc6..e111f1e2f3 100644 --- a/packages/examples/cvat/exchange-oracle/src/endpoints/middleware.py +++ b/packages/examples/cvat/exchange-oracle/src/endpoints/middleware.py @@ -1,6 +1,7 @@ import json import time -from typing import Any, Callable +from collections.abc import Callable +from typing import Any import fastapi import packaging.version as pv @@ -61,7 +62,7 @@ class RequestLoggingMiddleware(BaseHTTPMiddleware): """ @staticmethod - async def _set_body(request: Request, body: bytes): + async def _set_body(request: Request, body: bytes) -> None: # Before FastAPI 0.108.0 infinite hang is expected, # if request body is awaited more than once. # It's not needed when using FastAPI >= 0.108.0. @@ -119,7 +120,7 @@ async def _log_request(self, request: Request) -> dict[str, Any]: try: body = await request.body() await self._set_body(request, body) - except Exception: + except Exception: # noqa: BLE001 body = None else: if body is not None: @@ -188,7 +189,7 @@ async def _execute_request(self, call_next: Callable, request: Request) -> Respo except Exception as e: self.logger.exception({"path": request.url.path, "method": request.method, "reason": e}) - raise e + raise else: return response diff --git a/packages/examples/cvat/exchange-oracle/src/endpoints/webhook.py b/packages/examples/cvat/exchange-oracle/src/endpoints/webhook.py index a770ce7c1f..8d8d34c432 100644 --- a/packages/examples/cvat/exchange-oracle/src/endpoints/webhook.py +++ b/packages/examples/cvat/exchange-oracle/src/endpoints/webhook.py @@ -1,5 +1,3 @@ -from typing import Union - from fastapi import APIRouter, Header, HTTPException, Request import src.services.webhook as oracle_db_service @@ -14,7 +12,7 @@ async def receive_oracle_webhook( webhook: OracleWebhook, request: Request, - human_signature: Union[str, None] = Header(default=None), + human_signature: str | None = Header(default=None), ) -> OracleWebhookResponse: try: sender_type = await validate_oracle_webhook_signature(request, human_signature, webhook) diff --git a/packages/examples/cvat/exchange-oracle/src/handlers/__init__.py b/packages/examples/cvat/exchange-oracle/src/handlers/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/examples/cvat/exchange-oracle/src/handlers/completed_escrows.py b/packages/examples/cvat/exchange-oracle/src/handlers/completed_escrows.py index 7e031f20a7..346d8eda29 100644 --- a/packages/examples/cvat/exchange-oracle/src/handlers/completed_escrows.py +++ b/packages/examples/cvat/exchange-oracle/src/handlers/completed_escrows.py @@ -2,8 +2,9 @@ import itertools import logging from collections import Counter +from collections.abc import Callable from functools import partial -from typing import Any, Callable, Dict, List, Optional +from typing import Any from datumaro.util import take_by from sqlalchemy import exc as sa_errors @@ -43,7 +44,7 @@ class _CompletedEscrowsHandler: 4. Prepares a webhook to recording oracle """ - def __init__(self, logger: Optional[logging.Logger]) -> None: + def __init__(self, logger: logging.Logger | None) -> None: self.logger = logger or NullLogger() def _download_with_retries( @@ -51,7 +52,7 @@ def _download_with_retries( download_callback: Callable[[], io.RawIOBase], retry_callback: Callable[[], Any], *, - max_attempts: Optional[int] = None, + max_attempts: int | None = None, ) -> io.RawIOBase: """ Sometimes CVAT downloading can fail with the 500 error. @@ -74,11 +75,12 @@ def _download_with_retries( retry_callback() else: raise + return None def _process_plain_escrows(self): logger = self.logger - plain_task_types = [t for t in TaskTypes if not t == TaskTypes.image_skeletons_from_boxes] + plain_task_types = [t for t in TaskTypes if t != TaskTypes.image_skeletons_from_boxes] with SessionLocal.begin() as session: completed_projects = cvat_service.get_projects_by_status( session, @@ -95,7 +97,7 @@ def _process_plain_escrows(self): # TODO: such escrows can fill all the queried completed projects # need to improve handling for such projects # (e.g. cancel depending on the escrow status) - logger.error( + logger.exception( "Failed to handle completed project id {} for escrow {}: {}".format( project.cvat_id, project.escrow_address, e ) @@ -113,7 +115,7 @@ def _process_plain_escrows(self): jobs = cvat_service.get_jobs_by_cvat_project_id(session, project.cvat_id) annotation_format = CVAT_EXPORT_FORMAT_MAPPING[project.job_type] - job_annotations: Dict[int, FileDescriptor] = {} + job_annotations: dict[int, FileDescriptor] = {} for jobs_batch in take_by( jobs, count=CronConfig.track_completed_escrows_jobs_downloading_batch_size @@ -170,7 +172,7 @@ def _process_plain_escrows(self): file=project_annotations_file, ) - annotation_files: List[FileDescriptor] = [] + annotation_files: list[FileDescriptor] = [] annotation_files.append(project_annotations_file_desc) annotation_metafile = prepare_annotation_metafile( @@ -253,10 +255,8 @@ def _process_skeletons_from_boxes_escrows(self): # TODO: such escrows can fill all the queried completed projects # need to improve handling for such projects # (e.g. cancel depending on the escrow status) - logger.error( - "Failed to handle completed projects for escrow {}: {}".format( - escrow_address, e - ) + logger.exception( + f"Failed to handle completed projects for escrow {escrow_address}: {e}" ) continue @@ -297,7 +297,7 @@ def _process_skeletons_from_boxes_escrows(self): f"Downloading results for the escrow (escrow_address={escrow_address})" ) - jobs: List[cvat_models.Job] = list( + jobs: list[cvat_models.Job] = list( itertools.chain.from_iterable( cvat_service.get_jobs_by_cvat_project_id(session, p.cvat_id) for p in escrow_projects @@ -305,7 +305,7 @@ def _process_skeletons_from_boxes_escrows(self): ) annotation_format = CVAT_EXPORT_FORMAT_MAPPING[manifest.annotation.type] - job_annotations: Dict[int, FileDescriptor] = {} + job_annotations: dict[int, FileDescriptor] = {} # Collect raw annotations from CVAT, validate and convert them # into a recording oracle suitable format @@ -347,7 +347,7 @@ def _process_skeletons_from_boxes_escrows(self): file=None, ) - annotation_files: List[FileDescriptor] = [] + annotation_files: list[FileDescriptor] = [] annotation_files.append(resulting_annotations_file_desc) annotation_metafile = prepare_annotation_metafile( diff --git a/packages/examples/cvat/exchange-oracle/src/handlers/cvat_events.py b/packages/examples/cvat/exchange-oracle/src/handlers/cvat_events.py index 96353138da..7076bc225f 100644 --- a/packages/examples/cvat/exchange-oracle/src/handlers/cvat_events.py +++ b/packages/examples/cvat/exchange-oracle/src/handlers/cvat_events.py @@ -1,5 +1,3 @@ -from typing import List - from dateutil.parser import parse as parse_aware_datetime from sqlalchemy import exc as sa_errors @@ -42,7 +40,7 @@ def handle_update_job_event(payload: dict) -> None: webhook_time = parse_aware_datetime(payload.job["updated_date"]) webhook_assignee_id = (payload.job["assignee"] or {}).get("id") - job_assignments: List[models.Assignment] = sorted( + job_assignments: list[models.Assignment] = sorted( job_assignments, key=lambda a: a.created_at, reverse=True ) latest_assignment = job.assignments[0] diff --git a/packages/examples/cvat/exchange-oracle/src/handlers/error_handlers.py b/packages/examples/cvat/exchange-oracle/src/handlers/error_handlers.py index 86d410aabb..d476e9af6a 100644 --- a/packages/examples/cvat/exchange-oracle/src/handlers/error_handlers.py +++ b/packages/examples/cvat/exchange-oracle/src/handlers/error_handlers.py @@ -1,4 +1,5 @@ -""" Custom error handlers for the FastAPI""" +"""Custom error handlers for the FastAPI""" + from fastapi import FastAPI from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse diff --git a/packages/examples/cvat/exchange-oracle/src/handlers/job_creation.py b/packages/examples/cvat/exchange-oracle/src/handlers/job_creation.py index e95435baa6..93532aba4b 100644 --- a/packages/examples/cvat/exchange-oracle/src/handlers/job_creation.py +++ b/packages/examples/cvat/exchange-oracle/src/handlers/job_creation.py @@ -6,10 +6,9 @@ from contextlib import ExitStack from dataclasses import dataclass, field from itertools import chain, groupby -from logging import Logger from math import ceil from tempfile import TemporaryDirectory -from typing import Dict, List, Optional, Sequence, Tuple, TypeVar, Union, cast +from typing import TYPE_CHECKING, TypeVar, Union, cast import cv2 import datumaro as dm @@ -26,7 +25,6 @@ import src.services.cvat as db_service from src.chain.escrow import get_escrow_manifest from src.core.config import Config -from src.core.manifest import TaskManifest from src.core.storage import compose_data_bucket_filename from src.core.types import CvatLabelTypes, TaskStatuses, TaskTypes from src.db import SessionLocal @@ -37,6 +35,12 @@ from src.utils.assignments import parse_manifest from src.utils.logging import NullLogger, get_function_logger +if TYPE_CHECKING: + from collections.abc import Sequence + from logging import Logger + + from src.core.manifest import TaskManifest + module_logger = f"{ROOT_LOGGER_NAME}.cron.cvat" LABEL_TYPE_MAPPING = { @@ -103,7 +107,7 @@ def __bool__(self) -> bool: _unset = _Undefined() -_MaybeUnset = Union[T, _Undefined] +_MaybeUnset = T | _Undefined @dataclass @@ -115,7 +119,7 @@ class _ExcludedAnnotationInfo: @dataclass class _ExcludedAnnotationsInfo: - messages: List[_ExcludedAnnotationInfo] = field(default_factory=list) + messages: list[_ExcludedAnnotationInfo] = field(default_factory=list) excluded_count: int = 0 "The number of excluded annotations. Can be different from len(messages)" @@ -135,7 +139,7 @@ class SimpleTaskBuilder: Handles task creation for IMAGE_POINTS and IMAGE_BOXES task types """ - def __init__(self, manifest: TaskManifest, escrow_address: str, chain_id: int): + def __init__(self, manifest: TaskManifest, escrow_address: str, chain_id: int) -> None: self.exit_stack = ExitStack() self.manifest = manifest self.escrow_address = escrow_address @@ -163,7 +167,7 @@ def set_logger(self, logger: Logger): return self def _format_list( - self, items: Sequence[str], *, max_items: int = None, separator: str = ", " + self, items: Sequence[str], *, max_items: int | None = None, separator: str = ", " ) -> str: if max_items is None: max_items = self.list_display_threshold @@ -198,7 +202,7 @@ def _upload_task_meta(self, gt_dataset: dm.Dataset): ) def _parse_gt_dataset( - self, gt_file_data: bytes, *, add_prefix: Optional[str] = None + self, gt_file_data: bytes, *, add_prefix: str | None = None ) -> dm.Dataset: with TemporaryDirectory() as gt_temp_dir: gt_filename = os.path.join(gt_temp_dir, "gt_annotations.json") @@ -222,8 +226,8 @@ def _parse_gt_dataset( return gt_dataset def _get_gt_filenames( - self, gt_dataset: dm.Dataset, data_filenames: List[str], *, manifest: TaskManifest - ) -> List[str]: + self, gt_dataset: dm.Dataset, data_filenames: list[str], *, manifest: TaskManifest + ) -> list[str]: gt_filenames = set(s.id + s.media.ext for s in gt_dataset) known_data_filenames = set(data_filenames) matched_gt_filenames = gt_filenames.intersection(known_data_filenames) @@ -246,14 +250,14 @@ def _get_gt_filenames( def _make_job_configuration( self, - data_filenames: List[str], - gt_filenames: List[str], + data_filenames: list[str], + gt_filenames: list[str], *, manifest: TaskManifest, - ) -> List[List[str]]: + ) -> list[list[str]]: # Make job layouts wrt. manifest params, 1 job per task (CVAT can't repeat images in jobs) gt_filenames_index = set(gt_filenames) - data_filenames = [fn for fn in data_filenames if not fn in gt_filenames_index] + data_filenames = [fn for fn in data_filenames if fn not in gt_filenames_index] random.shuffle(data_filenames) job_layout = [] @@ -357,7 +361,7 @@ def build(self): class BoxesFromPointsTaskBuilder: - def __init__(self, manifest: TaskManifest, escrow_address: str, chain_id: int): + def __init__(self, manifest: TaskManifest, escrow_address: str, chain_id: int) -> None: self.exit_stack = ExitStack() self.manifest = manifest self.escrow_address = escrow_address @@ -376,7 +380,7 @@ def __init__(self, manifest: TaskManifest, escrow_address: str, chain_id: int): self._bbox_point_mapping: _MaybeUnset[boxes_from_points_task.BboxPointMapping] = _unset "bbox_id -> point_id" - self._roi_size_estimations: _MaybeUnset[Dict[int, Tuple[float, float]]] = _unset + self._roi_size_estimations: _MaybeUnset[dict[int, tuple[float, float]]] = _unset "label_id -> (rel. w, rel. h)" self._rois: _MaybeUnset[boxes_from_points_task.RoiInfos] = _unset @@ -613,7 +617,7 @@ def _validate_gt(self): self._validate_gt_annotations() def _format_list( - self, items: Sequence[str], *, max_items: int = None, separator: str = ", " + self, items: Sequence[str], *, max_items: int | None = None, separator: str = ", " ) -> str: if max_items is None: max_items = self.list_display_threshold @@ -683,7 +687,7 @@ def _validate_skeleton(skeleton: dm.Skeleton, *, sample_bbox: dm.Bbox): if len(skeleton.elements) != 1: raise DatasetValidationError( - "invalid points count ({}), expected 1".format(len(skeleton.elements)) + f"invalid points count ({len(skeleton.elements)}), expected 1" ) point = skeleton.elements[0] @@ -776,9 +780,9 @@ def _is_point_in_bbox(px: float, py: float, bbox: dm.Bbox) -> bool: def _prepare_gt(self): def _find_unambiguous_matches( - input_skeletons: List[dm.Skeleton], - gt_boxes: List[dm.Bbox], - ) -> List[Tuple[dm.Skeleton, dm.Bbox]]: + input_skeletons: list[dm.Skeleton], + gt_boxes: list[dm.Bbox], + ) -> list[tuple[dm.Skeleton, dm.Bbox]]: matches = [ [ (input_skeleton.label == gt_bbox.label) @@ -795,7 +799,7 @@ def _find_unambiguous_matches( ambiguous_boxes: list[int] = set() ambiguous_skeletons: list[int] = set() for skeleton_idx, input_skeleton in enumerate(input_skeletons): - matched_boxes: List[dm.Bbox] = [ + matched_boxes: list[dm.Bbox] = [ gt_boxes[j] for j in range(len(gt_boxes)) if matches[skeleton_idx][j] ] @@ -818,7 +822,7 @@ def _find_unambiguous_matches( continue for gt_idx, gt_bbox in enumerate(gt_boxes): - matched_skeletons: List[dm.Skeleton] = [ + matched_skeletons: list[dm.Skeleton] = [ input_skeletons[i] for i in range(len(input_skeletons)) if matches[i][gt_idx] ] @@ -839,7 +843,7 @@ def _find_unambiguous_matches( ambiguous_boxes.add(gt_bbox.id) ambiguous_skeletons.update(a.id for a in matched_skeletons) continue - elif not matched_skeletons: + if not matched_skeletons: # Handle unmatched skeletons excluded_gt_info.add_message( "Sample '{}': GT bbox #{} ({}) skipped - " @@ -854,7 +858,7 @@ def _find_unambiguous_matches( excluded_gt_info.excluded_count += 1 # an error continue - unambiguous_matches: List[Tuple[dm.Bbox, dm.Skeleton]] = [] + unambiguous_matches: list[tuple[dm.Bbox, dm.Skeleton]] = [] for skeleton_idx, input_skeleton in enumerate(input_skeletons): if input_skeleton.id in ambiguous_skeletons: continue @@ -874,9 +878,9 @@ def _find_unambiguous_matches( return unambiguous_matches def _find_good_gt_boxes( - input_skeletons: List[dm.Skeleton], - gt_boxes: List[dm.Bbox], - ) -> List[dm.Bbox]: + input_skeletons: list[dm.Skeleton], + gt_boxes: list[dm.Bbox], + ) -> list[dm.Bbox]: matches = _find_unambiguous_matches(input_skeletons, gt_boxes) matched_boxes = [] @@ -1030,7 +1034,7 @@ def _estimate_roi_sizes(self): if classes_with_default_roi: label_cat = self._gt_dataset.categories()[dm.AnnotationType.label] labels_by_reason = { - g_reason: list(v[0] for v in g_items) + g_reason: [v[0] for v in g_items] for g_reason, g_items in groupby( sorted(classes_with_default_roi.items(), key=lambda v: v[1]), key=lambda v: v[1] ) @@ -1054,7 +1058,7 @@ def _prepare_roi_info(self): assert self._roi_size_estimations is not _unset assert self._points_dataset is not _unset - rois: List[boxes_from_points_task.RoiInfo] = [] + rois: list[boxes_from_points_task.RoiInfo] = [] for sample in self._points_dataset: for skeleton in sample.annotations: if not isinstance(skeleton, dm.Skeleton): @@ -1133,9 +1137,9 @@ def _prepare_job_layout(self): data_filenames = [ fn for point_id, fn in self._roi_filenames.items() - if not point_id in gt_point_ids - if not original_image_id_to_filename[point_id_to_original_image_id[point_id]] - in input_gt_filenames + if point_id not in gt_point_ids + if original_image_id_to_filename[point_id_to_original_image_id[point_id]] + not in input_gt_filenames ] random.shuffle(data_filenames) @@ -1234,7 +1238,7 @@ def _draw_roi_point( (255, 255, 255), cv2.FILLED, ) - roi_pixels = cv2.circle( + return cv2.circle( roi_pixels, center, point_size, @@ -1242,10 +1246,9 @@ def _draw_roi_point( cv2.FILLED, ) - return roi_pixels - def _extract_and_upload_rois(self): - # TODO: maybe optimize via splitting into separate threads (downloading, uploading, processing) + # TODO: maybe optimize via splitting into separate + # threads (downloading, uploading, processing) # Watch for the memory used, as the whole dataset can be quite big (gigabytes, terabytes) # Consider also packing RoIs cut into archives @@ -1267,8 +1270,10 @@ def _extract_and_upload_rois(self): filename_to_sample = {sample.image.path: sample for sample in self._points_dataset} - _roi_key = lambda e: e.original_image_key - rois_by_image: Dict[str, Sequence[boxes_from_points_task.RoiInfo]] = { + def _roi_key(e): + return e.original_image_key + + rois_by_image: dict[str, Sequence[boxes_from_points_task.RoiInfo]] = { image_id_to_filename[image_id]: list(g) for image_id, g in groupby(sorted(self._rois, key=_roi_key), key=_roi_key) } @@ -1420,9 +1425,9 @@ class SkeletonsFromBoxesTaskBuilder: @dataclass class _JobParams: label_id: int - roi_ids: List[int] + roi_ids: list[int] - def __init__(self, manifest: TaskManifest, escrow_address: str, chain_id: int): + def __init__(self, manifest: TaskManifest, escrow_address: str, chain_id: int) -> None: self.exit_stack = ExitStack() self.manifest = manifest self.escrow_address = escrow_address @@ -1438,12 +1443,12 @@ def __init__(self, manifest: TaskManifest, escrow_address: str, chain_id: int): self._gt_dataset: _MaybeUnset[dm.Dataset] = _unset self._boxes_dataset: _MaybeUnset[dm.Dataset] = _unset - self._skeleton_bbox_mapping: _MaybeUnset[ - skeletons_from_boxes_task.SkeletonBboxMapping - ] = _unset + self._skeleton_bbox_mapping: _MaybeUnset[skeletons_from_boxes_task.SkeletonBboxMapping] = ( + _unset + ) self._roi_infos: _MaybeUnset[skeletons_from_boxes_task.RoiInfos] = _unset - self._roi_filenames: _MaybeUnset[Dict[int, str]] = _unset - self._job_params: _MaybeUnset[List[self._JobParams]] = _unset + self._roi_filenames: _MaybeUnset[dict[int, str]] = _unset + self._job_params: _MaybeUnset[list[self._JobParams]] = _unset self._excluded_gt_info: _MaybeUnset[_ExcludedAnnotationsInfo] = _unset self._excluded_boxes_info: _MaybeUnset[_ExcludedAnnotationsInfo] = _unset @@ -1603,7 +1608,8 @@ def _validate_skeleton(skeleton: dm.Skeleton, *, sample_bbox: dm.Bbox): for element in skeleton.elements: # This is what Datumaro is expected to parse - assert len(element.points) == 2 and len(element.visibility) == 1 + assert len(element.points) == 2 + assert len(element.visibility) == 1 if element.visibility[0] == dm.Points.Visibility.absent: continue @@ -1806,7 +1812,7 @@ def _validate_boxes(self): self._validate_boxes_annotations() def _format_list( - self, items: Sequence[str], *, max_items: int = None, separator: str = ", " + self, items: Sequence[str], *, max_items: int | None = None, separator: str = ", " ) -> str: if max_items is None: max_items = self.list_display_threshold @@ -1849,11 +1855,11 @@ def _get_skeleton_bbox( def _prepare_gt(self): def _find_unambiguous_matches( - input_boxes: List[dm.Bbox], - gt_skeletons: List[dm.Skeleton], + input_boxes: list[dm.Bbox], + gt_skeletons: list[dm.Skeleton], *, - gt_annotations: List[dm.Annotation], - ) -> List[Tuple[dm.Bbox, dm.Skeleton]]: + gt_annotations: list[dm.Annotation], + ) -> list[tuple[dm.Bbox, dm.Skeleton]]: matches = [ [ (input_bbox.label == gt_skeleton.label) @@ -1871,7 +1877,7 @@ def _find_unambiguous_matches( ambiguous_boxes: list[int] = set() ambiguous_skeletons: list[int] = set() for bbox_idx, input_bbox in enumerate(input_boxes): - matched_skeletons: List[dm.Skeleton] = [ + matched_skeletons: list[dm.Skeleton] = [ gt_skeletons[j] for j in range(len(gt_skeletons)) if matches[bbox_idx][j] ] @@ -1894,7 +1900,7 @@ def _find_unambiguous_matches( continue for skeleton_idx, gt_skeleton in enumerate(gt_skeletons): - matched_boxes: List[dm.Bbox] = [ + matched_boxes: list[dm.Bbox] = [ input_boxes[i] for i in range(len(input_boxes)) if matches[i][skeleton_idx] ] @@ -1915,7 +1921,7 @@ def _find_unambiguous_matches( ambiguous_skeletons.add(gt_skeleton.id) ambiguous_boxes.update(b.id for b in matched_boxes) continue - elif not matched_boxes: + if not matched_boxes: # Handle unmatched skeletons excluded_gt_info.add_message( "Sample '{}': GT skeleton #{} ({}) skipped - " @@ -1930,7 +1936,7 @@ def _find_unambiguous_matches( excluded_gt_info.excluded_count += 1 # an error continue - unambiguous_matches: List[Tuple[dm.Bbox, dm.Skeleton]] = [] + unambiguous_matches: list[tuple[dm.Bbox, dm.Skeleton]] = [] for bbox_idx, input_bbox in enumerate(input_boxes): if input_bbox.id in ambiguous_boxes: continue @@ -1950,11 +1956,11 @@ def _find_unambiguous_matches( return unambiguous_matches def _find_good_gt_skeletons( - input_boxes: List[dm.Bbox], - gt_skeletons: List[dm.Skeleton], + input_boxes: list[dm.Bbox], + gt_skeletons: list[dm.Skeleton], *, - gt_annotations: List[dm.Annotation], - ) -> List[dm.Bbox]: + gt_annotations: list[dm.Annotation], + ) -> list[dm.Bbox]: matches = _find_unambiguous_matches( input_boxes, gt_skeletons, gt_annotations=gt_annotations ) @@ -2080,7 +2086,7 @@ def _prepare_roi_infos(self): assert self._gt_dataset is not _unset assert self._boxes_dataset is not _unset - rois: List[skeletons_from_boxes_task.RoiInfo] = [] + rois: list[skeletons_from_boxes_task.RoiInfo] = [] for sample in self._boxes_dataset: for bbox in sample.annotations: if not isinstance(bbox, dm.Bbox): @@ -2150,7 +2156,7 @@ def _prepare_job_params(self): gt_ratio = self.manifest.validation.val_size / (self.manifest.annotation.job_size or 1) job_size_mult = self.job_size_mult - job_params: List[self._JobParams] = [] + job_params: list[self._JobParams] = [] roi_info_by_id = {roi_info.bbox_id: roi_info for roi_info in self._roi_infos} for label_id, _ in enumerate(self.manifest.annotation.labels): @@ -2289,8 +2295,10 @@ def _extract_and_upload_rois(self): filename_to_sample = {sample.image.path: sample for sample in self._boxes_dataset} - _roi_info_key = lambda e: e.original_image_key - roi_info_by_image: Dict[str, Sequence[skeletons_from_boxes_task.RoiInfo]] = { + def _roi_info_key(e): + return e.original_image_key + + roi_info_by_image: dict[str, Sequence[skeletons_from_boxes_task.RoiInfo]] = { image_id_to_filename[image_id]: list(g) for image_id, g in groupby( sorted(self._roi_infos, key=_roi_info_key), key=_roi_info_key @@ -2339,7 +2347,9 @@ def _create_on_cvat(self): assert self._job_params is not _unset assert self.point_labels is not _unset - _job_params_label_key = lambda ts: ts.label_id + def _job_params_label_key(ts): + return ts.label_id + jobs_by_skeleton_label = { skeleton_label_id: list(g) for skeleton_label_id, g in groupby( @@ -2386,7 +2396,7 @@ def _create_on_cvat(self): # Each skeleton point uses the same file layout in jobs skeleton_label_filenames = [] for skeleton_label_job in skeleton_label_jobs: - skeleton_label_filenames.append( + skeleton_label_filenames.append( # noqa: PERF401 [ compose_data_bucket_filename( self.escrow_address, self.chain_id, self._roi_filenames[roi_id] @@ -2444,8 +2454,10 @@ def _create_on_cvat(self): ) db_service.get_task_by_id(session, task_id, for_update=True) # lock the row - # Actual task creation in CVAT takes some time, so it's done in an async process. - # The task is fully created once 'update:task' or 'update:job' webhook is received. + # Actual task creation in CVAT takes some time, + # so it's done in an async process. + # The task is fully created once 'update:task' or 'update:job' + # webhook is received. cvat_api.put_task_data( cvat_task.id, cvat_cloud_storage.id, @@ -2485,15 +2497,15 @@ def is_image(path: str) -> bool: return trunk and ext.lower() in IMAGE_EXTENSIONS -def filter_image_files(data_filenames: List[str]) -> List[str]: - return list(fn for fn in data_filenames if is_image(fn)) +def filter_image_files(data_filenames: list[str]) -> list[str]: + return [fn for fn in data_filenames if is_image(fn)] -def strip_bucket_prefix(data_filenames: List[str], prefix: str) -> List[str]: - return list(os.path.relpath(fn, prefix) for fn in data_filenames) +def strip_bucket_prefix(data_filenames: list[str], prefix: str) -> list[str]: + return [os.path.relpath(fn, prefix) for fn in data_filenames] -def make_label_configuration(manifest: TaskManifest) -> List[dict]: +def make_label_configuration(manifest: TaskManifest) -> list[dict]: return [ { "name": label.name, @@ -2503,7 +2515,7 @@ def make_label_configuration(manifest: TaskManifest) -> List[dict]: ] -def _make_cvat_cloud_storage_params(bucket_info: BucketAccessInfo) -> Dict: +def _make_cvat_cloud_storage_params(bucket_info: BucketAccessInfo) -> dict: CLOUD_PROVIDER_TO_CVAT_CLOUD_PROVIDER = { CloudProviders.aws: "AWS_S3_BUCKET", CloudProviders.gcs: "GOOGLE_CLOUD_STORAGE", diff --git a/packages/examples/cvat/exchange-oracle/src/handlers/job_export.py b/packages/examples/cvat/exchange-oracle/src/handlers/job_export.py index 8a1df6cac1..a175d58bbd 100644 --- a/packages/examples/cvat/exchange-oracle/src/handlers/job_export.py +++ b/packages/examples/cvat/exchange-oracle/src/handlers/job_export.py @@ -3,7 +3,6 @@ import zipfile from dataclasses import dataclass from tempfile import TemporaryDirectory -from typing import Dict, List, Optional, Type import datumaro as dm from datumaro.components.dataset import Dataset @@ -39,11 +38,11 @@ @dataclass class FileDescriptor: filename: str - file: Optional[io.RawIOBase] + file: io.RawIOBase | None def prepare_annotation_metafile( - jobs: List[Job], job_annotations: Dict[int, FileDescriptor] + jobs: list[Job], job_annotations: dict[int, FileDescriptor] ) -> FileDescriptor: """ Prepares a task/project annotation descriptor file with annotator mapping. @@ -69,12 +68,12 @@ def __init__( self, escrow_address: str, chain_id: int, - annotations: List[FileDescriptor], + annotations: list[FileDescriptor], merged_annotation: FileDescriptor, *, manifest: TaskManifest, - project_images: List[Image], - ): + project_images: list[Image], + ) -> None: self.escrow_address = escrow_address self.chain_id = chain_id self.annotation_files = annotations @@ -123,7 +122,7 @@ def _process_annotation_file( output_dataset = self._process_dataset(input_dataset, ann_descriptor=ann_descriptor) self._export_dataset(output_dataset, output_dir) - def _parse_dataset(self, ann_descriptor: FileDescriptor, dataset_dir: str) -> dm.Dataset: + def _parse_dataset(self, ann_descriptor: FileDescriptor, dataset_dir: str) -> dm.Dataset: # noqa: ARG002 return dm.Dataset.import_from(dataset_dir, self.input_format) def _export_dataset(self, dataset: dm.Dataset, output_dir: str): @@ -176,7 +175,7 @@ def _process_dataset(self, dataset: Dataset, *, ann_descriptor: FileDescriptor) class _BoxesFromPointsTaskProcessor(_TaskProcessor): - def __init__(self, *args, **kwargs): + def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) roi_filenames, roi_infos, points_dataset = self._download_task_meta() @@ -186,7 +185,7 @@ def __init__(self, *args, **kwargs): roi_info_by_id = {roi_info.point_id: roi_info for roi_info in roi_infos} - self.roi_name_to_roi_info: Dict[str, boxes_from_points_task.RoiInfo] = { + self.roi_name_to_roi_info: dict[str, boxes_from_points_task.RoiInfo] = { os.path.splitext(roi_filename)[0]: roi_info_by_id[roi_id] for roi_id, roi_filename in roi_filenames.items() } @@ -271,7 +270,7 @@ def _process_merged_dataset(self, input_dataset: Dataset) -> Dataset: class _SkeletonsFromBoxesTaskProcessor(_TaskProcessor): - def __init__(self, *args, **kwargs): + def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) roi_filenames, roi_infos, boxes_dataset, job_label_mapping = self._download_task_meta() @@ -281,7 +280,7 @@ def __init__(self, *args, **kwargs): roi_info_by_id = {roi_info.bbox_id: roi_info for roi_info in roi_infos} - self.roi_name_to_roi_info: Dict[str, skeletons_from_boxes_task.RoiInfo] = { + self.roi_name_to_roi_info: dict[str, skeletons_from_boxes_task.RoiInfo] = { os.path.splitext(roi_filename)[0]: roi_info_by_id[roi_id] for roi_id, roi_filename in roi_filenames.items() } @@ -503,7 +502,7 @@ def _process_dataset(self, dataset: Dataset, *, ann_descriptor: FileDescriptor) skeleton_bbox.group = skeleton_group skeleton_bbox.label = converted_skeleton.label converted_job_dataset.put( - converted_sample.wrap(annotations=converted_sample.annotations + [skeleton_bbox]) + converted_sample.wrap(annotations=[*converted_sample.annotations, skeleton_bbox]) ) # Rename the job skeleton and point to the original names @@ -572,16 +571,16 @@ def process(self): def postprocess_annotations( escrow_address: str, chain_id: int, - annotations: List[FileDescriptor], + annotations: list[FileDescriptor], merged_annotation: FileDescriptor, *, manifest: TaskManifest, - project_images: List[Image], + project_images: list[Image], ) -> None: """ Processes annotations and updates the files list inplace """ - processor_classes: Dict[TaskTypes, Type[_TaskProcessor]] = { + processor_classes: dict[TaskTypes, type[_TaskProcessor]] = { TaskTypes.image_label_binary: _LabelsTaskProcessor, TaskTypes.image_boxes: _BoxesTaskProcessor, TaskTypes.image_points: _PointsTaskProcessor, diff --git a/packages/examples/cvat/exchange-oracle/src/log.py b/packages/examples/cvat/exchange-oracle/src/log.py index 5f5ab8983a..09349ef6f4 100644 --- a/packages/examples/cvat/exchange-oracle/src/log.py +++ b/packages/examples/cvat/exchange-oracle/src/log.py @@ -1,4 +1,5 @@ -""" Config for the application logger""" +"""Config for the application logger""" + import logging from logging.config import dictConfig diff --git a/packages/examples/cvat/exchange-oracle/src/models/__init__.py b/packages/examples/cvat/exchange-oracle/src/models/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/examples/cvat/exchange-oracle/src/models/cvat.py b/packages/examples/cvat/exchange-oracle/src/models/cvat.py index 71678b520d..ad4c6769bf 100644 --- a/packages/examples/cvat/exchange-oracle/src/models/cvat.py +++ b/packages/examples/cvat/exchange-oracle/src/models/cvat.py @@ -1,8 +1,6 @@ # pylint: disable=too-few-public-methods from __future__ import annotations -from typing import List, Optional - from sqlalchemy import Column, DateTime, Enum, ForeignKey, Integer, String, UniqueConstraint from sqlalchemy.orm import Mapped, relationship from sqlalchemy.sql import func @@ -35,23 +33,23 @@ class Project(Base): updated_at = Column(DateTime(timezone=True), onupdate=func.now()) cvat_webhook_id = Column(Integer, nullable=True) - images: Mapped[List["Image"]] = relationship( + images: Mapped[list[Image]] = relationship( back_populates="project", cascade="all, delete", passive_deletes=True ) - tasks: Mapped[List["Task"]] = relationship( + tasks: Mapped[list[Task]] = relationship( back_populates="project", cascade="all, delete", passive_deletes=True, ) - jobs: Mapped[List["Job"]] = relationship( + jobs: Mapped[list[Job]] = relationship( back_populates="project", cascade="all, delete", passive_deletes=True, ) - escrow_creation: Mapped["EscrowCreation"] = relationship( + escrow_creation: Mapped[EscrowCreation] = relationship( back_populates="projects", passive_deletes=True, # A custom join is used because the foreign keys do not actually reference any objects @@ -64,7 +62,7 @@ class Project(Base): foreign_keys=[escrow_address, chain_id], ) - def __repr__(self): + def __repr__(self) -> str: return f"Project. id={self.id}" @@ -81,17 +79,17 @@ class Task(Base): created_at = Column(DateTime(timezone=True), server_default=func.now()) updated_at = Column(DateTime(timezone=True), onupdate=func.now()) - project: Mapped["Project"] = relationship(back_populates="tasks") - jobs: Mapped[List["Job"]] = relationship( + project: Mapped[Project] = relationship(back_populates="tasks") + jobs: Mapped[list[Job]] = relationship( back_populates="task", cascade="all, delete", passive_deletes=True, ) - data_upload: Mapped["DataUpload"] = relationship( + data_upload: Mapped[DataUpload] = relationship( back_populates="task", cascade="all, delete", passive_deletes=True ) - def __repr__(self): + def __repr__(self) -> str: return f"Task. id={self.id}" @@ -108,7 +106,7 @@ class EscrowCreation(Base): total_jobs = Column(Integer, nullable=False) - projects: Mapped[List["Project"]] = relationship( + projects: Mapped[list[Project]] = relationship( back_populates="escrow_creation", # A custom join is used because the foreign keys do not actually reference any objects primaryjoin=( @@ -120,7 +118,7 @@ class EscrowCreation(Base): foreign_keys=[Project.escrow_address, Project.chain_id], ) - def __repr__(self): + def __repr__(self) -> str: return f"EscrowCreation. id={self.id} escrow={self.escrow_address}" @@ -135,9 +133,9 @@ class DataUpload(Base): nullable=False, ) - task: Mapped["Task"] = relationship(back_populates="data_upload") + task: Mapped[Task] = relationship(back_populates="data_upload") - def __repr__(self): + def __repr__(self) -> str: return f"DataUpload. id={self.id} task={self.task_id}" @@ -155,9 +153,9 @@ class Job(Base): created_at = Column(DateTime(timezone=True), server_default=func.now()) updated_at = Column(DateTime(timezone=True), onupdate=func.now()) - task: Mapped["Task"] = relationship(back_populates="jobs") - project: Mapped["Project"] = relationship(back_populates="jobs") - assignments: Mapped[List["Assignment"]] = relationship( + task: Mapped[Task] = relationship(back_populates="jobs") + project: Mapped[Project] = relationship(back_populates="jobs") + assignments: Mapped[list[Assignment]] = relationship( back_populates="job", cascade="all, delete", passive_deletes=True, @@ -165,11 +163,11 @@ class Job(Base): ) @property - def latest_assignment(self) -> Optional[Assignment]: + def latest_assignment(self) -> Assignment | None: assignments = self.assignments return assignments[0] if assignments else None - def __repr__(self): + def __repr__(self) -> str: return f"Job. id={self.id}" @@ -179,11 +177,11 @@ class User(Base): cvat_email = Column(String, unique=True, index=True, nullable=True) cvat_id = Column(Integer, unique=True, index=True, nullable=True) - assignments: Mapped[List["Assignment"]] = relationship( + assignments: Mapped[list[Assignment]] = relationship( back_populates="user", cascade="all, delete", passive_deletes=True ) - def __repr__(self): + def __repr__(self) -> str: return f"User. wallet_address={self.wallet_address} cvat_id={self.cvat_id}" @@ -206,8 +204,8 @@ class Assignment(Base): nullable=False, ) - user: Mapped["User"] = relationship(back_populates="assignments") - job: Mapped["Job"] = relationship(back_populates="assignments") + user: Mapped[User] = relationship(back_populates="assignments") + job: Mapped[Job] = relationship(back_populates="assignments") @property def is_finished(self) -> bool: @@ -217,7 +215,7 @@ def is_finished(self) -> bool: or self.status != AssignmentStatuses.created ) - def __repr__(self): + def __repr__(self) -> str: return f"Assignment. id={self.id} user={self.user.cvat_id} job={self.job.cvat_id}" @@ -231,11 +229,11 @@ class Image(Base): ) filename = Column(String, nullable=False) - project: Mapped["Project"] = relationship(back_populates="images") + project: Mapped[Project] = relationship(back_populates="images") __table_args__ = (UniqueConstraint("cvat_project_id", "filename", name="_project_filename_uc"),) - def __repr__(self): + def __repr__(self) -> str: return ( f"Image. id={self.id} cvat_project_id={self.cvat_project_id} filename={self.filename}" ) diff --git a/packages/examples/cvat/exchange-oracle/src/models/webhook.py b/packages/examples/cvat/exchange-oracle/src/models/webhook.py index 10c4bec69c..64ca2fb0e7 100644 --- a/packages/examples/cvat/exchange-oracle/src/models/webhook.py +++ b/packages/examples/cvat/exchange-oracle/src/models/webhook.py @@ -26,5 +26,5 @@ class Webhook(Base): event_data = Column(JSON, nullable=True, server_default=None) direction = Column(String, nullable=False) - def __repr__(self): + def __repr__(self) -> str: return f"Webhook. id={self.id} type={self.type}.{self.event_type}" diff --git a/packages/examples/cvat/exchange-oracle/src/schemas/__init__.py b/packages/examples/cvat/exchange-oracle/src/schemas/__init__.py index d3d08c0dd9..e26cbee23e 100644 --- a/packages/examples/cvat/exchange-oracle/src/schemas/__init__.py +++ b/packages/examples/cvat/exchange-oracle/src/schemas/__init__.py @@ -1,8 +1,4 @@ -# pylint: disable=too-few-public-methods - -""" Schema for API input&output""" - -from typing import List, Optional +"""Schema for API input&output""" from pydantic import BaseModel @@ -28,7 +24,7 @@ class ResponseError(BaseModel): class SupportedNetwork(BaseModel): chain_id: int - addr: Optional[str] + addr: str | None class MetaResponse(BaseModel): @@ -36,4 +32,4 @@ class MetaResponse(BaseModel): message: str version: str - supported_networks: List[SupportedNetwork] + supported_networks: list[SupportedNetwork] diff --git a/packages/examples/cvat/exchange-oracle/src/schemas/cvat.py b/packages/examples/cvat/exchange-oracle/src/schemas/cvat.py index e7b7252802..36cc946948 100644 --- a/packages/examples/cvat/exchange-oracle/src/schemas/cvat.py +++ b/packages/examples/cvat/exchange-oracle/src/schemas/cvat.py @@ -1,10 +1,8 @@ -from typing import Optional - from pydantic import BaseModel class CvatWebhook(BaseModel): event: str - job: Optional[dict] - task: Optional[dict] - before_update: Optional[dict] + job: dict | None + task: dict | None + before_update: dict | None diff --git a/packages/examples/cvat/exchange-oracle/src/schemas/exchange.py b/packages/examples/cvat/exchange-oracle/src/schemas/exchange.py index db156e7f8c..12047ec05f 100644 --- a/packages/examples/cvat/exchange-oracle/src/schemas/exchange.py +++ b/packages/examples/cvat/exchange-oracle/src/schemas/exchange.py @@ -1,5 +1,4 @@ from datetime import datetime -from typing import Optional from pydantic import AnyUrl, BaseModel, Field @@ -22,7 +21,7 @@ class TaskResponse(BaseModel): job_size: int job_time_limit: int job_type: TaskTypes - assignment: Optional[AssignmentResponse] = None + assignment: AssignmentResponse | None = None status: ProjectStatuses diff --git a/packages/examples/cvat/exchange-oracle/src/schemas/webhook.py b/packages/examples/cvat/exchange-oracle/src/schemas/webhook.py index 5893d6ee42..7e8a169c71 100644 --- a/packages/examples/cvat/exchange-oracle/src/schemas/webhook.py +++ b/packages/examples/cvat/exchange-oracle/src/schemas/webhook.py @@ -1,5 +1,4 @@ from datetime import datetime -from typing import Optional from pydantic import BaseModel, validator @@ -11,8 +10,8 @@ class OracleWebhook(BaseModel): escrow_address: str chain_id: Networks event_type: str - event_data: Optional[dict] = None - timestamp: Optional[datetime] = None # TODO: remove optional + event_data: dict | None = None + timestamp: datetime | None = None # TODO: remove optional @validator("escrow_address", allow_reuse=True) def validate_escrow_(cls, value): diff --git a/packages/examples/cvat/exchange-oracle/src/services/__init__.py b/packages/examples/cvat/exchange-oracle/src/services/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/examples/cvat/exchange-oracle/src/services/cloud/client.py b/packages/examples/cvat/exchange-oracle/src/services/cloud/client.py index 5bb92d77e3..53cf13dcc0 100644 --- a/packages/examples/cvat/exchange-oracle/src/services/cloud/client.py +++ b/packages/examples/cvat/exchange-oracle/src/services/cloud/client.py @@ -1,37 +1,29 @@ from abc import ABCMeta, abstractmethod -from typing import List, Optional from urllib.parse import unquote class StorageClient(metaclass=ABCMeta): def __init__( self, - bucket: Optional[str] = None, + bucket: str | None = None, ) -> None: self._bucket = unquote(bucket) if bucket else None @abstractmethod - def create_file(self, key: str, data: bytes = b"", *, bucket: Optional[str] = None): - ... + def create_file(self, key: str, data: bytes = b"", *, bucket: str | None = None): ... @abstractmethod - def remove_file(self, key: str, *, bucket: Optional[str] = None): - ... + def remove_file(self, key: str, *, bucket: str | None = None): ... @abstractmethod - def file_exists(self, key: str, *, bucket: Optional[str] = None) -> bool: - ... + def file_exists(self, key: str, *, bucket: str | None = None) -> bool: ... @abstractmethod - def download_file(self, key: str, *, bucket: Optional[str] = None) -> bytes: - ... + def download_file(self, key: str, *, bucket: str | None = None) -> bytes: ... @abstractmethod - def list_files( - self, *, bucket: Optional[str] = None, prefix: Optional[str] = None - ) -> List[str]: - ... + def list_files(self, *, bucket: str | None = None, prefix: str | None = None) -> list[str]: ... @staticmethod - def normalize_prefix(prefix: Optional[str]) -> Optional[str]: + def normalize_prefix(prefix: str | None) -> str | None: return unquote(prefix).strip("/\\") + "/" if prefix else prefix diff --git a/packages/examples/cvat/exchange-oracle/src/services/cloud/gcs.py b/packages/examples/cvat/exchange-oracle/src/services/cloud/gcs.py index 36611b363f..014be4ce1a 100644 --- a/packages/examples/cvat/exchange-oracle/src/services/cloud/gcs.py +++ b/packages/examples/cvat/exchange-oracle/src/services/cloud/gcs.py @@ -1,5 +1,4 @@ from io import BytesIO -from typing import Dict, List, Optional from urllib.parse import unquote from google.cloud import storage @@ -13,8 +12,8 @@ class GcsClient(StorageClient): def __init__( self, *, - bucket: Optional[str] = None, - service_account_key: Optional[Dict] = None, + bucket: str | None = None, + service_account_key: dict | None = None, ) -> None: super().__init__(bucket) @@ -23,22 +22,22 @@ def __init__( else: self.client = storage.Client.create_anonymous_client() - def create_file(self, key: str, data: bytes = b"", *, bucket: Optional[str] = None) -> None: + def create_file(self, key: str, data: bytes = b"", *, bucket: str | None = None) -> None: bucket = unquote(bucket) if bucket else self._bucket bucket_client = self.client.get_bucket(bucket) bucket_client.blob(unquote(key)).upload_from_string(data) - def remove_file(self, key: str, *, bucket: Optional[str] = None) -> None: + def remove_file(self, key: str, *, bucket: str | None = None) -> None: bucket = unquote(bucket) if bucket else self._bucket bucket_client = self.client.get_bucket(bucket) bucket_client.delete_blob(unquote(key)) - def file_exists(self, key: str, *, bucket: Optional[str] = None) -> bool: + def file_exists(self, key: str, *, bucket: str | None = None) -> bool: bucket = unquote(bucket) if bucket else self._bucket bucket_client = self.client.get_bucket(bucket) return bucket_client.blob(unquote(key)).exists() - def download_file(self, key: str, *, bucket: Optional[str] = None) -> bytes: + def download_file(self, key: str, *, bucket: str | None = None) -> bytes: bucket = unquote(bucket) if bucket else self._bucket bucket_client = self.client.get_bucket(bucket) blob = bucket_client.blob(unquote(key)) @@ -47,9 +46,7 @@ def download_file(self, key: str, *, bucket: Optional[str] = None) -> bytes: self.client.download_blob_to_file(blob, data) return data.getvalue() - def list_files( - self, *, bucket: Optional[str] = None, prefix: Optional[str] = None - ) -> List[str]: + def list_files(self, *, bucket: str | None = None, prefix: str | None = None) -> list[str]: bucket = unquote(bucket) if bucket else self._bucket prefix = self.normalize_prefix(prefix) diff --git a/packages/examples/cvat/exchange-oracle/src/services/cloud/s3.py b/packages/examples/cvat/exchange-oracle/src/services/cloud/s3.py index e8e608ce99..ccb5557e7d 100644 --- a/packages/examples/cvat/exchange-oracle/src/services/cloud/s3.py +++ b/packages/examples/cvat/exchange-oracle/src/services/cloud/s3.py @@ -1,5 +1,4 @@ from io import BytesIO -from typing import List, Optional from urllib.parse import unquote import boto3 @@ -15,15 +14,15 @@ class S3Client(StorageClient): def __init__( self, *, - bucket: Optional[str] = None, - access_key: Optional[str] = None, - secret_key: Optional[str] = None, - endpoint_url: Optional[str] = None, + bucket: str | None = None, + access_key: str | None = None, + secret_key: str | None = None, + endpoint_url: str | None = None, ) -> None: super().__init__(bucket) session = boto3.Session( - **(dict(aws_access_key_id=access_key) if access_key else {}), - **(dict(aws_secret_access_key=secret_key) if secret_key else {}), + **({"aws_access_key_id": access_key} if access_key else {}), + **({"aws_secret_access_key": secret_key} if secret_key else {}), ) s3 = session.resource( "s3", **({"endpoint_url": unquote(endpoint_url)} if endpoint_url else {}) @@ -34,15 +33,15 @@ def __init__( if not access_key and not secret_key: self.client.meta.events.register("choose-signer.s3.*", disable_signing) - def create_file(self, key: str, data: bytes = b"", *, bucket: Optional[str] = None): + def create_file(self, key: str, data: bytes = b"", *, bucket: str | None = None): bucket = unquote(bucket) if bucket else self._bucket self.client.put_object(Body=data, Bucket=bucket, Key=unquote(key)) - def remove_file(self, key: str, *, bucket: Optional[str] = None): + def remove_file(self, key: str, *, bucket: str | None = None): bucket = unquote(bucket) if bucket else self._bucket self.client.delete_object(Bucket=bucket, Key=unquote(key)) - def file_exists(self, key: str, *, bucket: Optional[str] = None) -> bool: + def file_exists(self, key: str, *, bucket: str | None = None) -> bool: bucket = unquote(bucket) if bucket else self._bucket try: self.client.head_object(Bucket=bucket, Key=unquote(key)) @@ -53,19 +52,14 @@ def file_exists(self, key: str, *, bucket: Optional[str] = None) -> bool: else: raise - def download_file(self, key: str, *, bucket: Optional[str] = None) -> bytes: + def download_file(self, key: str, *, bucket: str | None = None) -> bytes: bucket = unquote(bucket) if bucket else self._bucket with BytesIO() as data: self.client.download_fileobj(Bucket=bucket, Key=unquote(key), Fileobj=data) return data.getvalue() - def list_files( - self, *, bucket: Optional[str] = None, prefix: Optional[str] = None - ) -> List[str]: + def list_files(self, *, bucket: str | None = None, prefix: str | None = None) -> list[str]: bucket = unquote(bucket) if bucket else self._bucket objects = self.resource.Bucket(bucket).objects - if prefix: - objects = objects.filter(Prefix=self.normalize_prefix(prefix)) - else: - objects = objects.all() + objects = objects.filter(Prefix=self.normalize_prefix(prefix)) if prefix else objects.all() return [file_info.key for file_info in objects] diff --git a/packages/examples/cvat/exchange-oracle/src/services/cloud/types.py b/packages/examples/cvat/exchange-oracle/src/services/cloud/types.py index 5f5b0db3ad..45e0dbffec 100644 --- a/packages/examples/cvat/exchange-oracle/src/services/cloud/types.py +++ b/packages/examples/cvat/exchange-oracle/src/services/cloud/types.py @@ -4,7 +4,6 @@ from dataclasses import asdict, dataclass, is_dataclass from enum import Enum, auto from inspect import isclass -from typing import Dict, Optional, Type, Union from urllib.parse import urlparse from src.core import manifest @@ -31,14 +30,14 @@ def from_str(cls, provider: str) -> CloudProviders: class BucketCredentials: - def to_dict(self) -> Dict: + def to_dict(self) -> dict: if not is_dataclass(self): raise NotImplementedError return asdict(self) @classmethod - def from_storage_config(cls, config: Type[StorageConfig]) -> Optional[BucketCredentials]: + def from_storage_config(cls, config: type[StorageConfig]) -> BucketCredentials | None: credentials = None if (config.access_key or config.secret_key) and config.provider.lower() != "aws": @@ -46,9 +45,8 @@ def from_storage_config(cls, config: Type[StorageConfig]) -> Optional[BucketCred "Invalid storage configuration. The access_key/secret_key pair" f"cannot be specified with {config.provider} provider" ) - elif ( - bool(config.access_key) ^ bool(config.secret_key) - ) and config.provider.lower() == "aws": + + if (bool(config.access_key) ^ bool(config.secret_key)) and config.provider.lower() == "aws": raise ValueError( "Invalid storage configuration. " "Either none or both access_key and secret_key must be specified for an AWS storage" @@ -71,7 +69,7 @@ def from_storage_config(cls, config: Type[StorageConfig]) -> Optional[BucketCred @dataclass class GcsBucketCredentials(BucketCredentials): - service_account_key: Dict + service_account_key: dict @dataclass @@ -85,8 +83,8 @@ class BucketAccessInfo: provider: CloudProviders host_url: str bucket_name: str - path: Optional[str] = None - credentials: Optional[BucketCredentials] = None + path: str | None = None + credentials: BucketCredentials | None = None @classmethod def from_url(cls, url: str) -> BucketAccessInfo: @@ -129,7 +127,7 @@ def from_url(cls, url: str) -> BucketAccessInfo: raise ValueError(f"{parsed_url.netloc} cloud provider is not supported.") @classmethod - def _from_dict(cls, data: Dict) -> BucketAccessInfo: + def _from_dict(cls, data: dict) -> BucketAccessInfo: for required_field in ( "provider", "bucket_name", @@ -159,7 +157,7 @@ def _from_dict(cls, data: Dict) -> BucketAccessInfo: return BucketAccessInfo(**data) @classmethod - def from_storage_config(cls, config: Type[StorageConfig]) -> BucketAccessInfo: + def from_storage_config(cls, config: type[StorageConfig]) -> BucketAccessInfo: credentials = BucketCredentials.from_storage_config(config) return BucketAccessInfo( @@ -174,9 +172,7 @@ def from_bucket_url(cls, bucket_url: manifest.BucketUrl) -> BucketAccessInfo: return cls._from_dict(bucket_url.dict()) @classmethod - def parse_obj( - cls, data: Union[str, Type[StorageConfig], manifest.BucketUrl] - ) -> BucketAccessInfo: + def parse_obj(cls, data: str | type[StorageConfig] | manifest.BucketUrl) -> BucketAccessInfo: if isinstance(data, manifest.BucketUrlBase): return cls.from_bucket_url(data) elif isinstance(data, str): diff --git a/packages/examples/cvat/exchange-oracle/src/services/cloud/utils.py b/packages/examples/cvat/exchange-oracle/src/services/cloud/utils.py index a9f821d174..bfc23305c7 100644 --- a/packages/examples/cvat/exchange-oracle/src/services/cloud/utils.py +++ b/packages/examples/cvat/exchange-oracle/src/services/cloud/utils.py @@ -1,5 +1,3 @@ -from typing import Optional - from src.services.cloud.client import StorageClient from src.services.cloud.gcs import DEFAULT_GCS_HOST, GcsClient from src.services.cloud.s3 import DEFAULT_S3_HOST, S3Client @@ -7,7 +5,7 @@ def compose_bucket_url( - bucket_name: str, provider: CloudProviders, *, bucket_host: Optional[str] = None + bucket_name: str, provider: CloudProviders, *, bucket_host: str | None = None ) -> str: match provider: case CloudProviders.aws: diff --git a/packages/examples/cvat/exchange-oracle/src/services/cvat.py b/packages/examples/cvat/exchange-oracle/src/services/cvat.py index a57791e8ef..ccd6fd9ddd 100644 --- a/packages/examples/cvat/exchange-oracle/src/services/cvat.py +++ b/packages/examples/cvat/exchange-oracle/src/services/cvat.py @@ -1,7 +1,7 @@ import itertools import uuid +from collections.abc import Sequence from datetime import datetime -from typing import List, Optional, Sequence, Union from sqlalchemy import delete, insert, update from sqlalchemy.orm import Session @@ -22,7 +22,7 @@ def create_project( escrow_address: str, chain_id: int, bucket_url: str, - cvat_webhook_id: Optional[int] = None, + cvat_webhook_id: int | None = None, status: ProjectStatuses = ProjectStatuses.creation, ) -> str: """ @@ -50,13 +50,10 @@ def get_project_by_id( session: Session, project_id: str, *, - for_update: Union[bool, ForUpdateParams] = False, - status_in: Optional[List[ProjectStatuses]] = None, -) -> Optional[Project]: - if status_in: - status_filter_arg = [Project.status.in_(s.value for s in status_in)] - else: - status_filter_arg = [] + for_update: bool | ForUpdateParams = False, + status_in: list[ProjectStatuses] | None = None, +) -> Project | None: + status_filter_arg = [Project.status.in_(s.value for s in status_in)] if status_in else [] return ( _maybe_for_update(session.query(Project), enable=for_update) @@ -69,14 +66,11 @@ def get_projects_by_cvat_ids( session: Session, project_cvat_ids: Sequence[int], *, - for_update: Union[bool, ForUpdateParams] = False, - status_in: Optional[List[ProjectStatuses]] = None, + for_update: bool | ForUpdateParams = False, + status_in: list[ProjectStatuses] | None = None, limit: int = 5, -) -> List[Project]: - if status_in: - status_filter_arg = [Project.status.in_(s.value for s in status_in)] - else: - status_filter_arg = [] +) -> list[Project]: + status_filter_arg = [Project.status.in_(s.value for s in status_in)] if status_in else [] return ( _maybe_for_update(session.query(Project), enable=for_update) @@ -87,8 +81,8 @@ def get_projects_by_cvat_ids( def get_project_by_escrow_address( - session: Session, escrow_address: str, *, for_update: Union[bool, ForUpdateParams] = False -) -> Optional[Project]: + session: Session, escrow_address: str, *, for_update: bool | ForUpdateParams = False +) -> Project | None: return ( _maybe_for_update(session.query(Project), enable=for_update) .where(Project.escrow_address == escrow_address) @@ -100,9 +94,9 @@ def get_projects_by_escrow_address( session: Session, escrow_address: str, *, - for_update: Union[bool, ForUpdateParams] = False, - limit: Optional[int] = 5, -) -> List[Project]: + for_update: bool | ForUpdateParams = False, + limit: int | None = 5, +) -> list[Project]: projects = _maybe_for_update(session.query(Project), enable=for_update).where( Project.escrow_address == escrow_address ) @@ -116,7 +110,7 @@ def get_projects_by_escrow_address( def get_project_cvat_ids_by_escrow_address( session: Session, escrow_address: str, -) -> List[int]: +) -> list[int]: projects = session.query(Project).where(Project.escrow_address == escrow_address) return list(itertools.chain.from_iterable(projects.values(Project.cvat_id))) @@ -126,11 +120,11 @@ def get_projects_by_status( session: Session, status: ProjectStatuses, *, - included_types: Optional[Sequence[TaskTypes]] = None, - task_status: Optional[TaskStatuses] = None, + included_types: Sequence[TaskTypes] | None = None, + task_status: TaskStatuses | None = None, limit: int = 5, - for_update: Union[bool, ForUpdateParams] = False, -) -> List[Project]: + for_update: bool | ForUpdateParams = False, +) -> list[Project]: projects = _maybe_for_update(session.query(Project), enable=for_update).where( Project.status == status.value ) @@ -141,18 +135,16 @@ def get_projects_by_status( if included_types is not None: projects = projects.where(Project.job_type.in_([t.value for t in included_types])) - projects = projects.limit(limit).all() - - return projects + return projects.limit(limit).all() def get_escrows_by_project_status( session: Session, project_status: ProjectStatuses, *, - included_types: Optional[Sequence[TaskTypes]] = None, + included_types: Sequence[TaskTypes] | None = None, limit: int = 5, -) -> List[tuple[str, int]]: +) -> list[tuple[str, int]]: escrows = ( session.query(Project.escrow_address, Project.chain_id) .group_by(Project.escrow_address, Project.chain_id) @@ -162,12 +154,10 @@ def get_escrows_by_project_status( if included_types: escrows = escrows.where(Project.job_type.in_([t.value for t in included_types])) - escrows = escrows.limit(limit).all() - - return escrows + return escrows.limit(limit).all() -def get_available_projects(session: Session, *, limit: int = 10) -> List[Project]: +def get_available_projects(session: Session, *, limit: int = 10) -> list[Project]: return ( session.query(Project) .where( @@ -185,11 +175,11 @@ def get_available_projects(session: Session, *, limit: int = 10) -> List[Project def get_projects_by_assignee( session: Session, - wallet_address: Optional[str] = None, + wallet_address: str | None = None, *, limit: int = 10, - for_update: Union[bool, ForUpdateParams] = False, -) -> List[Project]: + for_update: bool | ForUpdateParams = False, +) -> list[Project]: return ( _maybe_for_update(session.query(Project), enable=for_update) .where( @@ -237,10 +227,7 @@ def delete_project(session: Session, project_id: str) -> None: def is_project_completed(session: Session, project_id: str) -> bool: project = get_project_by_id(session, project_id) jobs = get_jobs_by_cvat_project_id(session, project.cvat_id) - if len(jobs) > 0 and all(job.status == JobStatuses.completed.value for job in jobs): - return True - else: - return False + return bool(len(jobs) > 0 and all(job.status == JobStatuses.completed.value for job in jobs)) # EscrowCreation @@ -271,8 +258,8 @@ def get_escrow_creation_by_id( session: Session, escrow_creation_id: str, *, - for_update: Union[bool, ForUpdateParams] = False, -) -> Optional[EscrowCreation]: + for_update: bool | ForUpdateParams = False, +) -> EscrowCreation | None: return ( _maybe_for_update(session.query(EscrowCreation), enable=for_update) .where(EscrowCreation.id == escrow_creation_id, EscrowCreation.finished_at.is_(None)) @@ -285,8 +272,8 @@ def get_escrow_creation_by_escrow_address( escrow_address: str, chain_id: int, *, - for_update: Union[bool, ForUpdateParams] = False, -) -> Optional[EscrowCreation]: + for_update: bool | ForUpdateParams = False, +) -> EscrowCreation | None: return ( _maybe_for_update(session.query(EscrowCreation), enable=for_update) .where( @@ -299,8 +286,8 @@ def get_escrow_creation_by_escrow_address( def get_active_escrow_creations( - session: Session, *, limit: int = 10, for_update: Union[bool, ForUpdateParams] = False -) -> List[EscrowCreation]: + session: Session, *, limit: int = 10, for_update: bool | ForUpdateParams = False +) -> list[EscrowCreation]: return ( _maybe_for_update(session.query(EscrowCreation), enable=for_update) .where(EscrowCreation.finished_at.is_(None)) @@ -309,7 +296,7 @@ def get_active_escrow_creations( ) -def finish_escrow_creations(session: Session, escrow_creations: List[EscrowCreation]) -> None: +def finish_escrow_creations(session: Session, escrow_creations: list[EscrowCreation]) -> None: statement = ( update(EscrowCreation) .where(EscrowCreation.id.in_(c.id for c in escrow_creations)) @@ -348,16 +335,16 @@ def create_task(session: Session, cvat_id: int, cvat_project_id: int, status: Ta def get_task_by_id( - session: Session, task_id: str, *, for_update: Union[bool, ForUpdateParams] = False -) -> Optional[Task]: + session: Session, task_id: str, *, for_update: bool | ForUpdateParams = False +) -> Task | None: return ( _maybe_for_update(session.query(Task), enable=for_update).where(Task.id == task_id).first() ) def get_tasks_by_cvat_id( - session: Session, task_ids: List[int], *, for_update: Union[bool, ForUpdateParams] = False -) -> List[Task]: + session: Session, task_ids: list[int], *, for_update: bool | ForUpdateParams = False +) -> list[Task]: return ( _maybe_for_update(session.query(Task), enable=for_update) .where(Task.cvat_id.in_(task_ids)) @@ -369,11 +356,11 @@ def get_tasks_by_status( session: Session, status: TaskStatuses, *, - job_status: Optional[JobStatuses] = None, - project_status: Optional[ProjectStatuses] = None, - for_update: Union[bool, ForUpdateParams] = False, - limit: Optional[int] = 20, -) -> List[Task]: + job_status: JobStatuses | None = None, + project_status: ProjectStatuses | None = None, + for_update: bool | ForUpdateParams = False, + limit: int | None = 20, +) -> list[Task]: query = _maybe_for_update(session.query(Task), enable=for_update).where( Task.status == status.value ) @@ -396,8 +383,8 @@ def update_task_status(session: Session, task_id: int, status: TaskStatuses) -> def get_tasks_by_cvat_project_id( - session: Session, cvat_project_id: int, *, for_update: Union[bool, ForUpdateParams] = False -) -> List[Task]: + session: Session, cvat_project_id: int, *, for_update: bool | ForUpdateParams = False +) -> list[Task]: return ( _maybe_for_update(session.query(Task), enable=for_update) .where(Task.cvat_project_id == cvat_project_id) @@ -421,8 +408,8 @@ def create_data_upload( def get_active_task_uploads_by_task_id( - session: Session, task_ids: List[int], *, for_update: Union[bool, ForUpdateParams] = False -) -> List[DataUpload]: + session: Session, task_ids: list[int], *, for_update: bool | ForUpdateParams = False +) -> list[DataUpload]: return ( _maybe_for_update(session.query(DataUpload), enable=for_update) .where(DataUpload.task_id.in_(task_ids)) @@ -431,8 +418,8 @@ def get_active_task_uploads_by_task_id( def get_active_task_uploads( - session: Session, *, limit: int = 10, for_update: Union[bool, ForUpdateParams] = False -) -> List[DataUpload]: + session: Session, *, limit: int = 10, for_update: bool | ForUpdateParams = False +) -> list[DataUpload]: return _maybe_for_update(session.query(DataUpload), enable=for_update).limit(limit).all() @@ -469,14 +456,14 @@ def create_job( def get_job_by_id( - session: Session, job_id: str, *, for_update: Union[bool, ForUpdateParams] = False -) -> Optional[Job]: + session: Session, job_id: str, *, for_update: bool | ForUpdateParams = False +) -> Job | None: return _maybe_for_update(session.query(Job), enable=for_update).where(Job.id == job_id).first() def get_jobs_by_cvat_id( - session: Session, cvat_ids: List[int], *, for_update: Union[bool, ForUpdateParams] = False -) -> List[Job]: + session: Session, cvat_ids: list[int], *, for_update: bool | ForUpdateParams = False +) -> list[Job]: return ( _maybe_for_update(session.query(Job), enable=for_update) .where(Job.cvat_id.in_(cvat_ids)) @@ -490,8 +477,8 @@ def update_job_status(session: Session, job_id: int, status: JobStatuses) -> Non def get_jobs_by_cvat_task_id( - session: Session, cvat_task_id: int, *, for_update: Union[bool, ForUpdateParams] = False -) -> List[Job]: + session: Session, cvat_task_id: int, *, for_update: bool | ForUpdateParams = False +) -> list[Job]: return ( _maybe_for_update(session.query(Job), enable=for_update) .where(Job.cvat_task_id == cvat_task_id) @@ -500,8 +487,8 @@ def get_jobs_by_cvat_task_id( def get_jobs_by_cvat_project_id( - session: Session, cvat_project_id: int, *, for_update: Union[bool, ForUpdateParams] = False -) -> List[Job]: + session: Session, cvat_project_id: int, *, for_update: bool | ForUpdateParams = False +) -> list[Job]: return ( _maybe_for_update(session.query(Job), enable=for_update) .where(Job.cvat_project_id == cvat_project_id) @@ -526,10 +513,10 @@ def count_jobs_by_escrow_address( def get_free_job( session: Session, - cvat_projects: List[int], + cvat_projects: list[int], *, - for_update: Union[bool, ForUpdateParams] = False, -) -> Optional[Job]: + for_update: bool | ForUpdateParams = False, +) -> Job | None: return ( _maybe_for_update(session.query(Job), enable=for_update) .where( @@ -564,8 +551,8 @@ def put_user(session: Session, wallet_address: str, cvat_email: str, cvat_id: in def get_user_by_id( - session: Session, wallet_address: str, *, for_update: Union[bool, ForUpdateParams] = False -) -> Optional[User]: + session: Session, wallet_address: str, *, for_update: bool | ForUpdateParams = False +) -> User | None: return ( _maybe_for_update(session.query(User), enable=for_update) .where(User.wallet_address == wallet_address) @@ -574,8 +561,8 @@ def get_user_by_id( def get_user_by_email( - session: Session, email: str, *, for_update: Union[bool, ForUpdateParams] = False -) -> Optional[User]: + session: Session, email: str, *, for_update: bool | ForUpdateParams = False +) -> User | None: return ( _maybe_for_update(session.query(User), enable=for_update) .where(User.cvat_email == email) @@ -606,8 +593,8 @@ def create_assignment( def get_assignments_by_id( - session: Session, ids: List[str], *, for_update: Union[bool, ForUpdateParams] = False -) -> List[Assignment]: + session: Session, ids: list[str], *, for_update: bool | ForUpdateParams = False +) -> list[Assignment]: return ( _maybe_for_update(session.query(Assignment), enable=for_update) .where(Assignment.id.in_(ids)) @@ -616,8 +603,8 @@ def get_assignments_by_id( def get_latest_assignment_by_cvat_job_id( - session: Session, cvat_job_id: int, *, for_update: Union[bool, ForUpdateParams] = False -) -> Optional[Assignment]: + session: Session, cvat_job_id: int, *, for_update: bool | ForUpdateParams = False +) -> Assignment | None: return ( _maybe_for_update(session.query(Assignment), enable=for_update) .where(Assignment.cvat_job_id == cvat_job_id) @@ -627,8 +614,8 @@ def get_latest_assignment_by_cvat_job_id( def get_unprocessed_expired_assignments( - session: Session, *, limit: int = 10, for_update: Union[bool, ForUpdateParams] = False -) -> List[Assignment]: + session: Session, *, limit: int = 10, for_update: bool | ForUpdateParams = False +) -> list[Assignment]: return ( _maybe_for_update(session.query(Assignment), enable=for_update) .where( @@ -642,8 +629,8 @@ def get_unprocessed_expired_assignments( def get_active_assignments( - session: Session, *, limit: int = 10, for_update: Union[bool, ForUpdateParams] = False -) -> List[Assignment]: + session: Session, *, limit: int = 10, for_update: bool | ForUpdateParams = False +) -> list[Assignment]: return ( _maybe_for_update(session.query(Assignment), enable=for_update) .where( @@ -661,7 +648,7 @@ def update_assignment( id: str, *, status: AssignmentStatuses, - completed_at: Optional[datetime] = None, + completed_at: datetime | None = None, ): statement = ( update(Assignment) @@ -691,10 +678,10 @@ def complete_assignment(session: Session, assignment_id: str, completed_at: date def get_user_assignments_in_cvat_projects( session: Session, wallet_address: int, - cvat_projects: List[int], + cvat_projects: list[int], *, - for_update: Union[bool, ForUpdateParams] = False, -) -> List[Assignment]: + for_update: bool | ForUpdateParams = False, +) -> list[Assignment]: return ( _maybe_for_update(session.query(Assignment), enable=for_update) .where( @@ -708,7 +695,7 @@ def get_user_assignments_in_cvat_projects( def count_active_user_assignments( session: Session, wallet_address: int, - cvat_projects: List[int], + cvat_projects: list[int], ) -> int: return ( session.query(Assignment) @@ -724,23 +711,23 @@ def count_active_user_assignments( # Image -def add_project_images(session: Session, cvat_project_id: int, filenames: List[str]) -> None: +def add_project_images(session: Session, cvat_project_id: int, filenames: list[str]) -> None: session.execute( insert(Image), [ - dict( - id=str(uuid.uuid4()), - cvat_project_id=cvat_project_id, - filename=fn, - ) + { + "id": str(uuid.uuid4()), + "cvat_project_id": cvat_project_id, + "filename": fn, + } for fn in filenames ], ) def get_project_images( - session: Session, cvat_project_id: int, *, for_update: Union[bool, ForUpdateParams] = False -) -> List[Image]: + session: Session, cvat_project_id: int, *, for_update: bool | ForUpdateParams = False +) -> list[Image]: return ( _maybe_for_update(session.query(Image), enable=for_update) .where(Image.cvat_project_id == cvat_project_id) diff --git a/packages/examples/cvat/exchange-oracle/src/services/exchange.py b/packages/examples/cvat/exchange-oracle/src/services/exchange.py index b651180654..d072e5f53a 100644 --- a/packages/examples/cvat/exchange-oracle/src/services/exchange.py +++ b/packages/examples/cvat/exchange-oracle/src/services/exchange.py @@ -1,5 +1,4 @@ from datetime import timedelta -from typing import Optional import src.cvat.api_calls as cvat_api import src.services.cvat as cvat_service @@ -18,7 +17,7 @@ def serialize_task( - project_id: str, *, assignment_id: Optional[str] = None + project_id: str, *, assignment_id: str | None = None ) -> service_api.TaskResponse: with SessionLocal.begin() as session: project = cvat_service.get_project_by_id(session, project_id) @@ -57,19 +56,14 @@ def serialize_task( def get_available_tasks() -> list[service_api.TaskResponse]: - results = [] - with SessionLocal.begin() as session: cvat_projects = cvat_service.get_available_projects(session) - for project in cvat_projects: - results.append(serialize_task(project.id)) - - return results + return [serialize_task(project.id) for project in cvat_projects] def get_tasks_by_assignee( - wallet_address: Optional[str] = None, + wallet_address: str | None = None, ) -> list[service_api.TaskResponse]: results = [] @@ -104,7 +98,7 @@ class UserHasUnfinishedAssignmentError(Exception): pass -def create_assignment(project_id: int, wallet_address: str) -> Optional[str]: +def create_assignment(project_id: int, wallet_address: str) -> str | None: with SessionLocal.begin() as session: user = get_or_404( cvat_service.get_user_by_id(session, wallet_address, for_update=True), diff --git a/packages/examples/cvat/exchange-oracle/src/services/webhook.py b/packages/examples/cvat/exchange-oracle/src/services/webhook.py index 7610cf9dab..e2bc9c7fbe 100644 --- a/packages/examples/cvat/exchange-oracle/src/services/webhook.py +++ b/packages/examples/cvat/exchange-oracle/src/services/webhook.py @@ -1,7 +1,6 @@ import datetime import uuid from enum import Enum -from typing import List, Optional from attrs import define from sqlalchemy import case, update @@ -25,7 +24,7 @@ class OracleWebhookDirectionTags(str, Enum, metaclass=BetterEnumMeta): @define class OracleWebhookQueue: direction: OracleWebhookDirectionTags - default_sender: Optional[OracleWebhookTypes] = None + default_sender: OracleWebhookTypes | None = None def create_webhook( self, @@ -33,10 +32,10 @@ def create_webhook( escrow_address: str, chain_id: int, type: OracleWebhookTypes, - signature: Optional[str] = None, - event_type: Optional[str] = None, - event_data: Optional[dict] = None, - event: Optional[OracleEvent] = None, + signature: str | None = None, + event_type: str | None = None, + event_data: dict | None = None, + event: OracleEvent | None = None, ) -> str: """ Creates a webhook in a database @@ -44,7 +43,7 @@ def create_webhook( assert not event_data or event_type, "'event_data' requires 'event_type'" assert bool(event) ^ bool( event_type - ), f"'event' and 'event_type' cannot be used together. Please use only one of the fields" + ), "'event' and 'event_type' cannot be used together. Please use only one of the fields" if event_type: if self.direction == OracleWebhookDirectionTags.incoming: @@ -59,7 +58,7 @@ def create_webhook( if self.direction == OracleWebhookDirectionTags.incoming and not signature: raise ValueError("Webhook signature must be specified for incoming events") - elif self.direction == OracleWebhookDirectionTags.outgoing and signature: + if self.direction == OracleWebhookDirectionTags.outgoing and signature: raise ValueError("Webhook signature must not be specified for outgoing events") if signature: @@ -93,8 +92,8 @@ def get_pending_webhooks( *, limit: int = 10, for_update: bool = False, - ) -> List[Webhook]: - webhooks = ( + ) -> list[Webhook]: + return ( _maybe_for_update(session.query(Webhook), enable=for_update) .where( Webhook.direction == self.direction.value, @@ -105,7 +104,6 @@ def get_pending_webhooks( .limit(limit) .all() ) - return webhooks def update_webhook_status( self, session: Session, webhook_id: str, status: OracleWebhookStatuses diff --git a/packages/examples/cvat/exchange-oracle/src/utils/__init__.py b/packages/examples/cvat/exchange-oracle/src/utils/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/examples/cvat/exchange-oracle/src/utils/annotations.py b/packages/examples/cvat/exchange-oracle/src/utils/annotations.py index 5deed7efc4..075ce7d035 100644 --- a/packages/examples/cvat/exchange-oracle/src/utils/annotations.py +++ b/packages/examples/cvat/exchange-oracle/src/utils/annotations.py @@ -1,16 +1,18 @@ import os +from argparse import ArgumentParser +from collections.abc import Iterable, Sequence from copy import deepcopy from glob import glob -from typing import Dict, Iterable, List, Optional, Sequence, Tuple, TypeVar, Union +from typing import TypeVar import datumaro as dm import numpy as np from datumaro.util import filter_dict, mask_tools from datumaro.util.annotation_util import find_group_leader, find_instances, max_bbox -from defusedxml import ElementTree as ET +from defusedxml import ElementTree -def flatten_points(input_points: Sequence[dm.Points]) -> List[dm.Points]: +def flatten_points(input_points: Sequence[dm.Points]) -> list[dm.Points]: results = [] for pts in input_points: @@ -48,7 +50,7 @@ def prepare_cvat_annotations_for_dm(dataset_root: str): for annotation_filename in glob(os.path.join(dataset_root, "**/*.xml"), recursive=True): with open(annotation_filename, "rb+") as f: - doc = ET.parse(f) + doc = ElementTree.parse(f) doc_root = doc.getroot() if doc_root.find("meta/project"): @@ -98,7 +100,7 @@ def _get_skeleton_label(original_label: str) -> str: media_type=dm.Image, ) - label_id_map: Dict[int, int] = { + label_id_map: dict[int, int] = { original_id: new_label_cat.find(label.name, parent=_get_skeleton_label(label.name))[0] for original_id, label in enumerate(dataset.categories()[dm.AnnotationType.label]) } # old id -> new id @@ -173,7 +175,7 @@ def shift_ann(ann: T, offset_x: float, offset_y: float, *, img_w: int, img_h: in ] ) else: - assert False, f"Unsupported annotation type '{ann.type}'" + raise TypeError(f"Unsupported annotation type '{ann.type}'") return shifted_ann @@ -200,7 +202,7 @@ class ProjectLabels(dm.ItemTransform): """ @classmethod - def build_cmdline_parser(cls, **kwargs): + def build_cmdline_parser(cls, **kwargs) -> ArgumentParser: parser = super().build_cmdline_parser(**kwargs) parser.add_argument( "-l", @@ -211,19 +213,19 @@ def build_cmdline_parser(cls, **kwargs): ) return parser - def __init__( + def __init__( # noqa: PLR0912 self, extractor: dm.IExtractor, - dst_labels: Union[Iterable[Union[str, Tuple[str, str]]], dm.LabelCategories], - ): + dst_labels: Iterable[str | tuple[str, str]] | dm.LabelCategories, + ) -> None: super().__init__(extractor) self._categories = {} src_categories = self._extractor.categories() - src_label_cat: Optional[dm.LabelCategories] = src_categories.get(dm.AnnotationType.label) - src_point_cat: Optional[dm.PointsCategories] = src_categories.get(dm.AnnotationType.points) + src_label_cat: dm.LabelCategories | None = src_categories.get(dm.AnnotationType.label) + src_point_cat: dm.PointsCategories | None = src_categories.get(dm.AnnotationType.points) if isinstance(dst_labels, dm.LabelCategories): dst_label_cat = deepcopy(dst_labels) @@ -234,7 +236,7 @@ def __init__( dst_label_cat = dm.LabelCategories(attributes=deepcopy(src_label_cat.attributes)) for dst_label in dst_labels: - assert isinstance(dst_label, str) or isinstance(dst_label, tuple) + assert isinstance(dst_label, str | tuple) dst_parent = "" if isinstance(dst_label, tuple): @@ -316,7 +318,7 @@ def _make_label_id_map(self, src_label_cat, dst_label_cat): src_id: dst_label_cat.find(src_label_cat[src_id].name, src_label_cat[src_id].parent)[0] for src_id in range(len(src_label_cat or ())) } - self._map_id = lambda src_id: id_mapping.get(src_id, None) + self._map_id = lambda src_id: id_mapping.get(src_id) def categories(self): return self._categories diff --git a/packages/examples/cvat/exchange-oracle/src/utils/enums.py b/packages/examples/cvat/exchange-oracle/src/utils/enums.py index 4f3d688251..d4c133b0e5 100644 --- a/packages/examples/cvat/exchange-oracle/src/utils/enums.py +++ b/packages/examples/cvat/exchange-oracle/src/utils/enums.py @@ -6,5 +6,5 @@ class BetterEnumMeta(EnumMeta): Extends the default enum metaclass with extra methods for better usability """ - def __contains__(cls, item): + def __contains__(cls, item) -> bool: return isinstance(item, cls) or item in [v.value for v in cls.__members__.values()] diff --git a/packages/examples/cvat/exchange-oracle/src/utils/logging.py b/packages/examples/cvat/exchange-oracle/src/utils/logging.py index be2c5feba3..e7660eb0d7 100644 --- a/packages/examples/cvat/exchange-oracle/src/utils/logging.py +++ b/packages/examples/cvat/exchange-oracle/src/utils/logging.py @@ -1,5 +1,5 @@ import logging -from typing import NewType, Optional, Union +from typing import NewType from src.utils.stack import current_function_name @@ -15,7 +15,7 @@ def parse_log_level(level: str) -> LogLevel: def get_function_logger( - parent_logger: Optional[Union[str, logging.Logger]] = None, + parent_logger: str | logging.Logger | None = None, ) -> logging.Logger: if isinstance(parent_logger, str): parent_logger = logging.getLogger(parent_logger) diff --git a/packages/examples/cvat/exchange-oracle/src/utils/net.py b/packages/examples/cvat/exchange-oracle/src/utils/net.py index 360dafaebb..04ad799510 100644 --- a/packages/examples/cvat/exchange-oracle/src/utils/net.py +++ b/packages/examples/cvat/exchange-oracle/src/utils/net.py @@ -1,7 +1,7 @@ import ipaddress -def is_ipv4(addr: str, allow_port: bool = True) -> bool: +def is_ipv4(addr: str, *, allow_port: bool = True) -> bool: try: if allow_port: addr = addr.split(":", maxsplit=1)[0] diff --git a/packages/examples/cvat/exchange-oracle/src/utils/requests.py b/packages/examples/cvat/exchange-oracle/src/utils/requests.py index 785c2cfc87..ef2174f9b9 100644 --- a/packages/examples/cvat/exchange-oracle/src/utils/requests.py +++ b/packages/examples/cvat/exchange-oracle/src/utils/requests.py @@ -1,4 +1,4 @@ -from typing import Optional, TypeVar +from typing import TypeVar from fastapi import HTTPException @@ -7,11 +7,11 @@ def get_or_404( - obj: Optional[T], + obj: T | None, object_id: V, object_type_name: str, *, - reason: Optional[str] = None, + reason: str | None = None, ) -> T: if obj is None: raise HTTPException( diff --git a/packages/examples/cvat/exchange-oracle/src/utils/webhooks.py b/packages/examples/cvat/exchange-oracle/src/utils/webhooks.py index acb534c265..9e1b59bf90 100644 --- a/packages/examples/cvat/exchange-oracle/src/utils/webhooks.py +++ b/packages/examples/cvat/exchange-oracle/src/utils/webhooks.py @@ -1,5 +1,4 @@ from datetime import datetime -from typing import Dict, Optional, Tuple from src.chain.web3 import sign_message from src.core.oracle_events import parse_event @@ -11,8 +10,8 @@ def prepare_outgoing_webhook_body( chain_id: Networks, event_type: str, event_data: dict, - timestamp: Optional[datetime], -) -> Dict: + timestamp: datetime | None, +) -> dict: body = {"escrow_address": escrow_address, "chain_id": chain_id} if timestamp: @@ -29,11 +28,11 @@ def prepare_outgoing_webhook_body( def prepare_signed_message( - escrow_address: str, + escrow_address: str, # noqa: ARG001 chain_id: Networks, - message: Optional[str] = None, - body: Optional[dict] = None, -) -> Tuple[str, str]: + message: str | None = None, + body: dict | None = None, +) -> tuple[str, str]: """ Sign the message with the service identity. Optionally, can serialize the input structure. diff --git a/packages/examples/cvat/exchange-oracle/src/validators/__init__.py b/packages/examples/cvat/exchange-oracle/src/validators/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/examples/cvat/exchange-oracle/src/validators/validation.py b/packages/examples/cvat/exchange-oracle/src/validators/validation.py index c8ce69d5f2..4d9d0279c8 100644 --- a/packages/examples/cvat/exchange-oracle/src/validators/validation.py +++ b/packages/examples/cvat/exchange-oracle/src/validators/validation.py @@ -1,4 +1,4 @@ -""" Validation utils""" +"""Validation utils""" class ValidationResult: @@ -7,7 +7,7 @@ class ValidationResult: It encapsulates validation logic and helping during generating response body """ - def __init__(self): + def __init__(self) -> None: self.is_valid = True self.errors = [] diff --git a/packages/examples/cvat/exchange-oracle/tests/api/__init__.py b/packages/examples/cvat/exchange-oracle/tests/api/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/examples/cvat/exchange-oracle/tests/api/test_exchange_api.py b/packages/examples/cvat/exchange-oracle/tests/api/test_exchange_api.py index 9eba05e767..b910addd60 100644 --- a/packages/examples/cvat/exchange-oracle/tests/api/test_exchange_api.py +++ b/packages/examples/cvat/exchange-oracle/tests/api/test_exchange_api.py @@ -38,7 +38,7 @@ def test_empty_list_tasks_200_without_address(client: TestClient) -> None: def test_list_tasks_200_with_address(client: TestClient) -> None: - with (SessionLocal.begin() as session,): + with SessionLocal.begin() as session: _, _, cvat_job_1 = create_project_task_and_job( session, "0x86e83d346041E8806e352681f3F14549C0d2BC67", 1 ) @@ -95,7 +95,7 @@ def test_list_tasks_200_with_address(client: TestClient) -> None: def test_list_tasks_200_without_address(client: TestClient) -> None: - with (SessionLocal.begin() as session,): + with SessionLocal.begin() as session: _, _, cvat_job_1 = create_project_task_and_job( session, "0x86e83d346041E8806e352681f3F14549C0d2BC67", 1 ) diff --git a/packages/examples/cvat/exchange-oracle/tests/api/test_greet.py b/packages/examples/cvat/exchange-oracle/tests/api/test_greet.py index e1f46b0df0..e721439fd8 100644 --- a/packages/examples/cvat/exchange-oracle/tests/api/test_greet.py +++ b/packages/examples/cvat/exchange-oracle/tests/api/test_greet.py @@ -2,5 +2,5 @@ def test_greet_route(client: TestClient) -> None: - response = client.get(f"/") + response = client.get("/") assert response.status_code == 200 diff --git a/packages/examples/cvat/exchange-oracle/tests/conftest.py b/packages/examples/cvat/exchange-oracle/tests/conftest.py index e027999628..f39f40a8ca 100644 --- a/packages/examples/cvat/exchange-oracle/tests/conftest.py +++ b/packages/examples/cvat/exchange-oracle/tests/conftest.py @@ -1,4 +1,4 @@ -from typing import Generator +from collections.abc import Generator import pytest from fastapi.testclient import TestClient diff --git a/packages/examples/cvat/exchange-oracle/tests/integration/chain/__init__.py b/packages/examples/cvat/exchange-oracle/tests/integration/chain/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/examples/cvat/exchange-oracle/tests/integration/chain/test_escrow.py b/packages/examples/cvat/exchange-oracle/tests/integration/chain/test_escrow.py index cb3245f716..d65097e64c 100644 --- a/packages/examples/cvat/exchange-oracle/tests/integration/chain/test_escrow.py +++ b/packages/examples/cvat/exchange-oracle/tests/integration/chain/test_escrow.py @@ -2,6 +2,7 @@ import unittest from unittest.mock import patch +import pytest from human_protocol_sdk.constants import ChainId, Status from human_protocol_sdk.encryption import EncryptionUtils from human_protocol_sdk.escrow import EscrowClientError, EscrowData @@ -53,45 +54,40 @@ def test_validate_escrow(self): with patch("src.chain.escrow.EscrowUtils.get_escrow") as mock_function: mock_function.return_value = self.escrow_data validation = validate_escrow(chain_id, escrow_address) - self.assertIsNone(validation) + assert validation is None def test_validate_escrow_invalid_address(self): - with self.assertRaises(EscrowClientError) as error: + with pytest.raises(EscrowClientError, match="Invalid escrow address: invalid_address"): validate_escrow(chain_id, "invalid_address") - self.assertEqual(f"Invalid escrow address: invalid_address", str(error.exception)) - def test_validate_escrow_invalid_status(self): with patch("src.chain.escrow.EscrowUtils.get_escrow") as mock_function: self.escrow_data.status = Status.Launched.name mock_function.return_value = self.escrow_data - with self.assertRaises(ValueError) as error: + with pytest.raises( + ValueError, + match=rf"Escrow is not in any of the accepted states \(Pending\). " + f"Current state: {self.escrow_data.status}", + ): validate_escrow(chain_id, escrow_address) - self.assertEqual( - f"Escrow is not in any of the accepted states (Pending). Current state: {self.escrow_data.status}", - str(error.exception), - ) def test_validate_escrow_without_funds(self): with patch("src.chain.escrow.EscrowUtils.get_escrow") as mock_function: self.escrow_data.balance = "0" mock_function.return_value = self.escrow_data - with self.assertRaises(ValueError) as error: + with pytest.raises(ValueError, match="Escrow doesn't have funds"): validate_escrow(chain_id, escrow_address) - self.assertEqual( - f"Escrow doesn't have funds", - str(error.exception), - ) def test_get_escrow_manifest(self): - with patch("src.chain.escrow.EscrowUtils.get_escrow") as mock_function, patch( - "src.chain.escrow.StorageUtils.download_file_from_url" - ) as mock_download: + with ( + patch("src.chain.escrow.EscrowUtils.get_escrow") as mock_function, + patch("src.chain.escrow.StorageUtils.download_file_from_url") as mock_download, + ): mock_download.return_value = json.dumps({"title": "test"}).encode() mock_function.return_value = self.escrow_data manifest = get_escrow_manifest(chain_id, escrow_address) - self.assertIsInstance(manifest, dict) - self.assertIsNotNone(manifest) + assert isinstance(manifest, dict) + assert manifest is not None def test_get_encrypted_escrow_manifest(self): with ( @@ -112,62 +108,55 @@ def test_get_encrypted_escrow_manifest(self): encrypted_manifest = EncryptionUtils.encrypt( original_manifest, public_keys=[PGP_PUBLIC_KEY1, PGP_PUBLIC_KEY2] ) - self.assertNotEqual(encrypted_manifest, original_manifest) + assert encrypted_manifest != original_manifest mock_download.return_value = encrypted_manifest.encode() downloaded_manifest_content = get_escrow_manifest(chain_id, escrow_address) - self.assertDictEqual(downloaded_manifest_content, original_manifest_content) + assert downloaded_manifest_content == original_manifest_content def test_get_escrow_manifest_invalid_address(self): - with self.assertRaises(EscrowClientError) as error: + with pytest.raises(EscrowClientError, match="Invalid escrow address: invalid_address"): get_escrow_manifest(chain_id, "invalid_address") - self.assertEqual(f"Invalid escrow address: invalid_address", str(error.exception)) def test_get_job_launcher_address(self): with patch("src.chain.escrow.EscrowUtils.get_escrow") as mock_function: mock_function.return_value = self.escrow_data job_launcher_address = get_job_launcher_address(chain_id, escrow_address) - self.assertIsInstance(job_launcher_address, str) - self.assertEqual(job_launcher_address, JOB_LAUNCHER_ADDRESS) + assert isinstance(job_launcher_address, str) + assert job_launcher_address == JOB_LAUNCHER_ADDRESS def test_get_job_launcher_address_invalid_address(self): - with self.assertRaises(EscrowClientError) as error: + with pytest.raises(EscrowClientError, match="Invalid escrow address: invalid_address"): get_job_launcher_address(chain_id, "invalid_address") - self.assertEqual(f"Invalid escrow address: invalid_address", str(error.exception)) def test_get_job_launcher_address_invalid_chain_id(self): - with self.assertRaises(ValueError) as error: + with pytest.raises(ValueError, match="123 is not a valid ChainId"): get_job_launcher_address(123, escrow_address) - self.assertEqual(f"123 is not a valid ChainId", str(error.exception)) def test_get_job_launcher_address_empty_escrow(self): with patch("src.chain.escrow.EscrowUtils.get_escrow") as mock_function: mock_function.return_value = None - with self.assertRaises(Exception) as error: + with pytest.raises(Exception, match=f"Can't find escrow {ESCROW_ADDRESS}"): get_job_launcher_address(chain_id, escrow_address) - self.assertEqual(f"Can't find escrow {ESCROW_ADDRESS}", str(error.exception)) def test_get_recording_oracle_address(self): with patch("src.chain.escrow.EscrowUtils.get_escrow") as mock_function: self.escrow_data.recording_oracle = RECORDING_ORACLE_ADDRESS mock_function.return_value = self.escrow_data recording_oracle_address = get_recording_oracle_address(chain_id, escrow_address) - self.assertIsInstance(recording_oracle_address, str) - self.assertEqual(recording_oracle_address, RECORDING_ORACLE_ADDRESS) + assert isinstance(recording_oracle_address, str) + assert recording_oracle_address == RECORDING_ORACLE_ADDRESS def test_get_recording_oracle_address_invalid_address(self): - with self.assertRaises(EscrowClientError) as error: + with pytest.raises(EscrowClientError, match="Invalid escrow address: invalid_address"): get_recording_oracle_address(chain_id, "invalid_address") - self.assertEqual(f"Invalid escrow address: invalid_address", str(error.exception)) def test_get_recording_oracle_address_invalid_chain_id(self): - with self.assertRaises(ValueError) as error: + with pytest.raises(ValueError, match="123 is not a valid ChainId"): get_recording_oracle_address(123, escrow_address) - self.assertEqual(f"123 is not a valid ChainId", str(error.exception)) def test_get_recording_oracle_address_empty_escrow(self): with patch("src.chain.escrow.EscrowUtils.get_escrow") as mock_function: mock_function.return_value = None - with self.assertRaises(Exception) as error: + with pytest.raises(Exception, match=f"Can't find escrow {ESCROW_ADDRESS}"): get_recording_oracle_address(chain_id, escrow_address) - self.assertEqual(f"Can't find escrow {ESCROW_ADDRESS}", str(error.exception)) diff --git a/packages/examples/cvat/exchange-oracle/tests/integration/chain/test_kvstore.py b/packages/examples/cvat/exchange-oracle/tests/integration/chain/test_kvstore.py index 32dbe9599d..b2c26160f1 100644 --- a/packages/examples/cvat/exchange-oracle/tests/integration/chain/test_kvstore.py +++ b/packages/examples/cvat/exchange-oracle/tests/integration/chain/test_kvstore.py @@ -1,6 +1,7 @@ import unittest from unittest.mock import MagicMock, Mock, patch +import pytest from human_protocol_sdk.constants import ChainId, Status from human_protocol_sdk.escrow import EscrowClientError, EscrowData from human_protocol_sdk.kvstore import KVStoreClient, KVStoreClientError @@ -42,52 +43,54 @@ def setUp(self): ) def test_get_job_launcher_url(self): - with patch("src.chain.kvstore.get_escrow") as mock_escrow, patch( - "src.chain.kvstore.OperatorUtils.get_leader" - ) as mock_leader: + with ( + patch("src.chain.kvstore.get_escrow") as mock_escrow, + patch("src.chain.kvstore.OperatorUtils.get_leader") as mock_leader, + ): mock_escrow.return_value = self.escrow_data mock_leader.return_value = MagicMock(webhook_url=DEFAULT_MANIFEST_URL) recording_url = get_job_launcher_url(self.w3.eth.chain_id, escrow_address) - self.assertEqual(recording_url, DEFAULT_MANIFEST_URL) + assert recording_url == DEFAULT_MANIFEST_URL def test_get_job_launcher_url_invalid_escrow(self): - with self.assertRaises(EscrowClientError) as error: + with pytest.raises(EscrowClientError, match="Invalid escrow address: invalid_address"): get_job_launcher_url(self.w3.eth.chain_id, "invalid_address") - self.assertEqual(f"Invalid escrow address: invalid_address", str(error.exception)) def test_get_job_launcher_url_invalid_recording_address(self): - with patch("src.chain.kvstore.get_escrow") as mock_escrow, patch( - "src.chain.kvstore.OperatorUtils.get_leader" - ) as mock_leader: + with ( + patch("src.chain.kvstore.get_escrow") as mock_escrow, + patch("src.chain.kvstore.OperatorUtils.get_leader") as mock_leader, + ): mock_escrow.return_value = self.escrow_data mock_leader.return_value = MagicMock(webhook_url="") recording_url = get_job_launcher_url(self.w3.eth.chain_id, escrow_address) - self.assertEqual(recording_url, "") + assert recording_url == "" def test_get_recording_oracle_url(self): - with patch("src.chain.kvstore.get_escrow") as mock_escrow, patch( - "src.chain.kvstore.OperatorUtils.get_leader" - ) as mock_leader: + with ( + patch("src.chain.kvstore.get_escrow") as mock_escrow, + patch("src.chain.kvstore.OperatorUtils.get_leader") as mock_leader, + ): self.escrow_data.recording_oracle = RECORDING_ORACLE_ADDRESS mock_escrow.return_value = self.escrow_data mock_leader.return_value = MagicMock(webhook_url=DEFAULT_MANIFEST_URL) recording_url = get_recording_oracle_url(self.w3.eth.chain_id, escrow_address) - self.assertEqual(recording_url, DEFAULT_MANIFEST_URL) + assert recording_url == DEFAULT_MANIFEST_URL def test_get_recording_oracle_url_invalid_escrow(self): - with self.assertRaises(EscrowClientError) as error: + with pytest.raises(EscrowClientError, match="Invalid escrow address: invalid_address"): get_recording_oracle_url(self.w3.eth.chain_id, "invalid_address") - self.assertEqual(f"Invalid escrow address: invalid_address", str(error.exception)) def test_get_recording_oracle_url_invalid_recording_address(self): - with patch("src.chain.kvstore.get_escrow") as mock_escrow, patch( - "src.chain.kvstore.OperatorUtils.get_leader" - ) as mock_leader: + with ( + patch("src.chain.kvstore.get_escrow") as mock_escrow, + patch("src.chain.kvstore.OperatorUtils.get_leader") as mock_leader, + ): self.escrow_data.recording_oracle = RECORDING_ORACLE_ADDRESS mock_escrow.return_value = self.escrow_data mock_leader.return_value = MagicMock(webhook_url="") recording_url = get_recording_oracle_url(self.w3.eth.chain_id, escrow_address) - self.assertEqual(recording_url, "") + assert recording_url == "" def test_store_public_key(self): PGP_PUBLIC_KEY_URL_1 = "http://pgp-public-key-url-1" @@ -107,7 +110,7 @@ def get_file_url_and_verify_hash(*args, **kwargs): hash_ = store["public_key_hash"] if hash_ != hash(public_key): - raise KVStoreClientError(f"Invalid hash") + raise KVStoreClientError("Invalid hash") return public_key @@ -134,7 +137,7 @@ def set_file_url_and_hash(url: str, key: str): mock_web3.return_value = self.w3 kvstore_client = KVStoreClient(self.w3) - self.assertIsNone(kvstore_client.get_file_url_and_verify_hash(LocalhostConfig.addr)) + assert kvstore_client.get_file_url_and_verify_hash(LocalhostConfig.addr) is None # check that public key will be set to KVStore at first time with patch( @@ -143,9 +146,9 @@ def set_file_url_and_hash(url: str, key: str): mock_set_file_url_and_hash.side_effect = set_file_url_and_hash register_in_kvstore() mock_set_file_url_and_hash.assert_called_once() - self.assertEquals( - kvstore_client.get_file_url_and_verify_hash(LocalhostConfig.addr), - PGP_PUBLIC_KEY_URL_1, + assert ( + kvstore_client.get_file_url_and_verify_hash(LocalhostConfig.addr) + == PGP_PUBLIC_KEY_URL_1 ) # check that the same public key URL is not written to KVStore a second time @@ -156,7 +159,8 @@ def set_file_url_and_hash(url: str, key: str): register_in_kvstore() mock_set_file_url_and_hash.assert_not_called() - # check that public key URL and hash will be updated in KVStore if previous hash is outdated/corrupted + # check that public key URL and hash will be updated in KVStore + # if previous hash is outdated/corrupted with patch( "human_protocol_sdk.kvstore.KVStoreClient.set_file_url_and_hash", Mock() ) as mock_set_file_url_and_hash: @@ -164,9 +168,10 @@ def set_file_url_and_hash(url: str, key: str): store["public_key_hash"] = "corrupted_hash" register_in_kvstore() mock_set_file_url_and_hash.assert_called_once() - self.assertNotEquals(store["public_key_hash"], "corrupted_hash") + assert store["public_key_hash"] != "corrupted_hash" - # check that a new public key URL will be written to KVStore when an outdated URL is stored there + # check that a new public key URL will be written to KVStore when + # an outdated URL is stored there with ( patch( "src.core.config.Config.encryption_config.pgp_public_key_url", @@ -179,7 +184,7 @@ def set_file_url_and_hash(url: str, key: str): mock_set_file_url_and_hash.side_effect = set_file_url_and_hash register_in_kvstore() mock_set_file_url_and_hash.assert_called_once() - self.assertEquals( - kvstore_client.get_file_url_and_verify_hash(LocalhostConfig.addr), - PGP_PUBLIC_KEY_URL_2, + assert ( + kvstore_client.get_file_url_and_verify_hash(LocalhostConfig.addr) + == PGP_PUBLIC_KEY_URL_2 ) diff --git a/packages/examples/cvat/exchange-oracle/tests/integration/chain/test_web3.py b/packages/examples/cvat/exchange-oracle/tests/integration/chain/test_web3.py index 9c7da3e4f2..22f430e478 100644 --- a/packages/examples/cvat/exchange-oracle/tests/integration/chain/test_web3.py +++ b/packages/examples/cvat/exchange-oracle/tests/integration/chain/test_web3.py @@ -2,6 +2,7 @@ import unittest from unittest.mock import patch +import pytest from human_protocol_sdk.constants import ChainId from web3 import HTTPProvider, Web3 from web3.middleware import construct_sign_and_send_raw_middleware @@ -32,9 +33,9 @@ class PolygonMainnetConfig: with patch("src.chain.web3.Config.polygon_mainnet", PolygonMainnetConfig): w3 = get_web3(ChainId.POLYGON.value) - self.assertIsInstance(w3, Web3) - self.assertEqual(w3.eth.default_account, DEFAULT_GAS_PAYER) - self.assertEqual(w3.manager._provider.endpoint_uri, PolygonMainnetConfig.rpc_api) + assert isinstance(w3, Web3) + assert w3.eth.default_account == DEFAULT_GAS_PAYER + assert w3.manager._provider.endpoint_uri == PolygonMainnetConfig.rpc_api def test_get_web3_amoy(self): class PolygonAmoyConfig: @@ -44,23 +45,19 @@ class PolygonAmoyConfig: with patch("src.chain.web3.Config.polygon_amoy", PolygonAmoyConfig): w3 = get_web3(ChainId.POLYGON_AMOY.value) - self.assertIsInstance(w3, Web3) - self.assertEqual(w3.eth.default_account, DEFAULT_GAS_PAYER) - self.assertEqual(w3.manager._provider.endpoint_uri, PolygonAmoyConfig.rpc_api) + assert isinstance(w3, Web3) + assert w3.eth.default_account == DEFAULT_GAS_PAYER + assert w3.manager._provider.endpoint_uri == PolygonAmoyConfig.rpc_api def test_get_web3_localhost(self): w3 = get_web3(ChainId.LOCALHOST.value) - self.assertIsInstance(w3, Web3) - self.assertEqual(w3.eth.default_account, DEFAULT_GAS_PAYER) - self.assertEqual(w3.manager._provider.endpoint_uri, LocalhostConfig.rpc_api) + assert isinstance(w3, Web3) + assert w3.eth.default_account == DEFAULT_GAS_PAYER + assert w3.manager._provider.endpoint_uri == LocalhostConfig.rpc_api def test_get_web3_invalid_chain_id(self): - with self.assertRaises(ValueError) as error: - w3 = get_web3(1234) - self.assertEqual( - "1234 is not in available list of networks.", - str(error.exception), - ) + with pytest.raises(ValueError, match="1234 is not in available list of networks."): + get_web3(1234) def test_sign_message_polygon(self): with patch("src.chain.web3.get_web3") as mock_function: @@ -70,8 +67,8 @@ def test_sign_message_polygon(self): ): mock_function.return_value = self.w3 signature, serialized_message = sign_message(ChainId.POLYGON.value, "message") - self.assertEqual(signature, SIGNATURE) - self.assertEqual(serialized_message, json.dumps("message")) + assert signature == SIGNATURE + assert serialized_message == json.dumps("message") def test_sign_message_amoy(self): with patch("src.chain.web3.get_web3") as mock_function: @@ -81,37 +78,29 @@ def test_sign_message_amoy(self): ): mock_function.return_value = self.w3 signature, serialized_message = sign_message(ChainId.POLYGON_AMOY.value, "message") - self.assertEqual(signature, SIGNATURE) - self.assertEqual(serialized_message, json.dumps("message")) + assert signature == SIGNATURE + assert serialized_message == json.dumps("message") def test_sign_message_invalid_chain_id(self): - with self.assertRaises(ValueError) as error: + with pytest.raises(ValueError, match="1234 is not in available list of networks."): sign_message(1234, "message") - self.assertEqual( - "1234 is not in available list of networks.", - str(error.exception), - ) def test_recover_signer(self): with patch("src.chain.web3.get_web3") as mock_function: mock_function.return_value = self.w3 signer = recover_signer(ChainId.POLYGON.value, "message", SIGNATURE) - self.assertEqual(signer, DEFAULT_GAS_PAYER) + assert signer == DEFAULT_GAS_PAYER def test_recover_signer_invalid_signature(self): with patch("src.chain.web3.get_web3") as mock_function: mock_function.return_value = self.w3 signer = recover_signer(ChainId.POLYGON.value, "test", SIGNATURE) - self.assertNotEqual(signer, DEFAULT_GAS_PAYER) + assert signer != DEFAULT_GAS_PAYER def test_validate_address(self): address = validate_address(DEFAULT_GAS_PAYER) - self.assertEqual(address, DEFAULT_GAS_PAYER) + assert address == DEFAULT_GAS_PAYER def test_validate_address_invalid_address(self): - with self.assertRaises(ValueError) as error: + with pytest.raises(ValueError, match="invalid_address is not a correct Web3 address"): validate_address("invalid_address") - self.assertEqual( - f"invalid_address is not a correct Web3 address", - str(error.exception), - ) diff --git a/packages/examples/cvat/exchange-oracle/tests/integration/cron/__init__.py b/packages/examples/cvat/exchange-oracle/tests/integration/cron/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/__init__.py b/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/test_track_assignments.py b/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/test_track_assignments.py index 446482bfae..2a0008ce37 100644 --- a/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/test_track_assignments.py +++ b/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/test_track_assignments.py @@ -3,20 +3,16 @@ from datetime import datetime, timedelta from unittest.mock import patch +import pytest from sqlalchemy import update -from sqlalchemy.sql import select from src.core.types import ( AssignmentStatuses, - JobStatuses, - Networks, ProjectStatuses, - TaskStatuses, - TaskTypes, ) from src.crons.state_trackers import track_assignments from src.db import SessionLocal -from src.models.cvat import Assignment, Job, Project, Task, User +from src.models.cvat import Assignment, Project, User from tests.utils.db_helper import create_project_task_and_job @@ -67,8 +63,8 @@ def test_track_expired_assignments(self): db_assignments = sorted( self.session.query(Assignment).all(), key=lambda assignment: assignment.user.cvat_id ) - self.assertEqual(db_assignments[0].status, AssignmentStatuses.created.value) - self.assertEqual(db_assignments[1].status, AssignmentStatuses.created.value) + assert db_assignments[0].status == AssignmentStatuses.created.value + assert db_assignments[1].status == AssignmentStatuses.created.value with patch("src.crons.state_trackers.cvat_api.update_job_assignee") as mock_cvat_api: track_assignments() @@ -79,74 +75,77 @@ def test_track_expired_assignments(self): db_assignments = sorted( self.session.query(Assignment).all(), key=lambda assignment: assignment.user.cvat_id ) - self.assertEqual(db_assignments[0].status, AssignmentStatuses.created.value) - self.assertEqual(db_assignments[1].status, AssignmentStatuses.expired.value) - - # TODO: - # Fix src/crons/state_trackers.py - # Where in `cvat_service.get_active_assignments()` return value will be empty - # because it actually looking for the expired assignments - - # def test_track_canceled_assignments(self): - # (_, _, cvat_job) = create_project_task_and_job( - # self.session, "0x86e83d346041E8806e352681f3F14549C0d2BC67", 1 - # ) - # (cvat_project_2, _, cvat_job_2) = create_project_task_and_job( - # self.session, "0x86e83d346041E8806e352681f3F14549C0d2BC68", 2 - # ) - # wallet_address_1 = "0x86e83d346041E8806e352681f3F14549C0d2BC67" - # user = User( - # wallet_address=wallet_address_1, - # cvat_email="test@hmt.ai", - # cvat_id=1, - # ) - # self.session.add(user) - - # wallet_address_2 = "0x86e83d346041E8806e352681f3F14549C0d2BC68" - # user = User( - # wallet_address=wallet_address_2, - # cvat_email="test2@hmt.ai", - # cvat_id=2, - # ) - # self.session.add(user) - # assignment = Assignment( - # id=str(uuid.uuid4()), - # user_wallet_address=wallet_address_1, - # cvat_job_id=cvat_job.cvat_id, - # expires_at=datetime.now() + timedelta(days=1), - # ) - # assignment_2 = Assignment( - # id=str(uuid.uuid4()), - # user_wallet_address=wallet_address_2, - # cvat_job_id=cvat_job_2.cvat_id, - # expires_at=datetime.now() + timedelta(days=1), - # created_at=datetime.now() + timedelta(hours=1), - # ) - # self.session.add(assignment) - # self.session.add(assignment_2) - - # self.session.execute( - # update(Project) - # .where(Project.id == cvat_project_2.id) - # .values(status=ProjectStatuses.completed.value) - # ) - - # self.session.commit() - - # db_assignments = sorted( - # self.session.query(Assignment).all(), key=lambda assignment: assignment.user.cvat_id - # ) - # self.assertEqual(db_assignments[0].status, AssignmentStatus.created.value) - # self.assertEqual(db_assignments[1].status, AssignmentStatus.created.value) - - # with patch("src.crons.state_trackers.cvat_api.update_job_assignee") as mock_cvat_api: - # track_assignments() - # mock_cvat_api.assert_called_once_with(assignment_2.cvat_job_id, assignee_id=None) - - # self.session.commit() - - # db_assignments = sorted( - # self.session.query(Assignment).all(), key=lambda assignment: assignment.user.cvat_id - # ) - # self.assertEqual(db_assignments[0].status, AssignmentStatus.created.value) - # self.assertEqual(db_assignments[1].status, AssignmentStatus.canceled.value) + assert db_assignments[0].status == AssignmentStatuses.created.value + assert db_assignments[1].status == AssignmentStatuses.expired.value + + @pytest.mark.xfail( + strict=True, + reason=""" +Fix src/crons/state_trackers.py +Where in `cvat_service.get_active_assignments()` return value will be empty +because it actually looking for the expired assignments +""", + ) + def test_track_canceled_assignments(self): + (_, _, cvat_job) = create_project_task_and_job( + self.session, "0x86e83d346041E8806e352681f3F14549C0d2BC67", 1 + ) + (cvat_project_2, _, cvat_job_2) = create_project_task_and_job( + self.session, "0x86e83d346041E8806e352681f3F14549C0d2BC68", 2 + ) + wallet_address_1 = "0x86e83d346041E8806e352681f3F14549C0d2BC67" + user = User( + wallet_address=wallet_address_1, + cvat_email="test@hmt.ai", + cvat_id=1, + ) + self.session.add(user) + + wallet_address_2 = "0x86e83d346041E8806e352681f3F14549C0d2BC68" + user = User( + wallet_address=wallet_address_2, + cvat_email="test2@hmt.ai", + cvat_id=2, + ) + self.session.add(user) + assignment = Assignment( + id=str(uuid.uuid4()), + user_wallet_address=wallet_address_1, + cvat_job_id=cvat_job.cvat_id, + expires_at=datetime.now() + timedelta(days=1), + ) + assignment_2 = Assignment( + id=str(uuid.uuid4()), + user_wallet_address=wallet_address_2, + cvat_job_id=cvat_job_2.cvat_id, + expires_at=datetime.now() + timedelta(days=1), + created_at=datetime.now() + timedelta(hours=1), + ) + self.session.add(assignment) + self.session.add(assignment_2) + + self.session.execute( + update(Project) + .where(Project.id == cvat_project_2.id) + .values(status=ProjectStatuses.completed.value) + ) + + self.session.commit() + + db_assignments = sorted( + self.session.query(Assignment).all(), key=lambda assignment: assignment.user.cvat_id + ) + assert db_assignments[0].status == AssignmentStatuses.created.value + assert db_assignments[1].status == AssignmentStatuses.created.value + + with patch("src.crons.state_trackers.cvat_api.update_job_assignee") as mock_cvat_api: + track_assignments() + mock_cvat_api.assert_called_once_with(assignment_2.cvat_job_id, assignee_id=None) + + self.session.commit() + + db_assignments = sorted( + self.session.query(Assignment).all(), key=lambda assignment: assignment.user.cvat_id + ) + assert db_assignments[0].status == AssignmentStatuses.created.value + assert db_assignments[1].status == AssignmentStatuses.canceled.value diff --git a/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/test_track_completed_escrows.py b/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/test_track_completed_escrows.py index 0844eb5560..dfcf5025f0 100644 --- a/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/test_track_completed_escrows.py +++ b/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/test_track_completed_escrows.py @@ -141,14 +141,13 @@ def test_retrieve_annotations(self): .filter_by(escrow_address=escrow_address, chain_id=Networks.localhost.value) .first() ) - self.assertIsNotNone(webhook) - self.assertEqual(webhook.event_type, ExchangeOracleEventTypes.task_finished) + assert webhook is not None + assert webhook.event_type == ExchangeOracleEventTypes.task_finished db_project = self.session.query(Project).filter_by(id=project_id).first() - self.assertEqual(db_project.status, ProjectStatuses.validation) + assert db_project.status == ProjectStatuses.validation - @patch("src.cvat.api_calls.get_job_annotations") - def test_retrieve_annotations_error_getting_annotations(self, mock_annotations): + def test_retrieve_annotations_error_getting_annotations(self): cvat_project_id = 1 escrow_address = "0x86e83d346041E8806e352681f3F14549C0d2BC67" project_id = str(uuid.uuid4()) @@ -232,11 +231,11 @@ def test_retrieve_annotations_error_getting_annotations(self, mock_annotations): .filter_by(escrow_address=escrow_address, chain_id=Networks.localhost.value) .first() ) - self.assertIsNone(webhook) + assert webhook is None db_project = self.session.query(Project).filter_by(id=project_id).first() - self.assertEqual(db_project.status, ProjectStatuses.completed.value) + assert db_project.status == ProjectStatuses.completed.value def test_retrieve_annotations_error_uploading_files(self): cvat_project_id = 1 @@ -311,11 +310,11 @@ def test_retrieve_annotations_error_uploading_files(self): .filter_by(escrow_address=escrow_address, chain_id=Networks.localhost.value) .first() ) - self.assertIsNone(webhook) + assert webhook is None db_project = self.session.query(Project).filter_by(id=project_id).first() - self.assertEqual(db_project.status, ProjectStatuses.completed.value) + assert db_project.status == ProjectStatuses.completed.value def test_retrieve_annotations_multiple_projects_per_escrow_all_completed(self): escrow_address = "0x86e83d346041E8806e352681f3F14549C0d2BC67" @@ -394,9 +393,10 @@ def test_retrieve_annotations_multiple_projects_per_escrow_all_completed(self): def _fake_get_annotations(*args, **kwargs): dummy_zip_file = io.BytesIO() - with zipfile.ZipFile( - dummy_zip_file, "w" - ) as archive, TemporaryDirectory() as tempdir: + with ( + zipfile.ZipFile(dummy_zip_file, "w") as archive, + TemporaryDirectory() as tempdir, + ): mock_dataset = dm.Dataset( media_type=dm.Image, categories={ @@ -443,17 +443,17 @@ def _fake_postprocess_annotations( .filter_by(escrow_address=escrow_address, chain_id=Networks.localhost.value) .first() ) - self.assertIsNotNone(webhook) - self.assertEqual(webhook.event_type, ExchangeOracleEventTypes.task_finished) + assert webhook is not None + assert webhook.event_type == ExchangeOracleEventTypes.task_finished db_projects = ( self.session.query(Project) .where(Project.id.in_([project1.id, project2.id, project3.id])) .all() ) - self.assertEqual(len(db_projects), 3) + assert len(db_projects) == 3 for db_project in db_projects: - self.assertEqual(db_project.status, ProjectStatuses.validation) + assert db_project.status == ProjectStatuses.validation def test_retrieve_annotations_multiple_projects_per_escrow_some_completed_some_validation(self): escrow_address = "0x86e83d346041E8806e352681f3F14549C0d2BC67" @@ -532,9 +532,10 @@ def test_retrieve_annotations_multiple_projects_per_escrow_some_completed_some_v def _fake_get_annotations(*args, **kwargs): dummy_zip_file = io.BytesIO() - with zipfile.ZipFile( - dummy_zip_file, "w" - ) as archive, TemporaryDirectory() as tempdir: + with ( + zipfile.ZipFile(dummy_zip_file, "w") as archive, + TemporaryDirectory() as tempdir, + ): mock_dataset = dm.Dataset( media_type=dm.Image, categories={ @@ -581,17 +582,17 @@ def _fake_postprocess_annotations( .filter_by(escrow_address=escrow_address, chain_id=Networks.localhost.value) .first() ) - self.assertIsNotNone(webhook) - self.assertEqual(webhook.event_type, ExchangeOracleEventTypes.task_finished) + assert webhook is not None + assert webhook.event_type == ExchangeOracleEventTypes.task_finished db_projects = ( self.session.query(Project) .where(Project.id.in_([project1.id, project2.id, project3.id])) .all() ) - self.assertEqual(len(db_projects), 3) + assert len(db_projects) == 3 for db_project in db_projects: - self.assertEqual(db_project.status, ProjectStatuses.validation) + assert db_project.status == ProjectStatuses.validation def test_retrieve_annotations_multiple_projects_per_escrow_all_validation(self): escrow_address = "0x86e83d346041E8806e352681f3F14549C0d2BC67" @@ -671,13 +672,13 @@ def test_retrieve_annotations_multiple_projects_per_escrow_all_validation(self): mock_postprocess_annotations.assert_not_called() - self.assertEqual(self.session.query(Webhook).count(), 0) + assert self.session.query(Webhook).count() == 0 db_projects = ( self.session.query(Project) .where(Project.id.in_([project1.id, project2.id, project3.id])) .all() ) - self.assertEqual(len(db_projects), 3) + assert len(db_projects) == 3 for db_project in db_projects: - self.assertEqual(db_project.status, ProjectStatuses.validation) + assert db_project.status == ProjectStatuses.validation diff --git a/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/test_track_completed_projects.py b/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/test_track_completed_projects.py index 489215e0db..36de489508 100644 --- a/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/test_track_completed_projects.py +++ b/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/test_track_completed_projects.py @@ -46,7 +46,7 @@ def test_track_completed_projects(self): self.session.execute(select(Project).where(Project.id == project_id)).scalars().first() ) - self.assertEqual(updated_project.status, ProjectStatuses.completed.value) + assert updated_project.status == ProjectStatuses.completed.value def test_track_completed_projects_with_unfinished_task(self): project_id = str(uuid.uuid4()) @@ -85,4 +85,4 @@ def test_track_completed_projects_with_unfinished_task(self): self.session.execute(select(Project).where(Project.id == project_id)).scalars().first() ) - self.assertEqual(updated_project.status, ProjectStatuses.annotation.value) + assert updated_project.status == ProjectStatuses.annotation.value diff --git a/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/test_track_completed_tasks.py b/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/test_track_completed_tasks.py index 4619c5b7cf..614afd20d6 100644 --- a/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/test_track_completed_tasks.py +++ b/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/test_track_completed_tasks.py @@ -55,7 +55,7 @@ def test_track_completed_tasks(self): self.session.execute(select(Task).where(Task.id == task_id)).scalars().first() ) - self.assertEqual(updated_task.status, TaskStatuses.completed.value) + assert updated_task.status == TaskStatuses.completed.value def test_track_completed_tasks_with_unfinished_job(self): project = Project( @@ -104,4 +104,4 @@ def test_track_completed_tasks_with_unfinished_job(self): self.session.execute(select(Task).where(Task.id == task_id)).scalars().first() ) - self.assertEqual(updated_task.status, TaskStatuses.annotation.value) + assert updated_task.status == TaskStatuses.annotation.value diff --git a/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/test_track_escrow_creation.py b/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/test_track_escrow_creation.py index 46e1dd9a23..b1cc99f939 100644 --- a/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/test_track_escrow_creation.py +++ b/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/test_track_escrow_creation.py @@ -46,7 +46,7 @@ def test_track_track_successful_escrow_creation(self): updated_projects = ( self.session.query(Project).where(Project.cvat_id.in_(cvat_project_ids)).all() ) - self.assertEqual( - [p.status for p in updated_projects], - [ProjectStatuses.annotation, ProjectStatuses.annotation], - ) + assert [p.status for p in updated_projects] == [ + ProjectStatuses.annotation, + ProjectStatuses.annotation, + ] diff --git a/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/test_track_task_creation.py b/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/test_track_task_creation.py index a140355d7d..c04c1181a5 100644 --- a/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/test_track_task_creation.py +++ b/packages/examples/cvat/exchange-oracle/tests/integration/cron/state_trackers/test_track_task_creation.py @@ -38,9 +38,9 @@ def test_track_track_failed_task_creation(self): track_task_creation() webhook = self.session.query(Webhook).filter_by(escrow_address=escrow_address).first() - self.assertIsNotNone(webhook) + assert webhook is not None data_upload = self.session.query(DataUpload).filter_by(id=upload_id).first() - self.assertIsNone(data_upload) + assert data_upload is None def test_track_track_completed_task_creation(self): escrow_address = "0x86e83d346041E8806e352681f3F14549C0d2BC67" @@ -75,11 +75,11 @@ def test_track_track_completed_task_creation(self): self.session.commit() jobs = self.session.query(Job).all() - self.assertIsNotNone(jobs) - self.assertEqual(len(jobs), 2) - self.assertTrue(any(job.cvat_id == 2 for job in jobs)) + assert jobs is not None + assert len(jobs) == 2 + assert any(job.cvat_id == 2 for job in jobs) data_upload = self.session.query(DataUpload).filter_by(id=upload_id).first() - self.assertIsNone(data_upload) + assert data_upload is None def test_track_track_completed_task_creation_error(self): escrow_address = "0x86e83d346041E8806e352681f3F14549C0d2BC67" @@ -107,5 +107,5 @@ def test_track_track_completed_task_creation_error(self): self.session.commit() webhook = self.session.query(Webhook).filter_by(escrow_address=escrow_address).first() - self.assertIsNotNone(webhook) - self.assertEqual(webhook.event_type, ExchangeOracleEventTypes.task_creation_failed) + assert webhook is not None + assert webhook.event_type == ExchangeOracleEventTypes.task_creation_failed diff --git a/packages/examples/cvat/exchange-oracle/tests/integration/cron/test_process_job_launcher_webhooks.py b/packages/examples/cvat/exchange-oracle/tests/integration/cron/test_process_job_launcher_webhooks.py index cddac828f7..1fbb1b1c35 100644 --- a/packages/examples/cvat/exchange-oracle/tests/integration/cron/test_process_job_launcher_webhooks.py +++ b/packages/examples/cvat/exchange-oracle/tests/integration/cron/test_process_job_launcher_webhooks.py @@ -92,23 +92,23 @@ def test_process_incoming_job_launcher_webhooks_escrow_created_type(self): self.session.execute(select(Webhook).where(Webhook.id == webhok_id)).scalars().first() ) - self.assertEqual(updated_webhook.status, OracleWebhookStatuses.completed.value) - self.assertEqual(updated_webhook.attempts, 1) + assert updated_webhook.status == OracleWebhookStatuses.completed.value + assert updated_webhook.attempts == 1 db_project = ( self.session.query(Project) .filter_by(escrow_address=escrow_address, chain_id=chain_id) .first() ) - self.assertEqual(db_project.status, ProjectStatuses.creation.value) + assert db_project.status == ProjectStatuses.creation.value db_escrow_creation_tracker = ( self.session.query(EscrowCreation) .filter_by(escrow_address=escrow_address, chain_id=chain_id) .first() ) - self.assertListEqual(db_escrow_creation_tracker.projects, [db_project]) - self.assertEqual(db_escrow_creation_tracker.total_jobs, 1) + assert db_escrow_creation_tracker.projects == [db_project] + assert db_escrow_creation_tracker.total_jobs == 1 def test_process_incoming_job_launcher_webhooks_escrow_created_type_invalid_escrow_status( self, @@ -138,8 +138,8 @@ def test_process_incoming_job_launcher_webhooks_escrow_created_type_invalid_escr updated_webhook = self.session.query(Webhook).filter_by(id=webhok_id).first() - self.assertEqual(updated_webhook.status, OracleWebhookStatuses.pending.value) - self.assertEqual(updated_webhook.attempts, 1) + assert updated_webhook.status == OracleWebhookStatuses.pending.value + assert updated_webhook.attempts == 1 def test_process_incoming_job_launcher_webhooks_escrow_created_type_exceed_max_retries( self, @@ -170,8 +170,8 @@ def test_process_incoming_job_launcher_webhooks_escrow_created_type_exceed_max_r updated_webhook = self.session.query(Webhook).filter_by(id=webhok_id).first() - self.assertEqual(updated_webhook.status, OracleWebhookStatuses.failed.value) - self.assertEqual(updated_webhook.attempts, 6) + assert updated_webhook.status == OracleWebhookStatuses.failed.value + assert updated_webhook.attempts == 6 new_webhook = ( self.session.query(Webhook) @@ -183,9 +183,9 @@ def test_process_incoming_job_launcher_webhooks_escrow_created_type_exceed_max_r .first() ) - self.assertEqual(new_webhook.status, OracleWebhookStatuses.pending.value) - self.assertEqual(new_webhook.event_type, ExchangeOracleEventTypes.task_creation_failed) - self.assertEqual(new_webhook.attempts, 0) + assert new_webhook.status == OracleWebhookStatuses.pending.value + assert new_webhook.event_type == ExchangeOracleEventTypes.task_creation_failed + assert new_webhook.attempts == 0 def test_process_incoming_job_launcher_webhooks_escrow_created_type_remove_when_error( self, @@ -240,15 +240,15 @@ def test_process_incoming_job_launcher_webhooks_escrow_created_type_remove_when_ self.session.execute(select(Webhook).where(Webhook.id == webhok_id)).scalars().first() ) - self.assertEqual(updated_webhook.status, OracleWebhookStatuses.pending.value) - self.assertEqual(updated_webhook.attempts, 1) + assert updated_webhook.status == OracleWebhookStatuses.pending.value + assert updated_webhook.attempts == 1 db_project = ( self.session.query(Project) .filter_by(escrow_address=escrow_address, chain_id=chain_id) .first() ) - self.assertIsNone(db_project) + assert db_project is None def test_process_incoming_job_launcher_webhooks_escrow_canceled_type(self): project_id = str(uuid.uuid4()) @@ -290,17 +290,17 @@ def test_process_incoming_job_launcher_webhooks_escrow_canceled_type(self): self.session.execute(select(Webhook).where(Webhook.id == webhok_id)).scalars().first() ) - self.assertEqual(updated_webhook.status, OracleWebhookStatuses.completed.value) - self.assertEqual(updated_webhook.attempts, 1) + assert updated_webhook.status == OracleWebhookStatuses.completed.value + assert updated_webhook.attempts == 1 db_project = ( self.session.query(Project) .filter_by(escrow_address=escrow_address, chain_id=chain_id) .first() ) - self.assertEqual(db_project.status, ProjectStatuses.canceled.value) + assert db_project.status == ProjectStatuses.canceled.value - def test_process_incoming_job_launcher_webhooks_escrow_canceled_type_with_multiple_creating_projects( + def test_process_incoming_job_launcher_webhooks_escrow_canceled_type_with_multiple_creating_projects( # noqa: E501 self, ): project_ids = [] @@ -353,22 +353,22 @@ def test_process_incoming_job_launcher_webhooks_escrow_canceled_type_with_multip self.session.execute(select(Webhook).where(Webhook.id == webhok_id)).scalars().first() ) - self.assertEqual(updated_webhook.status, OracleWebhookStatuses.completed.value) - self.assertEqual(updated_webhook.attempts, 1) + assert updated_webhook.status == OracleWebhookStatuses.completed.value + assert updated_webhook.attempts == 1 db_project = ( self.session.query(Project) .filter_by(escrow_address=escrow_address, chain_id=chain_id) .first() ) - self.assertEqual(db_project.status, ProjectStatuses.canceled.value) + assert db_project.status == ProjectStatuses.canceled.value db_escrow_creation_tracker = ( self.session.query(EscrowCreation) .filter_by(escrow_address=escrow_address, chain_id=chain_id) .first() ) - self.assertTrue(bool(db_escrow_creation_tracker.finished_at)) + assert bool(db_escrow_creation_tracker.finished_at) def test_process_incoming_job_launcher_webhooks_escrow_canceled_type_invalid_status( self, @@ -411,15 +411,15 @@ def test_process_incoming_job_launcher_webhooks_escrow_canceled_type_invalid_sta self.session.execute(select(Webhook).where(Webhook.id == webhok_id)).scalars().first() ) - self.assertEqual(updated_webhook.status, OracleWebhookStatuses.pending.value) - self.assertEqual(updated_webhook.attempts, 1) + assert updated_webhook.status == OracleWebhookStatuses.pending.value + assert updated_webhook.attempts == 1 db_project = ( self.session.query(Project) .filter_by(escrow_address=escrow_address, chain_id=chain_id) .first() ) - self.assertEqual(db_project.status, ProjectStatuses.annotation.value) + assert db_project.status == ProjectStatuses.annotation.value def test_process_incoming_job_launcher_webhooks_escrow_canceled_type_invalid_balance( self, @@ -463,15 +463,15 @@ def test_process_incoming_job_launcher_webhooks_escrow_canceled_type_invalid_bal self.session.execute(select(Webhook).where(Webhook.id == webhok_id)).scalars().first() ) - self.assertEqual(updated_webhook.status, OracleWebhookStatuses.pending.value) - self.assertEqual(updated_webhook.attempts, 1) + assert updated_webhook.status == OracleWebhookStatuses.pending.value + assert updated_webhook.attempts == 1 db_project = ( self.session.query(Project) .filter_by(escrow_address=escrow_address, chain_id=chain_id) .first() ) - self.assertEqual(db_project.status, ProjectStatuses.annotation.value) + assert db_project.status == ProjectStatuses.annotation.value def test_process_outgoing_job_launcher_webhooks(self): chain_id = Networks.localhost.value @@ -511,8 +511,8 @@ def test_process_outgoing_job_launcher_webhooks(self): self.session.execute(select(Webhook).where(Webhook.id == webhok_id)).scalars().first() ) - self.assertEqual(updated_webhook.status, OracleWebhookStatuses.completed.value) - self.assertEqual(updated_webhook.attempts, 1) + assert updated_webhook.status == OracleWebhookStatuses.completed.value + assert updated_webhook.attempts == 1 mock_httpx_post.assert_called_once() def test_process_outgoing_job_launcher_webhooks_invalid_type(self): @@ -539,5 +539,5 @@ def test_process_outgoing_job_launcher_webhooks_invalid_type(self): self.session.execute(select(Webhook).where(Webhook.id == webhok_id)).scalars().first() ) - self.assertEqual(updated_webhook.status, OracleWebhookStatuses.pending.value) - self.assertEqual(updated_webhook.attempts, 1) + assert updated_webhook.status == OracleWebhookStatuses.pending.value + assert updated_webhook.attempts == 1 diff --git a/packages/examples/cvat/exchange-oracle/tests/integration/cron/test_process_recording_oracle_webhooks.py b/packages/examples/cvat/exchange-oracle/tests/integration/cron/test_process_recording_oracle_webhooks.py index 9f3b6a5880..af027d81a9 100644 --- a/packages/examples/cvat/exchange-oracle/tests/integration/cron/test_process_recording_oracle_webhooks.py +++ b/packages/examples/cvat/exchange-oracle/tests/integration/cron/test_process_recording_oracle_webhooks.py @@ -73,11 +73,11 @@ def test_process_incoming_recording_oracle_webhooks_task_completed_type(self): self.session.execute(select(Webhook).where(Webhook.id == webhok_id)).scalars().first() ) - self.assertEqual(updated_webhook.status, OracleWebhookStatuses.completed.value) - self.assertEqual(updated_webhook.attempts, 1) + assert updated_webhook.status == OracleWebhookStatuses.completed.value + assert updated_webhook.attempts == 1 db_project = self.session.query(Project).filter_by(id=project_id).first() - self.assertEqual(db_project.status, ProjectStatuses.recorded.value) + assert db_project.status == ProjectStatuses.recorded.value def test_process_incoming_recording_oracle_webhooks_task_completed_type_invalid_project_status( self, @@ -116,12 +116,12 @@ def test_process_incoming_recording_oracle_webhooks_task_completed_type_invalid_ self.session.execute(select(Webhook).where(Webhook.id == webhok_id)).scalars().first() ) - self.assertEqual(updated_webhook.status, OracleWebhookStatuses.completed.value) - self.assertEqual(updated_webhook.attempts, 1) + assert updated_webhook.status == OracleWebhookStatuses.completed.value + assert updated_webhook.attempts == 1 db_project = self.session.query(Project).filter_by(id=project_id).first() - self.assertEqual(db_project.status, ProjectStatuses.completed.value) + assert db_project.status == ProjectStatuses.completed.value def test_process_incoming_recording_oracle_webhooks_task_task_rejected_type(self): cvat_id = 1 @@ -179,21 +179,21 @@ def test_process_incoming_recording_oracle_webhooks_task_task_rejected_type(self self.session.execute(select(Webhook).where(Webhook.id == webhok_id)).scalars().first() ) - self.assertEqual(updated_webhook.status, OracleWebhookStatuses.completed.value) - self.assertEqual(updated_webhook.attempts, 1) + assert updated_webhook.status == OracleWebhookStatuses.completed.value + assert updated_webhook.attempts == 1 db_project = self.session.query(Project).filter_by(id=project_id).first() - self.assertEqual(db_project.status, ProjectStatuses.annotation.value) + assert db_project.status == ProjectStatuses.annotation.value db_task = self.session.query(Task).filter_by(id=task_id).first() - self.assertEqual(db_task.status, TaskStatuses.annotation.value) + assert db_task.status == TaskStatuses.annotation.value db_job = self.session.query(Job).filter_by(id=job_id).first() - self.assertEqual(db_job.status, JobStatuses.new.value) + assert db_job.status == JobStatuses.new.value - def test_process_incoming_recording_oracle_webhooks_task_task_rejected_type_invalid_project_status( + def test_process_incoming_recording_oracle_webhooks_task_task_rejected_type_invalid_project_status( # noqa: E501 self, ): cvat_id = 1 @@ -233,12 +233,12 @@ def test_process_incoming_recording_oracle_webhooks_task_task_rejected_type_inva self.session.execute(select(Webhook).where(Webhook.id == webhok_id)).scalars().first() ) - self.assertEqual(updated_webhook.status, OracleWebhookStatuses.completed.value) - self.assertEqual(updated_webhook.attempts, 1) + assert updated_webhook.status == OracleWebhookStatuses.completed.value + assert updated_webhook.attempts == 1 db_project = self.session.query(Project).filter_by(id=project_id).first() - self.assertEqual(db_project.status, ProjectStatuses.completed.value) + assert db_project.status == ProjectStatuses.completed.value def test_process_outgoing_recording_oracle_webhooks(self): chain_id = Networks.localhost.value @@ -278,8 +278,8 @@ def test_process_outgoing_recording_oracle_webhooks(self): self.session.execute(select(Webhook).where(Webhook.id == webhok_id)).scalars().first() ) - self.assertEqual(updated_webhook.status, OracleWebhookStatuses.completed.value) - self.assertEqual(updated_webhook.attempts, 1) + assert updated_webhook.status == OracleWebhookStatuses.completed.value + assert updated_webhook.attempts == 1 mock_httpx_post.assert_called_once() def test_process_outgoing_recording_oracle_webhooks_invalid_type(self): @@ -306,5 +306,5 @@ def test_process_outgoing_recording_oracle_webhooks_invalid_type(self): self.session.execute(select(Webhook).where(Webhook.id == webhok_id)).scalars().first() ) - self.assertEqual(updated_webhook.status, OracleWebhookStatuses.pending.value) - self.assertEqual(updated_webhook.attempts, 1) + assert updated_webhook.status == OracleWebhookStatuses.pending.value + assert updated_webhook.attempts == 1 diff --git a/packages/examples/cvat/exchange-oracle/tests/integration/services/__init__.py b/packages/examples/cvat/exchange-oracle/tests/integration/services/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/examples/cvat/exchange-oracle/tests/integration/services/test_cvat.py b/packages/examples/cvat/exchange-oracle/tests/integration/services/test_cvat.py index 0a2bf196af..3a652aa20b 100644 --- a/packages/examples/cvat/exchange-oracle/tests/integration/services/test_cvat.py +++ b/packages/examples/cvat/exchange-oracle/tests/integration/services/test_cvat.py @@ -2,6 +2,7 @@ import uuid from datetime import datetime, timedelta +import pytest from sqlalchemy.exc import IntegrityError from sqlalchemy.orm.exc import UnmappedInstanceError @@ -50,14 +51,14 @@ def test_create_project(self): project = self.session.query(Project).filter_by(id=p_id).first() - self.assertIsNotNone(project) - self.assertEqual(project.id, p_id) - self.assertEqual(project.cvat_id, cvat_id) - self.assertEqual(project.status, ProjectStatuses.creation.value) - self.assertEqual(project.job_type, job_type) - self.assertEqual(project.escrow_address, escrow_address) - self.assertEqual(project.chain_id, chain_id) - self.assertEqual(project.bucket_url, bucket_url) + assert project is not None + assert project.id == p_id + assert project.cvat_id == cvat_id + assert project.status == ProjectStatuses.creation.value + assert project.job_type == job_type + assert project.escrow_address == escrow_address + assert project.chain_id == chain_id + assert project.bucket_url == bucket_url def test_create_duplicated_project(self): cvat_id = 1 @@ -86,7 +87,7 @@ def test_create_duplicated_project(self): chain_id, bucket_url, ) - with self.assertRaises(IntegrityError): + with pytest.raises(IntegrityError): self.session.commit() def test_create_project_none_cvat_id(self): @@ -104,7 +105,7 @@ def test_create_project_none_cvat_id(self): chain_id, bucket_url, ) - with self.assertRaises(IntegrityError): + with pytest.raises(IntegrityError): self.session.commit() def test_create_project_none_cvat_cloudstorage_id(self): @@ -122,7 +123,7 @@ def test_create_project_none_cvat_cloudstorage_id(self): chain_id, bucket_url, ) - with self.assertRaises(IntegrityError): + with pytest.raises(IntegrityError): self.session.commit() def test_create_project_none_job_type(self): @@ -140,7 +141,7 @@ def test_create_project_none_job_type(self): chain_id, bucket_url, ) - with self.assertRaises(IntegrityError): + with pytest.raises(IntegrityError): self.session.commit() def test_create_project_none_escrow_address(self): @@ -158,7 +159,7 @@ def test_create_project_none_escrow_address(self): chain_id, bucket_url, ) - with self.assertRaises(IntegrityError): + with pytest.raises(IntegrityError): self.session.commit() def test_create_project_none_chain_id(self): @@ -177,7 +178,7 @@ def test_create_project_none_chain_id(self): None, bucket_url, ) - with self.assertRaises(IntegrityError): + with pytest.raises(IntegrityError): self.session.commit() def test_create_project_none_bucket_url(self): @@ -195,7 +196,7 @@ def test_create_project_none_bucket_url(self): chain_id, None, ) - with self.assertRaises(IntegrityError): + with pytest.raises(IntegrityError): self.session.commit() def test_get_project_by_id(self): @@ -218,35 +219,35 @@ def test_get_project_by_id(self): project = cvat_service.get_project_by_id(self.session, p_id) - self.assertIsNotNone(project) - self.assertEqual(project.id, p_id) - self.assertEqual(project.cvat_id, cvat_id) - self.assertEqual(project.status, ProjectStatuses.annotation.value) - self.assertEqual(project.job_type, job_type) - self.assertEqual(project.escrow_address, escrow_address) - self.assertEqual(project.bucket_url, bucket_url) + assert project is not None + assert project.id == p_id + assert project.cvat_id == cvat_id + assert project.status == ProjectStatuses.annotation.value + assert project.job_type == job_type + assert project.escrow_address == escrow_address + assert project.bucket_url == bucket_url project = cvat_service.get_project_by_id(self.session, "dummy_id") - self.assertIsNone(project) + assert project is None project = cvat_service.get_project_by_id( self.session, p_id, status_in=[ProjectStatuses.annotation] ) - self.assertIsNotNone(project) - self.assertEqual(project.id, p_id) - self.assertEqual(project.cvat_id, cvat_id) - self.assertEqual(project.status, ProjectStatuses.annotation.value) - self.assertEqual(project.job_type, job_type) - self.assertEqual(project.escrow_address, escrow_address) - self.assertEqual(project.bucket_url, bucket_url) + assert project is not None + assert project.id == p_id + assert project.cvat_id == cvat_id + assert project.status == ProjectStatuses.annotation.value + assert project.job_type == job_type + assert project.escrow_address == escrow_address + assert project.bucket_url == bucket_url project = cvat_service.get_project_by_id( self.session, p_id, status_in=[ProjectStatuses.canceled] ) - self.assertIsNone(project) + assert project is None def test_get_project_by_escrow_address(self): cvat_id = 1 @@ -268,18 +269,18 @@ def test_get_project_by_escrow_address(self): project = cvat_service.get_project_by_escrow_address(self.session, escrow_address) - self.assertIsNotNone(project) - self.assertEqual(project.id, p_id) - self.assertEqual(project.cvat_id, cvat_id) - self.assertEqual(project.status, ProjectStatuses.annotation.value) - self.assertEqual(project.job_type, job_type) - self.assertEqual(project.escrow_address, escrow_address) - self.assertEqual(project.chain_id, chain_id) - self.assertEqual(project.bucket_url, bucket_url) + assert project is not None + assert project.id == p_id + assert project.cvat_id == cvat_id + assert project.status == ProjectStatuses.annotation.value + assert project.job_type == job_type + assert project.escrow_address == escrow_address + assert project.chain_id == chain_id + assert project.bucket_url == bucket_url project = cvat_service.get_project_by_escrow_address(self.session, "invalid escrow address") - self.assertIsNone(project) + assert project is None def test_get_projects_by_status(self): cvat_id = 1 @@ -333,17 +334,17 @@ def test_get_projects_by_status(self): projects = cvat_service.get_projects_by_status(self.session, ProjectStatuses.annotation) - self.assertEqual(len(projects), 3) + assert len(projects) == 3 cvat_service.update_project_status(self.session, p_id, ProjectStatuses.completed) projects = cvat_service.get_projects_by_status(self.session, ProjectStatuses.annotation) - self.assertEqual(len(projects), 2) + assert len(projects) == 2 projects = cvat_service.get_projects_by_status(self.session, ProjectStatuses.completed) - self.assertEqual(len(projects), 1) + assert len(projects) == 1 def test_get_available_projects(self): cvat_id_1 = 456 @@ -353,7 +354,7 @@ def test_get_available_projects(self): projects = cvat_service.get_available_projects(self.session) - self.assertEqual(len(projects), 1) + assert len(projects) == 1 cvat_id_2 = 457 (cvat_project, cvat_task) = create_project_and_task( @@ -377,9 +378,9 @@ def test_get_available_projects(self): ) projects = cvat_service.get_available_projects(self.session) - self.assertEqual(len(projects), 2) - self.assertTrue(any(project.cvat_id == cvat_id_1 for project in projects)) - self.assertTrue(any(project.cvat_id == cvat_id_3 for project in projects)) + assert len(projects) == 2 + assert any(project.cvat_id == cvat_id_1 for project in projects) + assert any(project.cvat_id == cvat_id_3 for project in projects) def test_get_projects_by_assignee(self): wallet_address_1 = "0x86e83d346041E8806e352681f3F14549C0d2BC60" @@ -418,13 +419,13 @@ def test_get_projects_by_assignee(self): projects = cvat_service.get_projects_by_assignee(self.session, wallet_address_1) - self.assertEqual(len(projects), 1) - self.assertEqual(projects[0].cvat_id, cvat_id_1) + assert len(projects) == 1 + assert projects[0].cvat_id == cvat_id_1 projects = cvat_service.get_projects_by_assignee(self.session, wallet_address_2) - self.assertEqual( - len(projects), 0 + assert ( + len(projects) == 0 ) # expired should not be shown, https://github.com/humanprotocol/human-protocol/pull/1879 def test_update_project_status(self): @@ -448,14 +449,14 @@ def test_update_project_status(self): project = cvat_service.get_project_by_id(self.session, p_id) - self.assertIsNotNone(project) - self.assertEqual(project.id, p_id) - self.assertEqual(project.cvat_id, cvat_id) - self.assertEqual(project.status, ProjectStatuses.completed.value) - self.assertEqual(project.job_type, job_type) - self.assertEqual(project.escrow_address, escrow_address) - self.assertEqual(project.chain_id, chain_id) - self.assertEqual(project.bucket_url, bucket_url) + assert project is not None + assert project.id == p_id + assert project.cvat_id == cvat_id + assert project.status == ProjectStatuses.completed.value + assert project.job_type == job_type + assert project.escrow_address == escrow_address + assert project.chain_id == chain_id + assert project.bucket_url == bucket_url def test_delete_project(self): cvat_id_1 = 456 @@ -465,12 +466,12 @@ def test_delete_project(self): ) projects = self.session.query(Project).all() - self.assertEqual(len(projects), 1) + assert len(projects) == 1 cvat_service.delete_project(self.session, project.id) projects = self.session.query(Project).all() - self.assertEqual(len(projects), 0) + assert len(projects) == 0 (cvat_project, cvat_task) = create_project_and_task( self.session, "0x86e83d346041E8806e352681f3F14549C0d2BC67", cvat_id_1 @@ -495,13 +496,13 @@ def test_delete_project(self): cvat_task_db = cvat_service.get_task_by_id(self.session, cvat_task.id) jobs = cvat_service.get_jobs_by_cvat_task_id(self.session, cvat_task_id=cvat_task.cvat_id) - self.assertIsNotNone(cvat_project) - self.assertEqual(cvat_project_db.id, cvat_project.id) + assert cvat_project is not None + assert cvat_project_db.id == cvat_project.id - self.assertIsNotNone(cvat_task_db) - self.assertEqual(cvat_task_db.id, cvat_task.id) + assert cvat_task_db is not None + assert cvat_task_db.id == cvat_task.id - self.assertEqual(len(jobs), 2) + assert len(jobs) == 2 cvat_service.delete_project(self.session, cvat_project_db.id) @@ -509,9 +510,9 @@ def test_delete_project(self): cvat_task_db = cvat_service.get_task_by_id(self.session, cvat_task.id) jobs = cvat_service.get_jobs_by_cvat_task_id(self.session, cvat_task_id=cvat_task.cvat_id) - self.assertIsNone(cvat_project_db) - self.assertIsNone(cvat_task_db) - self.assertEqual(len(jobs), 0) + assert cvat_project_db is None + assert cvat_task_db is None + assert len(jobs) == 0 def test_delete_project_wrong_project_id(self): cvat_id = 456 @@ -519,8 +520,8 @@ def test_delete_project_wrong_project_id(self): create_project(self.session, "0x86e83d346041E8806e352681f3F14549C0d2BC67", cvat_id) projects = self.session.query(Project).all() - self.assertEqual(len(projects), 1) - with self.assertRaises(UnmappedInstanceError): + assert len(projects) == 1 + with pytest.raises(UnmappedInstanceError): cvat_service.delete_project(self.session, "project_id") def test_create_task(self): @@ -535,11 +536,11 @@ def test_create_task(self): task = self.session.query(Task).filter_by(id=task_id).first() - self.assertIsNotNone(task) - self.assertEqual(task.id, task_id) - self.assertEqual(task.cvat_id, cvat_id) - self.assertEqual(task.cvat_project_id, cvat_project.cvat_id) - self.assertEqual(task.status, status) + assert task is not None + assert task.id == task_id + assert task.cvat_id == cvat_id + assert task.cvat_project_id == cvat_project.cvat_id + assert task.status == status def test_create_task_duplicated_cvat_id(self): cvat_id = 1 @@ -553,22 +554,22 @@ def test_create_task_duplicated_cvat_id(self): self.session.commit() cvat_service.create_task(self.session, cvat_id, cvat_project.cvat_id, status) - with self.assertRaises(IntegrityError): + with pytest.raises(IntegrityError): self.session.commit() def test_create_tas_without_project(self): cvat_service.create_task(self.session, 123, 123, TaskStatuses.annotation) - with self.assertRaises(IntegrityError): + with pytest.raises(IntegrityError): self.session.commit() def test_create_task_none_cvat_id(self): cvat_service.create_task(self.session, None, 123, TaskStatuses.annotation) - with self.assertRaises(IntegrityError): + with pytest.raises(IntegrityError): self.session.commit() def test_create_task_none_cvat_project_id(self): cvat_service.create_task(self.session, 123, None, TaskStatuses.annotation) - with self.assertRaises(IntegrityError): + with pytest.raises(IntegrityError): self.session.commit() def test_get_task_by_id(self): @@ -579,15 +580,15 @@ def test_get_task_by_id(self): ) task = cvat_service.get_task_by_id(self.session, task_id) - self.assertIsNotNone(task) - self.assertEqual(task.id, task_id) - self.assertEqual(task.cvat_id, cvat_project.cvat_id) - self.assertEqual(task.cvat_project_id, cvat_project.cvat_id) - self.assertEqual(task.status, TaskStatuses.annotation.value) + assert task is not None + assert task.id == task_id + assert task.cvat_id == cvat_project.cvat_id + assert task.cvat_project_id == cvat_project.cvat_id + assert task.status == TaskStatuses.annotation.value task = cvat_service.get_task_by_id(self.session, "dummy_id") - self.assertIsNone(task) + assert task is None def test_get_tasks_by_cvat_id(self): cvat_project = create_project(self.session, "0x86e83d346041E8806e352681f3F14549C0d2BC67", 1) @@ -598,15 +599,15 @@ def test_get_tasks_by_cvat_id(self): tasks = cvat_service.get_tasks_by_cvat_id(self.session, [1, 2]) - self.assertEqual(len(tasks), 2) + assert len(tasks) == 2 tasks = cvat_service.get_tasks_by_cvat_id(self.session, [3]) - self.assertEqual(len(tasks), 1) + assert len(tasks) == 1 tasks = cvat_service.get_tasks_by_cvat_id(self.session, [999]) - self.assertEqual(len(tasks), 0) + assert len(tasks) == 0 def test_get_tasks_by_status(self): cvat_project = create_project(self.session, "0x86e83d346041E8806e352681f3F14549C0d2BC67", 1) @@ -617,11 +618,11 @@ def test_get_tasks_by_status(self): tasks = cvat_service.get_tasks_by_status(self.session, TaskStatuses.annotation) - self.assertEqual(len(tasks), 2) + assert len(tasks) == 2 tasks = cvat_service.get_tasks_by_status(self.session, TaskStatuses.completed) - self.assertEqual(len(tasks), 1) + assert len(tasks) == 1 def test_update_task_status(self): cvat_project = create_project(self.session, "0x86e83d346041E8806e352681f3F14549C0d2BC67", 1) @@ -634,11 +635,11 @@ def test_update_task_status(self): task = cvat_service.get_task_by_id(self.session, task_id) - self.assertIsNotNone(task) - self.assertEqual(task.id, task_id) - self.assertEqual(task.cvat_id, cvat_project.cvat_id) - self.assertEqual(task.cvat_project_id, cvat_project.cvat_id) - self.assertEqual(task.status, TaskStatuses.completed.value) + assert task is not None + assert task.id == task_id + assert task.cvat_id == cvat_project.cvat_id + assert task.cvat_project_id == cvat_project.cvat_id + assert task.status == TaskStatuses.completed.value def test_get_tasks_by_cvat_project_id(self): cvat_project = create_project(self.session, "0x86e83d346041E8806e352681f3F14549C0d2BC67", 1) @@ -655,15 +656,15 @@ def test_get_tasks_by_cvat_project_id(self): tasks = cvat_service.get_tasks_by_cvat_project_id(self.session, cvat_project.cvat_id) - self.assertEqual(len(tasks), 3) + assert len(tasks) == 3 tasks = cvat_service.get_tasks_by_cvat_project_id(self.session, cvat_project_2.cvat_id) - self.assertEqual(len(tasks), 1) + assert len(tasks) == 1 tasks = cvat_service.get_tasks_by_cvat_project_id(self.session, 123) - self.assertEqual(len(tasks), 0) + assert len(tasks) == 0 def test_create_data_upload(self): cvat_id = 1 @@ -675,9 +676,9 @@ def test_create_data_upload(self): data_upload = self.session.query(DataUpload).filter_by(task_id=cvat_task.cvat_id).first() - self.assertIsNotNone(data_upload) - self.assertEqual(data_upload.id, data_upload_id) - self.assertEqual(data_upload.task_id, cvat_id) + assert data_upload is not None + assert data_upload.id == data_upload_id + assert data_upload.task_id == cvat_id def test_get_active_task_uploads_by_task_id(self): cvat_id_1 = 1 @@ -695,16 +696,16 @@ def test_get_active_task_uploads_by_task_id(self): data_uploads = cvat_service.get_active_task_uploads_by_task_id( self.session, [cvat_id_1, cvat_id_2] ) - self.assertEqual(len(data_uploads), 2) + assert len(data_uploads) == 2 data_uploads = cvat_service.get_active_task_uploads_by_task_id(self.session, [cvat_id_1]) - self.assertEqual(len(data_uploads), 1) + assert len(data_uploads) == 1 data_uploads = cvat_service.get_active_task_uploads_by_task_id(self.session, [cvat_id_2]) - self.assertEqual(len(data_uploads), 1) + assert len(data_uploads) == 1 data_uploads = cvat_service.get_active_task_uploads_by_task_id(self.session, []) - self.assertEqual(len(data_uploads), 0) + assert len(data_uploads) == 0 def test_get_active_task_uploads(self): cvat_id_1 = 1 @@ -720,10 +721,10 @@ def test_get_active_task_uploads(self): cvat_service.create_data_upload(self.session, cvat_task_2.cvat_id) data_uploads = cvat_service.get_active_task_uploads(self.session) - self.assertEqual(len(data_uploads), 2) + assert len(data_uploads) == 2 data_uploads = cvat_service.get_active_task_uploads(self.session, limit=1) - self.assertEqual(len(data_uploads), 1) + assert len(data_uploads) == 1 def test_get_active_task_uploads(self): cvat_id_1 = 1 @@ -739,17 +740,17 @@ def test_get_active_task_uploads(self): cvat_service.create_data_upload(self.session, cvat_task_2.cvat_id) data_uploads = self.session.query(DataUpload).all() - self.assertEqual(len(data_uploads), 2) + assert len(data_uploads) == 2 cvat_service.finish_data_uploads(self.session, [data_uploads[0]]) data_uploads = self.session.query(DataUpload).all() - self.assertEqual(len(data_uploads), 1) + assert len(data_uploads) == 1 cvat_service.finish_data_uploads(self.session, [data_uploads[0]]) data_uploads = self.session.query(DataUpload).all() - self.assertEqual(len(data_uploads), 0) + assert len(data_uploads) == 0 def test_create_job(self): (cvat_project, cvat_task) = create_project_and_task( @@ -769,14 +770,14 @@ def test_create_job(self): ) job_count = self.session.query(Job).count() - self.assertEqual(job_count, 1) + assert job_count == 1 job = self.session.query(Job).filter_by(id=job_id).first() - self.assertEqual(job.cvat_id, cvat_job_id) - self.assertEqual(job.cvat_task_id, cvat_task_id) - self.assertEqual(job.cvat_project_id, cvat_project_id) - self.assertEqual(job.status, status) + assert job.cvat_id == cvat_job_id + assert job.cvat_task_id == cvat_task_id + assert job.cvat_project_id == cvat_project_id + assert job.status == status def test_create_job_invalid_cvat_id(self): (cvat_project, cvat_task) = create_project_and_task( @@ -790,7 +791,7 @@ def test_create_job_invalid_cvat_id(self): cvat_project_id=cvat_project.cvat_id, status=JobStatuses.new, ) - with self.assertRaises(IntegrityError): + with pytest.raises(IntegrityError): self.session.commit() def test_create_job_without_task(self): @@ -803,7 +804,7 @@ def test_create_job_without_task(self): cvat_task_id=None, status=JobStatuses.new, ) - with self.assertRaises(IntegrityError): + with pytest.raises(IntegrityError): self.session.commit() def test_create_job_invalid_task_reference(self): @@ -818,7 +819,7 @@ def test_create_job_invalid_task_reference(self): cvat_project_id=cvat_project.cvat_id, status=JobStatuses.new, ) - with self.assertRaises(IntegrityError): + with pytest.raises(IntegrityError): self.session.commit() def test_create_job_invalid_project_reference(self): @@ -833,7 +834,7 @@ def test_create_job_invalid_project_reference(self): cvat_project_id=122, status=JobStatuses.new, ) - with self.assertRaises(IntegrityError): + with pytest.raises(IntegrityError): self.session.commit() def test_create_job_duplicated_cvat_id(self): @@ -856,7 +857,7 @@ def test_create_job_duplicated_cvat_id(self): cvat_project_id=cvat_project.cvat_id, status=JobStatuses.new, ) - with self.assertRaises(IntegrityError): + with pytest.raises(IntegrityError): self.session.commit() def test_get_job_by_id(self): @@ -878,15 +879,15 @@ def test_get_job_by_id(self): ) job = cvat_service.get_job_by_id(self.session, job_id) - self.assertIsNotNone(job) - self.assertEqual(job.id, job_id) - self.assertEqual(job.cvat_id, cvat_id) - self.assertEqual(job.cvat_task_id, cvat_task.cvat_id) - self.assertEqual(job.cvat_project_id, cvat_project.cvat_id) + assert job is not None + assert job.id == job_id + assert job.cvat_id == cvat_id + assert job.cvat_task_id == cvat_task.cvat_id + assert job.cvat_project_id == cvat_project.cvat_id job = cvat_service.get_job_by_id(self.session, "Dummy id") - self.assertIsNone(job) + assert job is None def test_get_jobs_by_cvat_id(self): (cvat_project, cvat_task) = create_project_and_task( @@ -907,15 +908,15 @@ def test_get_jobs_by_cvat_id(self): jobs = cvat_service.get_jobs_by_cvat_id(self.session, [cvat_id]) - self.assertIsNotNone(jobs) - self.assertEqual(jobs[0].id, job_id) - self.assertEqual(jobs[0].cvat_id, cvat_id) - self.assertEqual(jobs[0].cvat_task_id, cvat_task.cvat_id) - self.assertEqual(jobs[0].cvat_project_id, cvat_project.cvat_id) + assert jobs is not None + assert jobs[0].id == job_id + assert jobs[0].cvat_id == cvat_id + assert jobs[0].cvat_task_id == cvat_task.cvat_id + assert jobs[0].cvat_project_id == cvat_project.cvat_id def test_get_jobs_by_cvat_id_wrong_cvat_id(self): job = cvat_service.get_jobs_by_cvat_id(self.session, [457]) - self.assertEqual(job, []) + assert job == [] def test_update_job_status(self): (cvat_project, cvat_task) = create_project_and_task( @@ -936,10 +937,10 @@ def test_update_job_status(self): ) job = cvat_service.get_job_by_id(self.session, job_id) - self.assertEqual(job.cvat_id, cvat_id) - self.assertEqual(job.cvat_task_id, cvat_task.cvat_id) - self.assertEqual(job.cvat_project_id, cvat_project.cvat_id) - self.assertEqual(job.status, status) + assert job.cvat_id == cvat_id + assert job.cvat_task_id == cvat_task.cvat_id + assert job.cvat_project_id == cvat_project.cvat_id + assert job.status == status new_status = JobStatuses.completed @@ -947,12 +948,12 @@ def test_update_job_status(self): job = self.session.query(Job).filter_by(id=job_id).first() - self.assertIsNotNone(job) - self.assertEqual(job.id, job_id) - self.assertEqual(job.cvat_id, cvat_id) - self.assertEqual(job.cvat_task_id, cvat_task.cvat_id) - self.assertEqual(job.cvat_project_id, cvat_project.cvat_id) - self.assertEqual(job.status, new_status) + assert job is not None + assert job.id == job_id + assert job.cvat_id == cvat_id + assert job.cvat_task_id == cvat_task.cvat_id + assert job.cvat_project_id == cvat_project.cvat_id + assert job.status == new_status def test_get_jobs_by_cvat_task_id(self): (cvat_project, cvat_task) = create_project_and_task( @@ -995,7 +996,7 @@ def test_get_jobs_by_cvat_task_id(self): jobs = cvat_service.get_jobs_by_cvat_task_id(self.session, cvat_task_id=cvat_task.cvat_id) - self.assertEqual(len(jobs), 3) + assert len(jobs) == 3 def test_get_jobs_by_cvat_project_id(self): (cvat_project, cvat_task) = create_project_and_task( @@ -1038,7 +1039,7 @@ def test_get_jobs_by_cvat_project_id(self): jobs = cvat_service.get_jobs_by_cvat_project_id(self.session, cvat_project.cvat_id) - self.assertEqual(len(jobs), 3) + assert len(jobs) == 3 def test_put_user(self): wallet_address = "0x86e83d346041E8806e352681f3F14549C0d2BC67" @@ -1053,12 +1054,12 @@ def test_put_user(self): db_user = self.session.query(User).filter_by(cvat_id=cvat_id).first() - self.assertIsNotNone(user) - self.assertEqual(user, db_user) - self.assertEqual(user.id, db_user.id) - self.assertEqual(user.cvat_id, cvat_id) - self.assertEqual(user.cvat_email, cvat_email) - self.assertEqual(user.wallet_address, wallet_address) + assert user is not None + assert user == db_user + assert user.id == db_user.id + assert user.cvat_id == cvat_id + assert user.cvat_email == cvat_email + assert user.wallet_address == wallet_address def test_put_user(self): wallet_address = "0x86e83d346041E8806e352681f3F14549C0d2BC67" @@ -1073,13 +1074,13 @@ def test_put_user(self): db_user = self.session.query(User).filter_by(cvat_id=cvat_id).first() - self.assertIsNotNone(user) - self.assertEqual(user.cvat_id, cvat_id) - self.assertEqual(user.cvat_email, cvat_email) - self.assertEqual(user.wallet_address, wallet_address) - self.assertEqual(db_user.cvat_id, cvat_id) - self.assertEqual(db_user.cvat_email, cvat_email) - self.assertEqual(db_user.wallet_address, wallet_address) + assert user is not None + assert user.cvat_id == cvat_id + assert user.cvat_email == cvat_email + assert user.wallet_address == wallet_address + assert db_user.cvat_id == cvat_id + assert db_user.cvat_email == cvat_email + assert db_user.wallet_address == wallet_address def test_put_user_duplicated_address(self): wallet_address = "0x86e83d346041E8806e352681f3F14549C0d2BC67" @@ -1092,9 +1093,9 @@ def test_put_user_duplicated_address(self): self.session.commit() db_users = self.session.query(User).filter_by(wallet_address=wallet_address).all() - self.assertEqual(len(db_users), 1) - self.assertEqual(db_users[0].cvat_id, 1) - self.assertEqual(db_users[0].cvat_email, "test@hmt.ai") + assert len(db_users) == 1 + assert db_users[0].cvat_id == 1 + assert db_users[0].cvat_email == "test@hmt.ai" cvat_service.put_user( self.session, @@ -1105,9 +1106,9 @@ def test_put_user_duplicated_address(self): self.session.commit() db_users = self.session.query(User).filter_by(wallet_address=wallet_address).all() - self.assertEqual(len(db_users), 1) - self.assertEqual(db_users[0].cvat_id, 2) - self.assertEqual(db_users[0].cvat_email, "test2@hmt.ai") + assert len(db_users) == 1 + assert db_users[0].cvat_id == 2 + assert db_users[0].cvat_email == "test2@hmt.ai" def test_put_user_duplicated_email(self): email = "test@hmt.ai" @@ -1124,7 +1125,7 @@ def test_put_user_duplicated_email(self): email, 2, ) - with self.assertRaises(IntegrityError): + with pytest.raises(IntegrityError): self.session.commit() def test_put_user_duplicated_id(self): @@ -1142,7 +1143,7 @@ def test_put_user_duplicated_id(self): "test2@hmt.ai", cvat_id, ) - with self.assertRaises(IntegrityError): + with pytest.raises(IntegrityError): self.session.commit() def test_get_user_by_id(self): @@ -1164,19 +1165,19 @@ def test_get_user_by_id(self): user_1 = cvat_service.get_user_by_id( self.session, "0x86e83d346041E8806e352681f3F14549C0d2BC67" ) - self.assertEqual(user_1.cvat_id, 1) - self.assertEqual(user_1.cvat_email, "test@hmt.ai") + assert user_1.cvat_id == 1 + assert user_1.cvat_email == "test@hmt.ai" user_2 = cvat_service.get_user_by_id( self.session, "0x86e83d346041E8806e352681f3F14549C0d2BC68" ) - self.assertEqual(user_2.cvat_id, 2) - self.assertEqual(user_2.cvat_email, "test2@hmt.ai") + assert user_2.cvat_id == 2 + assert user_2.cvat_email == "test2@hmt.ai" user_3 = cvat_service.get_user_by_id( self.session, "0x86e83d346041E8806e352681f3F14549C0d2BC69" ) - self.assertIsNone(user_3) + assert user_3 is None def test_create_assignment(self): (_, _, cvat_job) = create_project_task_and_job( @@ -1199,14 +1200,14 @@ def test_create_assignment(self): ) assignment_count = self.session.query(Assignment).count() - self.assertEqual(assignment_count, 1) + assert assignment_count == 1 assignment = self.session.query(Assignment).filter_by(id=assignment_id).first() - self.assertIsNotNone(assignment) - self.assertEqual(assignment.user_wallet_address, wallet_address) - self.assertEqual(assignment.cvat_job_id, cvat_job.cvat_id) - self.assertEqual(assignment.status, AssignmentStatuses.created.value) + assert assignment is not None + assert assignment.user_wallet_address == wallet_address + assert assignment.cvat_job_id == cvat_job.cvat_id + assert assignment.status == AssignmentStatuses.created.value def test_create_assignment_invalid_address(self): (_, _, cvat_job) = create_project_task_and_job( @@ -1219,7 +1220,7 @@ def test_create_assignment_invalid_address(self): cvat_job_id=cvat_job.cvat_id, expires_at=datetime.now(), ) - with self.assertRaises(IntegrityError): + with pytest.raises(IntegrityError): self.session.commit() def test_create_assignment_invalid_address(self): @@ -1237,7 +1238,7 @@ def test_create_assignment_invalid_address(self): cvat_job_id=0, expires_at=datetime.now(), ) - with self.assertRaises(IntegrityError): + with pytest.raises(IntegrityError): self.session.commit() def test_get_assignments_by_id(self): @@ -1274,17 +1275,17 @@ def test_get_assignments_by_id(self): self.session.commit() assignments = cvat_service.get_assignments_by_id(self.session, [assignment, assignment_2]) - self.assertEqual(len(assignments), 2) + assert len(assignments) == 2 assignments = cvat_service.get_assignments_by_id(self.session, [assignment]) - self.assertEqual(len(assignments), 1) - self.assertEqual(assignments[0].id, assignment) - self.assertEqual(assignments[0].user_wallet_address, wallet_address_1) + assert len(assignments) == 1 + assert assignments[0].id == assignment + assert assignments[0].user_wallet_address == wallet_address_1 assignments = cvat_service.get_assignments_by_id(self.session, [assignment_2]) - self.assertEqual(len(assignments), 1) - self.assertEqual(assignments[0].id, assignment_2) - self.assertEqual(assignments[0].user_wallet_address, wallet_address_2) + assert len(assignments) == 1 + assert assignments[0].id == assignment_2 + assert assignments[0].user_wallet_address == wallet_address_2 def test_get_latest_assignment_by_cvat_job_id(self): (_, _, cvat_job) = create_project_task_and_job( @@ -1325,9 +1326,9 @@ def test_get_latest_assignment_by_cvat_job_id(self): received_assignment = cvat_service.get_latest_assignment_by_cvat_job_id( self.session, cvat_job.cvat_id ) - self.assertEqual(received_assignment.id, assignment_2.id) - self.assertNotEqual(received_assignment.id, assignment.id) - self.assertEqual(received_assignment.user_wallet_address, wallet_address_2) + assert received_assignment.id == assignment_2.id + assert received_assignment.id != assignment.id + assert received_assignment.user_wallet_address == wallet_address_2 def test_get_unprocessed_expired_assignments(self): (_, _, cvat_job) = create_project_task_and_job( @@ -1365,10 +1366,10 @@ def test_get_unprocessed_expired_assignments(self): self.session.commit() assignments = cvat_service.get_unprocessed_expired_assignments(self.session) - self.assertEqual(len(assignments), 1) - self.assertEqual(assignments[0].id, assignment_2.id) - self.assertNotEqual(assignments[0].id, assignment.id) - self.assertEqual(assignments[0].user_wallet_address, wallet_address_2) + assert len(assignments) == 1 + assert assignments[0].id == assignment_2.id + assert assignments[0].id != assignment.id + assert assignments[0].user_wallet_address == wallet_address_2 def test_update_assignment(self): (_, _, cvat_job) = create_project_task_and_job( @@ -1397,8 +1398,8 @@ def test_update_assignment(self): db_assignment = self.session.query(Assignment).filter_by(id=assignment.id).first() - self.assertEqual(db_assignment.id, assignment.id) - self.assertEqual(db_assignment.status, AssignmentStatuses.completed) + assert db_assignment.id == assignment.id + assert db_assignment.status == AssignmentStatuses.completed def test_cancel_assignment(self): (_, _, cvat_job) = create_project_task_and_job( @@ -1425,8 +1426,8 @@ def test_cancel_assignment(self): db_assignment = self.session.query(Assignment).filter_by(id=assignment.id).first() - self.assertEqual(db_assignment.id, assignment.id) - self.assertEqual(db_assignment.status, AssignmentStatuses.canceled) + assert db_assignment.id == assignment.id + assert db_assignment.status == AssignmentStatuses.canceled def test_expire_assignment(self): (_, _, cvat_job) = create_project_task_and_job( @@ -1453,8 +1454,8 @@ def test_expire_assignment(self): db_assignment = self.session.query(Assignment).filter_by(id=assignment.id).first() - self.assertEqual(db_assignment.id, assignment.id) - self.assertEqual(db_assignment.status, AssignmentStatuses.expired) + assert db_assignment.id == assignment.id + assert db_assignment.status == AssignmentStatuses.expired def test_complete_assignment(self): (_, _, cvat_job) = create_project_task_and_job( @@ -1481,9 +1482,9 @@ def test_complete_assignment(self): db_assignment = self.session.query(Assignment).filter_by(id=assignment.id).first() - self.assertEqual(db_assignment.id, assignment.id) - self.assertEqual(db_assignment.status, AssignmentStatuses.completed) - self.assertEqual(db_assignment.completed_at, completed_date) + assert db_assignment.id == assignment.id + assert db_assignment.status == AssignmentStatuses.completed + assert db_assignment.completed_at == completed_date def test_test_add_project_images(self): (_, _, cvat_job) = create_project_task_and_job( @@ -1523,10 +1524,10 @@ def test_test_add_project_images(self): assignments = cvat_service.get_user_assignments_in_cvat_projects( self.session, wallet_address_1, [cvat_job.cvat_id] ) - self.assertEqual(len(assignments), 1) - self.assertEqual(assignments[0].id, assignment.id) - self.assertNotEqual(assignments[0].id, assignment_2.id) - self.assertEqual(assignments[0].user_wallet_address, wallet_address_1) + assert len(assignments) == 1 + assert assignments[0].id == assignment.id + assert assignments[0].id != assignment_2.id + assert assignments[0].user_wallet_address == wallet_address_1 def test_add_project_images(self): cvat_project = create_project(self.session, "0x86e83d346041E8806e352681f3F14549C0d2BC67", 1) @@ -1543,16 +1544,16 @@ def test_add_project_images(self): self.session.query(Image).where(Image.cvat_project_id == cvat_project.cvat_id).all() ) - self.assertEqual(len(images), 2) - self.assertEqual(images[0].filename, filenames[0]) - self.assertEqual(images[1].filename, filenames[1]) + assert len(images) == 2 + assert images[0].filename == filenames[0] + assert images[1].filename == filenames[1] def test_add_project_images_wrong_project_id(self): filenames = [ "image1.jpg", "image2.jpg", ] - with self.assertRaises(IntegrityError): + with pytest.raises(IntegrityError): cvat_service.add_project_images(self.session, cvat_project_id=1, filenames=filenames) def test_add_project_images(self): @@ -1575,10 +1576,10 @@ def test_add_project_images(self): images = cvat_service.get_project_images(self.session, cvat_project.cvat_id) - self.assertEqual(len(images), 2) - self.assertEqual(images[0].filename, filenames[0]) - self.assertEqual(images[1].filename, filenames[1]) + assert len(images) == 2 + assert images[0].filename == filenames[0] + assert images[1].filename == filenames[1] images = cvat_service.get_project_images(self.session, 2) - self.assertEqual(len(images), 0) + assert len(images) == 0 diff --git a/packages/examples/cvat/exchange-oracle/tests/integration/services/test_exchange.py b/packages/examples/cvat/exchange-oracle/tests/integration/services/test_exchange.py index 7741790418..6bec628590 100644 --- a/packages/examples/cvat/exchange-oracle/tests/integration/services/test_exchange.py +++ b/packages/examples/cvat/exchange-oracle/tests/integration/services/test_exchange.py @@ -4,6 +4,7 @@ from datetime import datetime, timedelta from unittest.mock import patch +import pytest from fastapi import HTTPException from pydantic import ValidationError @@ -49,19 +50,19 @@ def test_serialize_task(self): mock_get_manifest.return_value = manifest data = serialize_task(cvat_project.id) - self.assertEqual(data.id, cvat_project.id) - self.assertEqual(data.escrow_address, escrow_address) - self.assertIn("Task ", data.title) - self.assertTrue(len(data.title.split("Task ")[1]) <= 10) - self.assertIsInstance(data.description, str) - self.assertIsInstance(data.job_bounty, str) - self.assertIsInstance(data.job_time_limit, int) - self.assertIsInstance(data.job_size, int) - self.assertEqual(data.job_type, cvat_project.job_type) - self.assertEqual(data.platform, PlatformTypes.CVAT) - self.assertEqual(data.status, cvat_project.status) - self.assertIsNone(data.assignment) - self.assertIsInstance(data, service_api.TaskResponse) + assert data.id == cvat_project.id + assert data.escrow_address == escrow_address + assert "Task " in data.title + assert len(data.title.split("Task ")[1]) <= 10 + assert isinstance(data.description, str) + assert isinstance(data.job_bounty, str) + assert isinstance(data.job_time_limit, int) + assert isinstance(data.job_size, int) + assert data.job_type == cvat_project.job_type + assert data.platform == PlatformTypes.CVAT + assert data.status == cvat_project.status + assert data.assignment is None + assert isinstance(data, service_api.TaskResponse) def test_serialize_task_with_assignment(self): cvat_id = 1 @@ -96,25 +97,25 @@ def test_serialize_task_with_assignment(self): mock_get_manifest.return_value = manifest data = serialize_task(project_id=cvat_project.id, assignment_id=assignment.id) - self.assertEqual(data.id, cvat_project.id) - self.assertEqual(data.escrow_address, escrow_address) - self.assertIn("Task ", data.title) - self.assertTrue(len(data.title.split("Task ")[1]) <= 10) - self.assertIsInstance(data.description, str) - self.assertIsInstance(data.job_bounty, str) - self.assertIsInstance(data.job_time_limit, int) - self.assertIsInstance(data.job_size, int) - self.assertEqual(data.job_type, cvat_project.job_type) - self.assertEqual(data.platform, PlatformTypes.CVAT) - self.assertEqual(data.status, cvat_project.status) - self.assertIsNotNone(data.assignment) - self.assertIsInstance(data.assignment.assignment_url, str) - self.assertEqual(data.assignment.started_at, assignment.created_at) - self.assertEqual(data.assignment.finishes_at, assignment.expires_at) - self.assertIsInstance(data, service_api.TaskResponse) + assert data.id == cvat_project.id + assert data.escrow_address == escrow_address + assert "Task " in data.title + assert len(data.title.split("Task ")[1]) <= 10 + assert isinstance(data.description, str) + assert isinstance(data.job_bounty, str) + assert isinstance(data.job_time_limit, int) + assert isinstance(data.job_size, int) + assert data.job_type == cvat_project.job_type + assert data.platform == PlatformTypes.CVAT + assert data.status == cvat_project.status + assert data.assignment is not None + assert isinstance(data.assignment.assignment_url, str) + assert data.assignment.started_at == assignment.created_at + assert data.assignment.finishes_at == assignment.expires_at + assert isinstance(data, service_api.TaskResponse) def test_serialize_task_invalid_project(self): - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): serialize_task(project_id=str(uuid.uuid4())) def test_serialize_task_invalid_manifest(self): @@ -126,7 +127,7 @@ def test_serialize_task_invalid_manifest(self): with patch("src.services.exchange.get_escrow_manifest") as mock_get_manifest: mock_get_manifest.return_value = None - with self.assertRaises(ValidationError): + with pytest.raises(ValidationError): serialize_task(project_id=cvat_project.id) def test_get_available_tasks(self): @@ -146,11 +147,11 @@ def test_get_available_tasks(self): mock_get_manifest.return_value = manifest tasks = get_available_tasks() - self.assertEqual(len(tasks), 2) - self.assertIsInstance(tasks[0], service_api.TaskResponse) - self.assertIsInstance(tasks[1], service_api.TaskResponse) - self.assertTrue(any(task.id == cvat_project_1.id for task in tasks)) - self.assertTrue(any(task.id == cvat_project_2.id for task in tasks)) + assert len(tasks) == 2 + assert isinstance(tasks[0], service_api.TaskResponse) + assert isinstance(tasks[1], service_api.TaskResponse) + assert any(task.id == cvat_project_1.id for task in tasks) + assert any(task.id == cvat_project_2.id for task in tasks) cvat_service.update_project_status( self.session, cvat_project_2.id, ProjectStatuses.completed @@ -158,9 +159,9 @@ def test_get_available_tasks(self): self.session.commit() tasks = get_available_tasks() - self.assertEqual(len(tasks), 1) - self.assertIsInstance(tasks[0], service_api.TaskResponse) - self.assertEqual(tasks[0].id, cvat_project_1.id) + assert len(tasks) == 1 + assert isinstance(tasks[0], service_api.TaskResponse) + assert tasks[0].id == cvat_project_1.id def test_get_tasks_by_assignee(self): cvat_project_1, _, cvat_job_1 = create_project_task_and_job( @@ -195,14 +196,14 @@ def test_get_tasks_by_assignee(self): mock_get_manifest.return_value = manifest tasks = get_tasks_by_assignee(user_address) - self.assertEqual(len(tasks), 1) - self.assertIsInstance(tasks[0], service_api.TaskResponse) - self.assertEqual(tasks[0].id, cvat_project_1.id) - self.assertIsNotNone(tasks[0].assignment) + assert len(tasks) == 1 + assert isinstance(tasks[0], service_api.TaskResponse) + assert tasks[0].id == cvat_project_1.id + assert tasks[0].assignment is not None def test_get_tasks_by_assignee_invalid_address(self): tasks = get_tasks_by_assignee("invalid_address") - self.assertEqual(len(tasks), 0) + assert len(tasks) == 0 def test_create_assignment(self): cvat_project_1, _, cvat_job_1 = create_project_task_and_job( @@ -228,9 +229,9 @@ def test_create_assignment(self): assignment = self.session.query(Assignment).filter_by(id=assignment_id).first() - self.assertEqual(assignment.cvat_job_id, cvat_job_1.cvat_id) - self.assertEqual(assignment.user_wallet_address, user_address) - self.assertEqual(assignment.status, AssignmentStatuses.created) + assert assignment.cvat_job_id == cvat_job_1.cvat_id + assert assignment.user_wallet_address == user_address + assert assignment.status == AssignmentStatuses.created def test_create_assignment_many_jobs_1_completed(self): cvat_project, _, cvat_job_1 = create_project_task_and_job( @@ -274,9 +275,9 @@ def test_create_assignment_many_jobs_1_completed(self): assignment = self.session.query(Assignment).filter_by(id=assignment_id).first() - self.assertEqual(assignment.cvat_job_id, cvat_job_2.cvat_id) - self.assertEqual(assignment.user_wallet_address, user_address) - self.assertEqual(assignment.status, AssignmentStatuses.created) + assert assignment.cvat_job_id == cvat_job_2.cvat_id + assert assignment.user_wallet_address == user_address + assert assignment.status == AssignmentStatuses.created def test_create_assignment_invalid_user_address(self): cvat_project_1, _, _ = create_project_task_and_job( @@ -284,7 +285,7 @@ def test_create_assignment_invalid_user_address(self): ) self.session.commit() - with self.assertRaises(HTTPException): + with pytest.raises(HTTPException): create_assignment(cvat_project_1.id, "invalid_address") def test_create_assignment_invalid_project(self): @@ -297,7 +298,7 @@ def test_create_assignment_invalid_project(self): self.session.add(user) self.session.commit() - with self.assertRaises(HTTPException): + with pytest.raises(HTTPException): create_assignment("1", user_address) def test_create_assignment_unfinished_assignment(self): @@ -329,7 +330,7 @@ def test_create_assignment_unfinished_assignment(self): manifest = json.load(data) mock_get_manifest.return_value = manifest - with self.assertRaises(HTTPException): + with pytest.raises(HTTPException): create_assignment("1", user_address) def test_create_assignment_no_available_jobs_completed_assignment(self): @@ -377,7 +378,7 @@ def test_create_assignment_no_available_jobs_completed_assignment(self): mock_get_manifest.return_value = manifest assignment_id = create_assignment(cvat_project.id, user_address2) - self.assertEqual(assignment_id, None) + assert assignment_id == None def test_create_assignment_no_available_jobs_active_foreign_assignment(self): cvat_project, _, cvat_job_1 = create_project_task_and_job( @@ -419,7 +420,7 @@ def test_create_assignment_no_available_jobs_active_foreign_assignment(self): mock_get_manifest.return_value = manifest assignment_id = create_assignment(cvat_project.id, user_address2) - self.assertEqual(assignment_id, None) + assert assignment_id == None def test_create_assignment_in_validated_and_rejected_job(self): cvat_project_1, _, cvat_job_1 = create_project_task_and_job( @@ -460,6 +461,6 @@ def test_create_assignment_in_validated_and_rejected_job(self): assignment = self.session.query(Assignment).filter_by(id=assignment_id).first() - self.assertEqual(assignment.cvat_job_id, cvat_job_1.cvat_id) - self.assertEqual(assignment.user_wallet_address, user_address) - self.assertEqual(assignment.status, AssignmentStatuses.created) + assert assignment.cvat_job_id == cvat_job_1.cvat_id + assert assignment.user_wallet_address == user_address + assert assignment.status == AssignmentStatuses.created diff --git a/packages/examples/cvat/exchange-oracle/tests/integration/services/test_webhook.py b/packages/examples/cvat/exchange-oracle/tests/integration/services/test_webhook.py index baa0a7cd6b..caaf24a612 100644 --- a/packages/examples/cvat/exchange-oracle/tests/integration/services/test_webhook.py +++ b/packages/examples/cvat/exchange-oracle/tests/integration/services/test_webhook.py @@ -1,6 +1,7 @@ import unittest import uuid +import pytest from sqlalchemy.exc import IntegrityError import src.services.webhook as webhook_service @@ -40,14 +41,14 @@ def test_create_incoming_webhook(self): webhook = self.session.query(Webhook).filter_by(id=webhook_id).first() - self.assertEqual(webhook.escrow_address, escrow_address) - self.assertEqual(webhook.chain_id, chain_id) - self.assertEqual(webhook.signature, signature) - self.assertEqual(webhook.attempts, 0) - self.assertEqual(webhook.type, OracleWebhookTypes.job_launcher.value) - self.assertEqual(webhook.event_type, JobLauncherEventTypes.escrow_created.value) - self.assertEqual(webhook.event_data, None) - self.assertEqual(webhook.status, OracleWebhookStatuses.pending.value) + assert webhook.escrow_address == escrow_address + assert webhook.chain_id == chain_id + assert webhook.signature == signature + assert webhook.attempts == 0 + assert webhook.type == OracleWebhookTypes.job_launcher.value + assert webhook.event_type == JobLauncherEventTypes.escrow_created.value + assert webhook.event_data == None + assert webhook.status == OracleWebhookStatuses.pending.value def test_create_incoming_webhook_none_escrow_address(self): chain_id = Networks.localhost.value @@ -60,7 +61,7 @@ def test_create_incoming_webhook_none_escrow_address(self): type=OracleWebhookTypes.job_launcher, event_type=JobLauncherEventTypes.escrow_created.value, ) - with self.assertRaises(IntegrityError): + with pytest.raises(IntegrityError): self.session.commit() def test_create_incoming_webhook_none_chain_id(self): @@ -74,13 +75,19 @@ def test_create_incoming_webhook_none_chain_id(self): type=OracleWebhookTypes.job_launcher, event_type=JobLauncherEventTypes.escrow_created.value, ) - with self.assertRaises(IntegrityError): + with pytest.raises(IntegrityError): self.session.commit() def test_create_incoming_webhook_none_event_type(self): escrow_address = "0x1234567890123456789012345678901234567890" signature = "signature" - with self.assertRaises(AssertionError) as error: + with pytest.raises( + AssertionError, + match=( + "'event' and 'event_type' cannot be used together. " + "Please use only one of the fields" + ), + ): webhook_service.inbox.create_webhook( self.session, escrow_address=escrow_address, @@ -88,16 +95,14 @@ def test_create_incoming_webhook_none_event_type(self): signature=signature, type=OracleWebhookTypes.job_launcher, ) - self.assertEqual( - str(error.exception), - "'event' and 'event_type' cannot be used together. Please use only one of the fields", - ) def test_create_incoming_webhook_none_signature(self): escrow_address = "0x1234567890123456789012345678901234567890" chain_id = Networks.localhost.value - with self.assertRaises(ValueError) as error: + with pytest.raises( + ValueError, match="Webhook signature must be specified for incoming events" + ): webhook_service.inbox.create_webhook( self.session, escrow_address=escrow_address, @@ -105,9 +110,6 @@ def test_create_incoming_webhook_none_signature(self): type=OracleWebhookTypes.job_launcher, event_type=JobLauncherEventTypes.escrow_created.value, ) - self.assertEqual( - str(error.exception), "Webhook signature must be specified for incoming events" - ) def test_create_outgoing_webhook(self): escrow_address = "0x1234567890123456789012345678901234567890" @@ -123,13 +125,13 @@ def test_create_outgoing_webhook(self): webhook = self.session.query(Webhook).filter_by(id=webhook_id).first() - self.assertEqual(webhook.escrow_address, escrow_address) - self.assertEqual(webhook.chain_id, chain_id) - self.assertEqual(webhook.attempts, 0) - self.assertEqual(webhook.type, OracleWebhookTypes.exchange_oracle.value) - self.assertEqual(webhook.event_type, ExchangeOracleEventTypes.task_finished.value) - self.assertEqual(webhook.event_data, {}) - self.assertEqual(webhook.status, OracleWebhookStatuses.pending.value) + assert webhook.escrow_address == escrow_address + assert webhook.chain_id == chain_id + assert webhook.attempts == 0 + assert webhook.type == OracleWebhookTypes.exchange_oracle.value + assert webhook.event_type == ExchangeOracleEventTypes.task_finished.value + assert webhook.event_data == {} + assert webhook.status == OracleWebhookStatuses.pending.value def test_create_outgoing_webhook_none_escrow_address(self): chain_id = Networks.localhost.value @@ -140,7 +142,7 @@ def test_create_outgoing_webhook_none_escrow_address(self): type=OracleWebhookTypes.exchange_oracle, event=ExchangeOracleEvent_TaskFinished(), ) - with self.assertRaises(IntegrityError): + with pytest.raises(IntegrityError): self.session.commit() def test_create_outgoing_webhook_none_chain_id(self): @@ -152,29 +154,33 @@ def test_create_outgoing_webhook_none_chain_id(self): type=OracleWebhookTypes.exchange_oracle, event=ExchangeOracleEvent_TaskFinished(), ) - with self.assertRaises(IntegrityError) as error: + with pytest.raises(IntegrityError): self.session.commit() def test_create_outgoing_webhook_none_event_type(self): escrow_address = "0x1234567890123456789012345678901234567890" - with self.assertRaises(AssertionError) as error: + with pytest.raises( + AssertionError, + match=( + "'event' and 'event_type' cannot be used together. " + "Please use only one of the fields" + ), + ): webhook_service.outbox.create_webhook( self.session, escrow_address=escrow_address, chain_id=None, type=OracleWebhookTypes.exchange_oracle, ) - self.assertEqual( - str(error.exception), - "'event' and 'event_type' cannot be used together. Please use only one of the fields", - ) def test_create_outgoing_webhook_with_signature(self): escrow_address = "0x1234567890123456789012345678901234567890" chain_id = Networks.localhost.value signature = "signature" - with self.assertRaises(ValueError) as error: + with pytest.raises( + ValueError, match="Webhook signature must not be specified for outgoing events" + ): webhook_service.outbox.create_webhook( self.session, escrow_address=escrow_address, @@ -183,9 +189,6 @@ def test_create_outgoing_webhook_with_signature(self): event=ExchangeOracleEvent_TaskFinished(), signature=signature, ) - self.assertEqual( - str(error.exception), "Webhook signature must not be specified for outgoing events" - ) def test_get_pending_webhooks(self): chain_id = Networks.localhost.value @@ -256,21 +259,21 @@ def test_get_pending_webhooks(self): pending_webhooks = webhook_service.inbox.get_pending_webhooks( self.session, type=OracleWebhookTypes.job_launcher, limit=10 ) - self.assertEqual(len(pending_webhooks), 2) - self.assertEqual(pending_webhooks[0].id, webhook1_id) - self.assertEqual(pending_webhooks[1].id, webhook2_id) + assert len(pending_webhooks) == 2 + assert pending_webhooks[0].id == webhook1_id + assert pending_webhooks[1].id == webhook2_id pending_webhooks = webhook_service.inbox.get_pending_webhooks( self.session, type=OracleWebhookTypes.recording_oracle, limit=10 ) - self.assertEqual(len(pending_webhooks), 1) - self.assertEqual(pending_webhooks[0].id, webhook4_id) + assert len(pending_webhooks) == 1 + assert pending_webhooks[0].id == webhook4_id pending_webhooks = webhook_service.outbox.get_pending_webhooks( self.session, type=OracleWebhookTypes.job_launcher, limit=10 ) - self.assertEqual(len(pending_webhooks), 1) - self.assertEqual(pending_webhooks[0].id, webhook5_id) + assert len(pending_webhooks) == 1 + assert pending_webhooks[0].id == webhook5_id def test_update_webhook_status(self): escrow_address = "0x1234567890123456789012345678901234567890" @@ -292,12 +295,12 @@ def test_update_webhook_status(self): webhook = self.session.query(Webhook).filter_by(id=webhook_id).first() - self.assertEqual(webhook.escrow_address, escrow_address) - self.assertEqual(webhook.chain_id, chain_id) - self.assertEqual(webhook.attempts, 0) - self.assertEqual(webhook.signature, signature) - self.assertEqual(webhook.type, OracleWebhookTypes.job_launcher.value) - self.assertEqual(webhook.status, OracleWebhookStatuses.completed.value) + assert webhook.escrow_address == escrow_address + assert webhook.chain_id == chain_id + assert webhook.attempts == 0 + assert webhook.signature == signature + assert webhook.type == OracleWebhookTypes.job_launcher.value + assert webhook.status == OracleWebhookStatuses.completed.value def test_handle_webhook_success(self): escrow_address = "0x1234567890123456789012345678901234567890" @@ -317,12 +320,12 @@ def test_handle_webhook_success(self): webhook = self.session.query(Webhook).filter_by(id=webhook_id).first() - self.assertEqual(webhook.escrow_address, escrow_address) - self.assertEqual(webhook.chain_id, chain_id) - self.assertEqual(webhook.attempts, 1) - self.assertEqual(webhook.signature, signature) - self.assertEqual(webhook.type, OracleWebhookTypes.job_launcher.value) - self.assertEqual(webhook.status, OracleWebhookStatuses.completed.value) + assert webhook.escrow_address == escrow_address + assert webhook.chain_id == chain_id + assert webhook.attempts == 1 + assert webhook.signature == signature + assert webhook.type == OracleWebhookTypes.job_launcher.value + assert webhook.status == OracleWebhookStatuses.completed.value def test_handle_webhook_fail(self): escrow_address = "0x1234567890123456789012345678901234567890" @@ -342,21 +345,21 @@ def test_handle_webhook_fail(self): webhook = self.session.query(Webhook).filter_by(id=webhook_id).first() - self.assertEqual(webhook.escrow_address, escrow_address) - self.assertEqual(webhook.chain_id, chain_id) - self.assertEqual(webhook.attempts, 1) - self.assertEqual(webhook.signature, signature) - self.assertEqual(webhook.type, OracleWebhookTypes.job_launcher.value) - self.assertEqual(webhook.status, OracleWebhookStatuses.pending.value) + assert webhook.escrow_address == escrow_address + assert webhook.chain_id == chain_id + assert webhook.attempts == 1 + assert webhook.signature == signature + assert webhook.type == OracleWebhookTypes.job_launcher.value + assert webhook.status == OracleWebhookStatuses.pending.value - for i in range(4): + for _i in range(4): webhook_service.inbox.handle_webhook_fail(self.session, webhook_id) webhook = self.session.query(Webhook).filter_by(id=webhook_id).first() - self.assertEqual(webhook.escrow_address, escrow_address) - self.assertEqual(webhook.chain_id, chain_id) - self.assertEqual(webhook.attempts, 5) - self.assertEqual(webhook.signature, signature) - self.assertEqual(webhook.type, OracleWebhookTypes.job_launcher.value) - self.assertEqual(webhook.status, OracleWebhookStatuses.failed.value) + assert webhook.escrow_address == escrow_address + assert webhook.chain_id == chain_id + assert webhook.attempts == 5 + assert webhook.signature == signature + assert webhook.type == OracleWebhookTypes.job_launcher.value + assert webhook.status == OracleWebhookStatuses.failed.value diff --git a/packages/examples/cvat/exchange-oracle/tests/unit/__init__.py b/packages/examples/cvat/exchange-oracle/tests/unit/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/examples/cvat/exchange-oracle/tests/unit/helpers/__init__.py b/packages/examples/cvat/exchange-oracle/tests/unit/helpers/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/examples/cvat/exchange-oracle/tests/utils/constants.py b/packages/examples/cvat/exchange-oracle/tests/utils/constants.py index 0e7e580002..2a5082c255 100644 --- a/packages/examples/cvat/exchange-oracle/tests/utils/constants.py +++ b/packages/examples/cvat/exchange-oracle/tests/utils/constants.py @@ -23,7 +23,10 @@ DEFAULT_MANIFEST_URL = "http://host.docker.internal:9000/manifests/manifest.json" DEFAULT_HASH = "test" -SIGNATURE = "0xa0c5626301e3c198cb91356e492890c0c28db8c37044846134939246911a693c4d7116d04aa4bc40a41077493868b8dd533d30980f6addb28d1b3610a84cb4091c" +SIGNATURE = ( + "0xa0c5626301e3c198cb91356e492890c0c28db8c37044846134939246911a693c" + "4d7116d04aa4bc40a41077493868b8dd533d30980f6addb28d1b3610a84cb4091c" +) WEBHOOK_MESSAGE = { "escrow_address": "0x12E66A452f95bff49eD5a30b0d06Ebc37C5A94B6", @@ -32,7 +35,10 @@ "event_data": {}, } -WEBHOOK_MESSAGE_SIGNED = "0x82d5c5845da8456226baf58862c1cefd964c884464f73b66abed938475bbd7e810bf99a10f2ad68e7febb7460112788c060e16e25d0e7c4e2e2dc7aafd9b81861c" +WEBHOOK_MESSAGE_SIGNED = ( + "0x82d5c5845da8456226baf58862c1cefd964c884464f73b66abed938475bbd7e8" + "10bf99a10f2ad68e7febb7460112788c060e16e25d0e7c4e2e2dc7aafd9b81861c" +) PGP_PASSPHRASE = "passphrase" PGP_PRIVATE_KEY1 = dedent( diff --git a/packages/examples/cvat/exchange-oracle/tests/utils/setup_cvat.py b/packages/examples/cvat/exchange-oracle/tests/utils/setup_cvat.py index 25d7baaf8c..3a87d3a57f 100644 --- a/packages/examples/cvat/exchange-oracle/tests/utils/setup_cvat.py +++ b/packages/examples/cvat/exchange-oracle/tests/utils/setup_cvat.py @@ -14,7 +14,7 @@ def generate_cvat_signature(data: dict): b_data = json.dumps(data).encode("utf-8") - signature = ( + return ( "sha256=" + hmac.new( CvatConfig.cvat_webhook_secret.encode("utf-8"), @@ -23,8 +23,6 @@ def generate_cvat_signature(data: dict): ).hexdigest() ) - return signature - def add_cvat_project_to_db(cvat_id: int) -> str: with SessionLocal.begin() as session: From 2736ceb685967feacfcacfd8453868444995aabf Mon Sep 17 00:00:00 2001 From: Arseny Boykov <36469655+Bobronium@users.noreply.github.com> Date: Tue, 27 Aug 2024 11:58:47 +0200 Subject: [PATCH 84/89] [Recording Oracle] Add ruff (#2396) Establish automatic code linting and formatting with ruff for CVAT Recording Oracle --- .../ci-lint-cvat-recording-oracle.yaml | 33 +++++ .../recording-oracle/.pre-commit-config.yaml | 24 ++-- .../cvat/recording-oracle/alembic.ini | 14 +- .../cvat/recording-oracle/alembic/env.py | 3 +- .../00271dfae3b1_add_task_iterations.py | 11 +- .../versions/a0c5c3a4c13f_add_gt_stats.py | 26 ++-- .../alembic/versions/ca93dce1a618_init.py | 3 +- .../cvat/recording-oracle/poetry.lock | 135 +++++++----------- .../cvat/recording-oracle/pyproject.toml | 121 ++++++++++++++-- .../examples/cvat/recording-oracle/run.py | 2 +- .../cvat/recording-oracle/src/chain/escrow.py | 12 +- .../recording-oracle/src/chain/kvstore.py | 4 +- .../cvat/recording-oracle/src/chain/web3.py | 4 +- .../recording-oracle/src/core/__init__.py | 0 .../src/core/annotation_meta.py | 3 +- .../cvat/recording-oracle/src/core/config.py | 46 +++--- .../recording-oracle/src/core/manifest.py | 22 +-- .../src/core/oracle_events.py | 17 +-- .../cvat/recording-oracle/src/core/storage.py | 5 +- .../src/core/tasks/boxes_from_points.py | 6 +- .../src/core/tasks/skeletons_from_boxes.py | 8 +- .../src/core/validation_meta.py | 6 +- .../src/core/validation_results.py | 3 +- .../crons/process_exchange_oracle_webhooks.py | 3 +- .../cvat/recording-oracle/src/db/__init__.py | 2 +- .../cvat/recording-oracle/src/db/utils.py | 9 +- .../src/endpoints/__init__.py | 13 +- .../src/endpoints/error_handlers.py | 3 +- .../recording-oracle/src/endpoints/webhook.py | 4 +- .../recording-oracle/src/handlers/__init__.py | 0 .../src/handlers/error_handlers.py | 3 +- .../handlers/process_intermediate_results.py | 124 ++++++++-------- .../src/handlers/validation.py | 17 ++- .../examples/cvat/recording-oracle/src/log.py | 3 +- .../recording-oracle/src/models/__init__.py | 0 .../recording-oracle/src/models/validation.py | 14 +- .../recording-oracle/src/models/webhook.py | 2 +- .../recording-oracle/src/schemas/__init__.py | 9 +- .../recording-oracle/src/schemas/webhook.py | 5 +- .../src/services/cloud/client.py | 22 +-- .../src/services/cloud/gcs.py | 17 +-- .../recording-oracle/src/services/cloud/s3.py | 33 ++--- .../src/services/cloud/types.py | 34 ++--- .../src/services/cloud/utils.py | 4 +- .../src/services/validation.py | 41 +++--- .../recording-oracle/src/services/webhook.py | 22 ++- .../recording-oracle/src/utils/annotations.py | 21 +-- .../cvat/recording-oracle/src/utils/enums.py | 2 +- .../recording-oracle/src/utils/logging.py | 4 +- .../cvat/recording-oracle/src/utils/net.py | 2 +- .../recording-oracle/src/utils/requests.py | 6 +- .../recording-oracle/src/utils/webhooks.py | 13 +- .../src/validation/__init__.py | 0 .../src/validation/annotation_matching.py | 13 +- .../src/validation/dataset_comparison.py | 56 ++++---- .../src/validators/__init__.py | 4 +- .../src/validators/validation.py | 4 +- .../cvat/recording-oracle/tests/conftest.py | 2 +- .../tests/integration/chain/test_escrow.py | 36 ++--- .../tests/integration/chain/test_kvstore.py | 35 ++--- .../tests/integration/chain/test_web3.py | 64 ++++----- .../test_process_exchange_oracle_webhooks.py | 16 +-- ...test_process_reputation_oracle_webhooks.py | 30 ++-- .../services/cloud/test_client_service.py | 6 +- .../services/test_webhook_service.py | 63 ++++---- .../recording-oracle/tests/utils/constants.py | 10 +- .../tests/utils/setup_escrow.py | 6 +- 67 files changed, 684 insertions(+), 601 deletions(-) create mode 100644 .github/workflows/ci-lint-cvat-recording-oracle.yaml create mode 100644 packages/examples/cvat/recording-oracle/src/core/__init__.py create mode 100644 packages/examples/cvat/recording-oracle/src/handlers/__init__.py create mode 100644 packages/examples/cvat/recording-oracle/src/models/__init__.py create mode 100644 packages/examples/cvat/recording-oracle/src/validation/__init__.py diff --git a/.github/workflows/ci-lint-cvat-recording-oracle.yaml b/.github/workflows/ci-lint-cvat-recording-oracle.yaml new file mode 100644 index 0000000000..8c91ac49ec --- /dev/null +++ b/.github/workflows/ci-lint-cvat-recording-oracle.yaml @@ -0,0 +1,33 @@ +name: CVAT Recording Oracle Lint + +on: + push: + paths: + - 'packages/examples/cvat/recording-oracle/**' + - '.github/workflows/ci-lint-cvat-recording-oracle.yaml' + +env: + WORKING_DIR: ./packages/examples/cvat/recording-oracle + +defaults: + run: + working-directory: ./packages/examples/cvat/recording-oracle + +jobs: + cvat-exo-lint: + name: CVAT Recording Oracle Lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + cache: 'pip' + cache-dependency-path: ${{ env.WORKING_DIR }}/poetry.lock + - run: python -m pip install poetry + - uses: actions/setup-python@v5 + with: + python-version: '3.10' + cache: 'poetry' + cache-dependency-path: ${{ env.WORKING_DIR }}/poetry.lock + - run: poetry install --no-root --only lint + - run: poetry run pre-commit run --all-files diff --git a/packages/examples/cvat/recording-oracle/.pre-commit-config.yaml b/packages/examples/cvat/recording-oracle/.pre-commit-config.yaml index 211285f89c..395275745a 100644 --- a/packages/examples/cvat/recording-oracle/.pre-commit-config.yaml +++ b/packages/examples/cvat/recording-oracle/.pre-commit-config.yaml @@ -1,11 +1,17 @@ repos: - - repo: https://github.com/ambv/black - rev: 22.6.0 + - repo: local hooks: - - id: black - language_version: python3.10 - - repo: https://github.com/PyCQA/isort - rev: 5.12.0 - hooks: - - id: isort - language_version: python3.11 \ No newline at end of file + - id: lint + name: lint + entry: ruff check --fix --unsafe-fixes --show-fixes + language: system + require_serial: true + files: "^packages/examples/cvat/recording-oracle/.*" + types: [python] + - id: format + name: format + entry: ruff format + require_serial: true + language: system + files: "^packages/examples/cvat/recording-oracle/.*" + types: [python] diff --git a/packages/examples/cvat/recording-oracle/alembic.ini b/packages/examples/cvat/recording-oracle/alembic.ini index d9f94e0c5a..e5d0ea3454 100644 --- a/packages/examples/cvat/recording-oracle/alembic.ini +++ b/packages/examples/cvat/recording-oracle/alembic.ini @@ -68,11 +68,15 @@ sqlalchemy.url = driver://user:pass@localhost/dbname # on newly generated revision scripts. See the documentation for further # detail and examples -# format using "black" - use the console_scripts runner, against the "black" entrypoint -# hooks = black -# black.type = console_scripts -# black.entrypoint = black -# black.options = -l 79 REVISION_SCRIPT_FILENAME +hooks=ruff, ruff_format, types_update + +ruff.type = exec +ruff.executable = ruff +ruff.options = check --fix --unsafe-fixes REVISION_SCRIPT_FILENAME + +ruff_format.type = exec +ruff_format.executable = ruff +ruff_format.options = format REVISION_SCRIPT_FILENAME # Logging configuration [loggers] diff --git a/packages/examples/cvat/recording-oracle/alembic/env.py b/packages/examples/cvat/recording-oracle/alembic/env.py index e6c51d07f3..1e85b134f0 100644 --- a/packages/examples/cvat/recording-oracle/alembic/env.py +++ b/packages/examples/cvat/recording-oracle/alembic/env.py @@ -16,13 +16,12 @@ if config.config_file_name is not None: fileConfig(config.config_file_name) -from src.db import Base +from src.db import Base # noqa: E402 # add your model's MetaData object here # for 'autogenerate' support # from myapp import mymodel # target_metadata = mymodel.Base.metadata -from src.models.webhook import Webhook target_metadata = Base.metadata diff --git a/packages/examples/cvat/recording-oracle/alembic/versions/00271dfae3b1_add_task_iterations.py b/packages/examples/cvat/recording-oracle/alembic/versions/00271dfae3b1_add_task_iterations.py index d16700325f..971891752b 100644 --- a/packages/examples/cvat/recording-oracle/alembic/versions/00271dfae3b1_add_task_iterations.py +++ b/packages/examples/cvat/recording-oracle/alembic/versions/00271dfae3b1_add_task_iterations.py @@ -5,24 +5,25 @@ Create Date: 2024-05-08 18:48:53.897599 """ -from alembic import op + import sqlalchemy as sa +from alembic import op # revision identifiers, used by Alembic. -revision = '00271dfae3b1' -down_revision = 'a0c5c3a4c13f' +revision = "00271dfae3b1" +down_revision = "a0c5c3a4c13f" branch_labels = None depends_on = None def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### - op.add_column('tasks', sa.Column('iteration', sa.Integer(), server_default='0', nullable=False)) + op.add_column("tasks", sa.Column("iteration", sa.Integer(), server_default="0", nullable=False)) # ### end Alembic commands ### def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### - op.drop_column('tasks', 'iteration') + op.drop_column("tasks", "iteration") # ### end Alembic commands ### diff --git a/packages/examples/cvat/recording-oracle/alembic/versions/a0c5c3a4c13f_add_gt_stats.py b/packages/examples/cvat/recording-oracle/alembic/versions/a0c5c3a4c13f_add_gt_stats.py index eb6471554d..be55735af5 100644 --- a/packages/examples/cvat/recording-oracle/alembic/versions/a0c5c3a4c13f_add_gt_stats.py +++ b/packages/examples/cvat/recording-oracle/alembic/versions/a0c5c3a4c13f_add_gt_stats.py @@ -5,32 +5,34 @@ Create Date: 2024-03-08 11:34:02.458845 """ -from alembic import op + import sqlalchemy as sa +from alembic import op # revision identifiers, used by Alembic. -revision = 'a0c5c3a4c13f' -down_revision = 'ca93dce1a618' +revision = "a0c5c3a4c13f" +down_revision = "ca93dce1a618" branch_labels = None depends_on = None def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### - op.create_table('gt_stats', - sa.Column('task_id', sa.String(), nullable=False), - sa.Column('gt_key', sa.String(), nullable=False), - sa.Column('failed_attempts', sa.Integer(), nullable=False), - sa.ForeignKeyConstraint(['task_id'], ['tasks.id'], ondelete='CASCADE'), - sa.PrimaryKeyConstraint('task_id', 'gt_key') + op.create_table( + "gt_stats", + sa.Column("task_id", sa.String(), nullable=False), + sa.Column("gt_key", sa.String(), nullable=False), + sa.Column("failed_attempts", sa.Integer(), nullable=False), + sa.ForeignKeyConstraint(["task_id"], ["tasks.id"], ondelete="CASCADE"), + sa.PrimaryKeyConstraint("task_id", "gt_key"), ) - op.create_index(op.f('ix_gt_stats_gt_key'), 'gt_stats', ['gt_key'], unique=False) + op.create_index(op.f("ix_gt_stats_gt_key"), "gt_stats", ["gt_key"], unique=False) # ### end Alembic commands ### def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### - op.drop_index(op.f('ix_gt_stats_gt_key'), table_name='gt_stats') - op.drop_table('gt_stats') + op.drop_index(op.f("ix_gt_stats_gt_key"), table_name="gt_stats") + op.drop_table("gt_stats") # ### end Alembic commands ### diff --git a/packages/examples/cvat/recording-oracle/alembic/versions/ca93dce1a618_init.py b/packages/examples/cvat/recording-oracle/alembic/versions/ca93dce1a618_init.py index b737376fe0..76f102d52c 100644 --- a/packages/examples/cvat/recording-oracle/alembic/versions/ca93dce1a618_init.py +++ b/packages/examples/cvat/recording-oracle/alembic/versions/ca93dce1a618_init.py @@ -1,10 +1,11 @@ """init Revision ID: ca93dce1a618 -Revises: +Revises: Create Date: 2023-09-05 15:02:51.779529 """ + import sqlalchemy as sa from alembic import op diff --git a/packages/examples/cvat/recording-oracle/poetry.lock b/packages/examples/cvat/recording-oracle/poetry.lock index e8fb4542ef..8d5acb95b5 100644 --- a/packages/examples/cvat/recording-oracle/poetry.lock +++ b/packages/examples/cvat/recording-oracle/poetry.lock @@ -1,4 +1,4 @@ -# This file is automatically @generated by Poetry 1.7.1 and should not be changed by hand. +# This file is automatically @generated by Poetry 1.8.3 and should not be changed by hand. [[package]] name = "aiohttp" @@ -397,52 +397,6 @@ files = [ {file = "bitarray-2.9.2.tar.gz", hash = "sha256:a8f286a51a32323715d77755ed959f94bef13972e9a2fe71b609e40e6d27957e"}, ] -[[package]] -name = "black" -version = "23.12.1" -description = "The uncompromising code formatter." -optional = false -python-versions = ">=3.8" -files = [ - {file = "black-23.12.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:e0aaf6041986767a5e0ce663c7a2f0e9eaf21e6ff87a5f95cbf3675bfd4c41d2"}, - {file = "black-23.12.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:c88b3711d12905b74206227109272673edce0cb29f27e1385f33b0163c414bba"}, - {file = "black-23.12.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a920b569dc6b3472513ba6ddea21f440d4b4c699494d2e972a1753cdc25df7b0"}, - {file = "black-23.12.1-cp310-cp310-win_amd64.whl", hash = "sha256:3fa4be75ef2a6b96ea8d92b1587dd8cb3a35c7e3d51f0738ced0781c3aa3a5a3"}, - {file = "black-23.12.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:8d4df77958a622f9b5a4c96edb4b8c0034f8434032ab11077ec6c56ae9f384ba"}, - {file = "black-23.12.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:602cfb1196dc692424c70b6507593a2b29aac0547c1be9a1d1365f0d964c353b"}, - {file = "black-23.12.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9c4352800f14be5b4864016882cdba10755bd50805c95f728011bcb47a4afd59"}, - {file = "black-23.12.1-cp311-cp311-win_amd64.whl", hash = "sha256:0808494f2b2df923ffc5723ed3c7b096bd76341f6213989759287611e9837d50"}, - {file = "black-23.12.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:25e57fd232a6d6ff3f4478a6fd0580838e47c93c83eaf1ccc92d4faf27112c4e"}, - {file = "black-23.12.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:2d9e13db441c509a3763a7a3d9a49ccc1b4e974a47be4e08ade2a228876500ec"}, - {file = "black-23.12.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6d1bd9c210f8b109b1762ec9fd36592fdd528485aadb3f5849b2740ef17e674e"}, - {file = "black-23.12.1-cp312-cp312-win_amd64.whl", hash = "sha256:ae76c22bde5cbb6bfd211ec343ded2163bba7883c7bc77f6b756a1049436fbb9"}, - {file = "black-23.12.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:1fa88a0f74e50e4487477bc0bb900c6781dbddfdfa32691e780bf854c3b4a47f"}, - {file = "black-23.12.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:a4d6a9668e45ad99d2f8ec70d5c8c04ef4f32f648ef39048d010b0689832ec6d"}, - {file = "black-23.12.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b18fb2ae6c4bb63eebe5be6bd869ba2f14fd0259bda7d18a46b764d8fb86298a"}, - {file = "black-23.12.1-cp38-cp38-win_amd64.whl", hash = "sha256:c04b6d9d20e9c13f43eee8ea87d44156b8505ca8a3c878773f68b4e4812a421e"}, - {file = "black-23.12.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:3e1b38b3135fd4c025c28c55ddfc236b05af657828a8a6abe5deec419a0b7055"}, - {file = "black-23.12.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:4f0031eaa7b921db76decd73636ef3a12c942ed367d8c3841a0739412b260a54"}, - {file = "black-23.12.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:97e56155c6b737854e60a9ab1c598ff2533d57e7506d97af5481141671abf3ea"}, - {file = "black-23.12.1-cp39-cp39-win_amd64.whl", hash = "sha256:dd15245c8b68fe2b6bd0f32c1556509d11bb33aec9b5d0866dd8e2ed3dba09c2"}, - {file = "black-23.12.1-py3-none-any.whl", hash = "sha256:78baad24af0f033958cad29731e27363183e140962595def56423e626f4bee3e"}, - {file = "black-23.12.1.tar.gz", hash = "sha256:4ce3ef14ebe8d9509188014d96af1c456a910d5b5cbf434a09fef7e024b3d0d5"}, -] - -[package.dependencies] -click = ">=8.0.0" -mypy-extensions = ">=0.4.3" -packaging = ">=22.0" -pathspec = ">=0.9.0" -platformdirs = ">=2" -tomli = {version = ">=1.1.0", markers = "python_version < \"3.11\""} -typing-extensions = {version = ">=4.0.1", markers = "python_version < \"3.11\""} - -[package.extras] -colorama = ["colorama (>=0.4.3)"] -d = ["aiohttp (>=3.7.4)", "aiohttp (>=3.7.4,!=3.9.0)"] -jupyter = ["ipython (>=7.8.0)", "tokenize-rt (>=3.2.0)"] -uvloop = ["uvloop (>=0.15.2)"] - [[package]] name = "boto3" version = "1.34.30" @@ -1870,20 +1824,6 @@ files = [ {file = "iniconfig-2.0.0.tar.gz", hash = "sha256:2d91e135bf72d31a410b17c16da610a82cb55f6b0477d1a902134b24a455b8b3"}, ] -[[package]] -name = "isort" -version = "5.13.2" -description = "A Python utility / library to sort Python imports." -optional = false -python-versions = ">=3.8.0" -files = [ - {file = "isort-5.13.2-py3-none-any.whl", hash = "sha256:8ca5e72a8d85860d5a3fa69b8745237f2939afe12dbf656afbcb47fe72d947a6"}, - {file = "isort-5.13.2.tar.gz", hash = "sha256:48fdfcb9face5d58a4f6dde2e72a1fb8dcaf8ab26f95ab49fab84c2ddefb0109"}, -] - -[package.extras] -colors = ["colorama (>=0.4.6)"] - [[package]] name = "jmespath" version = "1.0.1" @@ -2466,17 +2406,6 @@ files = [ {file = "multidict-6.0.4.tar.gz", hash = "sha256:3666906492efb76453c0e7b97f2cf459b0682e7402c0489a95484965dbc1da49"}, ] -[[package]] -name = "mypy-extensions" -version = "1.0.0" -description = "Type system extensions for programs checked with the mypy type checker." -optional = false -python-versions = ">=3.5" -files = [ - {file = "mypy_extensions-1.0.0-py3-none-any.whl", hash = "sha256:4392f6c0eb8a5668a69e23d168ffa70f0be9ccfd32b5cc2d26a34ae5b844552d"}, - {file = "mypy_extensions-1.0.0.tar.gz", hash = "sha256:75dbf8955dc00442a438fc4d0666508a9a97b6bd41aa2f0ffe9d2f2725af0782"}, -] - [[package]] name = "networkx" version = "3.2.1" @@ -2762,17 +2691,6 @@ files = [ [package.dependencies] regex = ">=2022.3.15" -[[package]] -name = "pathspec" -version = "0.12.1" -description = "Utility library for gitignore style pattern matching of file paths." -optional = false -python-versions = ">=3.8" -files = [ - {file = "pathspec-0.12.1-py3-none-any.whl", hash = "sha256:a0d503e138a4c123b27490a4f7beda6a01c6f288df0e4a8b79c7eb0dc7b4cc08"}, - {file = "pathspec-0.12.1.tar.gz", hash = "sha256:a482d51503a1ab33b1c67a6c3813a26953dbdc71c31dacaef9a838c4e29f5712"}, -] - [[package]] name = "pgpy" version = "0.6.0" @@ -2951,6 +2869,8 @@ files = [ {file = "psycopg2-2.9.9-cp310-cp310-win_amd64.whl", hash = "sha256:426f9f29bde126913a20a96ff8ce7d73fd8a216cfb323b1f04da402d452853c3"}, {file = "psycopg2-2.9.9-cp311-cp311-win32.whl", hash = "sha256:ade01303ccf7ae12c356a5e10911c9e1c51136003a9a1d92f7aa9d010fb98372"}, {file = "psycopg2-2.9.9-cp311-cp311-win_amd64.whl", hash = "sha256:121081ea2e76729acfb0673ff33755e8703d45e926e416cb59bae3a86c6a4981"}, + {file = "psycopg2-2.9.9-cp312-cp312-win32.whl", hash = "sha256:d735786acc7dd25815e89cc4ad529a43af779db2e25aa7c626de864127e5a024"}, + {file = "psycopg2-2.9.9-cp312-cp312-win_amd64.whl", hash = "sha256:a7653d00b732afb6fc597e29c50ad28087dcb4fbfb28e86092277a559ae4e693"}, {file = "psycopg2-2.9.9-cp37-cp37m-win32.whl", hash = "sha256:5e0d98cade4f0e0304d7d6f25bbfbc5bd186e07b38eac65379309c4ca3193efa"}, {file = "psycopg2-2.9.9-cp37-cp37m-win_amd64.whl", hash = "sha256:7e2dacf8b009a1c1e843b5213a87f7c544b2b042476ed7755be813eaf4e8347a"}, {file = "psycopg2-2.9.9-cp38-cp38-win32.whl", hash = "sha256:ff432630e510709564c01dafdbe996cb552e0b9f3f065eb89bdce5bd31fabf4c"}, @@ -3597,35 +3517,82 @@ files = [ {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:b42169467c42b692c19cf539c38d4602069d8c1505e97b86387fcf7afb766e1d"}, {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-macosx_13_0_arm64.whl", hash = "sha256:07238db9cbdf8fc1e9de2489a4f68474e70dffcb32232db7c08fa61ca0c7c462"}, {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:fff3573c2db359f091e1589c3d7c5fc2f86f5bdb6f24252c2d8e539d4e45f412"}, + {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-manylinux_2_24_aarch64.whl", hash = "sha256:aa2267c6a303eb483de8d02db2871afb5c5fc15618d894300b88958f729ad74f"}, + {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:840f0c7f194986a63d2c2465ca63af8ccbbc90ab1c6001b1978f05119b5e7334"}, + {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:024cfe1fc7c7f4e1aff4a81e718109e13409767e4f871443cbff3dba3578203d"}, {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-win32.whl", hash = "sha256:c69212f63169ec1cfc9bb44723bf2917cbbd8f6191a00ef3410f5a7fe300722d"}, {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-win_amd64.whl", hash = "sha256:cabddb8d8ead485e255fe80429f833172b4cadf99274db39abc080e068cbcc31"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:bef08cd86169d9eafb3ccb0a39edb11d8e25f3dae2b28f5c52fd997521133069"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-macosx_13_0_arm64.whl", hash = "sha256:b16420e621d26fdfa949a8b4b47ade8810c56002f5389970db4ddda51dbff248"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:25c515e350e5b739842fc3228d662413ef28f295791af5e5110b543cf0b57d9b"}, + {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-manylinux_2_24_aarch64.whl", hash = "sha256:1707814f0d9791df063f8c19bb51b0d1278b8e9a2353abbb676c2f685dee6afe"}, + {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:46d378daaac94f454b3a0e3d8d78cafd78a026b1d71443f4966c696b48a6d899"}, + {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:09b055c05697b38ecacb7ac50bdab2240bfca1a0c4872b0fd309bb07dc9aa3a9"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-win32.whl", hash = "sha256:53a300ed9cea38cf5a2a9b069058137c2ca1ce658a874b79baceb8f892f915a7"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-win_amd64.whl", hash = "sha256:c2a72e9109ea74e511e29032f3b670835f8a59bbdc9ce692c5b4ed91ccf1eedb"}, {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:ebc06178e8821efc9692ea7544aa5644217358490145629914d8020042c24aa1"}, {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-macosx_13_0_arm64.whl", hash = "sha256:edaef1c1200c4b4cb914583150dcaa3bc30e592e907c01117c08b13a07255ec2"}, {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d176b57452ab5b7028ac47e7b3cf644bcfdc8cacfecf7e71759f7f51a59e5c92"}, + {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-manylinux_2_24_aarch64.whl", hash = "sha256:1dc67314e7e1086c9fdf2680b7b6c2be1c0d8e3a8279f2e993ca2a7545fecf62"}, + {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:3213ece08ea033eb159ac52ae052a4899b56ecc124bb80020d9bbceeb50258e9"}, + {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:aab7fd643f71d7946f2ee58cc88c9b7bfc97debd71dcc93e03e2d174628e7e2d"}, + {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-win32.whl", hash = "sha256:5c365d91c88390c8d0a8545df0b5857172824b1c604e867161e6b3d59a827eaa"}, + {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-win_amd64.whl", hash = "sha256:1758ce7d8e1a29d23de54a16ae867abd370f01b5a69e1a3ba75223eaa3ca1a1b"}, {file = "ruamel.yaml.clib-0.2.8-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:a5aa27bad2bb83670b71683aae140a1f52b0857a2deff56ad3f6c13a017a26ed"}, {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:c58ecd827313af6864893e7af0a3bb85fd529f862b6adbefe14643947cfe2942"}, {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-macosx_12_0_arm64.whl", hash = "sha256:f481f16baec5290e45aebdc2a5168ebc6d35189ae6fea7a58787613a25f6e875"}, + {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-manylinux_2_24_aarch64.whl", hash = "sha256:77159f5d5b5c14f7c34073862a6b7d34944075d9f93e681638f6d753606c6ce6"}, {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:7f67a1ee819dc4562d444bbafb135832b0b909f81cc90f7aa00260968c9ca1b3"}, + {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:4ecbf9c3e19f9562c7fdd462e8d18dd902a47ca046a2e64dba80699f0b6c09b7"}, + {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:87ea5ff66d8064301a154b3933ae406b0863402a799b16e4a1d24d9fbbcbe0d3"}, {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-win32.whl", hash = "sha256:75e1ed13e1f9de23c5607fe6bd1aeaae21e523b32d83bb33918245361e9cc51b"}, {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-win_amd64.whl", hash = "sha256:3f215c5daf6a9d7bbed4a0a4f760f3113b10e82ff4c5c44bec20a68c8014f675"}, {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:1b617618914cb00bf5c34d4357c37aa15183fa229b24767259657746c9077615"}, {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-macosx_12_0_arm64.whl", hash = "sha256:a6a9ffd280b71ad062eae53ac1659ad86a17f59a0fdc7699fd9be40525153337"}, + {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-manylinux_2_24_aarch64.whl", hash = "sha256:305889baa4043a09e5b76f8e2a51d4ffba44259f6b4c72dec8ca56207d9c6fe1"}, {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:700e4ebb569e59e16a976857c8798aee258dceac7c7d6b50cab63e080058df91"}, + {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:e2b4c44b60eadec492926a7270abb100ef9f72798e18743939bdbf037aab8c28"}, + {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:e79e5db08739731b0ce4850bed599235d601701d5694c36570a99a0c5ca41a9d"}, {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-win32.whl", hash = "sha256:955eae71ac26c1ab35924203fda6220f84dce57d6d7884f189743e2abe3a9fbe"}, {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-win_amd64.whl", hash = "sha256:56f4252222c067b4ce51ae12cbac231bce32aee1d33fbfc9d17e5b8d6966c312"}, {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:03d1162b6d1df1caa3a4bd27aa51ce17c9afc2046c31b0ad60a0a96ec22f8001"}, {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-macosx_12_0_arm64.whl", hash = "sha256:bba64af9fa9cebe325a62fa398760f5c7206b215201b0ec825005f1b18b9bccf"}, + {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-manylinux_2_24_aarch64.whl", hash = "sha256:a1a45e0bb052edf6a1d3a93baef85319733a888363938e1fc9924cb00c8df24c"}, {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:da09ad1c359a728e112d60116f626cc9f29730ff3e0e7db72b9a2dbc2e4beed5"}, + {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:184565012b60405d93838167f425713180b949e9d8dd0bbc7b49f074407c5a8b"}, + {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:a75879bacf2c987c003368cf14bed0ffe99e8e85acfa6c0bfffc21a090f16880"}, {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-win32.whl", hash = "sha256:84b554931e932c46f94ab306913ad7e11bba988104c5cff26d90d03f68258cd5"}, {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-win_amd64.whl", hash = "sha256:25ac8c08322002b06fa1d49d1646181f0b2c72f5cbc15a85e80b4c30a544bb15"}, {file = "ruamel.yaml.clib-0.2.8.tar.gz", hash = "sha256:beb2e0404003de9a4cab9753a8805a8fe9320ee6673136ed7f04255fe60bb512"}, ] +[[package]] +name = "ruff" +version = "0.6.1" +description = "An extremely fast Python linter and code formatter, written in Rust." +optional = false +python-versions = ">=3.7" +files = [ + {file = "ruff-0.6.1-py3-none-linux_armv6l.whl", hash = "sha256:b4bb7de6a24169dc023f992718a9417380301b0c2da0fe85919f47264fb8add9"}, + {file = "ruff-0.6.1-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:45efaae53b360c81043e311cdec8a7696420b3d3e8935202c2846e7a97d4edae"}, + {file = "ruff-0.6.1-py3-none-macosx_11_0_arm64.whl", hash = "sha256:bc60c7d71b732c8fa73cf995efc0c836a2fd8b9810e115be8babb24ae87e0850"}, + {file = "ruff-0.6.1-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2c7477c3b9da822e2db0b4e0b59e61b8a23e87886e727b327e7dcaf06213c5cf"}, + {file = "ruff-0.6.1-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:3a0af7ab3f86e3dc9f157a928e08e26c4b40707d0612b01cd577cc84b8905cc9"}, + {file = "ruff-0.6.1-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:392688dbb50fecf1bf7126731c90c11a9df1c3a4cdc3f481b53e851da5634fa5"}, + {file = "ruff-0.6.1-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:5278d3e095ccc8c30430bcc9bc550f778790acc211865520f3041910a28d0024"}, + {file = "ruff-0.6.1-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:fe6d5f65d6f276ee7a0fc50a0cecaccb362d30ef98a110f99cac1c7872df2f18"}, + {file = "ruff-0.6.1-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b2e0dd11e2ae553ee5c92a81731d88a9883af8db7408db47fc81887c1f8b672e"}, + {file = "ruff-0.6.1-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d812615525a34ecfc07fd93f906ef5b93656be01dfae9a819e31caa6cfe758a1"}, + {file = "ruff-0.6.1-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:faaa4060f4064c3b7aaaa27328080c932fa142786f8142aff095b42b6a2eb631"}, + {file = "ruff-0.6.1-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:99d7ae0df47c62729d58765c593ea54c2546d5de213f2af2a19442d50a10cec9"}, + {file = "ruff-0.6.1-py3-none-musllinux_1_2_i686.whl", hash = "sha256:9eb18dfd7b613eec000e3738b3f0e4398bf0153cb80bfa3e351b3c1c2f6d7b15"}, + {file = "ruff-0.6.1-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:c62bc04c6723a81e25e71715aa59489f15034d69bf641df88cb38bdc32fd1dbb"}, + {file = "ruff-0.6.1-py3-none-win32.whl", hash = "sha256:9fb4c4e8b83f19c9477a8745e56d2eeef07a7ff50b68a6998f7d9e2e3887bdc4"}, + {file = "ruff-0.6.1-py3-none-win_amd64.whl", hash = "sha256:c2ebfc8f51ef4aca05dad4552bbcf6fe8d1f75b2f6af546cc47cc1c1ca916b5b"}, + {file = "ruff-0.6.1-py3-none-win_arm64.whl", hash = "sha256:3bc81074971b0ffad1bd0c52284b22411f02a11a012082a76ac6da153536e014"}, + {file = "ruff-0.6.1.tar.gz", hash = "sha256:af3ffd8c6563acb8848d33cd19a69b9bfe943667f0419ca083f8ebe4224a3436"}, +] + [[package]] name = "s3transfer" version = "0.10.0" @@ -4208,4 +4175,4 @@ multidict = ">=4.0" [metadata] lock-version = "2.0" python-versions = "^3.10, <3.13" -content-hash = "cedfa7b5254c80e53fb8a6a51fed164273319b165c45f085501eb4559db5787e" +content-hash = "eba0dfb48ad8e340536c8dc20a91fb5f1511e15d6c45438197d99ee79a72e85a" diff --git a/packages/examples/cvat/recording-oracle/pyproject.toml b/packages/examples/cvat/recording-oracle/pyproject.toml index b3a5b5180d..2e504f6678 100644 --- a/packages/examples/cvat/recording-oracle/pyproject.toml +++ b/packages/examples/cvat/recording-oracle/pyproject.toml @@ -24,20 +24,121 @@ google-cloud-storage = "^2.14.0" datumaro = {git = "https://github.com/cvat-ai/datumaro.git", rev = "ff83c00c2c1bc4b8fdfcc55067fcab0a9b5b6b11"} [tool.poetry.group.dev.dependencies] -black = "^23.3.0" -pre-commit = "^3.3.3" hypothesis = "^6.82.6" -isort = "^5.12.0" -[tool.isort] -profile = "black" -forced_separate = ["tests"] -line_length = 100 -skip_gitignore = true # align tool behavior with Black +[tool.poetry.group.lint.dependencies] +pre-commit = "^3.3.3" +ruff = "^0.6.0" -[tool.black] +[tool.ruff] line-length = 100 -target-version = ['py310'] +target-version = "py310" + + +[tool.ruff.lint] +select = ["ALL"] +unfixable = [ + "RUF005", # messes up concantenation with numpy structures +] +ignore = [ + "W191", # Rules conflicting with ruff format (https://docs.astral.sh/ruff/formatter/#conflicting-lint-rules) + "E111", # | + "E114", # | + "E117", # | + "D206", # | + "D300", # | + "Q000", # | + "Q001", # | + "Q002", # | + "Q003", # | + "COM812", # | + "COM819", # | + "ISC001", # | + "ISC002", # | + "ANN101", # Method args annotations (mypy will take care of that) + "ANN001", # | + "ANN202", # | + "ANN201", # | + "ANN401", # | + "ANN102", # | + "RUF001", # Allow cyrillic letters in comments + + "B904", # Raise from: modern pythons preserve previous exceptions + "EM", # Forbids using literal strings in exceptions. + # Sujested way of dealing with exceptions increases verbosity + # while giving little to no benefit in readability + "TRY003", # | + "G004", # Forbids using f-strings in logging. This project doesn't rely on lazy % formatting when using logging. + "A003", # Class attribute `id` is shadowing a Python builtin — it's ok in class body + "FIX001", # Forbids using TODOs, but TODOs are useful + "FIX002", # | + "TD001", # | + "TD002", # | + "TD003", # | + "E711", # Allow == None comparisons for sqlalchemy queries + "E712", # Allow == True comparisons for sqlalchemy queries + "PERF203", # Noisy microoptimisation + # Want to resolve eventually, but not now: + "S101", # Allow asserts (there are too many of them right now to fix) + "TRY401", # Checks for excesive logging of exception objects + "G001", # Forbid str.format for logging + "PTH123", # Checks for uses of `os.path.splitext` + "D", # Docstrings + "N806", # Variable in function should be lowercase + "RUF012", # Mutable class attributes should be annotated with `typing.ClassVar` + "SLF001", # Private member accessed + "F811", # Redefinition of unused + "RUF005", # Consider iterable unpacking instead of concatenation + "A002", # Argument is shadowing a Python builtin + "N818", # Exception name should be named with an Error suffix + "TRY002", # Create your own exception + "ANN003", # Missing type annotation for `**kwargs` + "ANN204", # Missing return type annotation for special method + "ERA001", # Found commented-out code + "N801", # Class name should use CapWords convention + "PLR0915", # Too many statements + "PLR2004", # Magic value used in comparison, consider replacing with a constant variable + "ANN002", # Missing type annotation for `*args` + "TRY300", # Consider moving this statement to an `else` block + "C901", # Function is too complex + "PLW2901", # Variable overwritten by assignment target + "PTH118", # Prefer pathlib instead of os.path + "PTH119", # `os.path.basename()` should be replaced by `Path.name` + "PTH122", # `os.path.splitext()` should be replaced by `Path.suffix`, `Path.stem`, and `Path.parent` + "PTH207", # Replace `glob` with `Path.glob` or `Path.rglob` +] + + +[tool.ruff.lint.per-file-ignores] +"tests/*" = [ + "PLR0913", # Annotations and args + "ANN202", # | + "ANN201", # | + "ANN001", # | + "ANN003", # | + "ARG001", # | + "SLF001", # Allow private attrs access + "PLR2004", # Allow magic values + "S", # security + "DTZ005", # allow datetimes without timezones +] +# alembic is not a package in a traditional sense, so putting __init__.py there doesn't make sense +"alembic/*" = ["INP001"] +"__init__.py" = ["F401"] + +[tool.ruff.lint.pep8-naming] +classmethod-decorators = [ + "pydantic.validator", +] + +[tool.ruff.lint.pylint] +max-args = 9 # Lower number might be beneficial to reduce cognitive load. Consider using data containers. + +[tool.ruff.lint.isort] +forced-separate = ["tests"] + +[tool.ruff.lint.flake8-tidy-imports] +ban-relative-imports = "all" [build-system] requires = ["poetry-core"] diff --git a/packages/examples/cvat/recording-oracle/run.py b/packages/examples/cvat/recording-oracle/run.py index 5b59b70a51..2f09b1a09f 100644 --- a/packages/examples/cvat/recording-oracle/run.py +++ b/packages/examples/cvat/recording-oracle/run.py @@ -11,7 +11,7 @@ uvicorn.run( app="src:app", - host="0.0.0.0", + host="0.0.0.0", # noqa: S104 port=int(Config.port), workers=Config.workers_amount, reload=is_dev, diff --git a/packages/examples/cvat/recording-oracle/src/chain/escrow.py b/packages/examples/cvat/recording-oracle/src/chain/escrow.py index 00381be5f4..5651f21e3c 100644 --- a/packages/examples/cvat/recording-oracle/src/chain/escrow.py +++ b/packages/examples/cvat/recording-oracle/src/chain/escrow.py @@ -1,8 +1,7 @@ import json -from typing import List from human_protocol_sdk.constants import ChainId, Status -from human_protocol_sdk.encryption import Encryption, EncryptionUtils +from human_protocol_sdk.encryption import Encryption from human_protocol_sdk.escrow import EscrowClient, EscrowData, EscrowUtils from human_protocol_sdk.storage import StorageUtils @@ -22,9 +21,11 @@ def validate_escrow( chain_id: int, escrow_address: str, *, - accepted_states: List[Status] = [Status.Pending], + accepted_states: list[Status] | None = None, allow_no_funds: bool = False, ) -> None: + if accepted_states is None: + accepted_states = [Status.Pending] assert accepted_states escrow = get_escrow(chain_id, escrow_address) @@ -37,9 +38,8 @@ def validate_escrow( ) ) - if status == Status.Pending and not allow_no_funds: - if int(escrow.balance) == 0: - raise ValueError("Escrow doesn't have funds") + if status == Status.Pending and not allow_no_funds and int(escrow.balance) == 0: + raise ValueError("Escrow doesn't have funds") def get_escrow_manifest(chain_id: int, escrow_address: str) -> dict: diff --git a/packages/examples/cvat/recording-oracle/src/chain/kvstore.py b/packages/examples/cvat/recording-oracle/src/chain/kvstore.py index b91f2ec3a1..0d7c763914 100644 --- a/packages/examples/cvat/recording-oracle/src/chain/kvstore.py +++ b/packages/examples/cvat/recording-oracle/src/chain/kvstore.py @@ -11,9 +11,7 @@ def get_role_by_address(chain_id: int, address: str) -> str: web3 = get_web3(chain_id) kvstore_client = KVStoreClient(web3) - role = kvstore_client.get(address, "role") - - return role + return kvstore_client.get(address, "role") def get_exchange_oracle_url(chain_id: int, escrow_address: str) -> str: diff --git a/packages/examples/cvat/recording-oracle/src/chain/web3.py b/packages/examples/cvat/recording-oracle/src/chain/web3.py index cc427c96b9..e76f77bf95 100644 --- a/packages/examples/cvat/recording-oracle/src/chain/web3.py +++ b/packages/examples/cvat/recording-oracle/src/chain/web3.py @@ -71,9 +71,7 @@ def sign_message(chain_id: Networks, message) -> str: def recover_signer(chain_id: Networks, message, signature: str) -> str: w3 = get_web3(chain_id) message_hash = encode_defunct(text=serialize_message(message)) - signer = w3.eth.account.recover_message(message_hash, signature=signature) - - return signer + return w3.eth.account.recover_message(message_hash, signature=signature) def validate_address(escrow_address: str) -> str: diff --git a/packages/examples/cvat/recording-oracle/src/core/__init__.py b/packages/examples/cvat/recording-oracle/src/core/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/examples/cvat/recording-oracle/src/core/annotation_meta.py b/packages/examples/cvat/recording-oracle/src/core/annotation_meta.py index e19a77efd5..d539787315 100644 --- a/packages/examples/cvat/recording-oracle/src/core/annotation_meta.py +++ b/packages/examples/cvat/recording-oracle/src/core/annotation_meta.py @@ -1,5 +1,4 @@ from pathlib import Path -from typing import List from pydantic import BaseModel @@ -15,4 +14,4 @@ class JobMeta(BaseModel): class AnnotationMeta(BaseModel): - jobs: List[JobMeta] + jobs: list[JobMeta] diff --git a/packages/examples/cvat/recording-oracle/src/core/config.py b/packages/examples/cvat/recording-oracle/src/core/config.py index c948fe474e..db5534ac4c 100644 --- a/packages/examples/cvat/recording-oracle/src/core/config.py +++ b/packages/examples/cvat/recording-oracle/src/core/config.py @@ -1,8 +1,10 @@ # pylint: disable=too-few-public-methods,missing-class-docstring -""" Project configuration from env vars """ +"""Project configuration from env vars""" + import inspect import os -from typing import ClassVar, Iterable, Optional +from collections.abc import Iterable +from typing import ClassVar from attrs.converters import to_bool from dotenv import load_dotenv @@ -14,7 +16,7 @@ from src.utils.net import is_ipv4 dotenv_path = os.getenv("DOTENV_PATH", None) -if dotenv_path and not os.path.exists(dotenv_path): +if dotenv_path and not os.path.exists(dotenv_path): # noqa: PTH110 raise FileNotFoundError(dotenv_path) load_dotenv(dotenv_path) @@ -28,22 +30,22 @@ def validate(cls) -> None: class Postgres: port = os.environ.get("PG_PORT", "5434") - host = os.environ.get("PG_HOST", "0.0.0.0") + host = os.environ.get("PG_HOST", "0.0.0.0") # noqa: S104 user = os.environ.get("PG_USER", "admin") password = os.environ.get("PG_PASSWORD", "admin") database = os.environ.get("PG_DB", "recording_oracle") lock_timeout = int(os.environ.get("PG_LOCK_TIMEOUT", "3000")) # milliseconds @classmethod - def connection_url(cls): + def connection_url(cls) -> str: return f"postgresql://{cls.user}:{cls.password}@{cls.host}:{cls.port}/{cls.database}" class _NetworkConfig: chain_id: ClassVar[int] - rpc_api: ClassVar[Optional[str]] - private_key: ClassVar[Optional[str]] - addr: ClassVar[Optional[str]] + rpc_api: ClassVar[str | None] + private_key: ClassVar[str | None] + addr: ClassVar[str | None] @classmethod def is_configured(cls) -> bool: @@ -101,12 +103,12 @@ class IStorageConfig: data_bucket_name: ClassVar[str] secure: ClassVar[bool] endpoint_url: ClassVar[str] # TODO: probably should be optional - region: ClassVar[Optional[str]] + region: ClassVar[str | None] # AWS S3 specific attributes - access_key: ClassVar[Optional[str]] - secret_key: ClassVar[Optional[str]] + access_key: ClassVar[str | None] + secret_key: ClassVar[str | None] # GCS specific attributes - key_file_path: ClassVar[Optional[str]] + key_file_path: ClassVar[str | None] @classmethod def get_scheme(cls) -> str: @@ -120,8 +122,7 @@ def provider_endpoint_url(cls) -> str: def bucket_url(cls) -> str: if is_ipv4(cls.endpoint_url): return f"{cls.get_scheme()}{cls.endpoint_url}/{cls.data_bucket_name}/" - else: - return f"{cls.get_scheme()}{cls.data_bucket_name}.{cls.endpoint_url}/" + return f"{cls.get_scheme()}{cls.data_bucket_name}.{cls.endpoint_url}/" class StorageConfig(IStorageConfig): @@ -192,7 +193,7 @@ class ValidationConfig: Each such job will be accepted "blindly", as we can't validate the annotations. """ - max_escrow_iterations = int(os.getenv("MAX_ESCROW_ITERATIONS", 0)) + max_escrow_iterations = int(os.getenv("MAX_ESCROW_ITERATIONS", "0")) """ Maximum escrow annotation-validation iterations. After this, the escrow is finished automatically. @@ -210,12 +211,12 @@ def validate(cls) -> None: ex_prefix = "Wrong server configuration." if (cls.pgp_public_key_url or cls.pgp_passphrase) and not cls.pgp_private_key: - raise Exception(" ".join([ex_prefix, "The PGP_PRIVATE_KEY environment is not set."])) + raise Exception(f"{ex_prefix} The PGP_PRIVATE_KEY environment is not set.") if cls.pgp_private_key: try: Encryption(cls.pgp_private_key, passphrase=cls.pgp_passphrase) - except Exception as ex: + except Exception as ex: # noqa: BLE001 # Possible reasons: # - private key is invalid # - private key is locked but no passphrase is provided @@ -251,9 +252,12 @@ def validate(cls) -> None: attr_or_method.validate() @classmethod - def get_network_configs(cls, only_configured: bool = True) -> Iterable[_NetworkConfig]: + def get_network_configs(cls, *, only_configured: bool = True) -> Iterable[_NetworkConfig]: for attr_or_method in cls.__dict__: attr_or_method = getattr(cls, attr_or_method) - if inspect.isclass(attr_or_method) and issubclass(attr_or_method, _NetworkConfig): - if not only_configured or attr_or_method.is_configured(): - yield attr_or_method + if ( + inspect.isclass(attr_or_method) + and issubclass(attr_or_method, _NetworkConfig) + and (not only_configured or attr_or_method.is_configured()) + ): + yield attr_or_method diff --git a/packages/examples/cvat/recording-oracle/src/core/manifest.py b/packages/examples/cvat/recording-oracle/src/core/manifest.py index c8a4c2260d..c70c1ed91a 100644 --- a/packages/examples/cvat/recording-oracle/src/core/manifest.py +++ b/packages/examples/cvat/recording-oracle/src/core/manifest.py @@ -1,6 +1,6 @@ from decimal import Decimal from enum import Enum -from typing import Annotated, Any, Dict, List, Literal, Optional, Tuple, Union +from typing import Annotated, Any, Literal from pydantic import AnyUrl, BaseModel, Field, root_validator @@ -28,22 +28,22 @@ class AwsBucketUrl(BucketUrlBase, BaseModel): class GcsBucketUrl(BucketUrlBase, BaseModel): provider: Literal[BucketProviders.gcs] - service_account_key: Dict[str, Any] = {} # (optional) Contents of GCS key file + service_account_key: dict[str, Any] = {} # (optional) Contents of GCS key file -BucketUrl = Annotated[Union[AwsBucketUrl, GcsBucketUrl], Field(discriminator="provider")] +BucketUrl = Annotated[AwsBucketUrl | GcsBucketUrl, Field(discriminator="provider")] class DataInfo(BaseModel): - data_url: Union[AnyUrl, BucketUrl] + data_url: AnyUrl | BucketUrl "Bucket URL, AWS S3 | GCS, virtual-hosted-style access" # https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-bucket-intro.html - points_url: Optional[Union[AnyUrl, BucketUrl]] = None + points_url: AnyUrl | BucketUrl | None = None "A path to an archive with a set of points in COCO Keypoints format, " "which provides information about all objects on images" - boxes_url: Optional[Union[AnyUrl, BucketUrl]] = None + boxes_url: AnyUrl | BucketUrl | None = None "A path to an archive with a set of boxes in COCO Instances format, " "which provides information about all objects on images" @@ -67,7 +67,7 @@ class PlainLabelInfo(LabelInfoBase): class SkeletonLabelInfo(LabelInfoBase): type: Literal[LabelTypes.skeleton] - nodes: List[str] = Field(min_items=1) + nodes: list[str] = Field(min_items=1) """ A list of node label names (only points are supposed to be nodes). Example: @@ -76,7 +76,7 @@ class SkeletonLabelInfo(LabelInfoBase): ] """ - joints: Optional[List[Tuple[int, int]]] = Field(default_factory=list) + joints: list[tuple[int, int]] | None = Field(default_factory=list) "A list of node adjacency, e.g. [[0, 1], [1, 2], [1, 3]]" @root_validator @@ -114,7 +114,7 @@ def validate_type(cls, values: dict) -> dict: return values -LabelInfo = Annotated[Union[PlainLabelInfo, SkeletonLabelInfo], Field(discriminator="type")] +LabelInfo = Annotated[PlainLabelInfo | SkeletonLabelInfo, Field(discriminator="type")] class AnnotationInfo(BaseModel): @@ -132,7 +132,7 @@ class AnnotationInfo(BaseModel): job_size: int = 10 "Frames per job, validation frames are not included" - max_time: Optional[int] = None # deprecated, TODO: mark deprecated with pydantic 2.7+ + max_time: int | None = None # deprecated, TODO: mark deprecated with pydantic 2.7+ "Maximum time per job (assignment) for an annotator, in seconds" @root_validator(pre=True) @@ -161,7 +161,7 @@ class ValidationInfo(BaseModel): val_size: int = Field(default=2, gt=0) "Validation frames per job" - gt_url: Union[AnyUrl, BucketUrl] + gt_url: AnyUrl | BucketUrl "URL to the archive with Ground Truth annotations, the format is COCO keypoints" diff --git a/packages/examples/cvat/recording-oracle/src/core/oracle_events.py b/packages/examples/cvat/recording-oracle/src/core/oracle_events.py index 519152e2de..721e3f0647 100644 --- a/packages/examples/cvat/recording-oracle/src/core/oracle_events.py +++ b/packages/examples/cvat/recording-oracle/src/core/oracle_events.py @@ -1,13 +1,8 @@ -from typing import Optional, Type, Union - from pydantic import BaseModel from src.core.types import ExchangeOracleEventTypes, OracleWebhookTypes, RecordingOracleEventTypes -EventTypeTag = Union[ - ExchangeOracleEventTypes, - RecordingOracleEventTypes, -] +EventTypeTag = ExchangeOracleEventTypes | RecordingOracleEventTypes class OracleEvent(BaseModel): @@ -50,7 +45,7 @@ class ExchangeOracleEvent_TaskFinished(OracleEvent): } -def get_class_for_event_type(event_type: str) -> Type[OracleEvent]: +def get_class_for_event_type(event_type: str) -> type[OracleEvent]: event_class = next((v for k, v in _event_type_map.items() if k == event_type), None) if not event_class: @@ -59,7 +54,7 @@ def get_class_for_event_type(event_type: str) -> Type[OracleEvent]: return event_class -def get_type_tag_for_event_class(event_class: Type[OracleEvent]) -> EventTypeTag: +def get_type_tag_for_event_class(event_class: type[OracleEvent]) -> EventTypeTag: event_type = next((k for k, v in _event_type_map.items() if v == event_class), None) if not event_type: @@ -69,7 +64,7 @@ def get_type_tag_for_event_class(event_class: Type[OracleEvent]) -> EventTypeTag def parse_event( - sender: OracleWebhookTypes, event_type: str, event_data: Optional[dict] = None + sender: OracleWebhookTypes, event_type: str, event_data: dict | None = None ) -> OracleEvent: sender_events_mapping = { OracleWebhookTypes.recording_oracle: RecordingOracleEventTypes, @@ -78,10 +73,10 @@ def parse_event( sender_events = sender_events_mapping.get(sender) if sender_events is not None: - if not event_type in sender_events: + if event_type not in sender_events: raise ValueError(f"Unknown event '{sender}.{event_type}'") else: - assert False, f"Unknown event sender type '{sender}'" + raise AssertionError(f"Unknown event sender type '{sender}'") event_class = get_class_for_event_type(event_type) return event_class.parse_obj(event_data or {}) diff --git a/packages/examples/cvat/recording-oracle/src/core/storage.py b/packages/examples/cvat/recording-oracle/src/core/storage.py index 6c5c53dbe2..939be882fd 100644 --- a/packages/examples/cvat/recording-oracle/src/core/storage.py +++ b/packages/examples/cvat/recording-oracle/src/core/storage.py @@ -7,4 +7,7 @@ def compose_data_bucket_filename(escrow_address: str, chain_id: Networks, filena def compose_results_bucket_filename(escrow_address: str, chain_id: Networks, filename: str) -> str: - return f"{escrow_address}@{chain_id}{Config.exchange_oracle_storage_config.results_dir_suffix}/{filename}" + return ( + f"{escrow_address}@{chain_id}{Config.exchange_oracle_storage_config.results_dir_suffix}" + f"/{filename}" + ) diff --git a/packages/examples/cvat/recording-oracle/src/core/tasks/boxes_from_points.py b/packages/examples/cvat/recording-oracle/src/core/tasks/boxes_from_points.py index c9320473b6..bd26aacc14 100644 --- a/packages/examples/cvat/recording-oracle/src/core/tasks/boxes_from_points.py +++ b/packages/examples/cvat/recording-oracle/src/core/tasks/boxes_from_points.py @@ -1,14 +1,14 @@ import os +from collections.abc import Sequence from pathlib import Path from tempfile import TemporaryDirectory -from typing import Dict, Sequence import attrs import datumaro as dm from attrs import frozen from datumaro.util import dump_json, parse_json -BboxPointMapping = Dict[int, int] +BboxPointMapping = dict[int, int] @frozen @@ -28,7 +28,7 @@ def asdict(self) -> dict: RoiInfos = Sequence[RoiInfo] -RoiFilenames = Dict[int, str] +RoiFilenames = dict[int, str] class TaskMetaLayout: diff --git a/packages/examples/cvat/recording-oracle/src/core/tasks/skeletons_from_boxes.py b/packages/examples/cvat/recording-oracle/src/core/tasks/skeletons_from_boxes.py index b6b680c19a..fb5f09b418 100644 --- a/packages/examples/cvat/recording-oracle/src/core/tasks/skeletons_from_boxes.py +++ b/packages/examples/cvat/recording-oracle/src/core/tasks/skeletons_from_boxes.py @@ -1,14 +1,14 @@ import os +from collections.abc import Sequence from pathlib import Path from tempfile import TemporaryDirectory -from typing import Dict, Sequence, Tuple import attrs import datumaro as dm from attrs import frozen from datumaro.util import dump_json, parse_json -SkeletonBboxMapping = Dict[int, int] +SkeletonBboxMapping = dict[int, int] # TODO: migrate to pydantic @@ -34,9 +34,9 @@ def asdict(self) -> dict: RoiInfos = Sequence[RoiInfo] -RoiFilenames = Dict[int, str] +RoiFilenames = dict[int, str] -PointLabelsMapping = Dict[Tuple[str, str], str] +PointLabelsMapping = dict[tuple[str, str], str] "(skeleton, point) -> job point name" diff --git a/packages/examples/cvat/recording-oracle/src/core/validation_meta.py b/packages/examples/cvat/recording-oracle/src/core/validation_meta.py index 027e3ed419..66b9aca8e0 100644 --- a/packages/examples/cvat/recording-oracle/src/core/validation_meta.py +++ b/packages/examples/cvat/recording-oracle/src/core/validation_meta.py @@ -1,5 +1,3 @@ -from typing import List - from pydantic import BaseModel VALIDATION_METAFILE_NAME = "validation_meta.json" @@ -19,5 +17,5 @@ class ResultMeta(BaseModel): class ValidationMeta(BaseModel): - jobs: List[JobMeta] - results: List[ResultMeta] + jobs: list[JobMeta] + results: list[ResultMeta] diff --git a/packages/examples/cvat/recording-oracle/src/core/validation_results.py b/packages/examples/cvat/recording-oracle/src/core/validation_results.py index 8d78bfc7c8..79d8ba001e 100644 --- a/packages/examples/cvat/recording-oracle/src/core/validation_results.py +++ b/packages/examples/cvat/recording-oracle/src/core/validation_results.py @@ -1,5 +1,4 @@ from dataclasses import dataclass -from typing import Dict from src.core.validation_errors import DatasetValidationError from src.core.validation_meta import ValidationMeta @@ -14,4 +13,4 @@ class ValidationSuccess: @dataclass class ValidationFailure: - rejected_jobs: Dict[int, DatasetValidationError] + rejected_jobs: dict[int, DatasetValidationError] diff --git a/packages/examples/cvat/recording-oracle/src/crons/process_exchange_oracle_webhooks.py b/packages/examples/cvat/recording-oracle/src/crons/process_exchange_oracle_webhooks.py index 86d1097ece..95f7cd0bd9 100644 --- a/packages/examples/cvat/recording-oracle/src/crons/process_exchange_oracle_webhooks.py +++ b/packages/examples/cvat/recording-oracle/src/crons/process_exchange_oracle_webhooks.py @@ -1,5 +1,4 @@ import logging -from typing import Dict import httpx from sqlalchemy.orm import Session @@ -75,7 +74,7 @@ def handle_exchange_oracle_event(webhook: Webhook, *, db_session: Session, logge ) case _: - assert False, f"Unknown exchange oracle event {webhook.event_type}" + raise AssertionError(f"Unknown exchange oracle event {webhook.event_type}") def process_outgoing_exchange_oracle_webhooks(): diff --git a/packages/examples/cvat/recording-oracle/src/db/__init__.py b/packages/examples/cvat/recording-oracle/src/db/__init__.py index 6e9c85cded..68068770e3 100644 --- a/packages/examples/cvat/recording-oracle/src/db/__init__.py +++ b/packages/examples/cvat/recording-oracle/src/db/__init__.py @@ -8,7 +8,7 @@ engine = sqlalchemy.create_engine( DATABASE_URL, echo="debug" if Config.loglevel <= src.utils.logging.TRACE else False, - connect_args={"options": "-c lock_timeout={:d}".format(Config.postgres_config.lock_timeout)}, + connect_args={"options": f"-c lock_timeout={Config.postgres_config.lock_timeout:d}"}, ) SessionLocal = sessionmaker(autocommit=False, bind=engine) diff --git a/packages/examples/cvat/recording-oracle/src/db/utils.py b/packages/examples/cvat/recording-oracle/src/db/utils.py index 24dfb41561..77651fa42a 100644 --- a/packages/examples/cvat/recording-oracle/src/db/utils.py +++ b/packages/examples/cvat/recording-oracle/src/db/utils.py @@ -1,5 +1,5 @@ from dataclasses import dataclass -from typing import TypeVar, Union +from typing import TypeVar from sqlalchemy import Select from sqlalchemy.orm import Query @@ -14,14 +14,11 @@ class ForUpdateParams: T = TypeVar("T", Query, Select) -def maybe_for_update(query: T, enable: Union[bool, ForUpdateParams]) -> T: +def maybe_for_update(query: T, enable: bool | ForUpdateParams) -> T: if not enable: return query - if isinstance(enable, ForUpdateParams): - params = enable - else: - params = ForUpdateParams() + params = enable if isinstance(enable, ForUpdateParams) else ForUpdateParams() return query.with_for_update( skip_locked=params.skip_locked, diff --git a/packages/examples/cvat/recording-oracle/src/endpoints/__init__.py b/packages/examples/cvat/recording-oracle/src/endpoints/__init__.py index 4b1802bc67..f3b167a2d7 100644 --- a/packages/examples/cvat/recording-oracle/src/endpoints/__init__.py +++ b/packages/examples/cvat/recording-oracle/src/endpoints/__init__.py @@ -1,4 +1,5 @@ -""" API endpoints """ +"""API endpoints""" + from fastapi import APIRouter, FastAPI from src.core.config import Config @@ -21,11 +22,11 @@ def meta_route() -> MetaResponse: ] return MetaResponse.parse_obj( - dict( - message="Recording Oracle API", - version="0.1.0", - supported_networks=networks_info, - ) + { + "message": "Recording Oracle API", + "version": "0.1.0", + "supported_networks": networks_info, + } ) diff --git a/packages/examples/cvat/recording-oracle/src/endpoints/error_handlers.py b/packages/examples/cvat/recording-oracle/src/endpoints/error_handlers.py index b8d1c424b1..294867ea07 100644 --- a/packages/examples/cvat/recording-oracle/src/endpoints/error_handlers.py +++ b/packages/examples/cvat/recording-oracle/src/endpoints/error_handlers.py @@ -1,4 +1,5 @@ -""" Custom error handlers for the FastAPI""" +"""Custom error handlers for the FastAPI""" + from fastapi import FastAPI from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse diff --git a/packages/examples/cvat/recording-oracle/src/endpoints/webhook.py b/packages/examples/cvat/recording-oracle/src/endpoints/webhook.py index f5fee7b483..df2e44dc80 100644 --- a/packages/examples/cvat/recording-oracle/src/endpoints/webhook.py +++ b/packages/examples/cvat/recording-oracle/src/endpoints/webhook.py @@ -1,5 +1,3 @@ -from typing import Union - from fastapi import APIRouter, Header, HTTPException, Request import src.services.webhook as oracle_db_service @@ -15,7 +13,7 @@ async def receive_oracle_webhook( webhook: OracleWebhook, request: Request, - human_signature: Union[str, None] = Header(default=None), + human_signature: str | None = Header(default=None), ) -> OracleWebhookResponse: try: sender = await validate_oracle_webhook_signature(request, human_signature, webhook) diff --git a/packages/examples/cvat/recording-oracle/src/handlers/__init__.py b/packages/examples/cvat/recording-oracle/src/handlers/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/examples/cvat/recording-oracle/src/handlers/error_handlers.py b/packages/examples/cvat/recording-oracle/src/handlers/error_handlers.py index b8d1c424b1..294867ea07 100644 --- a/packages/examples/cvat/recording-oracle/src/handlers/error_handlers.py +++ b/packages/examples/cvat/recording-oracle/src/handlers/error_handlers.py @@ -1,4 +1,5 @@ -""" Custom error handlers for the FastAPI""" +"""Custom error handlers for the FastAPI""" + from fastapi import FastAPI from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse diff --git a/packages/examples/cvat/recording-oracle/src/handlers/process_intermediate_results.py b/packages/examples/cvat/recording-oracle/src/handlers/process_intermediate_results.py index 1ff839f4f7..17d9e2522f 100644 --- a/packages/examples/cvat/recording-oracle/src/handlers/process_intermediate_results.py +++ b/packages/examples/cvat/recording-oracle/src/handlers/process_intermediate_results.py @@ -6,11 +6,10 @@ from dataclasses import dataclass, field from pathlib import Path from tempfile import TemporaryDirectory -from typing import Dict, NamedTuple, Optional, Set, Type, TypeVar, Union +from typing import TYPE_CHECKING, NamedTuple, TypeVar import datumaro as dm import numpy as np -from sqlalchemy.orm import Session import src.core.tasks.boxes_from_points as boxes_from_points_task import src.core.tasks.simple as simple_task @@ -18,7 +17,6 @@ import src.services.validation as db_service from src.core.annotation_meta import AnnotationMeta from src.core.config import Config -from src.core.manifest import TaskManifest from src.core.storage import compose_data_bucket_filename from src.core.types import TaskTypes from src.core.validation_errors import DatasetValidationError, LowAccuracyError @@ -37,6 +35,11 @@ TooFewGtError, ) +if TYPE_CHECKING: + from sqlalchemy.orm import Session + + from src.core.manifest import TaskManifest + DM_DATASET_FORMAT_MAPPING = { TaskTypes.image_label_binary: "cvat_images", TaskTypes.image_points: "coco_person_keypoints", @@ -54,7 +57,7 @@ } -DATASET_COMPARATOR_TYPE_MAP: Dict[TaskTypes, Type[DatasetComparator]] = { +DATASET_COMPARATOR_TYPE_MAP: dict[TaskTypes, type[DatasetComparator]] = { # TaskType.image_label_binary: TagDatasetComparator, # TODO: implement if support is needed TaskTypes.image_boxes: BboxDatasetComparator, TaskTypes.image_points: PointsDatasetComparator, @@ -62,21 +65,21 @@ TaskTypes.image_skeletons_from_boxes: SkeletonDatasetComparator, } -_JobResults = Dict[int, float] +_JobResults = dict[int, float] -_RejectedJobs = Dict[int, DatasetValidationError] +_RejectedJobs = dict[int, DatasetValidationError] -_FailedGtAttempts = Dict[str, int] +_FailedGtAttempts = dict[str, int] "gt key -> attempts" @dataclass class _UpdatedFailedGtInfo: - failed_jobs: Set[int] = field(default_factory=set) + failed_jobs: set[int] = field(default_factory=set) occurrences: int = 0 -_UpdatedFailedGtStats = Dict[str, _UpdatedFailedGtInfo] +_UpdatedFailedGtStats = dict[str, _UpdatedFailedGtInfo] @dataclass @@ -100,27 +103,27 @@ def __init__( chain_id: int, manifest: TaskManifest, *, - job_annotations: Dict[int, io.IOBase], + job_annotations: dict[int, io.IOBase], merged_annotations: io.IOBase, - gt_stats: Optional[_FailedGtAttempts] = None, - ): + gt_stats: _FailedGtAttempts | None = None, + ) -> None: self.escrow_address = escrow_address self.chain_id = chain_id self.manifest = manifest self._initial_gt_attempts: _FailedGtAttempts = gt_stats or {} - self._job_annotations: Dict[int, io.IOBase] = job_annotations + self._job_annotations: dict[int, io.IOBase] = job_annotations self._merged_annotations: io.IOBase = merged_annotations - self._updated_merged_dataset_archive: Optional[io.IOBase] = None - self._updated_gt_stats: Optional[_UpdatedFailedGtStats] = None - self._job_results: Optional[_JobResults] = None - self._rejected_jobs: Optional[_RejectedJobs] = None + self._updated_merged_dataset_archive: io.IOBase | None = None + self._updated_gt_stats: _UpdatedFailedGtStats | None = None + self._job_results: _JobResults | None = None + self._rejected_jobs: _RejectedJobs | None = None - self._temp_dir: Optional[Path] = None - self._gt_dataset: Optional[dm.Dataset] = None + self._temp_dir: Path | None = None + self._gt_dataset: dm.Dataset | None = None - def _require_field(self, field: Optional[T]) -> T: + def _require_field(self, field: T | None) -> T: assert field is not None return field @@ -133,7 +136,7 @@ def _get_gt_weight(self, failed_attempts: int) -> float: return weight - def _get_gt_weights(self) -> Dict[str, float]: + def _get_gt_weights(self) -> dict[str, float]: weights = {} ban_threshold = Config.validation.gt_ban_threshold @@ -164,7 +167,7 @@ def _parse_gt(self): ) ) - def _load_job_dataset(self, job_id: int, job_dataset_path: Path) -> dm.Dataset: + def _load_job_dataset(self, job_id: int, job_dataset_path: Path) -> dm.Dataset: # noqa: ARG002 manifest = self._require_field(self.manifest) return dm.Dataset.import_from( @@ -217,7 +220,7 @@ def _validate_jobs(self): def _restore_original_image_paths(self, merged_dataset: dm.Dataset) -> dm.Dataset: class RemoveCommonPrefix(dm.ItemTransform): - def __init__(self, extractor: dm.IExtractor, *, prefix: str): + def __init__(self, extractor: dm.IExtractor, *, prefix: str) -> None: super().__init__(extractor) self._prefix = prefix @@ -262,7 +265,7 @@ def _prepare_merged_dataset(self): @classmethod def _put_gt_into_merged_dataset( cls, gt_dataset: dm.Dataset, merged_dataset: dm.Dataset, *, manifest: TaskManifest - ): + ) -> None: """ Updates the merged dataset inplace, writing GT annotations corresponding to the task type. """ @@ -309,7 +312,7 @@ def _put_gt_into_merged_dataset( ) merged_dataset.update(gt_dataset) case _: - assert False, f"Unknown task type {manifest.annotation.type}" + raise AssertionError(f"Unknown task type {manifest.annotation.type}") def validate(self) -> _ValidationResult: with TemporaryDirectory() as tempdir: @@ -331,7 +334,7 @@ class _TaskValidatorWithPerJobGt(_TaskValidator): def _make_gt_dataset_for_job(self, job_id: int, job_dataset: dm.Dataset) -> dm.Dataset: raise NotImplementedError - def _get_gt_weights(self, *, job_cvat_id: int, job_gt_dataset: dm.Dataset) -> Dict[str, float]: + def _get_gt_weights(self, *, job_cvat_id: int, job_gt_dataset: dm.Dataset) -> dict[str, float]: weights = {} ban_threshold = Config.validation.gt_ban_threshold @@ -350,8 +353,12 @@ def _get_gt_weights(self, *, job_cvat_id: int, job_gt_dataset: dm.Dataset) -> Di return weights def _gt_key_to_sample_id( - self, gt_key: str, *, job_cvat_id: int, job_gt_dataset: dm.Dataset - ) -> Optional[str]: + self, + gt_key: str, + *, + job_cvat_id: int, # noqa: ARG002 + job_gt_dataset: dm.Dataset, # noqa: ARG002 + ) -> str | None: return gt_key def _update_gt_stats( @@ -418,7 +425,7 @@ def _validate_jobs(self): class _BoxesFromPointsValidator(_TaskValidatorWithPerJobGt): - def __init__(self, *args, **kwargs): + def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) ( @@ -448,7 +455,7 @@ def __init__(self, *args, **kwargs): self._point_key_to_bbox_key = {v: k for k, v in boxes_to_points_mapping.items()} self._roi_info_by_id = {roi_info.point_id: roi_info for roi_info in roi_infos} - self._roi_name_to_roi_info: Dict[str, boxes_from_points_task.RoiInfo] = { + self._roi_name_to_roi_info: dict[str, boxes_from_points_task.RoiInfo] = { os.path.splitext(roi_filename)[0]: self._roi_info_by_id[roi_id] for roi_id, roi_filename in roi_filenames.items() } @@ -521,7 +528,7 @@ def _download_task_meta(self): return boxes_to_points_mapping, roi_filenames, rois, gt_dataset, points_dataset - def _make_gt_dataset_for_job(self, job_id: int, job_dataset: dm.Dataset) -> dm.Dataset: + def _make_gt_dataset_for_job(self, job_id: int, job_dataset: dm.Dataset) -> dm.Dataset: # noqa: ARG002 job_gt_dataset = dm.Dataset(categories=self._gt_dataset.categories(), media_type=dm.Image) for job_sample in job_dataset: @@ -554,7 +561,7 @@ def _prepare_merged_dataset(self): class _SkeletonsFromBoxesValidator(_TaskValidatorWithPerJobGt): - def __init__(self, *args, **kwargs): + def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) ( @@ -589,7 +596,7 @@ def __init__(self, *args, **kwargs): self._bbox_key_to_skeleton_key = {v: k for k, v in skeletons_to_boxes_mapping.items()} self._roi_info_by_id = {roi_info.bbox_id: roi_info for roi_info in roi_infos} - self._roi_name_to_roi_info: Dict[str, skeletons_from_boxes_task.RoiInfo] = { + self._roi_name_to_roi_info: dict[str, skeletons_from_boxes_task.RoiInfo] = { os.path.splitext(roi_filename)[0]: self._roi_info_by_id[roi_id] for roi_id, roi_filename in roi_filenames.items() } @@ -731,7 +738,7 @@ def _load_job_dataset(self, job_id: int, job_dataset_path: Path) -> dm.Dataset: return updated_dataset - def _make_gt_dataset_for_job(self, job_id: int, job_dataset: dm.Dataset) -> dm.Dataset: + def _make_gt_dataset_for_job(self, job_id: int, job_dataset: dm.Dataset) -> dm.Dataset: # noqa: ARG002 job_label_cat: dm.LabelCategories = job_dataset.categories()[dm.AnnotationType.label] assert len(job_label_cat) == 2 job_skeleton_label_id, job_skeleton_label = next( @@ -832,8 +839,8 @@ class _LabelId(NamedTuple): def _get_gt_dataset_label_id(self, job_gt_dataset: dm.Dataset) -> _LabelId: label_cat: dm.LabelCategories = job_gt_dataset.categories()[dm.AnnotationType.label] assert len(label_cat) == 2 - job_skeleton_label = next(l for l in label_cat if not l.parent) - job_point_label = next(l for l in label_cat if l.parent) + job_skeleton_label = next(label for label in label_cat if not label.parent) + job_point_label = next(label for label in label_cat if label.parent) return self._LabelId( *next( @@ -846,8 +853,12 @@ def _get_gt_dataset_label_id(self, job_gt_dataset: dm.Dataset) -> _LabelId: ) def _gt_key_to_sample_id( - self, gt_key: str, *, job_cvat_id: int, job_gt_dataset: dm.Dataset - ) -> Optional[str]: + self, + gt_key: str, + *, + job_cvat_id: int, # noqa: ARG002 + job_gt_dataset: dm.Dataset, + ) -> str | None: parsed_gt_key = self._parse_gt_key(gt_key) job_label_id = self._get_gt_dataset_label_id(job_gt_dataset) if (parsed_gt_key.skeleton_id, parsed_gt_key.point_id) != job_label_id: @@ -904,17 +915,17 @@ def _compute_gt_stats_update( return updated_gt_stats -def process_intermediate_results( +def process_intermediate_results( # noqa: PLR0912 session: Session, *, escrow_address: str, chain_id: int, meta: AnnotationMeta, - job_annotations: Dict[int, io.RawIOBase], + job_annotations: dict[int, io.RawIOBase], merged_annotations: io.RawIOBase, manifest: TaskManifest, logger: logging.Logger, -) -> Union[ValidationSuccess, ValidationFailure]: +) -> ValidationSuccess | ValidationFailure: # actually validate jobs task_type = manifest.annotation.type @@ -979,7 +990,7 @@ def process_intermediate_results( db_service.update_gt_stats(session, task.id, updated_gt_stats) - job_final_result_ids: Dict[int, str] = {} + job_final_result_ids: dict[int, str] = {} for job_meta in meta.jobs: job = db_service.get_job_by_cvat_id(session, job_meta.job_id) if not job: @@ -1006,13 +1017,12 @@ def process_intermediate_results( should_complete = False - if 0 < Config.validation.max_escrow_iterations: + if Config.validation.max_escrow_iterations > 0: escrow_iteration = task.iteration if escrow_iteration and Config.validation.max_escrow_iterations <= escrow_iteration: logger.info( - "Validation for escrow_address={}: too many iterations, stopping annotation".format( - escrow_address - ) + f"Validation for escrow_address={escrow_address}:" + f" too many iterations, stopping annotation" ) should_complete = True @@ -1028,24 +1038,18 @@ def process_intermediate_results( < unverifiable_jobs_count ): logger.info( - "Validation for escrow_address={}: " - "too many assignments have insufficient GT for validation ({} of {} ({:.2f}%)), " - "stopping annotation".format( - escrow_address, - unverifiable_jobs_count, - total_jobs, - unverifiable_jobs_count / total_jobs * 100, - ) + f"Validation for escrow_address={escrow_address}: " + f"too many assignments have insufficient GT for validation " + f"({unverifiable_jobs_count} of {total_jobs} " + f"({unverifiable_jobs_count / total_jobs * 100:.2f}%)), stopping annotation" ) should_complete = True elif len(rejected_jobs) == unverifiable_jobs_count: if unverifiable_jobs_count: logger.info( - "Validation for escrow_address={}: " - "only unverifiable assignments left ({}), stopping annotation".format( - escrow_address, - unverifiable_jobs_count, - ) + f"Validation for escrow_address={escrow_address}: " + f"only unverifiable assignments left ({unverifiable_jobs_count})," + f" stopping annotation" ) should_complete = True @@ -1082,7 +1086,7 @@ def process_intermediate_results( validation_meta=validation_meta, resulting_annotations=updated_merged_dataset_archive.getvalue(), average_quality=np.mean( - list(v for v in job_results.values() if v != _TaskValidator.UNKNOWN_QUALITY and v >= 0) + [v for v in job_results.values() if v != _TaskValidator.UNKNOWN_QUALITY and v >= 0] or [0] ), ) diff --git a/packages/examples/cvat/recording-oracle/src/handlers/validation.py b/packages/examples/cvat/recording-oracle/src/handlers/validation.py index e398e91a6f..b6be970315 100644 --- a/packages/examples/cvat/recording-oracle/src/handlers/validation.py +++ b/packages/examples/cvat/recording-oracle/src/handlers/validation.py @@ -2,14 +2,13 @@ import os from collections import Counter from logging import Logger -from typing import Dict, Optional, Union from sqlalchemy.orm import Session -import src.chain.escrow as escrow import src.core.annotation_meta as annotation import src.core.validation_meta as validation import src.services.webhook as oracle_db_service +from src.chain import escrow from src.core.config import Config from src.core.manifest import TaskManifest, parse_manifest from src.core.oracle_events import ( @@ -48,9 +47,9 @@ def __init__( self.data_bucket = BucketAccessInfo.parse_obj(Config.exchange_oracle_storage_config) - self.annotation_meta: Optional[annotation.AnnotationMeta] = None - self.job_annotations: Optional[Dict[int, bytes]] = None - self.merged_annotations: Optional[bytes] = None + self.annotation_meta: annotation.AnnotationMeta | None = None + self.job_annotations: dict[int, bytes] | None = None + self.merged_annotations: bytes | None = None def set_logger(self, logger: Logger): self.logger = logger @@ -94,7 +93,7 @@ def _download_results(self): self._download_results_meta() self._download_annotations() - ValidationResult = Union[ValidationSuccess, ValidationFailure] + ValidationResult = ValidationSuccess | ValidationFailure def _process_annotation_results(self) -> ValidationResult: assert self.annotation_meta is not None @@ -159,7 +158,7 @@ def _handle_validation_result(self, validation_result: ValidationResult): escrow.store_results( chain_id, escrow_address, - Config.storage_config.bucket_url() + os.path.dirname(recor_merged_annotations_path), + Config.storage_config.bucket_url() + os.path.dirname(recor_merged_annotations_path), # noqa: PTH120 compute_resulting_annotations_hash(validation_result.resulting_annotations), ) @@ -194,13 +193,13 @@ def _handle_validation_result(self, validation_result: ValidationResult): OracleWebhookTypes.exchange_oracle, event=RecordingOracleEvent_TaskRejected( # TODO: update wrt. M2 API changes, send reason - rejected_job_ids=list( + rejected_job_ids=[ jid for jid, reason in validation_result.rejected_jobs.items() if not isinstance( reason, TooFewGtError ) # prevent such jobs from reannotation, can also be handled in ExcOr - ) + ] ), ) diff --git a/packages/examples/cvat/recording-oracle/src/log.py b/packages/examples/cvat/recording-oracle/src/log.py index c533f89d0e..9a2f7e4e7e 100644 --- a/packages/examples/cvat/recording-oracle/src/log.py +++ b/packages/examples/cvat/recording-oracle/src/log.py @@ -1,4 +1,5 @@ -""" Config for the application logger""" +"""Config for the application logger""" + import logging from logging.config import dictConfig diff --git a/packages/examples/cvat/recording-oracle/src/models/__init__.py b/packages/examples/cvat/recording-oracle/src/models/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/examples/cvat/recording-oracle/src/models/validation.py b/packages/examples/cvat/recording-oracle/src/models/validation.py index 80a250891f..51f8f681f5 100644 --- a/packages/examples/cvat/recording-oracle/src/models/validation.py +++ b/packages/examples/cvat/recording-oracle/src/models/validation.py @@ -1,8 +1,6 @@ # pylint: disable=too-few-public-methods from __future__ import annotations -from typing import List - from sqlalchemy import Column, DateTime, Enum, Float, ForeignKey, Integer, String from sqlalchemy.orm import Mapped, relationship from sqlalchemy.sql import func @@ -20,10 +18,10 @@ class Task(Base): updated_at = Column(DateTime(timezone=True), onupdate=func.now()) iteration = Column(Integer, server_default="0", nullable=False) - jobs: Mapped[List["Job"]] = relationship( + jobs: Mapped[list[Job]] = relationship( back_populates="task", cascade="all, delete", passive_deletes=True ) - gt_stats: Mapped[List["GtStats"]] = relationship( + gt_stats: Mapped[list[GtStats]] = relationship( back_populates="task", cascade="all, delete", passive_deletes=True ) @@ -34,8 +32,8 @@ class Job(Base): cvat_id = Column(Integer, unique=True, index=True, nullable=False) task_id = Column(String, ForeignKey("tasks.id", ondelete="CASCADE"), nullable=False) - task: Mapped["Task"] = relationship(back_populates="jobs") - validation_results: Mapped[List["ValidationResult"]] = relationship( + task: Mapped[Task] = relationship(back_populates="jobs") + validation_results: Mapped[list[ValidationResult]] = relationship( back_populates="job", cascade="all, delete", passive_deletes=True ) @@ -48,7 +46,7 @@ class ValidationResult(Base): annotator_wallet_address = Column(String, nullable=False) annotation_quality = Column(Float, nullable=False) - job: Mapped["Job"] = relationship(back_populates="validation_results") + job: Mapped[Job] = relationship(back_populates="validation_results") class GtStats(Base): @@ -64,4 +62,4 @@ class GtStats(Base): failed_attempts = Column(Integer, default=0, nullable=False) - task: Mapped["Task"] = relationship(back_populates="gt_stats") + task: Mapped[Task] = relationship(back_populates="gt_stats") diff --git a/packages/examples/cvat/recording-oracle/src/models/webhook.py b/packages/examples/cvat/recording-oracle/src/models/webhook.py index 10c4bec69c..64ca2fb0e7 100644 --- a/packages/examples/cvat/recording-oracle/src/models/webhook.py +++ b/packages/examples/cvat/recording-oracle/src/models/webhook.py @@ -26,5 +26,5 @@ class Webhook(Base): event_data = Column(JSON, nullable=True, server_default=None) direction = Column(String, nullable=False) - def __repr__(self): + def __repr__(self) -> str: return f"Webhook. id={self.id} type={self.type}.{self.event_type}" diff --git a/packages/examples/cvat/recording-oracle/src/schemas/__init__.py b/packages/examples/cvat/recording-oracle/src/schemas/__init__.py index a0811a145d..e26cbee23e 100644 --- a/packages/examples/cvat/recording-oracle/src/schemas/__init__.py +++ b/packages/examples/cvat/recording-oracle/src/schemas/__init__.py @@ -1,7 +1,4 @@ -# pylint: disable=too-few-public-methods -""" Schema for API input&output""" - -from typing import List, Optional +"""Schema for API input&output""" from pydantic import BaseModel @@ -27,7 +24,7 @@ class ResponseError(BaseModel): class SupportedNetwork(BaseModel): chain_id: int - addr: Optional[str] + addr: str | None class MetaResponse(BaseModel): @@ -35,4 +32,4 @@ class MetaResponse(BaseModel): message: str version: str - supported_networks: List[SupportedNetwork] + supported_networks: list[SupportedNetwork] diff --git a/packages/examples/cvat/recording-oracle/src/schemas/webhook.py b/packages/examples/cvat/recording-oracle/src/schemas/webhook.py index 62ae808f0a..c725d2cfa0 100644 --- a/packages/examples/cvat/recording-oracle/src/schemas/webhook.py +++ b/packages/examples/cvat/recording-oracle/src/schemas/webhook.py @@ -1,5 +1,4 @@ from datetime import datetime -from typing import Optional from pydantic import BaseModel, validator @@ -11,8 +10,8 @@ class OracleWebhook(BaseModel): escrow_address: str chain_id: Networks event_type: str - event_data: Optional[dict] = None - timestamp: Optional[datetime] = None # TODO: remove optional + event_data: dict | None = None + timestamp: datetime | None = None # TODO: remove optional @validator("escrow_address", allow_reuse=True) def validate_escrow_(cls, value): diff --git a/packages/examples/cvat/recording-oracle/src/services/cloud/client.py b/packages/examples/cvat/recording-oracle/src/services/cloud/client.py index 5bb92d77e3..53cf13dcc0 100644 --- a/packages/examples/cvat/recording-oracle/src/services/cloud/client.py +++ b/packages/examples/cvat/recording-oracle/src/services/cloud/client.py @@ -1,37 +1,29 @@ from abc import ABCMeta, abstractmethod -from typing import List, Optional from urllib.parse import unquote class StorageClient(metaclass=ABCMeta): def __init__( self, - bucket: Optional[str] = None, + bucket: str | None = None, ) -> None: self._bucket = unquote(bucket) if bucket else None @abstractmethod - def create_file(self, key: str, data: bytes = b"", *, bucket: Optional[str] = None): - ... + def create_file(self, key: str, data: bytes = b"", *, bucket: str | None = None): ... @abstractmethod - def remove_file(self, key: str, *, bucket: Optional[str] = None): - ... + def remove_file(self, key: str, *, bucket: str | None = None): ... @abstractmethod - def file_exists(self, key: str, *, bucket: Optional[str] = None) -> bool: - ... + def file_exists(self, key: str, *, bucket: str | None = None) -> bool: ... @abstractmethod - def download_file(self, key: str, *, bucket: Optional[str] = None) -> bytes: - ... + def download_file(self, key: str, *, bucket: str | None = None) -> bytes: ... @abstractmethod - def list_files( - self, *, bucket: Optional[str] = None, prefix: Optional[str] = None - ) -> List[str]: - ... + def list_files(self, *, bucket: str | None = None, prefix: str | None = None) -> list[str]: ... @staticmethod - def normalize_prefix(prefix: Optional[str]) -> Optional[str]: + def normalize_prefix(prefix: str | None) -> str | None: return unquote(prefix).strip("/\\") + "/" if prefix else prefix diff --git a/packages/examples/cvat/recording-oracle/src/services/cloud/gcs.py b/packages/examples/cvat/recording-oracle/src/services/cloud/gcs.py index 36611b363f..014be4ce1a 100644 --- a/packages/examples/cvat/recording-oracle/src/services/cloud/gcs.py +++ b/packages/examples/cvat/recording-oracle/src/services/cloud/gcs.py @@ -1,5 +1,4 @@ from io import BytesIO -from typing import Dict, List, Optional from urllib.parse import unquote from google.cloud import storage @@ -13,8 +12,8 @@ class GcsClient(StorageClient): def __init__( self, *, - bucket: Optional[str] = None, - service_account_key: Optional[Dict] = None, + bucket: str | None = None, + service_account_key: dict | None = None, ) -> None: super().__init__(bucket) @@ -23,22 +22,22 @@ def __init__( else: self.client = storage.Client.create_anonymous_client() - def create_file(self, key: str, data: bytes = b"", *, bucket: Optional[str] = None) -> None: + def create_file(self, key: str, data: bytes = b"", *, bucket: str | None = None) -> None: bucket = unquote(bucket) if bucket else self._bucket bucket_client = self.client.get_bucket(bucket) bucket_client.blob(unquote(key)).upload_from_string(data) - def remove_file(self, key: str, *, bucket: Optional[str] = None) -> None: + def remove_file(self, key: str, *, bucket: str | None = None) -> None: bucket = unquote(bucket) if bucket else self._bucket bucket_client = self.client.get_bucket(bucket) bucket_client.delete_blob(unquote(key)) - def file_exists(self, key: str, *, bucket: Optional[str] = None) -> bool: + def file_exists(self, key: str, *, bucket: str | None = None) -> bool: bucket = unquote(bucket) if bucket else self._bucket bucket_client = self.client.get_bucket(bucket) return bucket_client.blob(unquote(key)).exists() - def download_file(self, key: str, *, bucket: Optional[str] = None) -> bytes: + def download_file(self, key: str, *, bucket: str | None = None) -> bytes: bucket = unquote(bucket) if bucket else self._bucket bucket_client = self.client.get_bucket(bucket) blob = bucket_client.blob(unquote(key)) @@ -47,9 +46,7 @@ def download_file(self, key: str, *, bucket: Optional[str] = None) -> bytes: self.client.download_blob_to_file(blob, data) return data.getvalue() - def list_files( - self, *, bucket: Optional[str] = None, prefix: Optional[str] = None - ) -> List[str]: + def list_files(self, *, bucket: str | None = None, prefix: str | None = None) -> list[str]: bucket = unquote(bucket) if bucket else self._bucket prefix = self.normalize_prefix(prefix) diff --git a/packages/examples/cvat/recording-oracle/src/services/cloud/s3.py b/packages/examples/cvat/recording-oracle/src/services/cloud/s3.py index e8e608ce99..19b570216a 100644 --- a/packages/examples/cvat/recording-oracle/src/services/cloud/s3.py +++ b/packages/examples/cvat/recording-oracle/src/services/cloud/s3.py @@ -1,5 +1,4 @@ from io import BytesIO -from typing import List, Optional from urllib.parse import unquote import boto3 @@ -15,15 +14,15 @@ class S3Client(StorageClient): def __init__( self, *, - bucket: Optional[str] = None, - access_key: Optional[str] = None, - secret_key: Optional[str] = None, - endpoint_url: Optional[str] = None, + bucket: str | None = None, + access_key: str | None = None, + secret_key: str | None = None, + endpoint_url: str | None = None, ) -> None: super().__init__(bucket) session = boto3.Session( - **(dict(aws_access_key_id=access_key) if access_key else {}), - **(dict(aws_secret_access_key=secret_key) if secret_key else {}), + **({"aws_access_key_id": access_key} if access_key else {}), + **({"aws_secret_access_key": secret_key} if secret_key else {}), ) s3 = session.resource( "s3", **({"endpoint_url": unquote(endpoint_url)} if endpoint_url else {}) @@ -34,15 +33,15 @@ def __init__( if not access_key and not secret_key: self.client.meta.events.register("choose-signer.s3.*", disable_signing) - def create_file(self, key: str, data: bytes = b"", *, bucket: Optional[str] = None): + def create_file(self, key: str, data: bytes = b"", *, bucket: str | None = None): bucket = unquote(bucket) if bucket else self._bucket self.client.put_object(Body=data, Bucket=bucket, Key=unquote(key)) - def remove_file(self, key: str, *, bucket: Optional[str] = None): + def remove_file(self, key: str, *, bucket: str | None = None): bucket = unquote(bucket) if bucket else self._bucket self.client.delete_object(Bucket=bucket, Key=unquote(key)) - def file_exists(self, key: str, *, bucket: Optional[str] = None) -> bool: + def file_exists(self, key: str, *, bucket: str | None = None) -> bool: bucket = unquote(bucket) if bucket else self._bucket try: self.client.head_object(Bucket=bucket, Key=unquote(key)) @@ -50,22 +49,16 @@ def file_exists(self, key: str, *, bucket: Optional[str] = None) -> bool: except ClientError as e: if e.response["Error"]["Code"] == "404": return False - else: - raise + raise - def download_file(self, key: str, *, bucket: Optional[str] = None) -> bytes: + def download_file(self, key: str, *, bucket: str | None = None) -> bytes: bucket = unquote(bucket) if bucket else self._bucket with BytesIO() as data: self.client.download_fileobj(Bucket=bucket, Key=unquote(key), Fileobj=data) return data.getvalue() - def list_files( - self, *, bucket: Optional[str] = None, prefix: Optional[str] = None - ) -> List[str]: + def list_files(self, *, bucket: str | None = None, prefix: str | None = None) -> list[str]: bucket = unquote(bucket) if bucket else self._bucket objects = self.resource.Bucket(bucket).objects - if prefix: - objects = objects.filter(Prefix=self.normalize_prefix(prefix)) - else: - objects = objects.all() + objects = objects.filter(Prefix=self.normalize_prefix(prefix)) if prefix else objects.all() return [file_info.key for file_info in objects] diff --git a/packages/examples/cvat/recording-oracle/src/services/cloud/types.py b/packages/examples/cvat/recording-oracle/src/services/cloud/types.py index ec8cd9df9e..8a4c318966 100644 --- a/packages/examples/cvat/recording-oracle/src/services/cloud/types.py +++ b/packages/examples/cvat/recording-oracle/src/services/cloud/types.py @@ -4,7 +4,6 @@ from dataclasses import asdict, dataclass, is_dataclass from enum import Enum, auto from inspect import isclass -from typing import Dict, Optional, Type, Union from urllib.parse import urlparse from src.core import manifest @@ -31,14 +30,14 @@ def from_str(cls, provider: str) -> CloudProviders: class BucketCredentials: - def to_dict(self) -> Dict: + def to_dict(self) -> dict: if not is_dataclass(self): raise NotImplementedError return asdict(self) @classmethod - def from_storage_config(cls, config: Type[IStorageConfig]) -> Optional[BucketCredentials]: + def from_storage_config(cls, config: type[IStorageConfig]) -> BucketCredentials | None: credentials = None if (config.access_key or config.secret_key) and config.provider.lower() != "aws": @@ -46,9 +45,7 @@ def from_storage_config(cls, config: Type[IStorageConfig]) -> Optional[BucketCre "Invalid storage configuration. The access_key/secret_key pair" f"cannot be specified with {config.provider} provider" ) - elif ( - bool(config.access_key) ^ bool(config.secret_key) - ) and config.provider.lower() == "aws": + if (bool(config.access_key) ^ bool(config.secret_key)) and config.provider.lower() == "aws": raise ValueError( "Invalid storage configuration. " "Either none or both access_key and secret_key must be specified for an AWS storage" @@ -71,7 +68,7 @@ def from_storage_config(cls, config: Type[IStorageConfig]) -> Optional[BucketCre @dataclass class GcsBucketCredentials(BucketCredentials): - service_account_key: Dict + service_account_key: dict @dataclass @@ -85,8 +82,8 @@ class BucketAccessInfo: provider: CloudProviders host_url: str bucket_name: str - path: Optional[str] = None - credentials: Optional[BucketCredentials] = None + path: str | None = None + credentials: BucketCredentials | None = None @classmethod def from_url(cls, url: str) -> BucketAccessInfo: @@ -100,7 +97,7 @@ def from_url(cls, url: str) -> BucketAccessInfo: bucket_name=parsed_url.netloc.split(".")[0], path=parsed_url.path.lstrip("/"), ) - elif parsed_url.netloc.endswith(DEFAULT_GCS_HOST): + if parsed_url.netloc.endswith(DEFAULT_GCS_HOST): # Google Cloud Storage (GCS) bucket # Virtual hosted-style is expected: # https://BUCKET_NAME.storage.googleapis.com/OBJECT_NAME @@ -110,7 +107,7 @@ def from_url(cls, url: str) -> BucketAccessInfo: host_url=f"{parsed_url.scheme}://{DEFAULT_GCS_HOST}", path=parsed_url.path.lstrip("/"), ) - elif Config.features.enable_custom_cloud_host: + if Config.features.enable_custom_cloud_host: if is_ipv4(parsed_url.netloc): host = parsed_url.netloc bucket_name, path = parsed_url.path.lstrip("/").split("/", maxsplit=1) @@ -125,11 +122,10 @@ def from_url(cls, url: str) -> BucketAccessInfo: bucket_name=bucket_name, path=path, ) - else: - raise ValueError(f"{parsed_url.netloc} cloud provider is not supported.") + raise ValueError(f"{parsed_url.netloc} cloud provider is not supported.") @classmethod - def _from_dict(cls, data: Dict) -> BucketAccessInfo: + def _from_dict(cls, data: dict) -> BucketAccessInfo: for required_field in ( "provider", "bucket_name", @@ -159,7 +155,7 @@ def _from_dict(cls, data: Dict) -> BucketAccessInfo: return BucketAccessInfo(**data) @classmethod - def from_storage_config(cls, config: Type[IStorageConfig]) -> BucketAccessInfo: + def from_storage_config(cls, config: type[IStorageConfig]) -> BucketAccessInfo: credentials = BucketCredentials.from_storage_config(config) return BucketAccessInfo( @@ -174,14 +170,12 @@ def from_bucket_url(cls, bucket_url: manifest.BucketUrl) -> BucketAccessInfo: return cls._from_dict(bucket_url.dict()) @classmethod - def parse_obj( - cls, data: Union[str, Type[IStorageConfig], manifest.BucketUrl] - ) -> BucketAccessInfo: + def parse_obj(cls, data: str | type[IStorageConfig] | manifest.BucketUrl) -> BucketAccessInfo: if isinstance(data, manifest.BucketUrlBase): return cls.from_bucket_url(data) - elif isinstance(data, str): + if isinstance(data, str): return cls.from_url(data) - elif isclass(data) and issubclass(data, IStorageConfig): + if isclass(data) and issubclass(data, IStorageConfig): return cls.from_storage_config(data) raise TypeError(f"Unsupported data type ({type(data)}) was provided") diff --git a/packages/examples/cvat/recording-oracle/src/services/cloud/utils.py b/packages/examples/cvat/recording-oracle/src/services/cloud/utils.py index a9f821d174..bfc23305c7 100644 --- a/packages/examples/cvat/recording-oracle/src/services/cloud/utils.py +++ b/packages/examples/cvat/recording-oracle/src/services/cloud/utils.py @@ -1,5 +1,3 @@ -from typing import Optional - from src.services.cloud.client import StorageClient from src.services.cloud.gcs import DEFAULT_GCS_HOST, GcsClient from src.services.cloud.s3 import DEFAULT_S3_HOST, S3Client @@ -7,7 +5,7 @@ def compose_bucket_url( - bucket_name: str, provider: CloudProviders, *, bucket_host: Optional[str] = None + bucket_name: str, provider: CloudProviders, *, bucket_host: str | None = None ) -> str: match provider: case CloudProviders.aws: diff --git a/packages/examples/cvat/recording-oracle/src/services/validation.py b/packages/examples/cvat/recording-oracle/src/services/validation.py index ba139d3fec..4204bd90df 100644 --- a/packages/examples/cvat/recording-oracle/src/services/validation.py +++ b/packages/examples/cvat/recording-oracle/src/services/validation.py @@ -1,5 +1,4 @@ import uuid -from typing import Dict, List, Optional, Union from sqlalchemy import update from sqlalchemy.orm import Session @@ -20,8 +19,8 @@ def create_task(session: Session, escrow_address: str, chain_id: int) -> str: def get_task_by_escrow_address( - session: Session, escrow_address: str, *, for_update: Union[bool, ForUpdateParams] = False -) -> Optional[Task]: + session: Session, escrow_address: str, *, for_update: bool | ForUpdateParams = False +) -> Task | None: return ( _maybe_for_update(session.query(Task), enable=for_update) .where(Task.escrow_address == escrow_address) @@ -30,16 +29,16 @@ def get_task_by_escrow_address( def get_task_by_id( - session: Session, task_id: str, *, for_update: Union[bool, ForUpdateParams] = False -) -> Optional[Task]: + session: Session, task_id: str, *, for_update: bool | ForUpdateParams = False +) -> Task | None: return ( _maybe_for_update(session.query(Task), enable=for_update).where(Task.id == task_id).first() ) def get_task_validation_results( - session: Session, task_id: str, *, for_update: Union[bool, ForUpdateParams] = False -) -> List[ValidationResult]: + session: Session, task_id: str, *, for_update: bool | ForUpdateParams = False +) -> list[ValidationResult]: return ( _maybe_for_update(session.query(ValidationResult), enable=for_update) .where(ValidationResult.job.has(Job.task_id == task_id)) @@ -67,8 +66,8 @@ def create_job(session: Session, job_cvat_id: int, task_id: str) -> str: def get_job_by_cvat_id( - session: Session, job_cvat_id: int, *, for_update: Union[bool, ForUpdateParams] = False -) -> Optional[Job]: + session: Session, job_cvat_id: int, *, for_update: bool | ForUpdateParams = False +) -> Job | None: return ( _maybe_for_update(session.query(Job), enable=for_update) .where(Job.cvat_id == job_cvat_id) @@ -77,8 +76,8 @@ def get_job_by_cvat_id( def get_job_by_id( - session: Session, job_id: str, *, for_update: Union[bool, ForUpdateParams] = False -) -> Optional[Job]: + session: Session, job_id: str, *, for_update: bool | ForUpdateParams = False +) -> Job | None: return _maybe_for_update(session.query(Job), enable=for_update).where(Job.id == job_id).first() @@ -104,8 +103,8 @@ def create_validation_result( def get_validation_result_by_assignment_id( - session: Session, assignment_id: str, *, for_update: Union[bool, ForUpdateParams] = False -) -> Optional[ValidationResult]: + session: Session, assignment_id: str, *, for_update: bool | ForUpdateParams = False +) -> ValidationResult | None: return ( _maybe_for_update(session.query(ValidationResult), enable=for_update) .where(ValidationResult.assignment_id == assignment_id) @@ -114,8 +113,8 @@ def get_validation_result_by_assignment_id( def get_task_gt_stats( - session: Session, task_id: str, *, for_update: Union[bool, ForUpdateParams] = False -) -> List[GtStats]: + session: Session, task_id: str, *, for_update: bool | ForUpdateParams = False +) -> list[GtStats]: return ( _maybe_for_update(session.query(GtStats), enable=for_update) .where(GtStats.task_id == task_id) @@ -123,7 +122,7 @@ def get_task_gt_stats( ) -def update_gt_stats(session: Session, task_id: str, values: Dict[str, int]): +def update_gt_stats(session: Session, task_id: str, values: dict[str, int]): # Read more about upsert: # https://docs.sqlalchemy.org/en/20/orm/queryguide/dml.html#orm-upsert-statements @@ -138,11 +137,11 @@ def update_gt_stats(session: Session, task_id: str, values: Dict[str, int]): statement = psql_insert(GtStats).values( [ - dict( - task_id=task_id, - gt_key=gt_key, - failed_attempts=failed_attempts, - ) + { + "task_id": task_id, + "gt_key": gt_key, + "failed_attempts": failed_attempts, + } for gt_key, failed_attempts in values.items() ], ) diff --git a/packages/examples/cvat/recording-oracle/src/services/webhook.py b/packages/examples/cvat/recording-oracle/src/services/webhook.py index e14af05321..41e9ca1c10 100644 --- a/packages/examples/cvat/recording-oracle/src/services/webhook.py +++ b/packages/examples/cvat/recording-oracle/src/services/webhook.py @@ -1,7 +1,6 @@ import datetime import uuid from enum import Enum -from typing import List, Optional, Union from attrs import define from sqlalchemy import case, update @@ -26,7 +25,7 @@ class OracleWebhookDirectionTags(str, Enum, metaclass=BetterEnumMeta): @define class OracleWebhookQueue: direction: OracleWebhookDirectionTags - default_sender: Optional[OracleWebhookTypes] = None + default_sender: OracleWebhookTypes | None = None def create_webhook( self, @@ -34,10 +33,10 @@ def create_webhook( escrow_address: str, chain_id: int, type: OracleWebhookTypes, - signature: Optional[str] = None, - event_type: Optional[str] = None, - event_data: Optional[dict] = None, - event: Optional[OracleEvent] = None, + signature: str | None = None, + event_type: str | None = None, + event_data: dict | None = None, + event: OracleEvent | None = None, ) -> str: """ Creates a webhook in a database @@ -45,7 +44,7 @@ def create_webhook( assert not event_data or event_type, "'event_data' requires 'event_type'" assert bool(event) ^ bool( event_type - ), f"'event' and 'event_type' cannot be used together. Please use only one of the fields" + ), "'event' and 'event_type' cannot be used together. Please use only one of the fields" if event_type: if self.direction == OracleWebhookDirectionTags.incoming: @@ -60,7 +59,7 @@ def create_webhook( if self.direction == OracleWebhookDirectionTags.incoming and not signature: raise ValueError("Webhook signature must be specified for incoming events") - elif self.direction == OracleWebhookDirectionTags.outgoing and signature: + if self.direction == OracleWebhookDirectionTags.outgoing and signature: raise ValueError("Webhook signature must not be specified for outgoing events") if signature: @@ -93,9 +92,9 @@ def get_pending_webhooks( type: OracleWebhookTypes, *, limit: int = 10, - for_update: Union[bool, ForUpdateParams] = False, - ) -> List[Webhook]: - webhooks = ( + for_update: bool | ForUpdateParams = False, + ) -> list[Webhook]: + return ( _maybe_for_update(session.query(Webhook), enable=for_update) .where( Webhook.direction == self.direction.value, @@ -106,7 +105,6 @@ def get_pending_webhooks( .limit(limit) .all() ) - return webhooks def update_webhook_status( self, session: Session, webhook_id: str, status: OracleWebhookStatuses diff --git a/packages/examples/cvat/recording-oracle/src/utils/annotations.py b/packages/examples/cvat/recording-oracle/src/utils/annotations.py index 75ec29ec15..ea138a703b 100644 --- a/packages/examples/cvat/recording-oracle/src/utils/annotations.py +++ b/packages/examples/cvat/recording-oracle/src/utils/annotations.py @@ -1,5 +1,6 @@ +from argparse import ArgumentParser +from collections.abc import Iterable from copy import deepcopy -from typing import Iterable, Optional, Tuple, Union import datumaro as dm import numpy as np @@ -38,7 +39,7 @@ def shift_ann( ] ) else: - assert False, f"Unsupported annotation type '{ann.type}'" + raise TypeError(f"Unsupported annotation type '{ann.type}'") return shifted_ann @@ -65,7 +66,7 @@ class ProjectLabels(dm.ItemTransform): """ @classmethod - def build_cmdline_parser(cls, **kwargs): + def build_cmdline_parser(cls, **kwargs) -> ArgumentParser: parser = super().build_cmdline_parser(**kwargs) parser.add_argument( "-l", @@ -76,19 +77,19 @@ def build_cmdline_parser(cls, **kwargs): ) return parser - def __init__( + def __init__( # noqa: PLR0912 self, extractor: dm.IExtractor, - dst_labels: Union[Iterable[Union[str, Tuple[str, str]]], dm.LabelCategories], - ): + dst_labels: Iterable[str | tuple[str, str]] | dm.LabelCategories, + ) -> None: super().__init__(extractor) self._categories = {} src_categories = self._extractor.categories() - src_label_cat: Optional[dm.LabelCategories] = src_categories.get(dm.AnnotationType.label) - src_point_cat: Optional[dm.PointsCategories] = src_categories.get(dm.AnnotationType.points) + src_label_cat: dm.LabelCategories | None = src_categories.get(dm.AnnotationType.label) + src_point_cat: dm.PointsCategories | None = src_categories.get(dm.AnnotationType.points) if isinstance(dst_labels, dm.LabelCategories): dst_label_cat = deepcopy(dst_labels) @@ -99,7 +100,7 @@ def __init__( dst_label_cat = dm.LabelCategories(attributes=deepcopy(src_label_cat.attributes)) for dst_label in dst_labels: - assert isinstance(dst_label, str) or isinstance(dst_label, tuple) + assert isinstance(dst_label, str | tuple) dst_parent = "" if isinstance(dst_label, tuple): @@ -181,7 +182,7 @@ def _make_label_id_map(self, src_label_cat, dst_label_cat): src_id: dst_label_cat.find(src_label_cat[src_id].name, src_label_cat[src_id].parent)[0] for src_id in range(len(src_label_cat or ())) } - self._map_id = lambda src_id: id_mapping.get(src_id, None) + self._map_id = lambda src_id: id_mapping.get(src_id) def categories(self): return self._categories diff --git a/packages/examples/cvat/recording-oracle/src/utils/enums.py b/packages/examples/cvat/recording-oracle/src/utils/enums.py index 4f3d688251..d4c133b0e5 100644 --- a/packages/examples/cvat/recording-oracle/src/utils/enums.py +++ b/packages/examples/cvat/recording-oracle/src/utils/enums.py @@ -6,5 +6,5 @@ class BetterEnumMeta(EnumMeta): Extends the default enum metaclass with extra methods for better usability """ - def __contains__(cls, item): + def __contains__(cls, item) -> bool: return isinstance(item, cls) or item in [v.value for v in cls.__members__.values()] diff --git a/packages/examples/cvat/recording-oracle/src/utils/logging.py b/packages/examples/cvat/recording-oracle/src/utils/logging.py index be2c5feba3..e7660eb0d7 100644 --- a/packages/examples/cvat/recording-oracle/src/utils/logging.py +++ b/packages/examples/cvat/recording-oracle/src/utils/logging.py @@ -1,5 +1,5 @@ import logging -from typing import NewType, Optional, Union +from typing import NewType from src.utils.stack import current_function_name @@ -15,7 +15,7 @@ def parse_log_level(level: str) -> LogLevel: def get_function_logger( - parent_logger: Optional[Union[str, logging.Logger]] = None, + parent_logger: str | logging.Logger | None = None, ) -> logging.Logger: if isinstance(parent_logger, str): parent_logger = logging.getLogger(parent_logger) diff --git a/packages/examples/cvat/recording-oracle/src/utils/net.py b/packages/examples/cvat/recording-oracle/src/utils/net.py index 360dafaebb..04ad799510 100644 --- a/packages/examples/cvat/recording-oracle/src/utils/net.py +++ b/packages/examples/cvat/recording-oracle/src/utils/net.py @@ -1,7 +1,7 @@ import ipaddress -def is_ipv4(addr: str, allow_port: bool = True) -> bool: +def is_ipv4(addr: str, *, allow_port: bool = True) -> bool: try: if allow_port: addr = addr.split(":", maxsplit=1)[0] diff --git a/packages/examples/cvat/recording-oracle/src/utils/requests.py b/packages/examples/cvat/recording-oracle/src/utils/requests.py index 785c2cfc87..ef2174f9b9 100644 --- a/packages/examples/cvat/recording-oracle/src/utils/requests.py +++ b/packages/examples/cvat/recording-oracle/src/utils/requests.py @@ -1,4 +1,4 @@ -from typing import Optional, TypeVar +from typing import TypeVar from fastapi import HTTPException @@ -7,11 +7,11 @@ def get_or_404( - obj: Optional[T], + obj: T | None, object_id: V, object_type_name: str, *, - reason: Optional[str] = None, + reason: str | None = None, ) -> T: if obj is None: raise HTTPException( diff --git a/packages/examples/cvat/recording-oracle/src/utils/webhooks.py b/packages/examples/cvat/recording-oracle/src/utils/webhooks.py index e6d39202a3..a1bf128887 100644 --- a/packages/examples/cvat/recording-oracle/src/utils/webhooks.py +++ b/packages/examples/cvat/recording-oracle/src/utils/webhooks.py @@ -1,5 +1,4 @@ from datetime import datetime -from typing import Dict, Optional, Tuple from src.chain.web3 import sign_message from src.core.oracle_events import parse_event @@ -11,8 +10,8 @@ def prepare_outgoing_webhook_body( chain_id: Networks, event_type: str, event_data: dict, - timestamp: Optional[datetime], -) -> Dict: + timestamp: datetime | None, +) -> dict: body = {"escrow_address": escrow_address, "chain_id": chain_id} if timestamp: @@ -29,11 +28,11 @@ def prepare_outgoing_webhook_body( def prepare_signed_message( - escrow_address: str, + escrow_address: str, # noqa: ARG001 chain_id: Networks, - message: Optional[str] = None, - body: Optional[dict] = None, -) -> Tuple[str, str]: + message: str | None = None, + body: dict | None = None, +) -> tuple[str, str]: """ Sign the message with the service identity. Optionally, can serialize the input structure. diff --git a/packages/examples/cvat/recording-oracle/src/validation/__init__.py b/packages/examples/cvat/recording-oracle/src/validation/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/examples/cvat/recording-oracle/src/validation/annotation_matching.py b/packages/examples/cvat/recording-oracle/src/validation/annotation_matching.py index fa3a965f7f..b5d7855a85 100644 --- a/packages/examples/cvat/recording-oracle/src/validation/annotation_matching.py +++ b/packages/examples/cvat/recording-oracle/src/validation/annotation_matching.py @@ -1,5 +1,6 @@ import itertools -from typing import Callable, List, NamedTuple, Sequence, Tuple, TypeVar +from collections.abc import Callable, Sequence +from typing import NamedTuple, TypeVar import numpy as np from scipy.optimize import linear_sum_assignment @@ -77,10 +78,10 @@ def point_to_bbox_cmp( class MatchResult(NamedTuple): - matches: List[Tuple[Annotation, Annotation]] - mispred: List[Tuple[Annotation, Annotation]] - a_extra: List[Annotation] - b_extra: List[Annotation] + matches: list[tuple[Annotation, Annotation]] + mispred: list[tuple[Annotation, Annotation]] + a_extra: list[Annotation] + b_extra: list[Annotation] def match_annotations( @@ -121,7 +122,7 @@ def match_annotations( a_unmatched = [] b_unmatched = [] - for a_idx, b_idx in zip(a_matches, b_matches): + for a_idx, b_idx in zip(a_matches, b_matches, strict=False): dist = distances[a_idx, b_idx] if dist > 1 - min_similarity or dist == 1: if a_idx < len(a_anns): diff --git a/packages/examples/cvat/recording-oracle/src/validation/dataset_comparison.py b/packages/examples/cvat/recording-oracle/src/validation/dataset_comparison.py index cce97e89aa..168d01c820 100644 --- a/packages/examples/cvat/recording-oracle/src/validation/dataset_comparison.py +++ b/packages/examples/cvat/recording-oracle/src/validation/dataset_comparison.py @@ -2,17 +2,15 @@ import itertools from abc import ABCMeta, abstractmethod -from typing import Callable, Dict, Optional, Sequence, Set, Tuple, Union +from typing import TYPE_CHECKING import datumaro as dm import numpy as np from attrs import define, field -from datumaro.util.annotation_util import BboxCoords from src.core.config import Config from src.core.validation_errors import TooFewGtError - -from .annotation_matching import ( +from src.validation.annotation_matching import ( Bbox, MatchResult, Point, @@ -21,19 +19,24 @@ point_to_bbox_cmp, ) +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + from datumaro.util.annotation_util import BboxCoords + class SimilarityFunction(metaclass=ABCMeta): "A function to compute similarity between 2 annotations" - def __call__(self, gt_ann: dm.Annotation, ds_ann: dm.Annotation) -> float: - ... + @abstractmethod + def __call__(self, gt_ann: dm.Annotation, ds_ann: dm.Annotation) -> float: ... class CachedSimilarityFunction(SimilarityFunction): def __init__( - self, sim_fn: Callable, *, cache: Optional[Dict[Tuple[int, int], float]] = None + self, sim_fn: Callable, *, cache: dict[tuple[int, int], float] | None = None ) -> None: - self.cache: Dict[Tuple[int, int], float] = cache or {} + self.cache: dict[tuple[int, int], float] = cache or {} self.sim_fn = sim_fn def __call__(self, gt_ann: dm.Annotation, ds_ann: dm.Annotation) -> float: @@ -56,9 +59,9 @@ def clear_cache(self): @define class DatasetComparator(metaclass=ABCMeta): _min_similarity_threshold: float - _gt_weights: Dict[str, float] = field(factory=dict) + _gt_weights: dict[str, float] = field(factory=dict) - failed_gts: Set[str] = field(factory=set, init=False) + failed_gts: set[str] = field(factory=set, init=False) "Recorded list of failed GT samples, available after compare() call" def compare(self, gt_dataset: dm.Dataset, ds_dataset: dm.Dataset) -> float: @@ -106,7 +109,7 @@ def compare(self, gt_dataset: dm.Dataset, ds_dataset: dm.Dataset) -> float: dataset_failed_gts.add(gt_sample.id) if dataset_excluded_gts_count == len(gt_dataset): - raise TooFewGtError() + raise TooFewGtError dataset_accuracy = 0 if dataset_total_anns_to_compare: @@ -119,14 +122,13 @@ def compare(self, gt_dataset: dm.Dataset, ds_dataset: dm.Dataset) -> float: @abstractmethod def compare_sample_annotations( self, gt_sample: dm.DatasetItem, ds_sample: dm.DatasetItem, *, similarity_threshold: float - ) -> Tuple[MatchResult, SimilarityFunction]: - ... + ) -> tuple[MatchResult, SimilarityFunction]: ... class BboxDatasetComparator(DatasetComparator): def compare_sample_annotations( self, gt_sample: dm.DatasetItem, ds_sample: dm.DatasetItem, *, similarity_threshold: float - ) -> Tuple[MatchResult, SimilarityFunction]: + ) -> tuple[MatchResult, SimilarityFunction]: similarity_fn = CachedSimilarityFunction(bbox_iou) ds_boxes = [ @@ -153,7 +155,7 @@ def compare_sample_annotations( class PointsDatasetComparator(DatasetComparator): def compare_sample_annotations( self, gt_sample: dm.DatasetItem, ds_sample: dm.DatasetItem, *, similarity_threshold: float - ) -> Tuple[MatchResult, SimilarityFunction]: + ) -> tuple[MatchResult, SimilarityFunction]: similarity_fn = CachedSimilarityFunction(point_to_bbox_cmp) ds_points = [ @@ -186,8 +188,8 @@ def compare_sample_annotations( @define class SkeletonDatasetComparator(DatasetComparator): - _skeleton_info: Dict[int, _SkeletonInfo] = field(factory=dict, init=False) - _categories: Optional[dm.CategoriesInfo] = field(default=None, init=False) + _skeleton_info: dict[int, _SkeletonInfo] = field(factory=dict, init=False) + _categories: dm.CategoriesInfo | None = field(default=None, init=False) # TODO: find better strategy for sigma estimation _oks_sigma: float = Config.validation.default_oks_sigma @@ -198,7 +200,7 @@ def compare(self, gt_dataset: dm.Dataset, ds_dataset: dm.Dataset) -> float: def compare_sample_annotations( self, gt_sample: dm.DatasetItem, ds_sample: dm.DatasetItem, *, similarity_threshold: float - ) -> Tuple[MatchResult, SimilarityFunction]: + ) -> tuple[MatchResult, SimilarityFunction]: return self._match_skeletons( gt_sample, ds_sample, similarity_threshold=similarity_threshold ) @@ -220,7 +222,7 @@ def _get_skeleton_info(self, skeleton_label_id: int) -> _SkeletonInfo: def _match_skeletons( self, item_a: dm.DatasetItem, item_b: dm.DatasetItem, *, similarity_threshold: float - ) -> Tuple[MatchResult, SimilarityFunction]: + ) -> tuple[MatchResult, SimilarityFunction]: a_skeletons = [a for a in item_a.annotations if isinstance(a, dm.Skeleton)] b_skeletons = [a for a in item_b.annotations if isinstance(a, dm.Skeleton)] @@ -303,7 +305,7 @@ def _match_skeletons( def _instance_bbox( self, instance_anns: Sequence[dm.Annotation] - ) -> Tuple[float, float, float, float]: + ) -> tuple[float, float, float, float]: return dm.ops.max_bbox( a.get_bbox() if isinstance(a, dm.Skeleton) else a for a in instance_anns @@ -336,11 +338,11 @@ def _compute_oks( a: dm.Points, b: dm.Points, *, - sigma: Union[float, np.ndarray] = 0.1, - bbox: Optional[BboxCoords] = None, - scale: Union[None, float, np.ndarray] = None, - visibility_a: Union[None, bool, Sequence[bool]] = None, - visibility_b: Union[None, bool, Sequence[bool]] = None, + sigma: float | np.ndarray = 0.1, + bbox: BboxCoords | None = None, + scale: None | float | np.ndarray = None, + visibility_a: None | bool | Sequence[bool] = None, + visibility_b: None | bool | Sequence[bool] = None, ) -> float: """ Computes Object Keypoint Similarity metric for a pair of point sets. @@ -353,12 +355,12 @@ def _compute_oks( return 0 if visibility_a is None: - visibility_a = np.full(len(p1), True) + visibility_a = np.full(len(p1), fill_value=True) else: visibility_a = np.asarray(visibility_a, dtype=bool) if visibility_b is None: - visibility_b = np.full(len(p2), True) + visibility_b = np.full(len(p2), fill_value=True) else: visibility_b = np.asarray(visibility_b, dtype=bool) diff --git a/packages/examples/cvat/recording-oracle/src/validators/__init__.py b/packages/examples/cvat/recording-oracle/src/validators/__init__.py index c8ce69d5f2..4d9d0279c8 100644 --- a/packages/examples/cvat/recording-oracle/src/validators/__init__.py +++ b/packages/examples/cvat/recording-oracle/src/validators/__init__.py @@ -1,4 +1,4 @@ -""" Validation utils""" +"""Validation utils""" class ValidationResult: @@ -7,7 +7,7 @@ class ValidationResult: It encapsulates validation logic and helping during generating response body """ - def __init__(self): + def __init__(self) -> None: self.is_valid = True self.errors = [] diff --git a/packages/examples/cvat/recording-oracle/src/validators/validation.py b/packages/examples/cvat/recording-oracle/src/validators/validation.py index c8ce69d5f2..4d9d0279c8 100644 --- a/packages/examples/cvat/recording-oracle/src/validators/validation.py +++ b/packages/examples/cvat/recording-oracle/src/validators/validation.py @@ -1,4 +1,4 @@ -""" Validation utils""" +"""Validation utils""" class ValidationResult: @@ -7,7 +7,7 @@ class ValidationResult: It encapsulates validation logic and helping during generating response body """ - def __init__(self): + def __init__(self) -> None: self.is_valid = True self.errors = [] diff --git a/packages/examples/cvat/recording-oracle/tests/conftest.py b/packages/examples/cvat/recording-oracle/tests/conftest.py index e027999628..f39f40a8ca 100644 --- a/packages/examples/cvat/recording-oracle/tests/conftest.py +++ b/packages/examples/cvat/recording-oracle/tests/conftest.py @@ -1,4 +1,4 @@ -from typing import Generator +from collections.abc import Generator import pytest from fastapi.testclient import TestClient diff --git a/packages/examples/cvat/recording-oracle/tests/integration/chain/test_escrow.py b/packages/examples/cvat/recording-oracle/tests/integration/chain/test_escrow.py index b0565f5ee9..2bcb156c87 100644 --- a/packages/examples/cvat/recording-oracle/tests/integration/chain/test_escrow.py +++ b/packages/examples/cvat/recording-oracle/tests/integration/chain/test_escrow.py @@ -92,15 +92,16 @@ def test_validate_escrow_invalid_status(self): validate_escrow(self.w3.eth.chain_id, escrow_address) def test_get_escrow_manifest(self): - with patch("src.chain.escrow.get_escrow") as mock_get_escrow, patch( - "src.chain.escrow.StorageUtils.download_file_from_url" - ) as mock_download: + with ( + patch("src.chain.escrow.get_escrow") as mock_get_escrow, + patch("src.chain.escrow.StorageUtils.download_file_from_url") as mock_download, + ): mock_download.return_value = json.dumps({"title": "test"}).encode() mock_get_escrow.return_value = self.escrow() manifest = get_escrow_manifest(self.network_config.chain_id, self.escrow_address) - self.assertIsInstance(manifest, dict) - self.assertIsNotNone(manifest) + assert isinstance(manifest, dict) + assert manifest is not None def test_get_encrypted_escrow_manifest(self): with ( @@ -121,13 +122,13 @@ def test_get_encrypted_escrow_manifest(self): encrypted_manifest = EncryptionUtils.encrypt( original_manifest, public_keys=[PGP_PUBLIC_KEY1, PGP_PUBLIC_KEY2] ) - self.assertNotEqual(encrypted_manifest, original_manifest) + assert encrypted_manifest != original_manifest mock_download.return_value = encrypted_manifest.encode() downloaded_manifest_content = get_escrow_manifest( self.network_config.chain_id, self.escrow_address ) - self.assertDictEqual(downloaded_manifest_content, original_manifest_content) + assert downloaded_manifest_content == original_manifest_content def test_store_results(self): escrow_address = create_escrow(self.w3) @@ -136,38 +137,37 @@ def test_store_results(self): results = store_results( self.w3.eth.chain_id, escrow_address, DEFAULT_MANIFEST_URL, DEFAULT_HASH ) - self.assertIsNone(results) + assert results is None intermediate_results_url = get_intermediate_results_url(self.w3, escrow_address) - self.assertEqual(intermediate_results_url, DEFAULT_MANIFEST_URL) + assert intermediate_results_url == DEFAULT_MANIFEST_URL def test_store_results_invalid_url(self): escrow_address = create_escrow(self.w3) with patch("src.chain.escrow.get_web3") as mock_function: mock_function.return_value = self.w3 - with self.assertRaises(EscrowClientError) as error: + with pytest.raises(EscrowClientError, match="Invalid URL: invalid_url"): store_results(self.w3.eth.chain_id, escrow_address, "invalid_url", DEFAULT_HASH) - self.assertEqual(f"Invalid URL: invalid_url", str(error.exception)) def test_store_results_invalid_hash(self): escrow_address = create_escrow(self.w3) with patch("src.chain.escrow.get_web3") as mock_function: mock_function.return_value = self.w3 - with self.assertRaises(EscrowClientError) as error: + with pytest.raises(EscrowClientError, match="Invalid empty hash"): store_results(self.w3.eth.chain_id, escrow_address, DEFAULT_MANIFEST_URL, "") - self.assertEqual(f"Invalid empty hash", str(error.exception)) def test_get_reputation_oracle_address(self): escrow_address = create_escrow(self.w3) - with patch("src.chain.escrow.get_web3") as mock_get_web3, patch( - "src.chain.escrow.get_escrow" - ) as mock_get_escrow: + with ( + patch("src.chain.escrow.get_web3") as mock_get_web3, + patch("src.chain.escrow.get_escrow") as mock_get_escrow, + ): mock_get_web3.return_value = self.w3 mock_escrow = MagicMock() mock_escrow.reputation_oracle = REPUTATION_ORACLE_ADDRESS mock_get_escrow.return_value = mock_escrow address = get_reputation_oracle_address(self.w3.eth.chain_id, escrow_address) - self.assertIsInstance(address, str) - self.assertIsNotNone(address) + assert isinstance(address, str) + assert address is not None def test_get_reputation_oracle_address_invalid_address(self): with patch("src.chain.escrow.get_web3") as mock_function: diff --git a/packages/examples/cvat/recording-oracle/tests/integration/chain/test_kvstore.py b/packages/examples/cvat/recording-oracle/tests/integration/chain/test_kvstore.py index 245d50594e..081221c3d0 100644 --- a/packages/examples/cvat/recording-oracle/tests/integration/chain/test_kvstore.py +++ b/packages/examples/cvat/recording-oracle/tests/integration/chain/test_kvstore.py @@ -47,7 +47,7 @@ def test_get_reputation_oracle_url(self): mock_leader.return_value = MagicMock(webhook_url=DEFAULT_MANIFEST_URL) reputation_url = get_reputation_oracle_url(self.w3.eth.chain_id, escrow_address) - self.assertEqual(reputation_url, DEFAULT_MANIFEST_URL) + assert reputation_url == DEFAULT_MANIFEST_URL def test_get_reputation_oracle_url_invalid_escrow(self): with patch("src.chain.kvstore.get_web3") as mock_function: @@ -72,21 +72,20 @@ def test_get_reputation_oracle_url_invalid_address(self): reputation_url = get_reputation_oracle_url( self.w3.eth.chain_id, REPUTATION_ORACLE_ADDRESS ) - self.assertEqual(reputation_url, "") + assert reputation_url == "" def test_get_role_by_address(self): store_kvstore_value("role", "Reputation Oracle") with patch("src.chain.kvstore.get_web3") as mock_function: mock_function.return_value = self.w3 reputation_url = get_role_by_address(self.w3.eth.chain_id, REPUTATION_ORACLE_ADDRESS) - self.assertEqual(reputation_url, "Reputation Oracle") + assert reputation_url == "Reputation Oracle" def test_get_role_by_address_invalid_escrow(self): with patch("src.chain.kvstore.get_web3") as mock_function: mock_function.return_value = self.w3 - with self.assertRaises(KVStoreClientError) as error: + with pytest.raises(KVStoreClientError, match="Invalid address: invalid_address"): get_role_by_address(self.w3.eth.chain_id, "invalid_address") - self.assertEqual(f"Invalid address: invalid_address", str(error.exception)) def test_get_role_by_address_invalid_address(self): create_escrow(self.w3) @@ -94,7 +93,7 @@ def test_get_role_by_address_invalid_address(self): with patch("src.chain.kvstore.get_web3") as mock_function: mock_function.return_value = self.w3 reputation_url = get_role_by_address(self.w3.eth.chain_id, REPUTATION_ORACLE_ADDRESS) - self.assertEqual(reputation_url, "") + assert reputation_url == "" def test_store_public_key(self): PGP_PUBLIC_KEY_URL_1 = "http://pgp-public-key-url-1" @@ -114,7 +113,7 @@ def get_file_url_and_verify_hash(*args, **kwargs): hash_ = store["public_key_hash"] if hash_ != hash(public_key): - raise KVStoreClientError(f"Invalid hash") + raise KVStoreClientError("Invalid hash") return public_key @@ -141,7 +140,7 @@ def set_file_url_and_hash(url: str, key: str): mock_web3.return_value = self.w3 kvstore_client = KVStoreClient(self.w3) - self.assertIsNone(kvstore_client.get_file_url_and_verify_hash(LocalhostConfig.addr)) + assert kvstore_client.get_file_url_and_verify_hash(LocalhostConfig.addr) is None # check that public key will be set to KVStore at first time with patch( @@ -150,9 +149,9 @@ def set_file_url_and_hash(url: str, key: str): mock_set_file_url_and_hash.side_effect = set_file_url_and_hash register_in_kvstore() mock_set_file_url_and_hash.assert_called_once() - self.assertEquals( - kvstore_client.get_file_url_and_verify_hash(LocalhostConfig.addr), - PGP_PUBLIC_KEY_URL_1, + assert ( + kvstore_client.get_file_url_and_verify_hash(LocalhostConfig.addr) + == PGP_PUBLIC_KEY_URL_1 ) # check that the same public key URL is not written to KVStore a second time @@ -163,7 +162,8 @@ def set_file_url_and_hash(url: str, key: str): register_in_kvstore() mock_set_file_url_and_hash.assert_not_called() - # check that public key URL and hash will be updated in KVStore if previous hash is outdated/corrupted + # check that public key URL and hash will be updated in KVStore + # if previous hash is outdated/corrupted with patch( "human_protocol_sdk.kvstore.KVStoreClient.set_file_url_and_hash", Mock() ) as mock_set_file_url_and_hash: @@ -171,9 +171,10 @@ def set_file_url_and_hash(url: str, key: str): store["public_key_hash"] = "corrupted_hash" register_in_kvstore() mock_set_file_url_and_hash.assert_called_once() - self.assertNotEquals(store["public_key_hash"], "corrupted_hash") + assert store["public_key_hash"] != "corrupted_hash" - # check that a new public key URL will be written to KVStore when an outdated URL is stored there + # check that a new public key URL will be written to KVStore + # when an outdated URL is stored there with ( patch( "src.core.config.Config.encryption_config.pgp_public_key_url", @@ -186,7 +187,7 @@ def set_file_url_and_hash(url: str, key: str): mock_set_file_url_and_hash.side_effect = set_file_url_and_hash register_in_kvstore() mock_set_file_url_and_hash.assert_called_once() - self.assertEquals( - kvstore_client.get_file_url_and_verify_hash(LocalhostConfig.addr), - PGP_PUBLIC_KEY_URL_2, + assert ( + kvstore_client.get_file_url_and_verify_hash(LocalhostConfig.addr) + == PGP_PUBLIC_KEY_URL_2 ) diff --git a/packages/examples/cvat/recording-oracle/tests/integration/chain/test_web3.py b/packages/examples/cvat/recording-oracle/tests/integration/chain/test_web3.py index 4e37ea8a45..c6a97fd696 100644 --- a/packages/examples/cvat/recording-oracle/tests/integration/chain/test_web3.py +++ b/packages/examples/cvat/recording-oracle/tests/integration/chain/test_web3.py @@ -1,6 +1,7 @@ import unittest from unittest.mock import patch +import pytest from human_protocol_sdk.constants import ChainId from web3 import HTTPProvider, Web3 from web3.middleware import construct_sign_and_send_raw_middleware @@ -31,9 +32,9 @@ class PolygonMainnetConfig: with patch("src.chain.web3.Config.polygon_mainnet", PolygonMainnetConfig): w3 = get_web3(ChainId.POLYGON.value) - self.assertIsInstance(w3, Web3) - self.assertEqual(w3.eth.default_account, DEFAULT_GAS_PAYER) - self.assertEqual(w3.manager._provider.endpoint_uri, PolygonMainnetConfig.rpc_api) + assert isinstance(w3, Web3) + assert w3.eth.default_account == DEFAULT_GAS_PAYER + assert w3.manager._provider.endpoint_uri == PolygonMainnetConfig.rpc_api def test_get_web3_amoy(self): class PolygonAmoyConfig: @@ -43,67 +44,64 @@ class PolygonAmoyConfig: with patch("src.chain.web3.Config.polygon_amoy", PolygonAmoyConfig): w3 = get_web3(ChainId.POLYGON_AMOY.value) - self.assertIsInstance(w3, Web3) - self.assertEqual(w3.eth.default_account, DEFAULT_GAS_PAYER) - self.assertEqual(w3.manager._provider.endpoint_uri, PolygonAmoyConfig.rpc_api) + assert isinstance(w3, Web3) + assert w3.eth.default_account == DEFAULT_GAS_PAYER + assert w3.manager._provider.endpoint_uri == PolygonAmoyConfig.rpc_api def test_get_web3_localhost(self): w3 = get_web3(ChainId.LOCALHOST.value) - self.assertIsInstance(w3, Web3) - self.assertEqual(w3.eth.default_account, DEFAULT_GAS_PAYER) - self.assertEqual(w3.manager._provider.endpoint_uri, LocalhostConfig.rpc_api) + assert isinstance(w3, Web3) + assert w3.eth.default_account == DEFAULT_GAS_PAYER + assert w3.manager._provider.endpoint_uri == LocalhostConfig.rpc_api def test_get_web3_invalid_chain_id(self): - with self.assertRaises(ValueError) as error: - w3 = get_web3(1234) - self.assertEqual( - "1234 is not in available list of networks.", - str(error.exception), - ) + with pytest.raises(ValueError, match="1234 is not in available list of networks."): + get_web3(1234) def test_sign_message_polygon(self): - with patch("src.chain.web3.get_web3") as mock_function, patch( - "src.chain.web3.Config.polygon_mainnet.private_key", - DEFAULT_GAS_PAYER_PRIV, + with ( + patch("src.chain.web3.get_web3") as mock_function, + patch( + "src.chain.web3.Config.polygon_mainnet.private_key", + DEFAULT_GAS_PAYER_PRIV, + ), ): mock_function.return_value = self.w3 signed_message, _ = sign_message(ChainId.POLYGON.value, "message") - self.assertEqual(signed_message, SIGNATURE) + assert signed_message == SIGNATURE def test_sign_message_amoy(self): - with patch("src.chain.web3.get_web3") as mock_function, patch( - "src.chain.web3.Config.polygon_amoy.private_key", - DEFAULT_GAS_PAYER_PRIV, + with ( + patch("src.chain.web3.get_web3") as mock_function, + patch( + "src.chain.web3.Config.polygon_amoy.private_key", + DEFAULT_GAS_PAYER_PRIV, + ), ): mock_function.return_value = self.w3 signed_message, _ = sign_message(ChainId.POLYGON_AMOY.value, "message") - self.assertEqual(signed_message, SIGNATURE) + assert signed_message == SIGNATURE def test_sign_message_invalid_chain_id(self): - with self.assertRaises(ValueError) as error: + with pytest.raises(ValueError, match="1234 is not in available list of networks."): sign_message(1234, "message") - self.assertEqual( - "1234 is not in available list of networks.", - str(error.exception), - ) def test_recover_signer(self): with patch("src.chain.web3.get_web3") as mock_function: mock_function.return_value = self.w3 signer = recover_signer(ChainId.POLYGON.value, "message", SIGNATURE) - self.assertEqual(signer, DEFAULT_GAS_PAYER) + assert signer == DEFAULT_GAS_PAYER def test_recover_signer_invalid_signature(self): with patch("src.chain.web3.get_web3") as mock_function: mock_function.return_value = self.w3 signer = recover_signer(ChainId.POLYGON.value, "test", SIGNATURE) - self.assertNotEqual(signer, DEFAULT_GAS_PAYER) + assert signer != DEFAULT_GAS_PAYER def test_validate_address(self): address = validate_address(DEFAULT_GAS_PAYER) - self.assertEqual(address, DEFAULT_GAS_PAYER) + assert address == DEFAULT_GAS_PAYER def test_validate_address_invalid_address(self): - with self.assertRaises(ValueError) as error: + with pytest.raises(ValueError, match="invalid_address is not a correct Web3 address"): validate_address("invalid_address") - self.assertEqual(f"invalid_address is not a correct Web3 address", str(error.exception)) diff --git a/packages/examples/cvat/recording-oracle/tests/integration/cron/test_process_exchange_oracle_webhooks.py b/packages/examples/cvat/recording-oracle/tests/integration/cron/test_process_exchange_oracle_webhooks.py index 7204d319da..ab90d5cad2 100644 --- a/packages/examples/cvat/recording-oracle/tests/integration/cron/test_process_exchange_oracle_webhooks.py +++ b/packages/examples/cvat/recording-oracle/tests/integration/cron/test_process_exchange_oracle_webhooks.py @@ -63,8 +63,8 @@ def test_process_exchange_oracle_webhook(self): updated_webhook = ( self.session.execute(select(Webhook).where(Webhook.id == webhook.id)).scalars().first() ) - self.assertEqual(updated_webhook.status, OracleWebhookStatuses.completed) - self.assertEqual(updated_webhook.attempts, 1) + assert updated_webhook.status == OracleWebhookStatuses.completed + assert updated_webhook.attempts == 1 def test_process_recording_oracle_webhooks_invalid_escrow_address(self): escrow_address = "invalid_address" @@ -83,8 +83,8 @@ def test_process_recording_oracle_webhooks_invalid_escrow_address(self): self.session.execute(select(Webhook).where(Webhook.id == webhook.id)).scalars().first() ) - self.assertEqual(updated_webhook.status, OracleWebhookStatuses.pending.value) - self.assertEqual(updated_webhook.attempts, 1) + assert updated_webhook.status == OracleWebhookStatuses.pending.value + assert updated_webhook.attempts == 1 def test_process_recording_oracle_webhooks_invalid_escrow_balance(self): escrow_address = create_escrow(self.w3) @@ -103,8 +103,8 @@ def test_process_recording_oracle_webhooks_invalid_escrow_balance(self): self.session.execute(select(Webhook).where(Webhook.id == webhook.id)).scalars().first() ) - self.assertEqual(updated_webhook.status, OracleWebhookStatuses.pending.value) - self.assertEqual(updated_webhook.attempts, 1) + assert updated_webhook.status == OracleWebhookStatuses.pending.value + assert updated_webhook.attempts == 1 @patch("src.chain.escrow.EscrowClient.get_manifest_url") def test_process_job_launcher_webhooks_invalid_manifest_url(self, mock_manifest_url): @@ -123,5 +123,5 @@ def test_process_job_launcher_webhooks_invalid_manifest_url(self, mock_manifest_ self.session.execute(select(Webhook).where(Webhook.id == webhook.id)).scalars().first() ) - self.assertEqual(updated_webhook.status, OracleWebhookStatuses.pending.value) - self.assertEqual(updated_webhook.attempts, 1) + assert updated_webhook.status == OracleWebhookStatuses.pending.value + assert updated_webhook.attempts == 1 diff --git a/packages/examples/cvat/recording-oracle/tests/integration/cron/test_process_reputation_oracle_webhooks.py b/packages/examples/cvat/recording-oracle/tests/integration/cron/test_process_reputation_oracle_webhooks.py index a31c512f85..743c18af0a 100644 --- a/packages/examples/cvat/recording-oracle/tests/integration/cron/test_process_reputation_oracle_webhooks.py +++ b/packages/examples/cvat/recording-oracle/tests/integration/cron/test_process_reputation_oracle_webhooks.py @@ -53,13 +53,15 @@ def get_webhook(self, escrow_address, chain_id, event_data): def test_process_reputation_oracle_webhooks(self): expected_url = "expected_url" - with patch( - "src.crons.process_reputation_oracle_webhooks.httpx.Client.post" - ) as mock_httpx, patch( - "src.crons.process_reputation_oracle_webhooks.get_reputation_oracle_url" - ) as mock_get_repo_url, patch( - "src.crons.process_reputation_oracle_webhooks.prepare_signed_message" - ) as mock_signature: + with ( + patch("src.crons.process_reputation_oracle_webhooks.httpx.Client.post") as mock_httpx, + patch( + "src.crons.process_reputation_oracle_webhooks.get_reputation_oracle_url" + ) as mock_get_repo_url, + patch( + "src.crons.process_reputation_oracle_webhooks.prepare_signed_message" + ) as mock_signature, + ): mock_response = MagicMock() mock_response.raise_for_status.return_value = None mock_httpx.return_value = mock_response @@ -68,7 +70,7 @@ def test_process_reputation_oracle_webhooks(self): chain_id = Networks.localhost.value escrow_address = create_escrow(self.w3) store_kvstore_value("webhook_url", expected_url) - event_data = dict() + event_data = {} mock_signature.return_value = (None, SIGNATURE) webhook = self.get_webhook(escrow_address, chain_id, event_data) @@ -94,8 +96,8 @@ def test_process_reputation_oracle_webhooks(self): "event_type": RecordingOracleEventTypes.task_completed.value, }, ) - self.assertEqual(updated_webhook.status, OracleWebhookStatuses.completed.value) - self.assertEqual(updated_webhook.attempts, 1) + assert updated_webhook.status == OracleWebhookStatuses.completed.value + assert updated_webhook.attempts == 1 def test_process_reputation_oracle_webhooks_invalid_escrow_address(self): chain_id = Networks.localhost.value @@ -112,8 +114,8 @@ def test_process_reputation_oracle_webhooks_invalid_escrow_address(self): self.session.execute(select(Webhook).where(Webhook.id == webhook.id)).scalars().first() ) - self.assertEqual(updated_webhook.status, OracleWebhookStatuses.pending.value) - self.assertEqual(updated_webhook.attempts, 1) + assert updated_webhook.status == OracleWebhookStatuses.pending.value + assert updated_webhook.attempts == 1 def test_process_reputation_oracle_webhooks_invalid_reputation_oracle_url(self): with patch( @@ -131,5 +133,5 @@ def test_process_reputation_oracle_webhooks_invalid_reputation_oracle_url(self): .scalars() .first() ) - self.assertEqual(updated_webhook.status, OracleWebhookStatuses.pending.value) - self.assertEqual(updated_webhook.attempts, 1) + assert updated_webhook.status == OracleWebhookStatuses.pending.value + assert updated_webhook.attempts == 1 diff --git a/packages/examples/cvat/recording-oracle/tests/integration/services/cloud/test_client_service.py b/packages/examples/cvat/recording-oracle/tests/integration/services/cloud/test_client_service.py index 75cf94eec5..b26712d279 100644 --- a/packages/examples/cvat/recording-oracle/tests/integration/services/cloud/test_client_service.py +++ b/packages/examples/cvat/recording-oracle/tests/integration/services/cloud/test_client_service.py @@ -35,7 +35,7 @@ def test_file_operations(self): assert len(client.list_files()) == 0 file_name = "test_file" - data = "this is a test".encode("utf-8") + data = b"this is a test" assert not client.file_exists(file_name) client.create_file(file_name, data) @@ -68,7 +68,7 @@ def test_degenerate_file_operations(self): client.remove_file(invalid_file, bucket=self.bucket_name) def test_degenerate_client(self): - with pytest.raises(EndpointConnectionError): + with pytest.raises(EndpointConnectionError): # noqa: PT012 invalid_client = S3Client( endpoint_url="http://not.an.url:1234", access_key=self.access_key, @@ -76,5 +76,5 @@ def test_degenerate_client(self): ) invalid_client.create_file("test.txt", bucket=self.bucket_name) - with pytest.raises(ValueError): + with pytest.raises(ValueError): # noqa: PT011 S3Client(endpoint_url="nonsense-stuff") diff --git a/packages/examples/cvat/recording-oracle/tests/integration/services/test_webhook_service.py b/packages/examples/cvat/recording-oracle/tests/integration/services/test_webhook_service.py index a7cf4673d4..e7f5d8b828 100644 --- a/packages/examples/cvat/recording-oracle/tests/integration/services/test_webhook_service.py +++ b/packages/examples/cvat/recording-oracle/tests/integration/services/test_webhook_service.py @@ -2,6 +2,7 @@ import unittest import uuid +import pytest from sqlalchemy.exc import IntegrityError from src.core.types import Networks, OracleWebhookStatuses, OracleWebhookTypes @@ -13,14 +14,14 @@ class ServiceIntegrationTest(unittest.TestCase): def setUp(self): self.session = SessionLocal() - self.webhook_kwargs = dict( - session=self.session, - escrow_address="0x1234567890123456789012345678901234567890", - chain_id=Networks.polygon_mainnet.value, - type=OracleWebhookTypes.exchange_oracle, - signature="signature", - event_type="task_finished", - ) + self.webhook_kwargs = { + "session": self.session, + "escrow_address": "0x1234567890123456789012345678901234567890", + "chain_id": Networks.polygon_mainnet.value, + "type": OracleWebhookTypes.exchange_oracle, + "signature": "signature", + "event_type": "task_finished", + } random.seed(42) def tearDown(self): @@ -44,18 +45,18 @@ def test_create_webhook(self): webhook = self.session.query(Webhook).filter_by(id=webhook_id).first() - self.assertEqual(webhook.escrow_address, self.webhook_kwargs["escrow_address"]) - self.assertEqual(webhook.chain_id, self.webhook_kwargs["chain_id"]) - self.assertEqual(webhook.attempts, 0) - self.assertEqual(webhook.signature, self.webhook_kwargs["signature"]) - self.assertEqual(webhook.type, OracleWebhookTypes.exchange_oracle) - self.assertEqual(webhook.status, OracleWebhookStatuses.pending) + assert webhook.escrow_address == self.webhook_kwargs["escrow_address"] + assert webhook.chain_id == self.webhook_kwargs["chain_id"] + assert webhook.attempts == 0 + assert webhook.signature == self.webhook_kwargs["signature"] + assert webhook.type == OracleWebhookTypes.exchange_oracle + assert webhook.status == OracleWebhookStatuses.pending # TODO: check intended fields and verify those def _test_none_webhook_argument(self, argument_name, error_type): kwargs = dict(**self.webhook_kwargs) kwargs[argument_name] = None - with self.assertRaises(error_type): + with pytest.raises(error_type): # noqa: PT012 inbox.create_webhook(**kwargs) self.session.commit() @@ -95,29 +96,29 @@ def test_get_pending_webhooks(self): pending_webhooks = inbox.get_pending_webhooks( self.session, OracleWebhookTypes.exchange_oracle ) - self.assertEqual(len(pending_webhooks), 2) - self.assertEqual(pending_webhooks[0].id, webhook1.id) - self.assertEqual(pending_webhooks[1].id, webhook2.id) + assert len(pending_webhooks) == 2 + assert pending_webhooks[0].id == webhook1.id + assert pending_webhooks[1].id == webhook2.id pending_webhooks = inbox.get_pending_webhooks( self.session, OracleWebhookTypes.reputation_oracle ) - self.assertEqual(len(pending_webhooks), 1) - self.assertEqual(pending_webhooks[0].id, webhook4.id) + assert len(pending_webhooks) == 1 + assert pending_webhooks[0].id == webhook4.id def test_update_webhook_status(self): webhook_id = inbox.create_webhook(**self.webhook_kwargs) webhook = self.session.query(Webhook).filter_by(id=webhook_id).first() - self.assertEqual(webhook.status, OracleWebhookStatuses.pending) + assert webhook.status == OracleWebhookStatuses.pending inbox.update_webhook_status(self.session, webhook_id, OracleWebhookStatuses.completed) webhook = self.session.query(Webhook).filter_by(id=webhook_id).first() - self.assertEqual(webhook.status, OracleWebhookStatuses.completed) + assert webhook.status == OracleWebhookStatuses.completed def test_update_webhook_invalid_status(self): webhook_id = inbox.create_webhook(**self.webhook_kwargs) - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): inbox.update_webhook_status(self.session, webhook_id, "Invalid status") def test_handle_webhook_success(self): @@ -127,23 +128,23 @@ def test_handle_webhook_success(self): webhook = self.session.query(Webhook).filter_by(id=webhook_id).first() - self.assertEqual(webhook.attempts, 1) - self.assertEqual(webhook.status, OracleWebhookStatuses.completed.value) + assert webhook.attempts == 1 + assert webhook.status == OracleWebhookStatuses.completed.value def test_handle_webhook_fail(self): webhook_id = inbox.create_webhook(**self.webhook_kwargs) inbox.handle_webhook_fail(self.session, webhook_id) webhook = self.session.query(Webhook).filter_by(id=webhook_id).first() - self.assertEqual(webhook.attempts, 1) - self.assertEqual(webhook.type, OracleWebhookTypes.exchange_oracle.value) - self.assertEqual(webhook.status, OracleWebhookStatuses.pending.value) + assert webhook.attempts == 1 + assert webhook.type == OracleWebhookTypes.exchange_oracle.value + assert webhook.status == OracleWebhookStatuses.pending.value # assumes Config.webhook_max_retries == 5 - for i in range(4): + for _i in range(4): inbox.handle_webhook_fail(self.session, webhook_id) webhook = self.session.query(Webhook).filter_by(id=webhook_id).first() - self.assertEqual(webhook.attempts, 5) - self.assertEqual(webhook.status, OracleWebhookStatuses.failed.value) + assert webhook.attempts == 5 + assert webhook.status == OracleWebhookStatuses.failed.value diff --git a/packages/examples/cvat/recording-oracle/tests/utils/constants.py b/packages/examples/cvat/recording-oracle/tests/utils/constants.py index 839008f892..2df6f087da 100644 --- a/packages/examples/cvat/recording-oracle/tests/utils/constants.py +++ b/packages/examples/cvat/recording-oracle/tests/utils/constants.py @@ -17,14 +17,20 @@ DEFAULT_MANIFEST_URL = "http://host.docker.internal:9000/manifests/manifest.json" DEFAULT_HASH = "test" -SIGNATURE = "0xa0c5626301e3c198cb91356e492890c0c28db8c37044846134939246911a693c4d7116d04aa4bc40a41077493868b8dd533d30980f6addb28d1b3610a84cb4091c" +SIGNATURE = ( + "0xa0c5626301e3c198cb91356e492890c0c28db8c37044846134939246911a693c" + "4d7116d04aa4bc40a41077493868b8dd533d30980f6addb28d1b3610a84cb4091c" +) WEBHOOK_MESSAGE = { "escrow_address": "0xFE776895f6b00AA53969b20119a4777Ed920676a", "chain_id": 80002, } -WEBHOOK_MESSAGE_SIGNED = "0xfeef93fdb26b9b855da432ca3ccc4425366e656401d3a4f67c2f0cab053fe34c2c7d0ce026d47f9fa100c05c12945f94c60dcb63ed94124fa4c60e888c4156281c" +WEBHOOK_MESSAGE_SIGNED = ( + "0xfeef93fdb26b9b855da432ca3ccc4425366e656401d3a4f67c2f0cab053fe34c" + "2c7d0ce026d47f9fa100c05c12945f94c60dcb63ed94124fa4c60e888c4156281c" +) JOB_REQUESTER_ID = "9001" diff --git a/packages/examples/cvat/recording-oracle/tests/utils/setup_escrow.py b/packages/examples/cvat/recording-oracle/tests/utils/setup_escrow.py index afc161a1ed..b840fbc44b 100644 --- a/packages/examples/cvat/recording-oracle/tests/utils/setup_escrow.py +++ b/packages/examples/cvat/recording-oracle/tests/utils/setup_escrow.py @@ -25,7 +25,7 @@ def create_escrow(web3: Web3): escrow_client = EscrowClient(web3) staking_client.approve_stake(amount) staking_client.stake(amount) - escrow_address = escrow_client.create_and_setup_escrow( + return escrow_client.create_and_setup_escrow( token_address=NETWORKS[ChainId.LOCALHOST]["hmt_address"], trusted_handlers=[web3.eth.default_account], job_requester_id=JOB_REQUESTER_ID, @@ -40,7 +40,6 @@ def create_escrow(web3: Web3): hash=DEFAULT_HASH, ), ) - return escrow_address def fund_escrow(web3: Web3, escrow_address: str): @@ -57,7 +56,6 @@ def bulk_payout(web3: Web3, escrow_address: str, recipient: str, amount: Decimal def get_intermediate_results_url(web3: Web3, escrow_address: str): escrow_client = EscrowClient(web3) - intermediate_results_url = ( + return ( escrow_client._get_escrow_contract(escrow_address).functions.intermediateResultsUrl().call() ) - return intermediate_results_url From e4a18f5d6ffd44fc670ad3a5a123e473bda81210 Mon Sep 17 00:00:00 2001 From: KacperKoza343 <165884432+KacperKoza343@users.noreply.github.com> Date: Tue, 27 Aug 2024 12:46:31 +0200 Subject: [PATCH 85/89] Fix/loging out user when multitab (#2430) * feat(app/auth): fix logging out user when uses multiple tabs * feat(app/worker/profile): hide connected wallet address until its not registered * fix(app/operator-set-up): fix form validation --- .../services/operator/edit-existing-keys.ts | 62 ++++++++++++++----- .../components/layout/protected/layout.tsx | 2 +- .../components/layout/protected/navbar.tsx | 2 +- .../frontend/src/pages/homepage/home.page.tsx | 13 ++++ .../add-keys/edit-existing-keys-form.tsx | 6 +- .../sign-up/add-keys/pending-keys-form.tsx | 4 +- .../worker/profile/wallet-connect-done.tsx | 8 +-- .../src/pages/worker/sign-in.page.tsx | 9 +-- .../src/pages/worker/sign-up.page.tsx | 10 +-- .../human-app/frontend/src/styles/theme.ts | 2 +- .../apps/human-app/frontend/vite.config.mjs | 8 ++- 11 files changed, 85 insertions(+), 41 deletions(-) diff --git a/packages/apps/human-app/frontend/src/api/services/operator/edit-existing-keys.ts b/packages/apps/human-app/frontend/src/api/services/operator/edit-existing-keys.ts index 070896b8b4..28b5330373 100644 --- a/packages/apps/human-app/frontend/src/api/services/operator/edit-existing-keys.ts +++ b/packages/apps/human-app/frontend/src/api/services/operator/edit-existing-keys.ts @@ -6,7 +6,7 @@ import { import last from 'lodash/last'; import { useNavigate } from 'react-router-dom'; import type { JsonRpcSigner } from 'ethers'; -import { z } from 'zod'; +import { z, ZodError } from 'zod'; import { t } from 'i18next'; import { routerPaths } from '@/router/router-paths'; import { useConnectedWallet } from '@/auth-web3/use-connected-wallet'; @@ -20,24 +20,57 @@ import { getContractAddress } from '@/smart-contracts/get-contract-address'; import type { GetEthKVStoreValuesSuccessResponse } from '@/api/services/operator/get-keys'; import { isArray } from '@/shared/helpers/is-array'; +const fieldsValidations = { + [EthKVStoreKeys.PublicKey]: z.string().min(1), + [EthKVStoreKeys.Url]: z.string(), + [EthKVStoreKeys.WebhookUrl]: z.string().url(), + [EthKVStoreKeys.Role]: z.nativeEnum(Role), + [EthKVStoreKeys.JobTypes]: z.array(z.nativeEnum(JobTypes)).min(1), + [EthKVStoreKeys.Fee]: z.coerce.number().min(1).max(100).step(1), +}; + export const editEthKVStoreValuesMutationSchema = z.object({ - [EthKVStoreKeys.PublicKey]: z.string().min(1).optional(), - [EthKVStoreKeys.Url]: z.string().url().optional(), - [EthKVStoreKeys.WebhookUrl]: z.string().url().optional(), - [EthKVStoreKeys.Role]: z.nativeEnum(Role).optional(), - [EthKVStoreKeys.JobTypes]: z.array(z.nativeEnum(JobTypes)).optional(), - [EthKVStoreKeys.Fee]: z.coerce.number().min(1).max(100).step(1).optional(), + [EthKVStoreKeys.PublicKey]: + fieldsValidations[EthKVStoreKeys.PublicKey].optional(), + [EthKVStoreKeys.Url]: fieldsValidations[EthKVStoreKeys.Url].optional(), + [EthKVStoreKeys.WebhookUrl]: + fieldsValidations[EthKVStoreKeys.WebhookUrl].optional(), + [EthKVStoreKeys.Role]: fieldsValidations[EthKVStoreKeys.Role].optional(), + [EthKVStoreKeys.JobTypes]: + fieldsValidations[EthKVStoreKeys.JobTypes].optional(), + [EthKVStoreKeys.Fee]: fieldsValidations[EthKVStoreKeys.Fee].optional(), }); export type EditEthKVStoreValuesMutationData = z.infer< typeof editEthKVStoreValuesMutationSchema >; +export const setEthKVStoreValuesMutationSchema = ( + initialFields: GetEthKVStoreValuesSuccessResponse +) => { + return editEthKVStoreValuesMutationSchema.superRefine((newData, ctx) => { + Object.keys(initialFields).forEach((key) => { + const typedKey = key as keyof GetEthKVStoreValuesSuccessResponse; + const initialField = initialFields[typedKey]; + if (!initialField) { + try { + fieldsValidations[typedKey].parse(newData[typedKey]); + } catch (error) { + if (error instanceof ZodError) { + error.issues[0].path = [typedKey]; + ctx.addIssue(error.issues[0]); + } + } + } + }); + }); +}; + export const getEditEthKVStoreValuesMutationSchema = ( initialData: GetEthKVStoreValuesSuccessResponse ) => { return editEthKVStoreValuesMutationSchema.transform((newData, ctx) => { - const result: EditEthKVStoreValuesMutationData = {}; + const fieldsThatHasChanges: EditEthKVStoreValuesMutationData = {}; Object.values(EthKVStoreKeys).forEach((key) => { const newFiledData = newData[key]; const initialFiledData = initialData[key]; @@ -47,7 +80,7 @@ export const getEditEthKVStoreValuesMutationSchema = ( isArray(initialFiledData) && newFiledData.sort().toString() !== initialFiledData.sort().toString() ) { - Object.assign(result, { [key]: newFiledData.toString() }); + Object.assign(fieldsThatHasChanges, { [key]: newFiledData.toString() }); return; } @@ -55,16 +88,17 @@ export const getEditEthKVStoreValuesMutationSchema = ( typeof newFiledData === 'number' && newFiledData.toString() !== initialFiledData?.toString() ) { - Object.assign(result, { [key]: newFiledData }); + Object.assign(fieldsThatHasChanges, { [key]: newFiledData }); return; } - if (newFiledData !== initialFiledData) { - Object.assign(result, { [key]: newFiledData }); + // eslint-disable-next-line eqeqeq -- expect to do conversion for this compare + if (newFiledData != initialFiledData) { + Object.assign(fieldsThatHasChanges, { [key]: newFiledData }); } }); - if (!Object.values(result).length) { + if (!Object.values(fieldsThatHasChanges).length) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: t('operator.addKeysPage.editKeysForm.error'), @@ -72,7 +106,7 @@ export const getEditEthKVStoreValuesMutationSchema = ( }); } - return result; + return fieldsThatHasChanges; }); }; diff --git a/packages/apps/human-app/frontend/src/components/layout/protected/layout.tsx b/packages/apps/human-app/frontend/src/components/layout/protected/layout.tsx index 4411c2af14..09d36dc6ff 100644 --- a/packages/apps/human-app/frontend/src/components/layout/protected/layout.tsx +++ b/packages/apps/human-app/frontend/src/components/layout/protected/layout.tsx @@ -156,7 +156,7 @@ export function Layout({ [breakpoints.mobile]: { height: 'unset', position: 'absolute', - zIndex: 2000, + zIndex: 200, top: '0', left: '0', width: notificationWith ? `${notificationWith}px` : 'unset', diff --git a/packages/apps/human-app/frontend/src/components/layout/protected/navbar.tsx b/packages/apps/human-app/frontend/src/components/layout/protected/navbar.tsx index a282deb06a..85c34bbe64 100644 --- a/packages/apps/human-app/frontend/src/components/layout/protected/navbar.tsx +++ b/packages/apps/human-app/frontend/src/components/layout/protected/navbar.tsx @@ -70,7 +70,7 @@ export function Navbar({ width: '100%', px: isMobile ? NAVBAR_PADDING : 0, py: isMobile ? '32px' : 0, - zIndex: '1300', + zIndex: '130', position: open ? 'sticky' : 'relative', top: open ? '0' : 'unset', }} diff --git a/packages/apps/human-app/frontend/src/pages/homepage/home.page.tsx b/packages/apps/human-app/frontend/src/pages/homepage/home.page.tsx index 0408873f72..c715d0f6c1 100644 --- a/packages/apps/human-app/frontend/src/pages/homepage/home.page.tsx +++ b/packages/apps/human-app/frontend/src/pages/homepage/home.page.tsx @@ -1,11 +1,24 @@ import Box from '@mui/material/Box'; import { Paper } from '@mui/material'; +import { Navigate } from 'react-router-dom'; import { colorPalette } from '@/styles/color-palette'; import { useIsMobile } from '@/hooks/use-is-mobile'; +import { useWeb3Auth } from '@/auth-web3/use-web3-auth'; +import { useAuth } from '@/auth/use-auth'; +import { routerPaths } from '@/router/router-paths'; import { HomeContainer } from './components/home-container'; export function HomePage() { const isMobile = useIsMobile(); + const { user: worker } = useAuth(); + const { user: operator } = useWeb3Auth(); + + if (worker) { + return ; + } + if (operator) { + return ; + } return ( diff --git a/packages/apps/human-app/frontend/src/pages/operator/sign-up/add-keys/edit-existing-keys-form.tsx b/packages/apps/human-app/frontend/src/pages/operator/sign-up/add-keys/edit-existing-keys-form.tsx index 0b786a2a8f..83d1be2115 100644 --- a/packages/apps/human-app/frontend/src/pages/operator/sign-up/add-keys/edit-existing-keys-form.tsx +++ b/packages/apps/human-app/frontend/src/pages/operator/sign-up/add-keys/edit-existing-keys-form.tsx @@ -93,9 +93,9 @@ export function EditExistingKeysForm({ const formInputsConfigKey = key as EthKVStoreKeyValues; return ( <> - {existingKeysInitialState[formInputsConfigKey] - ? formInputsConfig[formInputsConfigKey] - : null} + {existingKeysInitialState[formInputsConfigKey] ? ( + {formInputsConfig[formInputsConfigKey]} + ) : null} ); })} diff --git a/packages/apps/human-app/frontend/src/pages/operator/sign-up/add-keys/pending-keys-form.tsx b/packages/apps/human-app/frontend/src/pages/operator/sign-up/add-keys/pending-keys-form.tsx index 7162c27613..b9e57e08df 100644 --- a/packages/apps/human-app/frontend/src/pages/operator/sign-up/add-keys/pending-keys-form.tsx +++ b/packages/apps/human-app/frontend/src/pages/operator/sign-up/add-keys/pending-keys-form.tsx @@ -3,7 +3,7 @@ import { zodResolver } from '@hookform/resolvers/zod'; import { FormProvider, useForm } from 'react-hook-form'; import type { EditEthKVStoreValuesMutationData } from '@/api/services/operator/edit-existing-keys'; import { - editEthKVStoreValuesMutationSchema, + setEthKVStoreValuesMutationSchema, useEditExistingKeysMutation, } from '@/api/services/operator/edit-existing-keys'; import { Button } from '@/components/ui/button'; @@ -25,7 +25,7 @@ export function PendingKeysForm({ EditEthKVStoreValuesMutationData >({ defaultValues: {}, - resolver: zodResolver(editEthKVStoreValuesMutationSchema), + resolver: zodResolver(setEthKVStoreValuesMutationSchema(keysData)), }); const handleEditPendingKey = (data: EditEthKVStoreValuesMutationData) => { diff --git a/packages/apps/human-app/frontend/src/pages/worker/profile/wallet-connect-done.tsx b/packages/apps/human-app/frontend/src/pages/worker/profile/wallet-connect-done.tsx index 54c905ce45..8ac978ece4 100644 --- a/packages/apps/human-app/frontend/src/pages/worker/profile/wallet-connect-done.tsx +++ b/packages/apps/human-app/frontend/src/pages/worker/profile/wallet-connect-done.tsx @@ -25,11 +25,9 @@ export function WalletConnectDone() { {t('worker.profile.walletConnected')} - + {address && !user.wallet_address ? null : ( + + )} ); } diff --git a/packages/apps/human-app/frontend/src/pages/worker/sign-in.page.tsx b/packages/apps/human-app/frontend/src/pages/worker/sign-in.page.tsx index cabe72a1a6..779196ab7d 100644 --- a/packages/apps/human-app/frontend/src/pages/worker/sign-in.page.tsx +++ b/packages/apps/human-app/frontend/src/pages/worker/sign-in.page.tsx @@ -18,9 +18,9 @@ import { FetchError } from '@/api/fetcher'; import { routerPaths } from '@/router/router-paths'; import { defaultErrorMessage } from '@/shared/helpers/default-error-message'; import { Alert } from '@/components/ui/alert'; -import { useAuth } from '@/auth/use-auth'; import { FormCaptcha } from '@/components/h-captcha'; import { useResetMutationErrors } from '@/hooks/use-reset-mutation-errors'; +import { browserAuthProvider } from '@/shared/helpers/browser-auth-provider'; function formattedSignInErrorMessage(unknownError: unknown) { if (unknownError instanceof FetchError && unknownError.status === 400) { @@ -30,13 +30,10 @@ function formattedSignInErrorMessage(unknownError: unknown) { export function SignInWorkerPage() { const { t } = useTranslation(); - const { user, signOut } = useAuth(); useEffect(() => { - if (user) { - signOut(); - } - }, [signOut, user]); + browserAuthProvider.signOut({ triggerSignOutSubscriptions: false }); + }, []); const methods = useForm({ defaultValues: { diff --git a/packages/apps/human-app/frontend/src/pages/worker/sign-up.page.tsx b/packages/apps/human-app/frontend/src/pages/worker/sign-up.page.tsx index b7fabf445f..7f1d8e9741 100644 --- a/packages/apps/human-app/frontend/src/pages/worker/sign-up.page.tsx +++ b/packages/apps/human-app/frontend/src/pages/worker/sign-up.page.tsx @@ -20,9 +20,9 @@ import { env } from '@/shared/env'; import { defaultErrorMessage } from '@/shared/helpers/default-error-message'; import { Alert } from '@/components/ui/alert'; import { FetchError } from '@/api/fetcher'; -import { useAuth } from '@/auth/use-auth'; import { FormCaptcha } from '@/components/h-captcha'; import { useResetMutationErrors } from '@/hooks/use-reset-mutation-errors'; +import { browserAuthProvider } from '@/shared/helpers/browser-auth-provider'; function formattedSignUpErrorMessage(unknownError: unknown) { if (unknownError instanceof FetchError && unknownError.status === 409) { @@ -31,13 +31,9 @@ function formattedSignUpErrorMessage(unknownError: unknown) { } export function SignUpWorkerPage() { - const { user, signOut } = useAuth(); - useEffect(() => { - if (user) { - signOut(); - } - }, [signOut, user]); + browserAuthProvider.signOut({ triggerSignOutSubscriptions: false }); + }, []); const methods = useForm({ defaultValues: { diff --git a/packages/apps/human-app/frontend/src/styles/theme.ts b/packages/apps/human-app/frontend/src/styles/theme.ts index a3d036011f..b75b6c3045 100644 --- a/packages/apps/human-app/frontend/src/styles/theme.ts +++ b/packages/apps/human-app/frontend/src/styles/theme.ts @@ -380,7 +380,7 @@ export const theme: ThemeOptions = { borderRadius: '20px', }, root: { - zIndex: 99999999, + zIndex: 800, }, }, }, diff --git a/packages/apps/human-app/frontend/vite.config.mjs b/packages/apps/human-app/frontend/vite.config.mjs index 039a13ea63..1d3bd3b702 100644 --- a/packages/apps/human-app/frontend/vite.config.mjs +++ b/packages/apps/human-app/frontend/vite.config.mjs @@ -30,7 +30,13 @@ const config = defineConfig({ port: 3001, }, optimizeDeps: { - include: ['@mui/material', '@emotion/react', '@emotion/styled'], + include: [ + '@mui/material', + '@emotion/react', + '@emotion/styled', + '@mui/material/Tooltip', + '@mui/material/Paper', + ], }, }); From 0e2a71a2545abea4092689d3de1f5be5d35bde78 Mon Sep 17 00:00:00 2001 From: Dzeranov Date: Wed, 28 Aug 2024 13:08:52 +0300 Subject: [PATCH 86/89] Added reputation for `/details/{address}` endpoint (#2459) --- .../src/modules/details/details.service.ts | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/packages/apps/dashboard/server/src/modules/details/details.service.ts b/packages/apps/dashboard/server/src/modules/details/details.service.ts index f4688d23f7..934f917d53 100644 --- a/packages/apps/dashboard/server/src/modules/details/details.service.ts +++ b/packages/apps/dashboard/server/src/modules/details/details.service.ts @@ -51,6 +51,9 @@ export class DetailsService { leaderDto.chainId = chainId; leaderDto.balance = await this.getHmtBalance(chainId, address); + const { reputation } = await this.fetchReputation(chainId, address); + leaderDto.reputation = reputation; + return leaderDto; } const walletDto: WalletDto = plainToInstance(WalletDto, { @@ -209,6 +212,28 @@ export class DetailsService { return allLeaders; } + private async fetchReputation( + chainId: ChainId, + address: string, + ): Promise<{ address: string; reputation: string }> { + try { + const response = await firstValueFrom( + this.httpService.get( + this.configService.reputationSource + `/reputation/${address}`, + { + params: { + chain_id: chainId, + }, + }, + ), + ); + return response.data; + } catch (error) { + this.logger.error('Error fetching reputation:', error); + return { address, reputation: 'Not available' }; + } + } + private async fetchReputations(): Promise< { address: string; reputation: string }[] > { From 92857255ee2bf295c6e47e8cda798e9ce6365d6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Francisco=20L=C3=B3pez?= <50665615+flopez7@users.noreply.github.com> Date: Thu, 29 Aug 2024 09:26:53 +0200 Subject: [PATCH 87/89] Modify fetchAndCacheHmtDailyStats to query all networks and sum all values before caching them (#2460) --- .../server/src/modules/stats/stats.service.ts | 111 ++++++++++-------- 1 file changed, 62 insertions(+), 49 deletions(-) diff --git a/packages/apps/dashboard/server/src/modules/stats/stats.service.ts b/packages/apps/dashboard/server/src/modules/stats/stats.service.ts index 0bef7bbe53..081a21a60a 100644 --- a/packages/apps/dashboard/server/src/modules/stats/stats.service.ts +++ b/packages/apps/dashboard/server/src/modules/stats/stats.service.ts @@ -208,8 +208,10 @@ export class StatsService implements OnModuleInit { private async fetchAndCacheHmtDailyStats(date: string) { const from = new Date(date); const to = new Date(dayjs().format('YYYY-MM-DD')); + const dailyData: Record = {}; + const monthlyData: Record = {}; - // Fetch daily data + // Fetch daily data for each network await Promise.all( ( Object.values(MainnetsId).filter( @@ -219,8 +221,6 @@ export class StatsService implements OnModuleInit { const statisticsClient = new StatisticsClient(NETWORKS[network]); let skip = 0; let fetchedRecords: DailyHMTData[] = []; - const dailyData: DailyHMTData[] = []; - const monthlyData: Record = {}; do { fetchedRecords = await statisticsClient.getHMTDailyData({ @@ -230,56 +230,69 @@ export class StatsService implements OnModuleInit { skip, }); - dailyData.push(...fetchedRecords); - skip += 1000; - } while (fetchedRecords.length === 1000); - - // Store daily records - for (const record of dailyData) { - const dailyCacheKey = `${HMT_PREFIX}${ - record.timestamp.toISOString().split('T')[0] - }`; - const dailyCachedData: CachedHMTData = { - totalTransactionAmount: record.totalTransactionAmount.toString(), - totalTransactionCount: record.totalTransactionCount, - dailyUniqueSenders: record.dailyUniqueSenders, - dailyUniqueReceivers: record.dailyUniqueReceivers, - }; - await this.cacheManager.set(dailyCacheKey, dailyCachedData); - - // Prepare for monthly aggregation - const month = dayjs(record.timestamp).format('YYYY-MM'); - if (!monthlyData[month]) { - monthlyData[month] = { - totalTransactionAmount: '0', - totalTransactionCount: 0, - dailyUniqueSenders: 0, - dailyUniqueReceivers: 0, - }; + for (const record of fetchedRecords) { + const dailyCacheKey = `${HMT_PREFIX}${ + record.timestamp.toISOString().split('T')[0] + }`; + + // Sum daily values + if (!dailyData[dailyCacheKey]) { + dailyData[dailyCacheKey] = { + totalTransactionAmount: '0', + totalTransactionCount: 0, + dailyUniqueSenders: 0, + dailyUniqueReceivers: 0, + }; + } + + dailyData[dailyCacheKey].totalTransactionAmount = ( + BigInt(dailyData[dailyCacheKey].totalTransactionAmount) + + BigInt(record.totalTransactionAmount) + ).toString(); + dailyData[dailyCacheKey].totalTransactionCount += + record.totalTransactionCount; + dailyData[dailyCacheKey].dailyUniqueSenders += + record.dailyUniqueSenders; + dailyData[dailyCacheKey].dailyUniqueReceivers += + record.dailyUniqueReceivers; + + // Sum monthly values + const month = dayjs(record.timestamp).format('YYYY-MM'); + if (!monthlyData[month]) { + monthlyData[month] = { + totalTransactionAmount: '0', + totalTransactionCount: 0, + dailyUniqueSenders: 0, + dailyUniqueReceivers: 0, + }; + } + + monthlyData[month].totalTransactionAmount = ( + BigInt(monthlyData[month].totalTransactionAmount) + + BigInt(record.totalTransactionAmount) + ).toString(); + monthlyData[month].totalTransactionCount += + record.totalTransactionCount; + monthlyData[month].dailyUniqueSenders += record.dailyUniqueSenders; + monthlyData[month].dailyUniqueReceivers += + record.dailyUniqueReceivers; } - monthlyData[month].totalTransactionAmount += - record.totalTransactionAmount; - monthlyData[month].totalTransactionCount += - record.totalTransactionCount; - monthlyData[month].dailyUniqueSenders += record.dailyUniqueSenders; - monthlyData[month].dailyUniqueReceivers += - record.dailyUniqueReceivers; - } - - // Store monthly aggregated data - for (const [month, stats] of Object.entries(monthlyData)) { - const monthlyCacheKey = `${HMT_PREFIX}${month}`; - const monthlyCachedData: CachedHMTData = { - totalTransactionAmount: stats.totalTransactionAmount.toString(), - totalTransactionCount: stats.totalTransactionCount, - dailyUniqueSenders: stats.dailyUniqueSenders, - dailyUniqueReceivers: stats.dailyUniqueReceivers, - }; - await this.cacheManager.set(monthlyCacheKey, monthlyCachedData); - } + skip += 1000; + } while (fetchedRecords.length === 1000); }), ); + + // Store daily records + for (const [dailyCacheKey, stats] of Object.entries(dailyData)) { + await this.cacheManager.set(dailyCacheKey, stats); + } + + // Store monthly records + for (const [month, stats] of Object.entries(monthlyData)) { + const monthlyCacheKey = `${HMT_PREFIX}${month}`; + await this.cacheManager.set(monthlyCacheKey, stats); + } } public async hmtPrice(): Promise { From e227f496a0a7614332775a8a3f953f9a79039491 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Francisco=20L=C3=B3pez?= <50665615+flopez7@users.noreply.github.com> Date: Thu, 29 Aug 2024 10:08:43 +0200 Subject: [PATCH 88/89] KVStoreUtils get method error handling (#2440) * KVStoreUtils get method error handling * Fix tests * Remove useless logs * Delete unused logger --- .../src/modules/job/job.service.spec.ts | 3 + .../src/modules/job/job.service.ts | 107 ++++++++++-------- .../server/src/modules/job/job.service.ts | 14 ++- .../qualification.service.spec.ts | 11 -- .../qualification/qualification.service.ts | 16 ++- .../server/src/modules/auth/auth.service.ts | 50 +++++--- .../server/src/modules/user/user.service.ts | 10 +- .../human-protocol-sdk/src/error.ts | 6 + .../human-protocol-sdk/src/kvstore.ts | 3 +- 9 files changed, 132 insertions(+), 88 deletions(-) diff --git a/packages/apps/fortune/recording-oracle/src/modules/job/job.service.spec.ts b/packages/apps/fortune/recording-oracle/src/modules/job/job.service.spec.ts index 3e09e591fc..06e99f2796 100644 --- a/packages/apps/fortune/recording-oracle/src/modules/job/job.service.spec.ts +++ b/packages/apps/fortune/recording-oracle/src/modules/job/job.service.spec.ts @@ -339,6 +339,9 @@ describe('JobService', () => { httpServicePostMock.mockRejectedValueOnce( new Error(ErrorJob.WebhookWasNotSent), ); + KVStoreUtils.get = jest + .fn() + .mockResolvedValueOnce(MOCK_REPUTATION_ORACLE_WEBHOOK_URL); const newSolution: WebhookDto = { escrowAddress: MOCK_ADDRESS, diff --git a/packages/apps/fortune/recording-oracle/src/modules/job/job.service.ts b/packages/apps/fortune/recording-oracle/src/modules/job/job.service.ts index 1105e03224..2f45e1e69f 100644 --- a/packages/apps/fortune/recording-oracle/src/modules/job/job.service.ts +++ b/packages/apps/fortune/recording-oracle/src/modules/job/job.service.ts @@ -182,56 +182,71 @@ export class JobService { recordingOracleSolutions.filter((solution) => !solution.error).length >= submissionsRequired ) { - const reputationOracleAddress = - await escrowClient.getReputationOracleAddress(webhook.escrowAddress); - const reputationOracleWebhook = (await KVStoreUtils.get( - webhook.chainId, - reputationOracleAddress, - KVStoreKeys.webhookUrl, - )) as string; - - await sendWebhook( - this.httpService, - this.logger, - reputationOracleWebhook, - { - chainId: webhook.chainId, - escrowAddress: webhook.escrowAddress, - eventType: EventType.TASK_COMPLETED, - }, - this.web3ConfigService.privateKey, - ); + let reputationOracleWebhook: string | null = null; + try { + const reputationOracleAddress = + await escrowClient.getReputationOracleAddress(webhook.escrowAddress); + reputationOracleWebhook = (await KVStoreUtils.get( + webhook.chainId, + reputationOracleAddress, + KVStoreKeys.webhookUrl, + )) as string; + } catch (e) { + //Ignore the error + } - return 'The requested job is completed.'; + if (reputationOracleWebhook) { + await sendWebhook( + this.httpService, + this.logger, + reputationOracleWebhook, + { + chainId: webhook.chainId, + escrowAddress: webhook.escrowAddress, + eventType: EventType.TASK_COMPLETED, + }, + this.web3ConfigService.privateKey, + ); + + return 'The requested job is completed.'; + } } + if (errorSolutions.length) { - const exchangeOracleURL = (await KVStoreUtils.get( - webhook.chainId, - await escrowClient.getExchangeOracleAddress(webhook.escrowAddress), - KVStoreKeys.webhookUrl, - )) as string; - - const eventData: AssignmentRejection[] = errorSolutions.map( - (solution) => ({ - assigneeId: solution.workerAddress, - reason: solution.error as SolutionError, - }), - ); + let exchangeOracleURL: string | null = null; + try { + exchangeOracleURL = (await KVStoreUtils.get( + webhook.chainId, + await escrowClient.getExchangeOracleAddress(webhook.escrowAddress), + KVStoreKeys.webhookUrl, + )) as string; + } catch { + //Ignore the error + } - const webhookBody: WebhookDto = { - escrowAddress: webhook.escrowAddress, - chainId: webhook.chainId, - eventType: EventType.SUBMISSION_REJECTED, - eventData: { assignments: eventData }, - }; - - await sendWebhook( - this.httpService, - this.logger, - exchangeOracleURL, - webhookBody, - this.web3ConfigService.privateKey, - ); + if (exchangeOracleURL) { + const eventData: AssignmentRejection[] = errorSolutions.map( + (solution) => ({ + assigneeId: solution.workerAddress, + reason: solution.error as SolutionError, + }), + ); + + const webhookBody: WebhookDto = { + escrowAddress: webhook.escrowAddress, + chainId: webhook.chainId, + eventType: EventType.SUBMISSION_REJECTED, + eventData: { assignments: eventData }, + }; + + await sendWebhook( + this.httpService, + this.logger, + exchangeOracleURL, + webhookBody, + this.web3ConfigService.privateKey, + ); + } } return 'Solutions recorded.'; diff --git a/packages/apps/job-launcher/server/src/modules/job/job.service.ts b/packages/apps/job-launcher/server/src/modules/job/job.service.ts index f5b58f1a6f..7f39b8732f 100644 --- a/packages/apps/job-launcher/server/src/modules/job/job.service.ts +++ b/packages/apps/job-launcher/server/src/modules/job/job.service.ts @@ -1570,11 +1570,15 @@ export class JobService { oracleAddress: string, chainId: ChainId, ): Promise { - const feeValue = await KVStoreUtils.get( - chainId, - oracleAddress, - KVStoreKeys.fee, - ); + let feeValue: string | undefined; + + try { + feeValue = await KVStoreUtils.get( + chainId, + oracleAddress, + KVStoreKeys.fee, + ); + } catch {} return BigInt(feeValue ? feeValue : 1); } diff --git a/packages/apps/job-launcher/server/src/modules/qualification/qualification.service.spec.ts b/packages/apps/job-launcher/server/src/modules/qualification/qualification.service.spec.ts index 98297874db..9f2209203c 100644 --- a/packages/apps/job-launcher/server/src/modules/qualification/qualification.service.spec.ts +++ b/packages/apps/job-launcher/server/src/modules/qualification/qualification.service.spec.ts @@ -69,17 +69,6 @@ describe.only('QualificationService', () => { it('should throw a ControlledError when KVStoreUtils.get fails', async () => { (KVStoreUtils.get as any).mockRejectedValue(new Error('KV store error')); - await expect(qualificationService.getQualifications()).rejects.toThrow( - new ControlledError( - ErrorQualification.FailedToFetchQualifications, - HttpStatus.BAD_REQUEST, - ), - ); - }); - - it('should throw a ControlledError when reputation oracle URL is not set', async () => { - (KVStoreUtils.get as any).mockResolvedValue(''); - await expect(qualificationService.getQualifications()).rejects.toThrow( new ControlledError( ErrorWeb3.ReputationOracleUrlNotSet, diff --git a/packages/apps/job-launcher/server/src/modules/qualification/qualification.service.ts b/packages/apps/job-launcher/server/src/modules/qualification/qualification.service.ts index 1266ef6111..3ec850ddff 100644 --- a/packages/apps/job-launcher/server/src/modules/qualification/qualification.service.ts +++ b/packages/apps/job-launcher/server/src/modules/qualification/qualification.service.ts @@ -18,13 +18,17 @@ export class QualificationService { public async getQualifications(): Promise { try { - const reputationOracleUrl = await KVStoreUtils.get( - ChainId.POLYGON_AMOY, - this.web3ConfigService.reputationOracleAddress, - KVStoreKeys.url, - ); + let reputationOracleUrl = ''; + + try { + reputationOracleUrl = await KVStoreUtils.get( + ChainId.POLYGON_AMOY, + this.web3ConfigService.reputationOracleAddress, + KVStoreKeys.url, + ); + } catch {} - if (!reputationOracleUrl) { + if (!reputationOracleUrl || reputationOracleUrl === '') { throw new ControlledError( ErrorWeb3.ReputationOracleUrlNotSet, HttpStatus.BAD_REQUEST, diff --git a/packages/apps/reputation-oracle/server/src/modules/auth/auth.service.ts b/packages/apps/reputation-oracle/server/src/modules/auth/auth.service.ts index 5f9ce69f67..78ded31917 100644 --- a/packages/apps/reputation-oracle/server/src/modules/auth/auth.service.ts +++ b/packages/apps/reputation-oracle/server/src/modules/auth/auth.service.ts @@ -172,17 +172,18 @@ export class AuthService { let status = userEntity.status.toString(); if (userEntity.role === UserRole.OPERATOR && userEntity.evmAddress) { - //Try to fetch status from subgraph, in case the data is not indexed yet, just use status from database. + let operatorStatus: string | undefined; try { - const operatorStatus = await KVStoreUtils.get( + operatorStatus = await KVStoreUtils.get( chainId, this.web3Service.getOperatorAddress(), userEntity.evmAddress.toLowerCase(), ); - if (operatorStatus && operatorStatus !== '') { - status = operatorStatus; - } - } catch (e) {} + } catch {} + + if (operatorStatus && operatorStatus !== '') { + status = operatorStatus; + } } const payload: any = { @@ -196,7 +197,7 @@ export class AuthService { }; if (userEntity.siteKeys && userEntity.siteKeys.length > 0) { - const existingHcaptchaSiteKey = userEntity.siteKeys?.find( + const existingHcaptchaSiteKey = userEntity.siteKeys.find( (key) => key.type === SiteKeyType.HCAPTCHA, ); if (existingHcaptchaSiteKey) { @@ -428,25 +429,48 @@ export class AuthService { const signer = this.web3Service.getSigner(chainId); const kvstore = await KVStoreClient.build(signer); + let role: string | undefined; + try { + role = await KVStoreUtils.get(chainId, data.address, KVStoreKeys.role); + } catch {} + if ( + !role || ![Role.JobLauncher, Role.ExchangeOracle, Role.RecordingOracle].includes( - await KVStoreUtils.get(chainId, data.address, KVStoreKeys.role), + role, ) ) { throw new ControlledError(ErrorAuth.InvalidRole, HttpStatus.BAD_REQUEST); } - if (!(await KVStoreUtils.get(chainId, data.address, KVStoreKeys.fee))) { + let fee: string | undefined; + try { + fee = await KVStoreUtils.get(chainId, data.address, KVStoreKeys.fee); + } catch {} + + if (!fee || fee === '') { throw new ControlledError(ErrorAuth.InvalidFee, HttpStatus.BAD_REQUEST); } - if (!(await KVStoreUtils.get(chainId, data.address, KVStoreKeys.url))) { + let url: string | undefined; + try { + url = await KVStoreUtils.get(chainId, data.address, KVStoreKeys.url); + } catch {} + + if (!url || url === '') { throw new ControlledError(ErrorAuth.InvalidUrl, HttpStatus.BAD_REQUEST); } - if ( - !(await KVStoreUtils.get(chainId, data.address, KVStoreKeys.jobTypes)) - ) { + let jobTypes: string | undefined; + try { + jobTypes = await KVStoreUtils.get( + chainId, + data.address, + KVStoreKeys.jobTypes, + ); + } catch {} + + if (!jobTypes || jobTypes === '') { throw new ControlledError( ErrorAuth.InvalidJobType, HttpStatus.BAD_REQUEST, diff --git a/packages/apps/reputation-oracle/server/src/modules/user/user.service.ts b/packages/apps/reputation-oracle/server/src/modules/user/user.service.ts index b7acf98510..79cb082bb5 100644 --- a/packages/apps/reputation-oracle/server/src/modules/user/user.service.ts +++ b/packages/apps/reputation-oracle/server/src/modules/user/user.service.ts @@ -256,14 +256,12 @@ export class UserService { } const signer = this.web3Service.getSigner(chainId); - const kvstore = await KVStoreClient.build(signer); - const status = await KVStoreUtils.get( - chainId, - signer.address, - user.evmAddress, - ); + let status: string | undefined; + try { + status = await KVStoreUtils.get(chainId, signer.address, user.evmAddress); + } catch {} if (status === OperatorStatus.ACTIVE) { throw new ControlledError( diff --git a/packages/sdk/typescript/human-protocol-sdk/src/error.ts b/packages/sdk/typescript/human-protocol-sdk/src/error.ts index 5da27b2bff..0d4ccd163c 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/error.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/error.ts @@ -345,3 +345,9 @@ export const ErrorUnsupportedStatus = new Error('Unsupported status for query'); */ export const WarnSubgraphApiKeyNotProvided = '"SUBGRAPH_API_KEY" is not being provided. It might cause issues with the subgraph.'; + +export class InvalidKeyError extends Error { + constructor(key: string, address: string) { + super(`Key "${key}" not found for address ${address}`); + } +} diff --git a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts b/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts index f48340babf..2ffde9386c 100644 --- a/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts +++ b/packages/sdk/typescript/human-protocol-sdk/src/kvstore.ts @@ -15,6 +15,7 @@ import { ErrorKVStoreEmptyKey, ErrorProviderDoesNotExist, ErrorUnsupportedChainID, + InvalidKeyError, } from './error'; import gqlFetch from 'graphql-request'; import { NetworkData } from './types'; @@ -406,7 +407,7 @@ export class KVStoreUtils { ); if (!kvstores || kvstores.length === 0) { - return ''; + throw new InvalidKeyError(key, address); } return kvstores[0].value; From cb332956961d44f770d65a8c64d61deae22cc498 Mon Sep 17 00:00:00 2001 From: Dzeranov Date: Thu, 29 Aug 2024 13:18:49 +0300 Subject: [PATCH 89/89] [Oracles][CVAT] Bump human-protocol-sdk version (#2437) * Bumped human-protocol-sdk version * Tests fix * Removed unused method, tests fix * Pin hexbytes dependency, remove unexpected changes * Update poetry lockfiles * Refactor some code --------- Co-authored-by: Maxim Zhiltsov --- .../examples/cvat/exchange-oracle/poetry.lock | 63 +++------ .../cvat/exchange-oracle/pyproject.toml | 3 +- .../cvat/exchange-oracle/src/chain/escrow.py | 15 +-- .../cvat/exchange-oracle/src/chain/kvstore.py | 6 +- .../cvat/exchange-oracle/src/chain/web3.py | 2 +- .../tests/integration/chain/test_kvstore.py | 18 ++- .../cvat/recording-oracle/poetry.lock | 63 +++------ .../cvat/recording-oracle/pyproject.toml | 3 +- .../cvat/recording-oracle/src/chain/escrow.py | 15 +-- .../recording-oracle/src/chain/kvstore.py | 13 +- .../cvat/recording-oracle/src/chain/web3.py | 2 +- .../tests/integration/chain/test_kvstore.py | 120 +++++++----------- .../recording-oracle/tests/utils/constants.py | 5 + 13 files changed, 122 insertions(+), 206 deletions(-) diff --git a/packages/examples/cvat/exchange-oracle/poetry.lock b/packages/examples/cvat/exchange-oracle/poetry.lock index 136c82ed69..4c5324f873 100644 --- a/packages/examples/cvat/exchange-oracle/poetry.lock +++ b/packages/examples/cvat/exchange-oracle/poetry.lock @@ -1032,13 +1032,13 @@ tools = ["hypothesis (>=4.18.2,<5.0.0)"] [[package]] name = "eth-account" -version = "0.10.0" +version = "0.9.0" description = "eth-account: Sign Ethereum transactions and messages with local private keys" optional = false python-versions = ">=3.7, <4" files = [ - {file = "eth-account-0.10.0.tar.gz", hash = "sha256:474a2fccf7286230cf66502565f03b536921d7e1fdfceba198e42160e5ac4bc1"}, - {file = "eth_account-0.10.0-py3-none-any.whl", hash = "sha256:b7a83f506a8edf57926569e5f04471ce3f1700e572d3421b4ad0dad7a26c0978"}, + {file = "eth-account-0.9.0.tar.gz", hash = "sha256:5f66ecb7bc52569924dfaf4a9add501b1c2a4901eec74e3c0598cd26d0971777"}, + {file = "eth_account-0.9.0-py3-none-any.whl", hash = "sha256:35636ca14e9063dea233648703338be1a44e8cb1a2f9de1519d2b1be4655da59"}, ] [package.dependencies] @@ -1048,7 +1048,7 @@ eth-keyfile = ">=0.6.0" eth-keys = ">=0.4.0" eth-rlp = ">=0.3.0" eth-utils = ">=2.0.0" -hexbytes = ">=0.1.0,<0.4.0" +hexbytes = ">=0.1.0" rlp = ">=1.0.0" [package.extras] @@ -1122,20 +1122,20 @@ test = ["asn1tools (>=0.146.2)", "eth-hash[pysha3]", "factory-boy (>=3.0.1)", "h [[package]] name = "eth-rlp" -version = "1.0.1" +version = "2.1.0" description = "eth-rlp: RLP definitions for common Ethereum objects in Python" optional = false python-versions = ">=3.8, <4" files = [ - {file = "eth-rlp-1.0.1.tar.gz", hash = "sha256:d61dbda892ee1220f28fb3663c08f6383c305db9f1f5624dc585c9cd05115027"}, - {file = "eth_rlp-1.0.1-py3-none-any.whl", hash = "sha256:dd76515d71654277377d48876b88e839d61553aaf56952e580bb7cebef2b1517"}, + {file = "eth-rlp-2.1.0.tar.gz", hash = "sha256:d5b408a8cd20ed496e8e66d0559560d29bc21cee482f893936a1f05d0dddc4a0"}, + {file = "eth_rlp-2.1.0-py3-none-any.whl", hash = "sha256:6f476eb7e37d81feaba5d98aed887e467be92648778c44b19fe594aea209cde1"}, ] [package.dependencies] eth-utils = ">=2.0.0" -hexbytes = ">=0.1.0,<1" +hexbytes = ">=1.2.0" rlp = ">=0.6.0" -typing-extensions = {version = ">=4.0.1", markers = "python_version <= \"3.11\""} +typing-extensions = {version = ">=4.0.1", markers = "python_version <= \"3.10\""} [package.extras] dev = ["build (>=0.9.0)", "bumpversion (>=0.5.3)", "eth-hash[pycryptodome]", "ipython", "pre-commit (>=3.4.0)", "pytest (>=7.0.0)", "pytest-xdist (>=2.4.0)", "sphinx (>=6.0.0)", "sphinx-rtd-theme (>=1.0.0)", "towncrier (>=21,<22)", "tox (>=4.0.0)", "twine", "wheel"] @@ -1710,20 +1710,19 @@ numpy = ">=1.17.3" [[package]] name = "hexbytes" -version = "0.3.1" +version = "1.2.1" description = "hexbytes: Python `bytes` subclass that decodes hex, with a readable console output" optional = false -python-versions = ">=3.7, <4" +python-versions = "<4,>=3.8" files = [ - {file = "hexbytes-0.3.1-py3-none-any.whl", hash = "sha256:383595ad75026cf00abd570f44b368c6cdac0c6becfae5c39ff88829877f8a59"}, - {file = "hexbytes-0.3.1.tar.gz", hash = "sha256:a3fe35c6831ee8fafd048c4c086b986075fc14fd46258fa24ecb8d65745f9a9d"}, + {file = "hexbytes-1.2.1-py3-none-any.whl", hash = "sha256:e64890b203a31f4a23ef11470ecfcca565beaee9198df623047df322b757471a"}, + {file = "hexbytes-1.2.1.tar.gz", hash = "sha256:515f00dddf31053db4d0d7636dd16061c1d896c3109b8e751005db4ca46bcca7"}, ] [package.extras] -dev = ["black (>=22)", "bumpversion (>=0.5.3)", "eth-utils (>=1.0.1,<3)", "flake8 (==6.0.0)", "flake8-bugbear (==23.3.23)", "hypothesis (>=3.44.24,<=6.31.6)", "ipython", "isort (>=5.10.1)", "mypy (==0.971)", "pydocstyle (>=5.0.0)", "pytest (>=7.0.0)", "pytest-watch (>=4.1.0)", "pytest-xdist (>=2.4.0)", "sphinx (>=5.0.0)", "sphinx-rtd-theme (>=1.0.0)", "towncrier (>=21,<22)", "tox (>=4.0.0)", "twine", "wheel"] -doc = ["sphinx (>=5.0.0)", "sphinx-rtd-theme (>=1.0.0)", "towncrier (>=21,<22)"] -lint = ["black (>=22)", "flake8 (==6.0.0)", "flake8-bugbear (==23.3.23)", "isort (>=5.10.1)", "mypy (==0.971)", "pydocstyle (>=5.0.0)"] -test = ["eth-utils (>=1.0.1,<3)", "hypothesis (>=3.44.24,<=6.31.6)", "pytest (>=7.0.0)", "pytest-xdist (>=2.4.0)"] +dev = ["build (>=0.9.0)", "bump-my-version (>=0.19.0)", "eth-utils (>=2.0.0)", "hypothesis (>=3.44.24,<=6.31.6)", "ipython", "mypy (==1.10.0)", "pre-commit (>=3.4.0)", "pytest (>=7.0.0)", "pytest-xdist (>=2.4.0)", "sphinx (>=5.3.0)", "sphinx-rtd-theme (>=1.0.0)", "towncrier (>=21,<22)", "tox (>=4.0.0)", "twine", "wheel"] +docs = ["sphinx (>=5.3.0)", "sphinx-rtd-theme (>=1.0.0)", "towncrier (>=21,<22)"] +test = ["eth-utils (>=2.0.0)", "hypothesis (>=3.44.24,<=6.31.6)", "pytest (>=7.0.0)", "pytest-xdist (>=2.4.0)"] [[package]] name = "httpcore" @@ -1771,13 +1770,13 @@ socks = ["socksio (==1.*)"] [[package]] name = "human-protocol-sdk" -version = "3.0.0" +version = "3.0.4" description = "A python library to launch escrow contracts to the HUMAN network." optional = false python-versions = "*" files = [ - {file = "human-protocol-sdk-3.0.0.tar.gz", hash = "sha256:3e5dd6acac30d8121fbdfdf01be7a3f8f3153e2668453b03b25427973d55f02f"}, - {file = "human_protocol_sdk-3.0.0-py3-none-any.whl", hash = "sha256:f75c38f0dc784d199274799b41b81f00ff4941fdd2049ab5ae3677867def46ef"}, + {file = "human-protocol-sdk-3.0.4.tar.gz", hash = "sha256:37ecfdbc74e572daaabd4b6c4439fc4821152a7b36ff9879c5dccbf71fd06c5c"}, + {file = "human_protocol_sdk-3.0.4-py3-none-any.whl", hash = "sha256:6379a27cc489c0761fb8cbc1446b3ee99d3a09217ddb60eb93bcab71361241a8"}, ] [package.dependencies] @@ -2873,8 +2872,6 @@ files = [ {file = "psycopg2-2.9.9-cp310-cp310-win_amd64.whl", hash = "sha256:426f9f29bde126913a20a96ff8ce7d73fd8a216cfb323b1f04da402d452853c3"}, {file = "psycopg2-2.9.9-cp311-cp311-win32.whl", hash = "sha256:ade01303ccf7ae12c356a5e10911c9e1c51136003a9a1d92f7aa9d010fb98372"}, {file = "psycopg2-2.9.9-cp311-cp311-win_amd64.whl", hash = "sha256:121081ea2e76729acfb0673ff33755e8703d45e926e416cb59bae3a86c6a4981"}, - {file = "psycopg2-2.9.9-cp312-cp312-win32.whl", hash = "sha256:d735786acc7dd25815e89cc4ad529a43af779db2e25aa7c626de864127e5a024"}, - {file = "psycopg2-2.9.9-cp312-cp312-win_amd64.whl", hash = "sha256:a7653d00b732afb6fc597e29c50ad28087dcb4fbfb28e86092277a559ae4e693"}, {file = "psycopg2-2.9.9-cp37-cp37m-win32.whl", hash = "sha256:5e0d98cade4f0e0304d7d6f25bbfbc5bd186e07b38eac65379309c4ca3193efa"}, {file = "psycopg2-2.9.9-cp37-cp37m-win_amd64.whl", hash = "sha256:7e2dacf8b009a1c1e843b5213a87f7c544b2b042476ed7755be813eaf4e8347a"}, {file = "psycopg2-2.9.9-cp38-cp38-win32.whl", hash = "sha256:ff432630e510709564c01dafdbe996cb552e0b9f3f065eb89bdce5bd31fabf4c"}, @@ -3597,50 +3594,30 @@ files = [ {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:b42169467c42b692c19cf539c38d4602069d8c1505e97b86387fcf7afb766e1d"}, {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-macosx_13_0_arm64.whl", hash = "sha256:07238db9cbdf8fc1e9de2489a4f68474e70dffcb32232db7c08fa61ca0c7c462"}, {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:fff3573c2db359f091e1589c3d7c5fc2f86f5bdb6f24252c2d8e539d4e45f412"}, - {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-manylinux_2_24_aarch64.whl", hash = "sha256:aa2267c6a303eb483de8d02db2871afb5c5fc15618d894300b88958f729ad74f"}, - {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:840f0c7f194986a63d2c2465ca63af8ccbbc90ab1c6001b1978f05119b5e7334"}, - {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:024cfe1fc7c7f4e1aff4a81e718109e13409767e4f871443cbff3dba3578203d"}, {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-win32.whl", hash = "sha256:c69212f63169ec1cfc9bb44723bf2917cbbd8f6191a00ef3410f5a7fe300722d"}, {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-win_amd64.whl", hash = "sha256:cabddb8d8ead485e255fe80429f833172b4cadf99274db39abc080e068cbcc31"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:bef08cd86169d9eafb3ccb0a39edb11d8e25f3dae2b28f5c52fd997521133069"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-macosx_13_0_arm64.whl", hash = "sha256:b16420e621d26fdfa949a8b4b47ade8810c56002f5389970db4ddda51dbff248"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:25c515e350e5b739842fc3228d662413ef28f295791af5e5110b543cf0b57d9b"}, - {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-manylinux_2_24_aarch64.whl", hash = "sha256:1707814f0d9791df063f8c19bb51b0d1278b8e9a2353abbb676c2f685dee6afe"}, - {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:46d378daaac94f454b3a0e3d8d78cafd78a026b1d71443f4966c696b48a6d899"}, - {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:09b055c05697b38ecacb7ac50bdab2240bfca1a0c4872b0fd309bb07dc9aa3a9"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-win32.whl", hash = "sha256:53a300ed9cea38cf5a2a9b069058137c2ca1ce658a874b79baceb8f892f915a7"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-win_amd64.whl", hash = "sha256:c2a72e9109ea74e511e29032f3b670835f8a59bbdc9ce692c5b4ed91ccf1eedb"}, {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:ebc06178e8821efc9692ea7544aa5644217358490145629914d8020042c24aa1"}, {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-macosx_13_0_arm64.whl", hash = "sha256:edaef1c1200c4b4cb914583150dcaa3bc30e592e907c01117c08b13a07255ec2"}, {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d176b57452ab5b7028ac47e7b3cf644bcfdc8cacfecf7e71759f7f51a59e5c92"}, - {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-manylinux_2_24_aarch64.whl", hash = "sha256:1dc67314e7e1086c9fdf2680b7b6c2be1c0d8e3a8279f2e993ca2a7545fecf62"}, - {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:3213ece08ea033eb159ac52ae052a4899b56ecc124bb80020d9bbceeb50258e9"}, - {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:aab7fd643f71d7946f2ee58cc88c9b7bfc97debd71dcc93e03e2d174628e7e2d"}, - {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-win32.whl", hash = "sha256:5c365d91c88390c8d0a8545df0b5857172824b1c604e867161e6b3d59a827eaa"}, - {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-win_amd64.whl", hash = "sha256:1758ce7d8e1a29d23de54a16ae867abd370f01b5a69e1a3ba75223eaa3ca1a1b"}, {file = "ruamel.yaml.clib-0.2.8-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:a5aa27bad2bb83670b71683aae140a1f52b0857a2deff56ad3f6c13a017a26ed"}, {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:c58ecd827313af6864893e7af0a3bb85fd529f862b6adbefe14643947cfe2942"}, {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-macosx_12_0_arm64.whl", hash = "sha256:f481f16baec5290e45aebdc2a5168ebc6d35189ae6fea7a58787613a25f6e875"}, - {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-manylinux_2_24_aarch64.whl", hash = "sha256:77159f5d5b5c14f7c34073862a6b7d34944075d9f93e681638f6d753606c6ce6"}, {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:7f67a1ee819dc4562d444bbafb135832b0b909f81cc90f7aa00260968c9ca1b3"}, - {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:4ecbf9c3e19f9562c7fdd462e8d18dd902a47ca046a2e64dba80699f0b6c09b7"}, - {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:87ea5ff66d8064301a154b3933ae406b0863402a799b16e4a1d24d9fbbcbe0d3"}, {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-win32.whl", hash = "sha256:75e1ed13e1f9de23c5607fe6bd1aeaae21e523b32d83bb33918245361e9cc51b"}, {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-win_amd64.whl", hash = "sha256:3f215c5daf6a9d7bbed4a0a4f760f3113b10e82ff4c5c44bec20a68c8014f675"}, {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:1b617618914cb00bf5c34d4357c37aa15183fa229b24767259657746c9077615"}, {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-macosx_12_0_arm64.whl", hash = "sha256:a6a9ffd280b71ad062eae53ac1659ad86a17f59a0fdc7699fd9be40525153337"}, - {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-manylinux_2_24_aarch64.whl", hash = "sha256:305889baa4043a09e5b76f8e2a51d4ffba44259f6b4c72dec8ca56207d9c6fe1"}, {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:700e4ebb569e59e16a976857c8798aee258dceac7c7d6b50cab63e080058df91"}, - {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:e2b4c44b60eadec492926a7270abb100ef9f72798e18743939bdbf037aab8c28"}, - {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:e79e5db08739731b0ce4850bed599235d601701d5694c36570a99a0c5ca41a9d"}, {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-win32.whl", hash = "sha256:955eae71ac26c1ab35924203fda6220f84dce57d6d7884f189743e2abe3a9fbe"}, {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-win_amd64.whl", hash = "sha256:56f4252222c067b4ce51ae12cbac231bce32aee1d33fbfc9d17e5b8d6966c312"}, {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:03d1162b6d1df1caa3a4bd27aa51ce17c9afc2046c31b0ad60a0a96ec22f8001"}, {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-macosx_12_0_arm64.whl", hash = "sha256:bba64af9fa9cebe325a62fa398760f5c7206b215201b0ec825005f1b18b9bccf"}, - {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-manylinux_2_24_aarch64.whl", hash = "sha256:a1a45e0bb052edf6a1d3a93baef85319733a888363938e1fc9924cb00c8df24c"}, {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:da09ad1c359a728e112d60116f626cc9f29730ff3e0e7db72b9a2dbc2e4beed5"}, - {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:184565012b60405d93838167f425713180b949e9d8dd0bbc7b49f074407c5a8b"}, - {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:a75879bacf2c987c003368cf14bed0ffe99e8e85acfa6c0bfffc21a090f16880"}, {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-win32.whl", hash = "sha256:84b554931e932c46f94ab306913ad7e11bba988104c5cff26d90d03f68258cd5"}, {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-win_amd64.whl", hash = "sha256:25ac8c08322002b06fa1d49d1646181f0b2c72f5cbc15a85e80b4c30a544bb15"}, {file = "ruamel.yaml.clib-0.2.8.tar.gz", hash = "sha256:beb2e0404003de9a4cab9753a8805a8fe9320ee6673136ed7f04255fe60bb512"}, @@ -4337,4 +4314,4 @@ multidict = ">=4.0" [metadata] lock-version = "2.0" python-versions = "^3.10,<3.13" -content-hash = "cca3e02a568c585382d045430da0c2d18234634f2a86bb81a12b6cad52ef226e" +content-hash = "b712896e193904e263c976c5caea68fe5e47bb16ec5c63f867a40d965acced1e" diff --git a/packages/examples/cvat/exchange-oracle/pyproject.toml b/packages/examples/cvat/exchange-oracle/pyproject.toml index bcca6ac50b..9f5cd3631b 100644 --- a/packages/examples/cvat/exchange-oracle/pyproject.toml +++ b/packages/examples/cvat/exchange-oracle/pyproject.toml @@ -19,12 +19,13 @@ pytest = "^7.2.2" cvat-sdk = "2.6.0" sqlalchemy = "^2.0.16" apscheduler = "^3.10.1" -human-protocol-sdk = "^3.0.0" xmltodict = "^0.13.0" datumaro = {git = "https://github.com/cvat-ai/datumaro.git", rev = "ff83c00c2c1bc4b8fdfcc55067fcab0a9b5b6b11"} boto3 = "^1.28.33" google-cloud-storage = "^2.14.0" pyinstrument = "^4.6.2" +human-protocol-sdk = "^3.0.4" +hexbytes = ">=1.2.0" # required for to_0x_hex() function [tool.poetry.group.dev.dependencies] diff --git a/packages/examples/cvat/exchange-oracle/src/chain/escrow.py b/packages/examples/cvat/exchange-oracle/src/chain/escrow.py index 1d76214f59..f8ccd86338 100644 --- a/packages/examples/cvat/exchange-oracle/src/chain/escrow.py +++ b/packages/examples/cvat/exchange-oracle/src/chain/escrow.py @@ -1,7 +1,7 @@ import json from human_protocol_sdk.constants import ChainId, Status -from human_protocol_sdk.encryption import Encryption +from human_protocol_sdk.encryption import Encryption, EncryptionUtils from human_protocol_sdk.escrow import EscrowData, EscrowUtils from human_protocol_sdk.storage import StorageUtils @@ -46,8 +46,7 @@ def get_escrow_manifest(chain_id: int, escrow_address: str) -> dict: manifest_content = StorageUtils.download_file_from_url(escrow.manifest_url).decode("utf-8") - # if EncryptionUtils.is_encrypted(manifest_content): - if is_data_encrypted(manifest_content): + if EncryptionUtils.is_encrypted(manifest_content): encryption = Encryption( Config.encryption_config.pgp_private_key, passphrase=Config.encryption_config.pgp_passphrase, @@ -66,13 +65,3 @@ def get_recording_oracle_address(chain_id: int, escrow_address: str) -> str: return address return get_escrow(chain_id, escrow_address).recording_oracle - - -# FUTURE-TODO: workaround until a new Human Protocol SDK version is released. -# Check wether data is encrypted without adding new dependencies (like PGPy) to Exchange Oracle. -# Should be replaced with EncryptionUtils.is_encrypted method. -def is_data_encrypted(data: str) -> bool: - normalized_data = data.strip() - return normalized_data.startswith("-----BEGIN PGP MESSAGE-----") and normalized_data.endswith( - "-----END PGP MESSAGE-----" - ) diff --git a/packages/examples/cvat/exchange-oracle/src/chain/kvstore.py b/packages/examples/cvat/exchange-oracle/src/chain/kvstore.py index 7545fe7a93..1a71d0bc2b 100644 --- a/packages/examples/cvat/exchange-oracle/src/chain/kvstore.py +++ b/packages/examples/cvat/exchange-oracle/src/chain/kvstore.py @@ -1,5 +1,5 @@ from human_protocol_sdk.constants import ChainId, KVStoreKeys -from human_protocol_sdk.kvstore import KVStoreClient, KVStoreClientError +from human_protocol_sdk.kvstore import KVStoreClient, KVStoreClientError, KVStoreUtils from human_protocol_sdk.operator import OperatorUtils from src.chain.escrow import get_escrow @@ -33,8 +33,8 @@ def register_in_kvstore() -> None: kvstore_public_key_url = None try: - kvstore_public_key_url = kvstore_client.get_file_url_and_verify_hash( - network_config.addr, KVStoreKeys.public_key.value + kvstore_public_key_url = KVStoreUtils.get_file_url_and_verify_hash( + network_config.chain_id, network_config.addr, KVStoreKeys.public_key.value ) except KVStoreClientError as ex: if "Invalid hash" not in str(ex): diff --git a/packages/examples/cvat/exchange-oracle/src/chain/web3.py b/packages/examples/cvat/exchange-oracle/src/chain/web3.py index e76f77bf95..82db46e9bd 100644 --- a/packages/examples/cvat/exchange-oracle/src/chain/web3.py +++ b/packages/examples/cvat/exchange-oracle/src/chain/web3.py @@ -65,7 +65,7 @@ def sign_message(chain_id: Networks, message) -> str: encode_defunct(text=serialized_message), private_key ) - return signed_message.signature.hex(), serialized_message + return signed_message.signature.to_0x_hex(), serialized_message def recover_signer(chain_id: Networks, message, signature: str) -> str: diff --git a/packages/examples/cvat/exchange-oracle/tests/integration/chain/test_kvstore.py b/packages/examples/cvat/exchange-oracle/tests/integration/chain/test_kvstore.py index b2c26160f1..00d264b560 100644 --- a/packages/examples/cvat/exchange-oracle/tests/integration/chain/test_kvstore.py +++ b/packages/examples/cvat/exchange-oracle/tests/integration/chain/test_kvstore.py @@ -4,7 +4,7 @@ import pytest from human_protocol_sdk.constants import ChainId, Status from human_protocol_sdk.escrow import EscrowClientError, EscrowData -from human_protocol_sdk.kvstore import KVStoreClient, KVStoreClientError +from human_protocol_sdk.kvstore import KVStoreClientError, KVStoreUtils from src.chain.kvstore import get_job_launcher_url, get_recording_oracle_url, register_in_kvstore from src.core.config import LocalhostConfig @@ -127,7 +127,7 @@ def set_file_url_and_hash(url: str, key: str): "src.core.config.Config.encryption_config.pgp_public_key_url", PGP_PUBLIC_KEY_URL_1 ), patch( - "human_protocol_sdk.kvstore.KVStoreClient.get_file_url_and_verify_hash", + "human_protocol_sdk.kvstore.KVStoreUtils.get_file_url_and_verify_hash", get_file_url_and_verify_hash, ), patch("src.core.config.LocalhostConfig.is_configured") as mock_localhost_configured, @@ -136,8 +136,10 @@ def set_file_url_and_hash(url: str, key: str): mock_localhost_configured.return_value = True mock_web3.return_value = self.w3 - kvstore_client = KVStoreClient(self.w3) - assert kvstore_client.get_file_url_and_verify_hash(LocalhostConfig.addr) is None + assert ( + KVStoreUtils.get_file_url_and_verify_hash(ChainId.LOCALHOST, LocalhostConfig.addr) + is None + ) # check that public key will be set to KVStore at first time with patch( @@ -147,7 +149,9 @@ def set_file_url_and_hash(url: str, key: str): register_in_kvstore() mock_set_file_url_and_hash.assert_called_once() assert ( - kvstore_client.get_file_url_and_verify_hash(LocalhostConfig.addr) + KVStoreUtils.get_file_url_and_verify_hash( + ChainId.LOCALHOST, LocalhostConfig.addr + ) == PGP_PUBLIC_KEY_URL_1 ) @@ -185,6 +189,8 @@ def set_file_url_and_hash(url: str, key: str): register_in_kvstore() mock_set_file_url_and_hash.assert_called_once() assert ( - kvstore_client.get_file_url_and_verify_hash(LocalhostConfig.addr) + KVStoreUtils.get_file_url_and_verify_hash( + ChainId.LOCALHOST, LocalhostConfig.addr + ) == PGP_PUBLIC_KEY_URL_2 ) diff --git a/packages/examples/cvat/recording-oracle/poetry.lock b/packages/examples/cvat/recording-oracle/poetry.lock index 8d5acb95b5..fa456351f3 100644 --- a/packages/examples/cvat/recording-oracle/poetry.lock +++ b/packages/examples/cvat/recording-oracle/poetry.lock @@ -1006,13 +1006,13 @@ tools = ["hypothesis (>=4.18.2,<5.0.0)"] [[package]] name = "eth-account" -version = "0.10.0" +version = "0.9.0" description = "eth-account: Sign Ethereum transactions and messages with local private keys" optional = false python-versions = ">=3.7, <4" files = [ - {file = "eth-account-0.10.0.tar.gz", hash = "sha256:474a2fccf7286230cf66502565f03b536921d7e1fdfceba198e42160e5ac4bc1"}, - {file = "eth_account-0.10.0-py3-none-any.whl", hash = "sha256:b7a83f506a8edf57926569e5f04471ce3f1700e572d3421b4ad0dad7a26c0978"}, + {file = "eth-account-0.9.0.tar.gz", hash = "sha256:5f66ecb7bc52569924dfaf4a9add501b1c2a4901eec74e3c0598cd26d0971777"}, + {file = "eth_account-0.9.0-py3-none-any.whl", hash = "sha256:35636ca14e9063dea233648703338be1a44e8cb1a2f9de1519d2b1be4655da59"}, ] [package.dependencies] @@ -1022,7 +1022,7 @@ eth-keyfile = ">=0.6.0" eth-keys = ">=0.4.0" eth-rlp = ">=0.3.0" eth-utils = ">=2.0.0" -hexbytes = ">=0.1.0,<0.4.0" +hexbytes = ">=0.1.0" rlp = ">=1.0.0" [package.extras] @@ -1096,20 +1096,20 @@ test = ["asn1tools (>=0.146.2)", "eth-hash[pysha3]", "factory-boy (>=3.0.1)", "h [[package]] name = "eth-rlp" -version = "1.0.1" +version = "2.1.0" description = "eth-rlp: RLP definitions for common Ethereum objects in Python" optional = false python-versions = ">=3.8, <4" files = [ - {file = "eth-rlp-1.0.1.tar.gz", hash = "sha256:d61dbda892ee1220f28fb3663c08f6383c305db9f1f5624dc585c9cd05115027"}, - {file = "eth_rlp-1.0.1-py3-none-any.whl", hash = "sha256:dd76515d71654277377d48876b88e839d61553aaf56952e580bb7cebef2b1517"}, + {file = "eth-rlp-2.1.0.tar.gz", hash = "sha256:d5b408a8cd20ed496e8e66d0559560d29bc21cee482f893936a1f05d0dddc4a0"}, + {file = "eth_rlp-2.1.0-py3-none-any.whl", hash = "sha256:6f476eb7e37d81feaba5d98aed887e467be92648778c44b19fe594aea209cde1"}, ] [package.dependencies] eth-utils = ">=2.0.0" -hexbytes = ">=0.1.0,<1" +hexbytes = ">=1.2.0" rlp = ">=0.6.0" -typing-extensions = {version = ">=4.0.1", markers = "python_version <= \"3.11\""} +typing-extensions = {version = ">=4.0.1", markers = "python_version <= \"3.10\""} [package.extras] dev = ["build (>=0.9.0)", "bumpversion (>=0.5.3)", "eth-hash[pycryptodome]", "ipython", "pre-commit (>=3.4.0)", "pytest (>=7.0.0)", "pytest-xdist (>=2.4.0)", "sphinx (>=6.0.0)", "sphinx-rtd-theme (>=1.0.0)", "towncrier (>=21,<22)", "tox (>=4.0.0)", "twine", "wheel"] @@ -1674,20 +1674,19 @@ numpy = ">=1.17.3" [[package]] name = "hexbytes" -version = "0.3.1" +version = "1.2.1" description = "hexbytes: Python `bytes` subclass that decodes hex, with a readable console output" optional = false -python-versions = ">=3.7, <4" +python-versions = "<4,>=3.8" files = [ - {file = "hexbytes-0.3.1-py3-none-any.whl", hash = "sha256:383595ad75026cf00abd570f44b368c6cdac0c6becfae5c39ff88829877f8a59"}, - {file = "hexbytes-0.3.1.tar.gz", hash = "sha256:a3fe35c6831ee8fafd048c4c086b986075fc14fd46258fa24ecb8d65745f9a9d"}, + {file = "hexbytes-1.2.1-py3-none-any.whl", hash = "sha256:e64890b203a31f4a23ef11470ecfcca565beaee9198df623047df322b757471a"}, + {file = "hexbytes-1.2.1.tar.gz", hash = "sha256:515f00dddf31053db4d0d7636dd16061c1d896c3109b8e751005db4ca46bcca7"}, ] [package.extras] -dev = ["black (>=22)", "bumpversion (>=0.5.3)", "eth-utils (>=1.0.1,<3)", "flake8 (==6.0.0)", "flake8-bugbear (==23.3.23)", "hypothesis (>=3.44.24,<=6.31.6)", "ipython", "isort (>=5.10.1)", "mypy (==0.971)", "pydocstyle (>=5.0.0)", "pytest (>=7.0.0)", "pytest-watch (>=4.1.0)", "pytest-xdist (>=2.4.0)", "sphinx (>=5.0.0)", "sphinx-rtd-theme (>=1.0.0)", "towncrier (>=21,<22)", "tox (>=4.0.0)", "twine", "wheel"] -doc = ["sphinx (>=5.0.0)", "sphinx-rtd-theme (>=1.0.0)", "towncrier (>=21,<22)"] -lint = ["black (>=22)", "flake8 (==6.0.0)", "flake8-bugbear (==23.3.23)", "isort (>=5.10.1)", "mypy (==0.971)", "pydocstyle (>=5.0.0)"] -test = ["eth-utils (>=1.0.1,<3)", "hypothesis (>=3.44.24,<=6.31.6)", "pytest (>=7.0.0)", "pytest-xdist (>=2.4.0)"] +dev = ["build (>=0.9.0)", "bump-my-version (>=0.19.0)", "eth-utils (>=2.0.0)", "hypothesis (>=3.44.24,<=6.31.6)", "ipython", "mypy (==1.10.0)", "pre-commit (>=3.4.0)", "pytest (>=7.0.0)", "pytest-xdist (>=2.4.0)", "sphinx (>=5.3.0)", "sphinx-rtd-theme (>=1.0.0)", "towncrier (>=21,<22)", "tox (>=4.0.0)", "twine", "wheel"] +docs = ["sphinx (>=5.3.0)", "sphinx-rtd-theme (>=1.0.0)", "towncrier (>=21,<22)"] +test = ["eth-utils (>=2.0.0)", "hypothesis (>=3.44.24,<=6.31.6)", "pytest (>=7.0.0)", "pytest-xdist (>=2.4.0)"] [[package]] name = "httpcore" @@ -1735,13 +1734,13 @@ socks = ["socksio (==1.*)"] [[package]] name = "human-protocol-sdk" -version = "3.0.0" +version = "3.0.4" description = "A python library to launch escrow contracts to the HUMAN network." optional = false python-versions = "*" files = [ - {file = "human-protocol-sdk-3.0.0.tar.gz", hash = "sha256:3e5dd6acac30d8121fbdfdf01be7a3f8f3153e2668453b03b25427973d55f02f"}, - {file = "human_protocol_sdk-3.0.0-py3-none-any.whl", hash = "sha256:f75c38f0dc784d199274799b41b81f00ff4941fdd2049ab5ae3677867def46ef"}, + {file = "human-protocol-sdk-3.0.4.tar.gz", hash = "sha256:37ecfdbc74e572daaabd4b6c4439fc4821152a7b36ff9879c5dccbf71fd06c5c"}, + {file = "human_protocol_sdk-3.0.4-py3-none-any.whl", hash = "sha256:6379a27cc489c0761fb8cbc1446b3ee99d3a09217ddb60eb93bcab71361241a8"}, ] [package.dependencies] @@ -2869,8 +2868,6 @@ files = [ {file = "psycopg2-2.9.9-cp310-cp310-win_amd64.whl", hash = "sha256:426f9f29bde126913a20a96ff8ce7d73fd8a216cfb323b1f04da402d452853c3"}, {file = "psycopg2-2.9.9-cp311-cp311-win32.whl", hash = "sha256:ade01303ccf7ae12c356a5e10911c9e1c51136003a9a1d92f7aa9d010fb98372"}, {file = "psycopg2-2.9.9-cp311-cp311-win_amd64.whl", hash = "sha256:121081ea2e76729acfb0673ff33755e8703d45e926e416cb59bae3a86c6a4981"}, - {file = "psycopg2-2.9.9-cp312-cp312-win32.whl", hash = "sha256:d735786acc7dd25815e89cc4ad529a43af779db2e25aa7c626de864127e5a024"}, - {file = "psycopg2-2.9.9-cp312-cp312-win_amd64.whl", hash = "sha256:a7653d00b732afb6fc597e29c50ad28087dcb4fbfb28e86092277a559ae4e693"}, {file = "psycopg2-2.9.9-cp37-cp37m-win32.whl", hash = "sha256:5e0d98cade4f0e0304d7d6f25bbfbc5bd186e07b38eac65379309c4ca3193efa"}, {file = "psycopg2-2.9.9-cp37-cp37m-win_amd64.whl", hash = "sha256:7e2dacf8b009a1c1e843b5213a87f7c544b2b042476ed7755be813eaf4e8347a"}, {file = "psycopg2-2.9.9-cp38-cp38-win32.whl", hash = "sha256:ff432630e510709564c01dafdbe996cb552e0b9f3f065eb89bdce5bd31fabf4c"}, @@ -3517,50 +3514,30 @@ files = [ {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:b42169467c42b692c19cf539c38d4602069d8c1505e97b86387fcf7afb766e1d"}, {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-macosx_13_0_arm64.whl", hash = "sha256:07238db9cbdf8fc1e9de2489a4f68474e70dffcb32232db7c08fa61ca0c7c462"}, {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:fff3573c2db359f091e1589c3d7c5fc2f86f5bdb6f24252c2d8e539d4e45f412"}, - {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-manylinux_2_24_aarch64.whl", hash = "sha256:aa2267c6a303eb483de8d02db2871afb5c5fc15618d894300b88958f729ad74f"}, - {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:840f0c7f194986a63d2c2465ca63af8ccbbc90ab1c6001b1978f05119b5e7334"}, - {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:024cfe1fc7c7f4e1aff4a81e718109e13409767e4f871443cbff3dba3578203d"}, {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-win32.whl", hash = "sha256:c69212f63169ec1cfc9bb44723bf2917cbbd8f6191a00ef3410f5a7fe300722d"}, {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-win_amd64.whl", hash = "sha256:cabddb8d8ead485e255fe80429f833172b4cadf99274db39abc080e068cbcc31"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:bef08cd86169d9eafb3ccb0a39edb11d8e25f3dae2b28f5c52fd997521133069"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-macosx_13_0_arm64.whl", hash = "sha256:b16420e621d26fdfa949a8b4b47ade8810c56002f5389970db4ddda51dbff248"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:25c515e350e5b739842fc3228d662413ef28f295791af5e5110b543cf0b57d9b"}, - {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-manylinux_2_24_aarch64.whl", hash = "sha256:1707814f0d9791df063f8c19bb51b0d1278b8e9a2353abbb676c2f685dee6afe"}, - {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:46d378daaac94f454b3a0e3d8d78cafd78a026b1d71443f4966c696b48a6d899"}, - {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:09b055c05697b38ecacb7ac50bdab2240bfca1a0c4872b0fd309bb07dc9aa3a9"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-win32.whl", hash = "sha256:53a300ed9cea38cf5a2a9b069058137c2ca1ce658a874b79baceb8f892f915a7"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-win_amd64.whl", hash = "sha256:c2a72e9109ea74e511e29032f3b670835f8a59bbdc9ce692c5b4ed91ccf1eedb"}, {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:ebc06178e8821efc9692ea7544aa5644217358490145629914d8020042c24aa1"}, {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-macosx_13_0_arm64.whl", hash = "sha256:edaef1c1200c4b4cb914583150dcaa3bc30e592e907c01117c08b13a07255ec2"}, {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d176b57452ab5b7028ac47e7b3cf644bcfdc8cacfecf7e71759f7f51a59e5c92"}, - {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-manylinux_2_24_aarch64.whl", hash = "sha256:1dc67314e7e1086c9fdf2680b7b6c2be1c0d8e3a8279f2e993ca2a7545fecf62"}, - {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:3213ece08ea033eb159ac52ae052a4899b56ecc124bb80020d9bbceeb50258e9"}, - {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:aab7fd643f71d7946f2ee58cc88c9b7bfc97debd71dcc93e03e2d174628e7e2d"}, - {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-win32.whl", hash = "sha256:5c365d91c88390c8d0a8545df0b5857172824b1c604e867161e6b3d59a827eaa"}, - {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-win_amd64.whl", hash = "sha256:1758ce7d8e1a29d23de54a16ae867abd370f01b5a69e1a3ba75223eaa3ca1a1b"}, {file = "ruamel.yaml.clib-0.2.8-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:a5aa27bad2bb83670b71683aae140a1f52b0857a2deff56ad3f6c13a017a26ed"}, {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:c58ecd827313af6864893e7af0a3bb85fd529f862b6adbefe14643947cfe2942"}, {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-macosx_12_0_arm64.whl", hash = "sha256:f481f16baec5290e45aebdc2a5168ebc6d35189ae6fea7a58787613a25f6e875"}, - {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-manylinux_2_24_aarch64.whl", hash = "sha256:77159f5d5b5c14f7c34073862a6b7d34944075d9f93e681638f6d753606c6ce6"}, {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:7f67a1ee819dc4562d444bbafb135832b0b909f81cc90f7aa00260968c9ca1b3"}, - {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:4ecbf9c3e19f9562c7fdd462e8d18dd902a47ca046a2e64dba80699f0b6c09b7"}, - {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:87ea5ff66d8064301a154b3933ae406b0863402a799b16e4a1d24d9fbbcbe0d3"}, {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-win32.whl", hash = "sha256:75e1ed13e1f9de23c5607fe6bd1aeaae21e523b32d83bb33918245361e9cc51b"}, {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-win_amd64.whl", hash = "sha256:3f215c5daf6a9d7bbed4a0a4f760f3113b10e82ff4c5c44bec20a68c8014f675"}, {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:1b617618914cb00bf5c34d4357c37aa15183fa229b24767259657746c9077615"}, {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-macosx_12_0_arm64.whl", hash = "sha256:a6a9ffd280b71ad062eae53ac1659ad86a17f59a0fdc7699fd9be40525153337"}, - {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-manylinux_2_24_aarch64.whl", hash = "sha256:305889baa4043a09e5b76f8e2a51d4ffba44259f6b4c72dec8ca56207d9c6fe1"}, {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:700e4ebb569e59e16a976857c8798aee258dceac7c7d6b50cab63e080058df91"}, - {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:e2b4c44b60eadec492926a7270abb100ef9f72798e18743939bdbf037aab8c28"}, - {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:e79e5db08739731b0ce4850bed599235d601701d5694c36570a99a0c5ca41a9d"}, {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-win32.whl", hash = "sha256:955eae71ac26c1ab35924203fda6220f84dce57d6d7884f189743e2abe3a9fbe"}, {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-win_amd64.whl", hash = "sha256:56f4252222c067b4ce51ae12cbac231bce32aee1d33fbfc9d17e5b8d6966c312"}, {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:03d1162b6d1df1caa3a4bd27aa51ce17c9afc2046c31b0ad60a0a96ec22f8001"}, {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-macosx_12_0_arm64.whl", hash = "sha256:bba64af9fa9cebe325a62fa398760f5c7206b215201b0ec825005f1b18b9bccf"}, - {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-manylinux_2_24_aarch64.whl", hash = "sha256:a1a45e0bb052edf6a1d3a93baef85319733a888363938e1fc9924cb00c8df24c"}, {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:da09ad1c359a728e112d60116f626cc9f29730ff3e0e7db72b9a2dbc2e4beed5"}, - {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:184565012b60405d93838167f425713180b949e9d8dd0bbc7b49f074407c5a8b"}, - {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:a75879bacf2c987c003368cf14bed0ffe99e8e85acfa6c0bfffc21a090f16880"}, {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-win32.whl", hash = "sha256:84b554931e932c46f94ab306913ad7e11bba988104c5cff26d90d03f68258cd5"}, {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-win_amd64.whl", hash = "sha256:25ac8c08322002b06fa1d49d1646181f0b2c72f5cbc15a85e80b4c30a544bb15"}, {file = "ruamel.yaml.clib-0.2.8.tar.gz", hash = "sha256:beb2e0404003de9a4cab9753a8805a8fe9320ee6673136ed7f04255fe60bb512"}, @@ -4175,4 +4152,4 @@ multidict = ">=4.0" [metadata] lock-version = "2.0" python-versions = "^3.10, <3.13" -content-hash = "eba0dfb48ad8e340536c8dc20a91fb5f1511e15d6c45438197d99ee79a72e85a" +content-hash = "f7c0a21b763dbb8dd24c096598743cdb0f243558bec5a786093f2f6bcc70366d" diff --git a/packages/examples/cvat/recording-oracle/pyproject.toml b/packages/examples/cvat/recording-oracle/pyproject.toml index 2e504f6678..eb7e0a550e 100644 --- a/packages/examples/cvat/recording-oracle/pyproject.toml +++ b/packages/examples/cvat/recording-oracle/pyproject.toml @@ -15,13 +15,14 @@ SQLAlchemy = "^2.0.17" psycopg2 = "^2.9.6" APScheduler = "^3.10.1" pytest = "^7.4.0" -human-protocol-sdk = "^3.0.0" alembic = "^1.11.1" httpx = "^0.24.1" numpy = "^1.25.2" boto3 = "^1.28.40" google-cloud-storage = "^2.14.0" datumaro = {git = "https://github.com/cvat-ai/datumaro.git", rev = "ff83c00c2c1bc4b8fdfcc55067fcab0a9b5b6b11"} +human-protocol-sdk = "^3.0.4" +hexbytes = ">=1.2.0" # required for to_0x_hex() function [tool.poetry.group.dev.dependencies] hypothesis = "^6.82.6" diff --git a/packages/examples/cvat/recording-oracle/src/chain/escrow.py b/packages/examples/cvat/recording-oracle/src/chain/escrow.py index 5651f21e3c..5306a7c583 100644 --- a/packages/examples/cvat/recording-oracle/src/chain/escrow.py +++ b/packages/examples/cvat/recording-oracle/src/chain/escrow.py @@ -1,7 +1,7 @@ import json from human_protocol_sdk.constants import ChainId, Status -from human_protocol_sdk.encryption import Encryption +from human_protocol_sdk.encryption import Encryption, EncryptionUtils from human_protocol_sdk.escrow import EscrowClient, EscrowData, EscrowUtils from human_protocol_sdk.storage import StorageUtils @@ -47,8 +47,7 @@ def get_escrow_manifest(chain_id: int, escrow_address: str) -> dict: manifest_content = StorageUtils.download_file_from_url(escrow.manifest_url).decode("utf-8") - # if EncryptionUtils.is_encrypted(manifest_content): - if is_data_encrypted(manifest_content): + if EncryptionUtils.is_encrypted(manifest_content): encryption = Encryption( Config.encryption_config.pgp_private_key, Config.encryption_config.pgp_passphrase, @@ -71,13 +70,3 @@ def get_reputation_oracle_address(chain_id: int, escrow_address: str) -> str: def get_exchange_oracle_address(chain_id: int, escrow_address: str) -> str: return get_escrow(chain_id, escrow_address).exchange_oracle - - -# FUTURE-TODO: workaround until a new Human Protocol SDK version is released. -# Check wether data is encrypted without adding new dependencies (like PGPy) to Recording Oracle. -# Should be replaced with EncryptionUtils.is_encrypted method. -def is_data_encrypted(data: str) -> bool: - normalized_data = data.strip() - return normalized_data.startswith("-----BEGIN PGP MESSAGE-----") and normalized_data.endswith( - "-----END PGP MESSAGE-----" - ) diff --git a/packages/examples/cvat/recording-oracle/src/chain/kvstore.py b/packages/examples/cvat/recording-oracle/src/chain/kvstore.py index 0d7c763914..2aa00fc50d 100644 --- a/packages/examples/cvat/recording-oracle/src/chain/kvstore.py +++ b/packages/examples/cvat/recording-oracle/src/chain/kvstore.py @@ -1,5 +1,5 @@ from human_protocol_sdk.constants import ChainId, KVStoreKeys -from human_protocol_sdk.kvstore import KVStoreClient, KVStoreClientError +from human_protocol_sdk.kvstore import KVStoreClient, KVStoreClientError, KVStoreUtils from human_protocol_sdk.operator import OperatorUtils from src.chain.escrow import get_escrow @@ -7,13 +7,6 @@ from src.core.config import Config -def get_role_by_address(chain_id: int, address: str) -> str: - web3 = get_web3(chain_id) - kvstore_client = KVStoreClient(web3) - - return kvstore_client.get(address, "role") - - def get_exchange_oracle_url(chain_id: int, escrow_address: str) -> str: if url := Config.localhost.exchange_oracle_url: return url @@ -40,8 +33,8 @@ def register_in_kvstore() -> None: kvstore_public_key_url = None try: - kvstore_public_key_url = kvstore_client.get_file_url_and_verify_hash( - network_config.addr, KVStoreKeys.public_key.value + kvstore_public_key_url = KVStoreUtils.get_file_url_and_verify_hash( + network_config.chain_id, network_config.addr, KVStoreKeys.public_key.value ) except KVStoreClientError as ex: if "Invalid hash" not in str(ex): diff --git a/packages/examples/cvat/recording-oracle/src/chain/web3.py b/packages/examples/cvat/recording-oracle/src/chain/web3.py index e76f77bf95..82db46e9bd 100644 --- a/packages/examples/cvat/recording-oracle/src/chain/web3.py +++ b/packages/examples/cvat/recording-oracle/src/chain/web3.py @@ -65,7 +65,7 @@ def sign_message(chain_id: Networks, message) -> str: encode_defunct(text=serialized_message), private_key ) - return signed_message.signature.hex(), serialized_message + return signed_message.signature.to_0x_hex(), serialized_message def recover_signer(chain_id: Networks, message, signature: str) -> str: diff --git a/packages/examples/cvat/recording-oracle/tests/integration/chain/test_kvstore.py b/packages/examples/cvat/recording-oracle/tests/integration/chain/test_kvstore.py index 081221c3d0..fc61acf4ce 100644 --- a/packages/examples/cvat/recording-oracle/tests/integration/chain/test_kvstore.py +++ b/packages/examples/cvat/recording-oracle/tests/integration/chain/test_kvstore.py @@ -2,98 +2,70 @@ from unittest.mock import MagicMock, Mock, patch import pytest -from human_protocol_sdk.escrow import EscrowClientError -from human_protocol_sdk.kvstore import KVStoreClient, KVStoreClientError -from web3 import HTTPProvider, Web3 -from web3.middleware import construct_sign_and_send_raw_middleware +from human_protocol_sdk.constants import ChainId, Status +from human_protocol_sdk.escrow import EscrowClientError, EscrowData +from human_protocol_sdk.kvstore import KVStoreClientError, KVStoreUtils -from src.chain.kvstore import get_reputation_oracle_url, get_role_by_address, register_in_kvstore +from src.chain.kvstore import get_reputation_oracle_url, register_in_kvstore from src.core.config import LocalhostConfig from tests.utils.constants import ( - DEFAULT_GAS_PAYER_PRIV, DEFAULT_MANIFEST_URL, + ESCROW_ADDRESS, + FACTORY_ADDRESS, + JOB_LAUNCHER_ADDRESS, REPUTATION_ORACLE_ADDRESS, + REPUTATION_ORACLE_WEBHOOK_URL, + TOKEN_ADDRESS, ) -from tests.utils.setup_escrow import create_escrow -from tests.utils.setup_kvstore import store_kvstore_value + +escrow_address = ESCROW_ADDRESS class ServiceIntegrationTest(unittest.TestCase): def setUp(self): - self.w3 = Web3(HTTPProvider()) - - # Set default gas payer - self.gas_payer = self.w3.eth.account.from_key(DEFAULT_GAS_PAYER_PRIV) - self.w3.middleware_onion.add( - construct_sign_and_send_raw_middleware(self.gas_payer), - "construct_sign_and_send_raw_middleware", + self.w3 = Mock() + self.w3.eth.chain_id = ChainId.LOCALHOST.value + self.escrow_data = EscrowData( + chain_id=ChainId.LOCALHOST.name, + id=1, + address=escrow_address, + amount_paid=100, + balance=100, + count=0, + factory_address=FACTORY_ADDRESS, + launcher=JOB_LAUNCHER_ADDRESS, + status=Status.Pending.name, + token=TOKEN_ADDRESS, + total_funded_amount=1000, + created_at="", + manifest_url=DEFAULT_MANIFEST_URL, + reputation_oracle=REPUTATION_ORACLE_ADDRESS, ) - self.w3.eth.default_account = self.gas_payer.address def test_get_reputation_oracle_url(self): - escrow_address = create_escrow(self.w3) - store_kvstore_value("webhook_url", DEFAULT_MANIFEST_URL) - with ( - patch("src.chain.kvstore.get_web3") as mock_get_web3, - patch("src.chain.kvstore.get_escrow") as mock_get_escrow, + patch("src.chain.kvstore.get_escrow") as mock_escrow, patch("src.chain.kvstore.OperatorUtils.get_leader") as mock_leader, ): - mock_get_web3.return_value = self.w3 - mock_escrow = Mock() - mock_escrow.reputationOracle = REPUTATION_ORACLE_ADDRESS - mock_get_escrow.return_value = mock_escrow - mock_leader.return_value = MagicMock(webhook_url=DEFAULT_MANIFEST_URL) - + mock_escrow.return_value = self.escrow_data + mock_leader.return_value = MagicMock(webhook_url=REPUTATION_ORACLE_WEBHOOK_URL) reputation_url = get_reputation_oracle_url(self.w3.eth.chain_id, escrow_address) - assert reputation_url == DEFAULT_MANIFEST_URL + assert reputation_url == REPUTATION_ORACLE_WEBHOOK_URL def test_get_reputation_oracle_url_invalid_escrow(self): - with patch("src.chain.kvstore.get_web3") as mock_function: - mock_function.return_value = self.w3 - with pytest.raises(EscrowClientError, match="Invalid escrow address: "): - get_reputation_oracle_url(self.w3.eth.chain_id, "invalid_address") + with pytest.raises(EscrowClientError, match="Invalid escrow address: invalid_address"): + get_reputation_oracle_url(self.w3.eth.chain_id, "invalid_address") def test_get_reputation_oracle_url_invalid_address(self): - create_escrow(self.w3) - store_kvstore_value("webhook_url", "") with ( - patch("src.chain.kvstore.get_web3") as mock_get_web3, - patch("src.chain.kvstore.get_escrow") as mock_get_escrow, + patch("src.chain.kvstore.get_escrow") as mock_escrow, patch("src.chain.kvstore.OperatorUtils.get_leader") as mock_leader, ): - mock_get_web3.return_value = self.w3 - mock_escrow = Mock() - mock_escrow.reputation_oracle = REPUTATION_ORACLE_ADDRESS - mock_get_escrow.return_value = mock_escrow + mock_escrow.return_value = self.escrow_data mock_leader.return_value = MagicMock(webhook_url="") - - reputation_url = get_reputation_oracle_url( - self.w3.eth.chain_id, REPUTATION_ORACLE_ADDRESS - ) - assert reputation_url == "" - - def test_get_role_by_address(self): - store_kvstore_value("role", "Reputation Oracle") - with patch("src.chain.kvstore.get_web3") as mock_function: - mock_function.return_value = self.w3 - reputation_url = get_role_by_address(self.w3.eth.chain_id, REPUTATION_ORACLE_ADDRESS) - assert reputation_url == "Reputation Oracle" - - def test_get_role_by_address_invalid_escrow(self): - with patch("src.chain.kvstore.get_web3") as mock_function: - mock_function.return_value = self.w3 - with pytest.raises(KVStoreClientError, match="Invalid address: invalid_address"): - get_role_by_address(self.w3.eth.chain_id, "invalid_address") - - def test_get_role_by_address_invalid_address(self): - create_escrow(self.w3) - store_kvstore_value("role", "") - with patch("src.chain.kvstore.get_web3") as mock_function: - mock_function.return_value = self.w3 - reputation_url = get_role_by_address(self.w3.eth.chain_id, REPUTATION_ORACLE_ADDRESS) - assert reputation_url == "" + recording_url = get_reputation_oracle_url(self.w3.eth.chain_id, escrow_address) + assert recording_url == "" def test_store_public_key(self): PGP_PUBLIC_KEY_URL_1 = "http://pgp-public-key-url-1" @@ -130,7 +102,7 @@ def set_file_url_and_hash(url: str, key: str): "src.core.config.Config.encryption_config.pgp_public_key_url", PGP_PUBLIC_KEY_URL_1 ), patch( - "human_protocol_sdk.kvstore.KVStoreClient.get_file_url_and_verify_hash", + "human_protocol_sdk.kvstore.KVStoreUtils.get_file_url_and_verify_hash", get_file_url_and_verify_hash, ), patch("src.core.config.LocalhostConfig.is_configured") as mock_localhost_configured, @@ -139,8 +111,10 @@ def set_file_url_and_hash(url: str, key: str): mock_localhost_configured.return_value = True mock_web3.return_value = self.w3 - kvstore_client = KVStoreClient(self.w3) - assert kvstore_client.get_file_url_and_verify_hash(LocalhostConfig.addr) is None + assert ( + KVStoreUtils.get_file_url_and_verify_hash(ChainId.LOCALHOST, LocalhostConfig.addr) + is None + ) # check that public key will be set to KVStore at first time with patch( @@ -150,7 +124,9 @@ def set_file_url_and_hash(url: str, key: str): register_in_kvstore() mock_set_file_url_and_hash.assert_called_once() assert ( - kvstore_client.get_file_url_and_verify_hash(LocalhostConfig.addr) + KVStoreUtils.get_file_url_and_verify_hash( + ChainId.LOCALHOST, LocalhostConfig.addr + ) == PGP_PUBLIC_KEY_URL_1 ) @@ -188,6 +164,8 @@ def set_file_url_and_hash(url: str, key: str): register_in_kvstore() mock_set_file_url_and_hash.assert_called_once() assert ( - kvstore_client.get_file_url_and_verify_hash(LocalhostConfig.addr) + KVStoreUtils.get_file_url_and_verify_hash( + ChainId(self.w3.eth.chain_id), LocalhostConfig.addr + ) == PGP_PUBLIC_KEY_URL_2 ) diff --git a/packages/examples/cvat/recording-oracle/tests/utils/constants.py b/packages/examples/cvat/recording-oracle/tests/utils/constants.py index 2df6f087da..75c05b1b14 100644 --- a/packages/examples/cvat/recording-oracle/tests/utils/constants.py +++ b/packages/examples/cvat/recording-oracle/tests/utils/constants.py @@ -11,6 +11,11 @@ REPUTATION_ORACLE_PRIV = "5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a" REPUTATION_ORACLE_FEE = 10 +ESCROW_ADDRESS = "0x9965507D1a55bcC2695C58ba16FB37d819B0A4dc" +TOKEN_ADDRESS = "0x976EA74026E726554dB657fA54763abd0C3a0aa9" +FACTORY_ADDRESS = "0x14dC79964da2C08b23698B3D3cc7Ca32193d9955" +JOB_LAUNCHER_ADDRESS = "0x15d34AAf54267DB7D7c367839AAf71A00a2C6A65" + EXCHANGE_ORACLE_ADDRESS = "0x90F79bf6EB2c4f870365E785982E1f101E93b906" EXCHANGE_ORACLE_FEE = 10