@prosopo/procaptcha 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +13 -0
  2. package/dist/api/ProsopoContract.d.ts +2 -1
  3. package/dist/api/ProsopoContract.d.ts.map +1 -1
  4. package/dist/api/ProsopoContract.js +4 -0
  5. package/dist/api/ProsopoContract.js.map +1 -1
  6. package/dist/modules/ProsopoCaptchaClient.d.ts +1 -0
  7. package/dist/modules/ProsopoCaptchaClient.d.ts.map +1 -1
  8. package/dist/modules/ProsopoCaptchaClient.js +2 -0
  9. package/dist/modules/ProsopoCaptchaClient.js.map +1 -1
  10. package/dist/modules/ProsopoCaptchaStateClient.d.ts.map +1 -1
  11. package/dist/modules/ProsopoCaptchaStateClient.js +9 -2
  12. package/dist/modules/ProsopoCaptchaStateClient.js.map +1 -1
  13. package/dist/types/api.d.ts +4 -0
  14. package/dist/types/api.d.ts.map +1 -1
  15. package/dist/types/client.d.ts +1 -1
  16. package/dist/types/client.d.ts.map +1 -1
  17. package/img/contracts-page.png +0 -0
  18. package/package.json +2 -2
  19. package/tsconfig.tsbuildinfo +1 -0
  20. package/src/api/AsyncFactory.ts +0 -30
  21. package/src/api/Extension.ts +0 -120
  22. package/src/api/HttpClientBase.ts +0 -37
  23. package/src/api/ProsopoContract.ts +0 -42
  24. package/src/api/ProsopoContractBase.ts +0 -169
  25. package/src/api/ProviderApi.ts +0 -59
  26. package/src/api/handlers.ts +0 -29
  27. package/src/api/index.ts +0 -21
  28. package/src/index.ts +0 -18
  29. package/src/modules/ProsopoCaptchaApi.ts +0 -105
  30. package/src/modules/ProsopoCaptchaClient.ts +0 -132
  31. package/src/modules/ProsopoCaptchaStateClient.ts +0 -146
  32. package/src/modules/client.ts +0 -39
  33. package/src/modules/contract.ts +0 -27
  34. package/src/modules/extension.ts +0 -20
  35. package/src/modules/index.ts +0 -22
  36. package/src/modules/storage.ts +0 -35
  37. package/src/types/api.ts +0 -80
  38. package/src/types/client.ts +0 -88
  39. package/src/types/contract.ts +0 -21
  40. package/src/types/index.ts +0 -18
  41. package/tests/mocks/browser.ts +0 -25
  42. package/tests/modules/client.test.ts +0 -56
@@ -1,30 +0,0 @@
1
- // Copyright (C) 2021-2022 Prosopo (UK) Ltd.
2
- // This file is part of procaptcha <https://github.com/prosopo-io/procaptcha>.
3
- //
4
- // procaptcha is free software: you can redistribute it and/or modify
5
- // it under the terms of the GNU General Public License as published by
6
- // the Free Software Foundation, either version 3 of the License, or
7
- // (at your option) any later version.
8
- //
9
- // procaptcha is distributed in the hope that it will be useful,
10
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
- // GNU General Public License for more details.
13
- //
14
- // You should have received a copy of the GNU General Public License
15
- // along with procaptcha. If not, see <http://www.gnu.org/licenses/>.
16
- export abstract class AsyncFactory {
17
-
18
- constructor() {
19
- throw new Error("Use `create` factory method");
20
- }
21
-
22
- public static async create(...args: any[]) {
23
- return await Object.create(this.prototype).init(...args);
24
- }
25
-
26
- public abstract init(...args: any[]): Promise<this>;
27
-
28
- }
29
-
30
- export default AsyncFactory;
@@ -1,120 +0,0 @@
1
- // Copyright (C) 2021-2022 Prosopo (UK) Ltd.
2
- // This file is part of procaptcha <https://github.com/prosopo-io/procaptcha>.
3
- //
4
- // procaptcha is free software: you can redistribute it and/or modify
5
- // it under the terms of the GNU General Public License as published by
6
- // the Free Software Foundation, either version 3 of the License, or
7
- // (at your option) any later version.
8
- //
9
- // procaptcha is distributed in the hope that it will be useful,
10
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
- // GNU General Public License for more details.
13
- //
14
- // You should have received a copy of the GNU General Public License
15
- // along with procaptcha. If not, see <http://www.gnu.org/licenses/>.
16
- import { web3Enable, web3FromSource, web3Accounts } from "@polkadot/extension-dapp";
17
- import { InjectedAccountWithMeta, InjectedExtension } from "@polkadot/extension-inject/types"
18
- import { SignerPayloadRaw } from "@polkadot/types/types";
19
- import storage from "../modules/storage";
20
- import { IExtensionInterface } from "../types/client";
21
- import AsyncFactory from "./AsyncFactory";
22
-
23
-
24
- export class Extension extends AsyncFactory implements IExtensionInterface {
25
-
26
- private extension: InjectedExtension;
27
- private account: InjectedAccountWithMeta | undefined;
28
- private accounts: InjectedAccountWithMeta[];
29
- private injectedExtensions: InjectedExtension[];
30
-
31
- public async init() {
32
- await this.checkExtension();
33
- await this.setAccounts();
34
- await this.setExtension();
35
- return this;
36
- }
37
-
38
- public async checkExtension() {
39
- try {
40
- this.injectedExtensions = await web3Enable('Prosopo');
41
- } catch (err) {
42
- throw new Error(err);
43
- }
44
- if (!this.injectedExtensions.length) {
45
- throw new Error("No extension found");
46
- }
47
- }
48
-
49
- public getExtension() {
50
- return this.extension;
51
- }
52
-
53
- private async setExtension() {
54
- try {
55
- // https://polkadot.js.org/docs/extension/cookbook/
56
- this.extension = await web3FromSource(this.accounts[0].meta.source);
57
- } catch (err) {
58
- throw new Error(err);
59
- }
60
- if (!this.extension) {
61
- throw new Error("Extension not found");
62
- }
63
- }
64
-
65
- public getAccounts() {
66
- return this.accounts;
67
- }
68
-
69
- private async setAccounts() {
70
- try {
71
- this.accounts = await web3Accounts();
72
- } catch (err) {
73
- throw new Error(err);
74
- }
75
- this.setDefaultAccount();
76
- }
77
-
78
- public getAccount() {
79
- return this.account;
80
- }
81
-
82
- public setAccount(address: string) {
83
- if (!this.accounts.length) {
84
- throw new Error("No accounts found");
85
- }
86
- const account = this.accounts.find(acc => acc.address === address);
87
- if (!account) {
88
- throw new Error("Account not found");
89
- }
90
- this.account = account;
91
- storage.setAccount(account.address);
92
- }
93
-
94
- public unsetAccount() {
95
- this.account = undefined;
96
- storage.setAccount("");
97
- }
98
-
99
- public getDefaultAccount() {
100
- const defaultAccount = storage.getAccount();
101
- return this.accounts.find(acc => acc.address === defaultAccount);
102
- }
103
-
104
- public setDefaultAccount() {
105
- const defaultAccount = storage.getAccount();
106
- if (defaultAccount) {
107
- this.setAccount(defaultAccount);
108
- }
109
- }
110
-
111
- // public async signRaw(raw: SignerPayloadRaw) {
112
- // if (!this.extension.signer) {
113
- // throw new Error("No signer found");
114
- // }
115
- // return this.extension.signer?.signRaw!({ ...raw, address: this.account!.address });
116
- // }
117
-
118
- }
119
-
120
- export default Extension;
@@ -1,37 +0,0 @@
1
- // Copyright (C) 2021-2022 Prosopo (UK) Ltd.
2
- // This file is part of procaptcha <https://github.com/prosopo-io/procaptcha>.
3
- //
4
- // procaptcha is free software: you can redistribute it and/or modify
5
- // it under the terms of the GNU General Public License as published by
6
- // the Free Software Foundation, either version 3 of the License, or
7
- // (at your option) any later version.
8
- //
9
- // procaptcha is distributed in the hope that it will be useful,
10
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
- // GNU General Public License for more details.
13
- //
14
- // You should have received a copy of the GNU General Public License
15
- // along with procaptcha. If not, see <http://www.gnu.org/licenses/>.
16
- import axios, { AxiosInstance, AxiosResponse } from "axios";
17
-
18
- export class HttpClientBase {
19
-
20
- protected readonly axios: AxiosInstance;
21
-
22
- constructor(baseURL: string, prefix = "") {
23
- baseURL = baseURL + prefix;
24
- this.axios = axios.create({ baseURL });
25
- this.axios.interceptors.response.use(this.responseHandler, this.errorHandler);
26
- }
27
-
28
- protected responseHandler = (response: AxiosResponse) => {
29
- console.log("API REQUEST", response.request);
30
- return response.data;
31
- }
32
-
33
- protected errorHandler = (error: any) => Promise.reject(error.response);
34
-
35
- }
36
-
37
- export default HttpClientBase;
@@ -1,42 +0,0 @@
1
- // Copyright (C) 2021-2022 Prosopo (UK) Ltd.
2
- // This file is part of procaptcha <https://github.com/prosopo-io/procaptcha>.
3
- //
4
- // procaptcha is free software: you can redistribute it and/or modify
5
- // it under the terms of the GNU General Public License as published by
6
- // the Free Software Foundation, either version 3 of the License, or
7
- // (at your option) any later version.
8
- //
9
- // procaptcha is distributed in the hope that it will be useful,
10
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
- // GNU General Public License for more details.
13
- //
14
- // You should have received a copy of the GNU General Public License
15
- // along with procaptcha. If not, see <http://www.gnu.org/licenses/>.
16
- // import {Hash} from '@polkadot/types/interfaces';
17
- import ProsopoContractBase from "./ProsopoContractBase";
18
- import { Signer } from '@polkadot/api/types';
19
- import { TransactionResponse } from '../types';
20
- import { ProsopoRandomProviderResponse } from "../types";
21
- import { CaptchaSolutionCommitment } from "@prosopo/contract";
22
-
23
- // TODO: import return types from provider: separate types/common package.
24
- export class ProsopoContract extends ProsopoContractBase {
25
-
26
- public async getRandomProvider(): Promise<ProsopoRandomProviderResponse> {
27
- return await this.query('getRandomActiveProvider', [this.account.address, this.dappAddress]) as ProsopoRandomProviderResponse;
28
- }
29
-
30
- public async getCaptchaSolutionCommitment(commitmentId: string) {
31
- return await this.query('getCaptchaSolutionCommitment', [commitmentId]) as CaptchaSolutionCommitment;
32
- }
33
-
34
- public async dappUserCommit(signer: Signer, captchaDatasetId: string, userMerkleTreeRoot: string, providerAddress: string): Promise<TransactionResponse> {
35
- return await this.transaction(signer, 'dappUserCommit', [this.dappAddress, captchaDatasetId, userMerkleTreeRoot, providerAddress]);
36
- }
37
-
38
-
39
-
40
- }
41
-
42
- export default ProsopoContract;
@@ -1,169 +0,0 @@
1
- // Copyright (C) 2021-2022 Prosopo (UK) Ltd.
2
- // This file is part of procaptcha <https://github.com/prosopo-io/procaptcha>.
3
- //
4
- // procaptcha is free software: you can redistribute it and/or modify
5
- // it under the terms of the GNU General Public License as published by
6
- // the Free Software Foundation, either version 3 of the License, or
7
- // (at your option) any later version.
8
- //
9
- // procaptcha is distributed in the hope that it will be useful,
10
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
- // GNU General Public License for more details.
13
- //
14
- // You should have received a copy of the GNU General Public License
15
- // along with procaptcha. If not, see <http://www.gnu.org/licenses/>.
16
- import { ApiPromise, SubmittableResult } from "@polkadot/api";
17
- import { Abi, ContractPromise } from "@polkadot/api-contract";
18
- import { InjectedAccountWithMeta } from "@polkadot/extension-inject/types";
19
-
20
- import { abiJson, unwrap, encodeStringArgs, ProsopoContractError } from "@prosopo/contract";
21
- import { AnyJson } from "@polkadot/types/types/codec";
22
- import { ProviderInterface } from "@polkadot/rpc-provider/types";
23
- import { Signer } from "@polkadot/api/types";
24
- import { TransactionResponse } from '../types';
25
- import AsyncFactory from "./AsyncFactory";
26
-
27
- export class ProsopoContractBase extends AsyncFactory {
28
-
29
- protected api: ApiPromise;
30
- protected abi: Abi;
31
- protected contract: ContractPromise;
32
- protected account: InjectedAccountWithMeta;
33
- protected dappAddress: string;
34
-
35
- public address: string;
36
-
37
- /**
38
- * @param address
39
- * @param dappAddress
40
- * @param account
41
- * @param providerInterface
42
- */
43
- public async init(address: string, dappAddress: string, account: InjectedAccountWithMeta, providerInterface: ProviderInterface) {
44
- this.api = await ApiPromise.create({ provider: providerInterface });
45
- this.abi = new Abi(abiJson, this.api.registry.getChainProperties());
46
- this.contract = new ContractPromise(this.api, this.abi, address);
47
- this.address = address;
48
- this.dappAddress = dappAddress;
49
- this.account = account;
50
- return this;
51
- }
52
-
53
- public getApi(): ApiPromise {
54
- return this.api;
55
- }
56
-
57
- public getContract(): ContractPromise {
58
- return this.contract;
59
- }
60
-
61
- public getAccount(): InjectedAccountWithMeta {
62
- return this.account;
63
- }
64
-
65
- public getDappAddress(): string {
66
- return this.dappAddress;
67
- }
68
-
69
- public async query<T>(method: string, args: any[]): Promise<T | AnyJson | null> {
70
- try {
71
- const abiMessage = this.abi.findMessage(method);
72
- const response = await this.contract.query[method](
73
- this.account.address,
74
- {},
75
- ...encodeStringArgs(abiMessage, args)
76
- );
77
- console.log("QUERY RESPONSE", method, args, response);
78
- if (response.result.isOk) {
79
- if (response.output) {
80
- return unwrap(response.output.toHuman());
81
- } else {
82
- return null;
83
- }
84
- } else {
85
- throw new ProsopoContractError(response.result.asErr);
86
- }
87
- } catch (e) {
88
- console.error("ERROR", e);
89
- return null;
90
- }
91
- }
92
-
93
- // https://polkadot.js.org/docs/api/cookbook/tx/
94
- // https://polkadot.js.org/docs/api/start/api.tx.subs/
95
- public async transaction(signer: Signer, method: string, args: any[]): Promise<TransactionResponse> {
96
-
97
- // TODO if DEBUG==true || env.development
98
- const queryBeforeTx = await this.query(method, args);
99
-
100
- console.log("QUERY BEFORE TX....................", queryBeforeTx);
101
-
102
- const abiMessage = this.abi.findMessage(method);
103
-
104
- const extrinsic = this.contract.tx[method]({}, ...encodeStringArgs(abiMessage, args));
105
-
106
- // this.api.setSigner(signer);
107
- // const response = await buildTx(this.api.registry, extrinsic, this.account.address, { signer });
108
- // console.log("buildTx RESPONSE", response);
109
- // return;
110
-
111
- return new Promise((resolve, reject) => {
112
-
113
- extrinsic.signAndSend(this.account.address, { signer }, (result: SubmittableResult) => {
114
-
115
- const { dispatchError, dispatchInfo, events, internalError, status, txHash, txIndex } = result;
116
-
117
- console.log("TX STATUS", status.type);
118
- console.log("IS FINALIZED", status?.isFinalized);
119
- console.log("IN BLOCK", status?.isInBlock);
120
- console.log("EVENTS", events);
121
-
122
- if (internalError) {
123
- console.error("internalError", internalError);
124
- reject(internalError);
125
-
126
- return;
127
- }
128
-
129
- if (dispatchError) {
130
- console.error("dispatchError", dispatchError);
131
- reject(dispatchError);
132
-
133
- return;
134
- }
135
-
136
- // [Ready, InBlock, Finalized...]
137
-
138
- // Instant seal ON.
139
- if (status?.isInBlock) {
140
-
141
- const blockHash = status.asInBlock.toHex();
142
-
143
- resolve({ dispatchError, dispatchInfo, events, internalError, status, txHash, txIndex, blockHash });
144
-
145
- }
146
-
147
- // TODO
148
- // Instant seal OFF.
149
- // if (status?.isFinalized) {
150
-
151
- // const blockHash = status.asFinalized.toHex();
152
-
153
- // resolve({ dispatchError, dispatchInfo, events, internalError, status, txHash, txIndex, blockHash });
154
-
155
- // }
156
-
157
- })
158
- .catch((e) => {
159
- console.error("signAndSend ERROR", e);
160
- reject(e);
161
- });
162
-
163
- });
164
-
165
- }
166
-
167
- }
168
-
169
- export default ProsopoContractBase;
@@ -1,59 +0,0 @@
1
- // Copyright (C) 2021-2022 Prosopo (UK) Ltd.
2
- // This file is part of procaptcha <https://github.com/prosopo-io/procaptcha>.
3
- //
4
- // procaptcha is free software: you can redistribute it and/or modify
5
- // it under the terms of the GNU General Public License as published by
6
- // the Free Software Foundation, either version 3 of the License, or
7
- // (at your option) any later version.
8
- //
9
- // procaptcha is distributed in the hope that it will be useful,
10
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
- // GNU General Public License for more details.
13
- //
14
- // You should have received a copy of the GNU General Public License
15
- // along with procaptcha. If not, see <http://www.gnu.org/licenses/>.
16
- import HttpClientBase from "./HttpClientBase";
17
- import Storage from "../modules/storage";
18
- import { ProsopoCaptchaConfig, ProsopoRandomProviderResponse, GetCaptchaResponse, CaptchaSolution, CaptchaSolutionResponse } from '../types';
19
-
20
- export class ProviderApi extends HttpClientBase {
21
-
22
- protected config: ProsopoCaptchaConfig;
23
-
24
- constructor(config: ProsopoCaptchaConfig) {
25
- super(config['providerApi.baseURL'], config['providerApi.prefix']);
26
- this.config = config;
27
- }
28
-
29
- /**
30
- *
31
- * @deprecated use ProsopoContract$getRandomProvider instead.
32
- */
33
- public getRandomProvider() {
34
- const userAccount = Storage.getAccount();
35
- return this.axios.get(`/random_provider/${userAccount}/${this.config['dappAccount']}`);
36
- }
37
-
38
- public getProviders(): Promise<{accounts: string[]}> {
39
- return this.axios.get(`/providers`);
40
- }
41
-
42
- public getContractAddress(): Promise<{contractAddress: string}> {
43
- return this.axios.get(`/contract_address`);
44
- }
45
-
46
- public getCaptchaChallenge(randomProvider: ProsopoRandomProviderResponse) : Promise<GetCaptchaResponse> {
47
- let { provider, blockNumber } = randomProvider;
48
- blockNumber = blockNumber.replace(/,/g, ''); // TODO: middleware schema parser/validator.
49
- const userAccount = Storage.getAccount();
50
- return this.axios.get(`/provider/captcha/${provider.captchaDatasetId}/${userAccount}/${this.config['dappAccount']}/${blockNumber}`);
51
- }
52
-
53
- public submitCaptchaSolution(blockHash: string, captchas: CaptchaSolution[], requestHash: string, txHash: string, userAccount: string) : Promise<CaptchaSolutionResponse> {
54
- return this.axios.post(`/provider/solution`, {blockHash, captchas, requestHash, txHash, userAccount, dappAccount: this.config['dappAccount']});
55
- }
56
-
57
- }
58
-
59
- export default ProviderApi;
@@ -1,29 +0,0 @@
1
- // Copyright (C) 2021-2022 Prosopo (UK) Ltd.
2
- // This file is part of procaptcha <https://github.com/prosopo-io/procaptcha>.
3
- //
4
- // procaptcha is free software: you can redistribute it and/or modify
5
- // it under the terms of the GNU General Public License as published by
6
- // the Free Software Foundation, either version 3 of the License, or
7
- // (at your option) any later version.
8
- //
9
- // procaptcha is distributed in the hope that it will be useful,
10
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
- // GNU General Public License for more details.
13
- //
14
- // You should have received a copy of the GNU General Public License
15
- // along with procaptcha. If not, see <http://www.gnu.org/licenses/>.
16
- import {AxiosResponse} from "axios";
17
-
18
- export class ProsopoApiError extends Error {
19
- constructor(error: AxiosResponse, context?: string, ...params: any[]) {
20
-
21
- super(`${error.data.message ? error.data.message : error.statusText}`)
22
-
23
- this.name = context && `${ProsopoApiError.name}@${context}` || ProsopoApiError.name;
24
-
25
- // TODO: if env.debug
26
- console.error('\n********************* ERROR *********************\n');
27
- console.error(this.cause, this.stack, ...params);
28
- }
29
- }
package/src/api/index.ts DELETED
@@ -1,21 +0,0 @@
1
- // Copyright (C) 2021-2022 Prosopo (UK) Ltd.
2
- // This file is part of procaptcha <https://github.com/prosopo-io/procaptcha>.
3
- //
4
- // procaptcha is free software: you can redistribute it and/or modify
5
- // it under the terms of the GNU General Public License as published by
6
- // the Free Software Foundation, either version 3 of the License, or
7
- // (at your option) any later version.
8
- //
9
- // procaptcha is distributed in the hope that it will be useful,
10
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
- // GNU General Public License for more details.
13
- //
14
- // You should have received a copy of the GNU General Public License
15
- // along with procaptcha. If not, see <http://www.gnu.org/licenses/>.
16
- export * from './AsyncFactory';
17
- export * from './Extension';
18
- export * from './HttpClientBase';
19
- export * from './ProsopoContract';
20
- export * from './ProsopoContractBase';
21
- export * from './ProviderApi';
package/src/index.ts DELETED
@@ -1,18 +0,0 @@
1
- // Copyright (C) 2021-2022 Prosopo (UK) Ltd.
2
- // This file is part of procaptcha <https://github.com/prosopo-io/procaptcha>.
3
- //
4
- // procaptcha is free software: you can redistribute it and/or modify
5
- // it under the terms of the GNU General Public License as published by
6
- // the Free Software Foundation, either version 3 of the License, or
7
- // (at your option) any later version.
8
- //
9
- // procaptcha is distributed in the hope that it will be useful,
10
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
- // GNU General Public License for more details.
13
- //
14
- // You should have received a copy of the GNU General Public License
15
- // along with procaptcha. If not, see <http://www.gnu.org/licenses/>.
16
- export * from './api';
17
- export * from './modules';
18
- export * from './types';
@@ -1,105 +0,0 @@
1
- // Copyright (C) 2021-2022 Prosopo (UK) Ltd.
2
- // This file is part of procaptcha <https://github.com/prosopo-io/procaptcha>.
3
- //
4
- // procaptcha is free software: you can redistribute it and/or modify
5
- // it under the terms of the GNU General Public License as published by
6
- // the Free Software Foundation, either version 3 of the License, or
7
- // (at your option) any later version.
8
- //
9
- // procaptcha is distributed in the hope that it will be useful,
10
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
- // GNU General Public License for more details.
13
- //
14
- // You should have received a copy of the GNU General Public License
15
- // along with procaptcha. If not, see <http://www.gnu.org/licenses/>.
16
- import { randomAsHex, blake2AsHex } from '@polkadot/util-crypto';
17
- // import {computeCaptchaSolutionHash} from '@prosopo/provider'; // TODO
18
- import { CaptchaSolution, CaptchaMerkleTree, CaptchaSolutionCommitment } from '@prosopo/contract';
19
- import { Signer } from "@polkadot/api/types";
20
-
21
- import { ProsopoRandomProviderResponse, GetCaptchaResponse, CaptchaSolutionResponse } from "../types/api";
22
- import { TransactionResponse } from "../types/contract";
23
-
24
- import ProviderApi from "../api/ProviderApi";
25
- import ProsopoContract from "../api/ProsopoContract";
26
- import { TCaptchaSubmitResult } from '../types/client';
27
- import {ProsopoApiError} from "../api/handlers";
28
-
29
-
30
- function hexHash(data: string | Uint8Array): string {
31
- return blake2AsHex(data);
32
- }
33
-
34
- function computeCaptchaSolutionHash(captcha: CaptchaSolution) {
35
- return hexHash([captcha.captchaId, captcha.solution, captcha.salt].join());
36
- }
37
-
38
- export class ProsopoCaptchaApi {
39
-
40
- protected contract: ProsopoContract;
41
- protected provider: ProsopoRandomProviderResponse;
42
- protected providerApi: ProviderApi;
43
-
44
- constructor(contract: ProsopoContract, provider: ProsopoRandomProviderResponse, providerApi: ProviderApi) {
45
- this.contract = contract;
46
- this.provider = provider;
47
- this.providerApi = providerApi;
48
- }
49
-
50
- public async getCaptchaChallenge(): Promise<GetCaptchaResponse> {
51
- let captchaChallenge: GetCaptchaResponse;
52
- try {
53
- captchaChallenge = await this.providerApi.getCaptchaChallenge(this.provider);
54
- } catch (err) {
55
- throw new ProsopoApiError(err)
56
- }
57
- return captchaChallenge;
58
- }
59
-
60
- public async submitCaptchaSolution(signer: Signer, requestHash: string, datasetId: string, solutions: CaptchaSolution[]) : Promise<TCaptchaSubmitResult> {
61
- const salt = randomAsHex();
62
- const tree = new CaptchaMerkleTree();
63
- const captchaSolutionsSalted: CaptchaSolution[] = solutions.map(solution => ({...solution, salt: salt}));
64
- const captchasHashed = captchaSolutionsSalted.map((captcha) => computeCaptchaSolutionHash(captcha));
65
-
66
- tree.build(captchasHashed);
67
- const commitmentId = tree.root!.hash;
68
-
69
- console.log("solveCaptchaChallenge commitmentId", commitmentId);
70
- // console.log("solveCaptchaChallenge USER ACCOUNT", this.contract.getAccount().address);
71
- // console.log("solveCaptchaChallenge DAPP ACCOUNT", this.contract.getDappAddress());
72
- // console.log("solveCaptchaChallenge CONTRACT ADDRESS", this.contract.getContract().address.toString());
73
-
74
- let tx: TransactionResponse;
75
-
76
- try {
77
- tx = await this.contract.dappUserCommit(signer, datasetId as string, commitmentId, this.provider.providerId);
78
- } catch (err) {
79
- throw new ProsopoApiError(err)
80
- }
81
-
82
- let result: CaptchaSolutionResponse;
83
-
84
- try {
85
- result = await this.providerApi.submitCaptchaSolution(tx.blockHash!, captchaSolutionsSalted, requestHash, tx.txHash.toString(), this.contract.getAccount().address);
86
- } catch (err) {
87
- throw new ProsopoApiError(err)
88
- }
89
-
90
- let commitment: CaptchaSolutionCommitment;
91
-
92
- // TODO concurrency?
93
- try {
94
- commitment = await this.contract.getCaptchaSolutionCommitment(commitmentId);
95
- } catch (err) {
96
- throw new ProsopoApiError(err)
97
- }
98
-
99
- return [result, tx, commitment];
100
- }
101
-
102
- }
103
-
104
- export default ProsopoCaptchaApi;
105
-