@blindmarket/sdk 0.1.8 → 0.5.0
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.
- package/dist/executor/WorkerRuntime.d.ts +21 -0
- package/dist/executor/WorkerRuntime.js +56 -27
- package/dist/index.d.ts +75 -9
- package/dist/index.js +54 -5
- package/dist/tools/helpers.js +14 -5
- package/dist/types.d.ts +7 -2
- package/package.json +8 -1
- package/biome.json +0 -19
- package/examples/agent-demo.ts +0 -121
- package/scripts/gen-crypto-fixtures.mjs +0 -72
- package/src/agent/Agent.ts +0 -122
- package/src/agent/index.ts +0 -1
- package/src/api/index.ts +0 -1
- package/src/chain/BlindEscrowClient.ts +0 -196
- package/src/chain/BlindReputationClient.ts +0 -60
- package/src/chain/ChainClient.ts +0 -65
- package/src/chain/IBlindMarketChain.ts +0 -109
- package/src/chain/TaskRegistryClient.ts +0 -91
- package/src/chain/abi/BlindEscrow.json +0 -1113
- package/src/chain/abi/BlindReputation.json +0 -447
- package/src/chain/abi/TaskRegistry.json +0 -586
- package/src/chain/abi/index.ts +0 -5
- package/src/chain/createChainAdapter.ts +0 -40
- package/src/chain/domain-types.ts +0 -92
- package/src/chain/errors.ts +0 -43
- package/src/chain/evm/EVMChainAdapter.ts +0 -212
- package/src/chain/evm/index.ts +0 -1
- package/src/chain/index.ts +0 -12
- package/src/compute/index.ts +0 -1
- package/src/crypto/aes.ts +0 -104
- package/src/crypto/constants.ts +0 -7
- package/src/crypto/ecies.ts +0 -60
- package/src/crypto/envelope.ts +0 -131
- package/src/crypto/hkdf.ts +0 -45
- package/src/crypto/index.ts +0 -6
- package/src/crypto/keys.ts +0 -56
- package/src/errors/BlindMarketError.ts +0 -38
- package/src/errors/codes.ts +0 -67
- package/src/errors/index.ts +0 -3
- package/src/errors/subclasses.ts +0 -59
- package/src/events/EventBus.ts +0 -45
- package/src/events/index.ts +0 -2
- package/src/events/types.ts +0 -13
- package/src/executor/WorkerRuntime.ts +0 -338
- package/src/executor/index.ts +0 -8
- package/src/index.ts +0 -636
- package/src/keystore/InMemoryKeyStore.ts +0 -146
- package/src/keystore/KeyStore.ts +0 -19
- package/src/keystore/index.ts +0 -2
- package/src/network/index.ts +0 -3
- package/src/network/presets.ts +0 -66
- package/src/network/resolve.ts +0 -31
- package/src/network/types.ts +0 -20
- package/src/signer/EthersSigner.ts +0 -82
- package/src/signer/PrivateKeySigner.ts +0 -19
- package/src/signer/Signer.ts +0 -40
- package/src/signer/index.ts +0 -3
- package/src/storage/MemoryStorage.ts +0 -49
- package/src/storage/Storage.ts +0 -15
- package/src/storage/ZgStorage.ts +0 -124
- package/src/storage/index.ts +0 -3
- package/src/testing/index.ts +0 -1
- package/src/tools/adapters.ts +0 -177
- package/src/tools/helpers.ts +0 -199
- package/src/tools/index.ts +0 -59
- package/src/tools/types.ts +0 -47
- package/src/types.ts +0 -297
- package/src/verifier/index.ts +0 -1
- package/src/worker/Worker.ts +0 -98
- package/src/worker/index.ts +0 -1
- package/test/agent.test.ts +0 -193
- package/test/chain.test.ts +0 -145
- package/test/crypto.aes.test.ts +0 -81
- package/test/crypto.compat.test.ts +0 -33
- package/test/crypto.ecies.test.ts +0 -64
- package/test/envelope.test.ts +0 -82
- package/test/errors.test.ts +0 -64
- package/test/events.test.ts +0 -59
- package/test/fixtures/crypto.json +0 -16
- package/test/keystore.test.ts +0 -103
- package/test/network.test.ts +0 -53
- package/test/signer.test.ts +0 -66
- package/test/smoke.test.ts +0 -7
- package/test/storage.test.ts +0 -55
- package/test/worker.test.ts +0 -181
- package/tsconfig.build.json +0 -1
- package/tsconfig.json +0 -14
- package/tsup.config.ts +0 -32
- package/vitest.config.ts +0 -17
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
/**
|
|
3
|
-
* Generates cross-compat crypto fixtures using Node's built-in crypto, matching
|
|
4
|
-
* backend/src/services/crypto.ts byte-for-byte. The SDK's test/crypto.compat.test.ts
|
|
5
|
-
* loads these and verifies WebCrypto-based decryption produces the same plaintext.
|
|
6
|
-
*
|
|
7
|
-
* Run: node scripts/gen-crypto-fixtures.mjs
|
|
8
|
-
* Output: test/fixtures/crypto.json (committed to the repo; regenerate only on
|
|
9
|
-
* intentional wire-format changes).
|
|
10
|
-
*/
|
|
11
|
-
import { createCipheriv, createECDH, hkdfSync, randomBytes } from 'node:crypto';
|
|
12
|
-
import { writeFileSync } from 'node:fs';
|
|
13
|
-
import { dirname, resolve } from 'node:path';
|
|
14
|
-
import { fileURLToPath } from 'node:url';
|
|
15
|
-
|
|
16
|
-
const IV_LENGTH = 12;
|
|
17
|
-
const TAG_LENGTH = 16;
|
|
18
|
-
const KEY_LENGTH = 32;
|
|
19
|
-
const ECIES_HKDF_INFO = 'BlindMarket-ECIES-v1';
|
|
20
|
-
|
|
21
|
-
function aesEncrypt(plaintext, key) {
|
|
22
|
-
const iv = randomBytes(IV_LENGTH);
|
|
23
|
-
const cipher = createCipheriv('aes-256-gcm', key, iv, { authTagLength: TAG_LENGTH });
|
|
24
|
-
const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final()]);
|
|
25
|
-
const tag = cipher.getAuthTag();
|
|
26
|
-
// [IV][tag][ciphertext] — matches backend/src/services/crypto.ts
|
|
27
|
-
return Buffer.concat([iv, tag, encrypted]);
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
function eciesEncrypt(plaintext, recipientPubKeyBuf) {
|
|
31
|
-
const ephemeral = createECDH('secp256k1');
|
|
32
|
-
ephemeral.generateKeys();
|
|
33
|
-
const shared = ephemeral.computeSecret(recipientPubKeyBuf);
|
|
34
|
-
const aesKey = Buffer.from(hkdfSync('sha256', shared, '', ECIES_HKDF_INFO, KEY_LENGTH));
|
|
35
|
-
const aesBlob = aesEncrypt(plaintext, aesKey);
|
|
36
|
-
return Buffer.concat([ephemeral.getPublicKey(), aesBlob]);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
const recipient = createECDH('secp256k1');
|
|
40
|
-
recipient.generateKeys();
|
|
41
|
-
const privateKey = recipient.getPrivateKey('hex');
|
|
42
|
-
const publicKey = recipient.getPublicKey('hex', 'uncompressed');
|
|
43
|
-
|
|
44
|
-
const plaintext = 'hello cross-compat';
|
|
45
|
-
const ptBuf = Buffer.from(plaintext, 'utf-8');
|
|
46
|
-
|
|
47
|
-
// AES fixture
|
|
48
|
-
const aesKey = randomBytes(KEY_LENGTH);
|
|
49
|
-
const aesBlob = aesEncrypt(ptBuf, aesKey);
|
|
50
|
-
|
|
51
|
-
// ECIES fixture (recipient's pubkey is encoded as Buffer for computeSecret)
|
|
52
|
-
const eciesBlob = eciesEncrypt(ptBuf, Buffer.from(publicKey, 'hex'));
|
|
53
|
-
|
|
54
|
-
const fixture = {
|
|
55
|
-
_note:
|
|
56
|
-
'Generated by scripts/gen-crypto-fixtures.mjs using Node built-in crypto, matching backend/src/services/crypto.ts. If the SDK decrypts these back to the expected plaintext, wire-format compatibility is proven. Regenerate only on intentional format changes.',
|
|
57
|
-
hkdf_info: ECIES_HKDF_INFO,
|
|
58
|
-
keypair: { privateKey, publicKey },
|
|
59
|
-
plaintext,
|
|
60
|
-
aes: {
|
|
61
|
-
key: aesKey.toString('hex'),
|
|
62
|
-
blob: aesBlob.toString('hex'),
|
|
63
|
-
},
|
|
64
|
-
ecies: {
|
|
65
|
-
blob: eciesBlob.toString('hex'),
|
|
66
|
-
},
|
|
67
|
-
};
|
|
68
|
-
|
|
69
|
-
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
70
|
-
const out = resolve(__dirname, '..', 'test', 'fixtures', 'crypto.json');
|
|
71
|
-
writeFileSync(out, `${JSON.stringify(fixture, null, 2)}\n`);
|
|
72
|
-
console.log(`wrote ${out}`);
|
package/src/agent/Agent.ts
DELETED
|
@@ -1,122 +0,0 @@
|
|
|
1
|
-
import type { BlindEscrowClient } from '../chain/index.js';
|
|
2
|
-
import {
|
|
3
|
-
aesEncrypt,
|
|
4
|
-
eciesEncrypt,
|
|
5
|
-
generateAesKey,
|
|
6
|
-
openEvidenceAsAgent,
|
|
7
|
-
} from '../crypto/index.js';
|
|
8
|
-
import { LifecycleError } from '../errors/index.js';
|
|
9
|
-
import type { EventBus, SdkEvents } from '../events/index.js';
|
|
10
|
-
import type { KeyStore } from '../keystore/index.js';
|
|
11
|
-
import type { Signer } from '../signer/index.js';
|
|
12
|
-
import type { Storage } from '../storage/index.js';
|
|
13
|
-
import type { Address, Hex, Reward, TaskId, TaskKey, TxReceiptLike } from '../types.js';
|
|
14
|
-
|
|
15
|
-
export interface AgentDeps {
|
|
16
|
-
escrow: BlindEscrowClient;
|
|
17
|
-
storage: Storage;
|
|
18
|
-
keystore: KeyStore;
|
|
19
|
-
signer: Signer;
|
|
20
|
-
events?: EventBus<SdkEvents>;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export interface CreateTaskInput {
|
|
24
|
-
instructions: string | Uint8Array;
|
|
25
|
-
category: string;
|
|
26
|
-
locationZone: string;
|
|
27
|
-
reward: Reward & { token: Address };
|
|
28
|
-
deadline: Date | bigint;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export interface CreateTaskResult {
|
|
32
|
-
taskId: TaskId;
|
|
33
|
-
taskKey: TaskKey;
|
|
34
|
-
rootHash: Hex;
|
|
35
|
-
txHash: Hex;
|
|
36
|
-
receipt: TxReceiptLike;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export interface AssignWorkerResult {
|
|
40
|
-
wrappedKey: Uint8Array;
|
|
41
|
-
receipt: TxReceiptLike;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* End-to-end agent flows. Composes storage + crypto + chain + keystore so a
|
|
46
|
-
* caller can post an encrypted bounty in one call. Key exchange with the
|
|
47
|
-
* worker is intentionally out-of-band: assignWorker() returns the wrapped
|
|
48
|
-
* AES key as bytes, and the caller is responsible for delivering it (backend
|
|
49
|
-
* API, DM, whatever). This keeps the SDK pluggable across different
|
|
50
|
-
* message-passing substrates.
|
|
51
|
-
*/
|
|
52
|
-
export class Agent {
|
|
53
|
-
constructor(private readonly deps: AgentDeps) {}
|
|
54
|
-
|
|
55
|
-
async createTask(input: CreateTaskInput): Promise<CreateTaskResult> {
|
|
56
|
-
const { storage, escrow, keystore, events } = this.deps;
|
|
57
|
-
|
|
58
|
-
const aesKey = await generateAesKey();
|
|
59
|
-
const plaintext = toBytes(input.instructions);
|
|
60
|
-
const ciphertext = await aesEncrypt(plaintext, aesKey);
|
|
61
|
-
|
|
62
|
-
const uploaded = await storage.upload(ciphertext);
|
|
63
|
-
const rootHash = uploaded.rootHash;
|
|
64
|
-
|
|
65
|
-
const deadline = typeof input.deadline === 'bigint' ? input.deadline : BigInt(Math.floor(input.deadline.getTime() / 1000));
|
|
66
|
-
|
|
67
|
-
const { taskId, receipt } = await escrow.createTask({
|
|
68
|
-
taskHash: rootHash,
|
|
69
|
-
token: input.reward.token as Address,
|
|
70
|
-
amount: input.reward.amount,
|
|
71
|
-
category: input.category,
|
|
72
|
-
locationZone: input.locationZone,
|
|
73
|
-
deadline,
|
|
74
|
-
});
|
|
75
|
-
|
|
76
|
-
const taskKey: TaskKey = { aesKey, createdAt: new Date() };
|
|
77
|
-
await keystore.putTaskKey(taskId, taskKey);
|
|
78
|
-
|
|
79
|
-
events?.emit('task.created', { taskId, txHash: receipt.hash, rootHash });
|
|
80
|
-
return { taskId, taskKey, rootHash, txHash: receipt.hash, receipt };
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
/**
|
|
84
|
-
* Wrap the stored AES key for the chosen worker and record the assignment
|
|
85
|
-
* on-chain. The caller must deliver `wrappedKey` to the worker separately
|
|
86
|
-
* (backend API, DM, etc.). Returns the wrapped bytes and the tx receipt.
|
|
87
|
-
*/
|
|
88
|
-
async assignWorker(taskId: TaskId, worker: Address, workerPubKey: string): Promise<AssignWorkerResult> {
|
|
89
|
-
const { keystore, escrow, events } = this.deps;
|
|
90
|
-
const stored = await keystore.getTaskKey(taskId);
|
|
91
|
-
if (!stored) {
|
|
92
|
-
throw new LifecycleError('LIFECYCLE/TASK_NOT_FOUND', `no task key in keystore for task ${taskId}`);
|
|
93
|
-
}
|
|
94
|
-
const wrappedKey = await eciesEncrypt(stored.aesKey, workerPubKey);
|
|
95
|
-
const receipt = await escrow.assignWorker(taskId, worker);
|
|
96
|
-
events?.emit('task.assigned', { taskId, worker, txHash: receipt.hash });
|
|
97
|
-
return { wrappedKey, receipt };
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
async cancelTask(taskId: TaskId): Promise<TxReceiptLike> {
|
|
101
|
-
const { escrow, keystore, events } = this.deps;
|
|
102
|
-
const receipt = await this.deps.escrow.cancelTask(taskId);
|
|
103
|
-
void escrow;
|
|
104
|
-
await keystore.delete(taskId);
|
|
105
|
-
events?.emit('task.cancelled', { taskId, txHash: receipt.hash });
|
|
106
|
-
return receipt;
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
/**
|
|
110
|
-
* Fetch evidence by root hash, unwrap the AES key with the agent's private
|
|
111
|
-
* key (signer's key material is not accessible, so a raw private key is
|
|
112
|
-
* required), and return the decrypted evidence plaintext.
|
|
113
|
-
*/
|
|
114
|
-
async fetchAndDecryptEvidence(evidenceHash: Hex, agentPrivKey: string): Promise<Uint8Array> {
|
|
115
|
-
const envelope = await this.deps.storage.download(evidenceHash);
|
|
116
|
-
return openEvidenceAsAgent(envelope, agentPrivKey);
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
function toBytes(x: string | Uint8Array): Uint8Array {
|
|
121
|
-
return typeof x === 'string' ? new TextEncoder().encode(x) : x;
|
|
122
|
-
}
|
package/src/agent/index.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from './Agent.js';
|
package/src/api/index.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1,196 +0,0 @@
|
|
|
1
|
-
import { ethers } from 'ethers';
|
|
2
|
-
import type { Address, Hex, TaskId, TaskStatus, TxReceiptLike } from '../types.js';
|
|
3
|
-
import { BlindEscrowAbi } from './abi/index.js';
|
|
4
|
-
import { wrapChainError } from './errors.js';
|
|
5
|
-
|
|
6
|
-
const STATUS_BY_INDEX: TaskStatus[] = ['funded', 'assigned', 'submitted', 'verified', 'completed', 'cancelled', 'disputed'];
|
|
7
|
-
|
|
8
|
-
export interface CreateTaskArgs {
|
|
9
|
-
taskHash: Hex;
|
|
10
|
-
token: Address;
|
|
11
|
-
amount: bigint;
|
|
12
|
-
category: string;
|
|
13
|
-
locationZone: string;
|
|
14
|
-
deadline: bigint;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
export interface OnChainTask {
|
|
18
|
-
taskId: TaskId;
|
|
19
|
-
agent: Address;
|
|
20
|
-
worker: Address;
|
|
21
|
-
token: Address;
|
|
22
|
-
amount: bigint;
|
|
23
|
-
taskHash: Hex;
|
|
24
|
-
evidenceHash: Hex;
|
|
25
|
-
status: TaskStatus;
|
|
26
|
-
category: string;
|
|
27
|
-
locationZone: string;
|
|
28
|
-
createdAt: Date;
|
|
29
|
-
deadline: Date;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
/**
|
|
33
|
-
* Typed ethers v6 wrapper for the BlindEscrow contract. Every state-changing
|
|
34
|
-
* method awaits one confirmation and returns a TxReceiptLike; every read
|
|
35
|
-
* returns decoded values. Ethers errors are mapped to ChainError via
|
|
36
|
-
* wrapChainError().
|
|
37
|
-
*/
|
|
38
|
-
export class BlindEscrowClient {
|
|
39
|
-
readonly contract: ethers.Contract;
|
|
40
|
-
readonly address: Address;
|
|
41
|
-
|
|
42
|
-
constructor(address: Address, runner: ethers.ContractRunner) {
|
|
43
|
-
this.address = address;
|
|
44
|
-
this.contract = new ethers.Contract(address, BlindEscrowAbi, runner);
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/** Create a task and return its id + receipt. Reads the TaskCreated event for the id. */
|
|
48
|
-
async createTask(args: CreateTaskArgs): Promise<{ taskId: TaskId; receipt: TxReceiptLike }> {
|
|
49
|
-
try {
|
|
50
|
-
const overrides: ethers.Overrides = {};
|
|
51
|
-
if (args.token === '0x0000000000000000000000000000000000000000') {
|
|
52
|
-
overrides.value = args.amount;
|
|
53
|
-
}
|
|
54
|
-
const tx = await this.contract.createTask!(
|
|
55
|
-
args.taskHash,
|
|
56
|
-
args.token,
|
|
57
|
-
args.amount,
|
|
58
|
-
args.category,
|
|
59
|
-
args.locationZone,
|
|
60
|
-
args.deadline,
|
|
61
|
-
overrides,
|
|
62
|
-
);
|
|
63
|
-
const rec = await tx.wait(1);
|
|
64
|
-
const taskId = this.extractTaskIdFromReceipt(rec);
|
|
65
|
-
return { taskId, receipt: toReceipt(rec) };
|
|
66
|
-
} catch (err) {
|
|
67
|
-
throw wrapChainError(err, 'createTask');
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
async assignWorker(taskId: TaskId, worker: Address): Promise<TxReceiptLike> {
|
|
72
|
-
return this.sendTx('assignWorker', [taskId, worker]);
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
async submitEvidence(taskId: TaskId, evidenceHash: Hex): Promise<TxReceiptLike> {
|
|
76
|
-
return this.sendTx('submitEvidence', [taskId, evidenceHash]);
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
async completeVerification(taskId: TaskId, passed: boolean): Promise<TxReceiptLike> {
|
|
80
|
-
return this.sendTx('completeVerification', [taskId, passed]);
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
async cancelTask(taskId: TaskId): Promise<TxReceiptLike> {
|
|
84
|
-
return this.sendTx('cancelTask', [taskId]);
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
async raiseDispute(taskId: TaskId): Promise<TxReceiptLike> {
|
|
88
|
-
return this.sendTx('raiseDispute', [taskId]);
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
async resolveDispute(taskId: TaskId, workerFavored: boolean): Promise<TxReceiptLike> {
|
|
92
|
-
return this.sendTx('resolveDispute', [taskId, workerFavored]);
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
async claimTimeout(taskId: TaskId): Promise<TxReceiptLike> {
|
|
96
|
-
return this.sendTx('claimTimeout', [taskId]);
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
async getTask(taskId: TaskId): Promise<OnChainTask> {
|
|
100
|
-
try {
|
|
101
|
-
const raw = await this.contract.getTask!(taskId);
|
|
102
|
-
return decodeTask(taskId, raw);
|
|
103
|
-
} catch (err) {
|
|
104
|
-
throw wrapChainError(err, 'getTask');
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
async isTaskExpired(taskId: TaskId): Promise<boolean> {
|
|
109
|
-
try {
|
|
110
|
-
return Boolean(await this.contract.isTaskExpired!(taskId));
|
|
111
|
-
} catch (err) {
|
|
112
|
-
throw wrapChainError(err, 'isTaskExpired');
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
async nextTaskId(): Promise<TaskId> {
|
|
117
|
-
try {
|
|
118
|
-
return BigInt(await this.contract.nextTaskId!());
|
|
119
|
-
} catch (err) {
|
|
120
|
-
throw wrapChainError(err, 'nextTaskId');
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
async feeBps(): Promise<bigint> {
|
|
125
|
-
try {
|
|
126
|
-
return BigInt(await this.contract.feeBps!());
|
|
127
|
-
} catch (err) {
|
|
128
|
-
throw wrapChainError(err, 'feeBps');
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
private async sendTx(method: string, args: unknown[]): Promise<TxReceiptLike> {
|
|
133
|
-
try {
|
|
134
|
-
const fn = this.contract[method];
|
|
135
|
-
if (typeof fn !== 'function') {
|
|
136
|
-
throw new Error(`unknown contract method: ${method}`);
|
|
137
|
-
}
|
|
138
|
-
const tx = await fn(...args);
|
|
139
|
-
const rec = await tx.wait(1);
|
|
140
|
-
return toReceipt(rec);
|
|
141
|
-
} catch (err) {
|
|
142
|
-
throw wrapChainError(err, method);
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
private extractTaskIdFromReceipt(receipt: ethers.ContractTransactionReceipt | null): TaskId {
|
|
147
|
-
if (!receipt) throw new Error('no receipt');
|
|
148
|
-
const iface = this.contract.interface;
|
|
149
|
-
for (const log of receipt.logs) {
|
|
150
|
-
try {
|
|
151
|
-
const parsed = iface.parseLog({ topics: log.topics as string[], data: log.data });
|
|
152
|
-
if (parsed?.name === 'TaskCreated') {
|
|
153
|
-
return BigInt(parsed.args.getValue('taskId'));
|
|
154
|
-
}
|
|
155
|
-
} catch {
|
|
156
|
-
// not our event, skip
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
throw new Error('TaskCreated event not found in receipt logs');
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
function toReceipt(rec: ethers.ContractTransactionReceipt | null): TxReceiptLike {
|
|
164
|
-
if (!rec) throw new Error('no receipt');
|
|
165
|
-
return {
|
|
166
|
-
hash: rec.hash as Hex,
|
|
167
|
-
blockNumber: rec.blockNumber,
|
|
168
|
-
gasUsed: rec.gasUsed,
|
|
169
|
-
};
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
function decodeTask(taskId: TaskId, raw: ethers.Result): OnChainTask {
|
|
173
|
-
// Live Task struct (12 fields) from BlindEscrow.getTask(): agent, worker,
|
|
174
|
-
// token, amount, taskHash, evidenceHash, status, category, locationZone,
|
|
175
|
-
// createdAt, deadline, submissionAttempts. The old decode read createdAt from
|
|
176
|
-
// arr[7] (actually category) and deadline from arr[8] (actually locationZone),
|
|
177
|
-
// yielding Invalid Date and discarding category/locationZone.
|
|
178
|
-
const arr = raw as unknown as unknown[];
|
|
179
|
-
const statusIndex = Number(arr[6]);
|
|
180
|
-
const status = STATUS_BY_INDEX[statusIndex];
|
|
181
|
-
if (!status) throw new Error(`BlindEscrow.getTask returned unknown status index ${statusIndex}`);
|
|
182
|
-
return {
|
|
183
|
-
taskId,
|
|
184
|
-
agent: arr[0] as Address,
|
|
185
|
-
worker: arr[1] as Address,
|
|
186
|
-
token: arr[2] as Address,
|
|
187
|
-
amount: BigInt(arr[3] as bigint | number),
|
|
188
|
-
taskHash: arr[4] as Hex,
|
|
189
|
-
evidenceHash: arr[5] as Hex,
|
|
190
|
-
status,
|
|
191
|
-
category: arr[7] as string,
|
|
192
|
-
locationZone: arr[8] as string,
|
|
193
|
-
createdAt: new Date(Number(arr[9] as bigint | number) * 1000),
|
|
194
|
-
deadline: new Date(Number(arr[10] as bigint | number) * 1000),
|
|
195
|
-
};
|
|
196
|
-
}
|
|
@@ -1,60 +0,0 @@
|
|
|
1
|
-
import { ethers } from 'ethers';
|
|
2
|
-
import type { Address, Hex, TaskId, TxReceiptLike } from '../types.js';
|
|
3
|
-
import { BlindReputationAbi } from './abi/index.js';
|
|
4
|
-
import { wrapChainError } from './errors.js';
|
|
5
|
-
|
|
6
|
-
export interface ReputationSnapshot {
|
|
7
|
-
tasksCompleted: bigint;
|
|
8
|
-
/** Raw on-chain value. NOTE: despite the name, the contract returns the
|
|
9
|
-
* average rating already scaled ×100 (450 = 4.50), NOT a cumulative sum. */
|
|
10
|
-
totalScore: bigint;
|
|
11
|
-
disputes: bigint;
|
|
12
|
-
/** 0–5 average rating. */
|
|
13
|
-
avgScore: number;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
export class BlindReputationClient {
|
|
17
|
-
readonly contract: ethers.Contract;
|
|
18
|
-
readonly address: Address;
|
|
19
|
-
|
|
20
|
-
constructor(address: Address, runner: ethers.ContractRunner) {
|
|
21
|
-
this.address = address;
|
|
22
|
-
this.contract = new ethers.Contract(address, BlindReputationAbi, runner);
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
async getReputation(worker: Address): Promise<ReputationSnapshot> {
|
|
26
|
-
try {
|
|
27
|
-
const raw = (await this.contract.getReputation!(worker)) as unknown as unknown[];
|
|
28
|
-
const tasksCompleted = BigInt(raw[0] as bigint | number);
|
|
29
|
-
// raw[1] is already avgScore × 100 (contract getReputation returns the
|
|
30
|
-
// average scaled ×100, "450 = 4.50") — divide by 100 only, NOT by tasks.
|
|
31
|
-
const totalScore = BigInt(raw[1] as bigint | number);
|
|
32
|
-
const disputes = BigInt(raw[2] as bigint | number);
|
|
33
|
-
const avgScore = Number(totalScore) / 100;
|
|
34
|
-
return { tasksCompleted, totalScore, disputes, avgScore };
|
|
35
|
-
} catch (err) {
|
|
36
|
-
throw wrapChainError(err, 'getReputation');
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
async rate(worker: Address, score: number, taskId: TaskId): Promise<TxReceiptLike> {
|
|
41
|
-
if (!Number.isInteger(score) || score < 1 || score > 5) {
|
|
42
|
-
throw wrapChainError(new Error(`score must be integer 1..5, got ${score}`), 'rate');
|
|
43
|
-
}
|
|
44
|
-
try {
|
|
45
|
-
const tx = await this.contract.rate!(worker, score, taskId);
|
|
46
|
-
const rec = await tx.wait(1);
|
|
47
|
-
return { hash: rec.hash as Hex, blockNumber: rec.blockNumber, gasUsed: rec.gasUsed };
|
|
48
|
-
} catch (err) {
|
|
49
|
-
throw wrapChainError(err, 'rate');
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
async hasBeenRated(worker: Address, taskId: TaskId): Promise<boolean> {
|
|
54
|
-
try {
|
|
55
|
-
return Boolean(await this.contract.hasBeenRated!(worker, taskId));
|
|
56
|
-
} catch (err) {
|
|
57
|
-
throw wrapChainError(err, 'hasBeenRated');
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
}
|
package/src/chain/ChainClient.ts
DELETED
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
import { ethers } from 'ethers';
|
|
2
|
-
import type { Signer as SdkSigner } from '../signer/index.js';
|
|
3
|
-
import type { EVMNetwork } from './domain-types.js';
|
|
4
|
-
import type { Network } from './domain-types.js';
|
|
5
|
-
import { BlindEscrowClient } from './BlindEscrowClient.js';
|
|
6
|
-
import { BlindReputationClient } from './BlindReputationClient.js';
|
|
7
|
-
import { TaskRegistryClient } from './TaskRegistryClient.js';
|
|
8
|
-
|
|
9
|
-
export interface ChainClientOptions {
|
|
10
|
-
network: Network;
|
|
11
|
-
signer?: SdkSigner;
|
|
12
|
-
/** If provided, used for reads even when signer is absent. Useful for public queries. */
|
|
13
|
-
provider?: ethers.Provider;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* Bundles typed clients for all three BlindMarket contracts plus the underlying
|
|
18
|
-
* ethers runner. Reads use provider (or signer's provider); writes require a
|
|
19
|
-
* signer. To keep the SDK's Signer abstraction decoupled from ethers at the
|
|
20
|
-
* call sites, we unwrap an EthersSigner's inner ethers.Signer lazily here.
|
|
21
|
-
*
|
|
22
|
-
* Only supports EVM networks.
|
|
23
|
-
*/
|
|
24
|
-
export class ChainClient {
|
|
25
|
-
readonly escrow: BlindEscrowClient;
|
|
26
|
-
readonly registry: TaskRegistryClient;
|
|
27
|
-
readonly reputation: BlindReputationClient;
|
|
28
|
-
readonly provider: ethers.Provider;
|
|
29
|
-
readonly network: EVMNetwork;
|
|
30
|
-
|
|
31
|
-
constructor(opts: ChainClientOptions) {
|
|
32
|
-
if (opts.network.chainType !== 'evm') {
|
|
33
|
-
throw new Error(`ChainClient requires an EVM network, got ${opts.network.chainType}`);
|
|
34
|
-
}
|
|
35
|
-
this.network = opts.network;
|
|
36
|
-
const provider =
|
|
37
|
-
opts.provider ??
|
|
38
|
-
(opts.signer && unwrapEthersSigner(opts.signer)?.provider) ??
|
|
39
|
-
defaultProvider(opts.network);
|
|
40
|
-
this.provider = provider;
|
|
41
|
-
|
|
42
|
-
const runner: ethers.ContractRunner = unwrapEthersSigner(opts.signer) ?? provider;
|
|
43
|
-
this.escrow = new BlindEscrowClient(opts.network.contracts.escrow, runner);
|
|
44
|
-
this.registry = new TaskRegistryClient(opts.network.contracts.registry, runner);
|
|
45
|
-
this.reputation = new BlindReputationClient(opts.network.contracts.reputation, runner);
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* If the SDK Signer is an EthersSigner, pull out the inner ethers.Signer
|
|
51
|
-
* (so ethers.Contract treats it as the transaction runner). Otherwise
|
|
52
|
-
* returns undefined — writes will fail at the contract layer with a clear
|
|
53
|
-
* signer-required error, as intended.
|
|
54
|
-
*/
|
|
55
|
-
function unwrapEthersSigner(signer: SdkSigner | undefined): ethers.Signer | undefined {
|
|
56
|
-
if (!signer) return undefined;
|
|
57
|
-
const maybe = signer as unknown as { inner?: ethers.Signer };
|
|
58
|
-
return maybe.inner;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
function defaultProvider(network: EVMNetwork): ethers.Provider {
|
|
62
|
-
const url = network.rpc[0];
|
|
63
|
-
if (!url) throw new Error(`network ${network.name} has no RPC endpoint configured`);
|
|
64
|
-
return new ethers.JsonRpcProvider(url, { chainId: Number(network.chainId), name: network.name });
|
|
65
|
-
}
|
|
@@ -1,109 +0,0 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
CreateTaskParams,
|
|
3
|
-
DomainReputation,
|
|
4
|
-
DomainTask,
|
|
5
|
-
DomainTaskMeta,
|
|
6
|
-
DomainTxReceipt,
|
|
7
|
-
Network,
|
|
8
|
-
} from './domain-types.js';
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* Chain-agnostic interface for BlindMarket on-chain operations.
|
|
12
|
-
*
|
|
13
|
-
* Every supported blockchain provides an adapter that implements this interface,
|
|
14
|
-
* translating domain operations into chain-native contract calls. Consumers
|
|
15
|
-
* (backend, agents, CLI) work against this interface and never need to know
|
|
16
|
-
* which chain they're talking to.
|
|
17
|
-
*/
|
|
18
|
-
export interface IBlindMarketChain {
|
|
19
|
-
// ── Chain identity ──────────────────────────────────────────────────────
|
|
20
|
-
|
|
21
|
-
/** The resolved network config this adapter is connected to. */
|
|
22
|
-
readonly network: Network;
|
|
23
|
-
|
|
24
|
-
/** The address of the active signer. */
|
|
25
|
-
getAddress(): Promise<string>;
|
|
26
|
-
|
|
27
|
-
// ── Task lifecycle (BlindEscrow equivalent) ─────────────────────────────
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* Create a new task with escrowed funds.
|
|
31
|
-
* Returns the assigned task ID and receipt.
|
|
32
|
-
*/
|
|
33
|
-
createTask(params: CreateTaskParams): Promise<{ taskId: bigint; receipt: DomainTxReceipt }>;
|
|
34
|
-
|
|
35
|
-
/** Assign a worker to a funded task. Caller must be the task agent. */
|
|
36
|
-
assignWorker(taskId: bigint, worker: string): Promise<DomainTxReceipt>;
|
|
37
|
-
|
|
38
|
-
/** Submit an evidence hash for an assigned task. Caller must be the worker. */
|
|
39
|
-
submitEvidence(taskId: bigint, evidenceHash: string): Promise<DomainTxReceipt>;
|
|
40
|
-
|
|
41
|
-
/** Complete verification for a submitted task (called by the verifier). */
|
|
42
|
-
completeVerification(taskId: bigint, passed: boolean): Promise<DomainTxReceipt>;
|
|
43
|
-
|
|
44
|
-
/** Cancel a funded/assigned task and return escrow to the agent. */
|
|
45
|
-
cancelTask(taskId: bigint): Promise<DomainTxReceipt>;
|
|
46
|
-
|
|
47
|
-
/** Claim escrow after timeout expiry (agent-side). */
|
|
48
|
-
claimTimeout(taskId: bigint): Promise<DomainTxReceipt>;
|
|
49
|
-
|
|
50
|
-
/** Raise a dispute on a task. */
|
|
51
|
-
raiseDispute(taskId: bigint): Promise<DomainTxReceipt>;
|
|
52
|
-
|
|
53
|
-
/** Resolve a dispute (admin only). */
|
|
54
|
-
resolveDispute(taskId: bigint, workerFavored: boolean): Promise<DomainTxReceipt>;
|
|
55
|
-
|
|
56
|
-
/** Read full on-chain task state. */
|
|
57
|
-
getTask(taskId: bigint): Promise<DomainTask>;
|
|
58
|
-
|
|
59
|
-
/** Check whether a task's deadline has passed. */
|
|
60
|
-
isTaskExpired(taskId: bigint): Promise<boolean>;
|
|
61
|
-
|
|
62
|
-
// ── Task discovery (TaskRegistry equivalent) ────────────────────────────
|
|
63
|
-
|
|
64
|
-
/** Publish task metadata to the on-chain discovery index. */
|
|
65
|
-
publishTask(taskId: bigint, meta: Omit<DomainTaskMeta, 'taskId'> & { taskId?: bigint }): Promise<DomainTxReceipt>;
|
|
66
|
-
|
|
67
|
-
/** Remove a task from the discovery index (called on assignment/completion). */
|
|
68
|
-
closeTask(taskId: bigint): Promise<DomainTxReceipt>;
|
|
69
|
-
|
|
70
|
-
/** Get a page of open task IDs from the discovery index. */
|
|
71
|
-
getOpenTasks(offset: bigint, limit: bigint): Promise<DomainTaskMeta[]>;
|
|
72
|
-
|
|
73
|
-
/** Count of currently open tasks. */
|
|
74
|
-
openTaskCount(): Promise<bigint>;
|
|
75
|
-
|
|
76
|
-
/** Total tasks ever published. */
|
|
77
|
-
totalTasks(): Promise<bigint>;
|
|
78
|
-
|
|
79
|
-
// ── Reputation (BlindReputation equivalent) ─────────────────────────────
|
|
80
|
-
|
|
81
|
-
/** Rate a worker after task completion (score 1-5). */
|
|
82
|
-
rateWorker(worker: string, score: number, taskId: bigint): Promise<DomainTxReceipt>;
|
|
83
|
-
|
|
84
|
-
/** Record a dispute against a worker. */
|
|
85
|
-
recordDispute(worker: string, taskId: bigint): Promise<DomainTxReceipt>;
|
|
86
|
-
|
|
87
|
-
/** Fetch on-chain reputation for a worker. */
|
|
88
|
-
getReputation(worker: string): Promise<DomainReputation>;
|
|
89
|
-
|
|
90
|
-
/** Check if a worker has already been rated for a given task. */
|
|
91
|
-
hasBeenRated(worker: string, taskId: bigint): Promise<boolean>;
|
|
92
|
-
|
|
93
|
-
// ── Agent identity (INFT equivalent) ────────────────────────────────────
|
|
94
|
-
|
|
95
|
-
/** Mint an agent identity token. Returns the token ID and receipt. */
|
|
96
|
-
mintAgent(params: {
|
|
97
|
-
to: string;
|
|
98
|
-
encryptedURI: string;
|
|
99
|
-
metadataHash: string;
|
|
100
|
-
}): Promise<{ tokenId: bigint; receipt: DomainTxReceipt }>;
|
|
101
|
-
|
|
102
|
-
/** Read the encrypted metadata URI for an agent token. */
|
|
103
|
-
getEncryptedURI(tokenId: bigint): Promise<string>;
|
|
104
|
-
|
|
105
|
-
// ── Queries ──────────────────────────────────────────────────────────────
|
|
106
|
-
|
|
107
|
-
/** Get native balance for an address. */
|
|
108
|
-
getBalance(address: string): Promise<bigint>;
|
|
109
|
-
}
|