-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path7.2.computeJob-start.js
337 lines (309 loc) · 8.32 KB
/
7.2.computeJob-start.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
const { ProviderInstance, Aquarius, Datatoken } = require('@oceanprotocol/lib');
const Web3 = require('web3');
const { web3Provider, oceanConfig, web3Instance } = require('./config');
// const HDWalletProvider = require('@truffle/hdwallet-provider');
const web3 = new Web3(web3Provider);
const aquarius = new Aquarius(oceanConfig.metadataCacheUri);
const providerUrl = oceanConfig.providerUri;
// const getConsumerAccount = async () => {
// const web3Provider2 = new HDWalletProvider(
// process.env.PRIVATE_KEY2,
// oceanConfig.nodeUri
// );
// const web3Consumer = new Web3(web3Provider2);
// const consumerAccount = (await web3Consumer.eth.getAccounts())[0];
// return { web3Provider2, consumerAccount };
// }
const approveWei = async (
web3,
config,
account,
tokenAddress,
spender,
amount,
force,
estimateGas
) => {
const tokenContract = new web3.eth.Contract(minAbi, tokenAddress);
if (!force) {
const currentAllowence = await allowanceWei(
web3,
tokenAddress,
account,
spender
);
if (new BigNumber(currentAllowence).gt(new BigNumber(amount))) {
return new Decimal(currentAllowence).toNumber();
}
}
let result = null;
const estGas = await calculateEstimatedGas(
account,
tokenContract.methods.approve,
spender,
amount
);
if (estimateGas) return estGas;
try {
result = await sendTx(
account,
estGas + 1,
web3,
config?.gasFeeMultiplier,
tokenContract.methods.approve,
spender,
amount
);
} catch (e) {
console.error('erere');
}
return result;
};
async function handleOrder(
web3,
order,
datatokenAddress,
payerAccount,
consumerAccount,
serviceIndex,
consumeMarkerFee
) {
let datatoken = new Datatoken(web3);
if (order.providerFee && order.providerFee.providerFeeAmount) {
console.log('To do');
// await approveWei(
// web3,
// config,
// payerAccount,
// order.providerFee.providerFeeToken,
// datatokenAddress,
// order.providerFee.providerFeeAmount
// );
}
if (order.validOrder) {
if (!order.providerFee) return order.validOrder;
const tx = await datatoken.reuseOrder(
datatokenAddress,
payerAccount,
order.validOrder,
order.providerFee
);
return tx.transactionHash;
}
const tx = await datatoken.startOrder(
datatokenAddress,
payerAccount,
consumerAccount,
serviceIndex,
order.providerFee,
consumeMarkerFee
);
return tx.transactionHash;
}
const startComputeJob = async (
algoDid,
datasetDid,
datasetInput,
algorithmInput
) => {
const resolvedDataDdo = await aquarius.waitForAqua(datasetDid);
const resolvedAlgoDdo = await aquarius.waitForAqua(algoDid);
// const { web3Provider2, consumerAccount } = await getConsumerAccount();
const consumerAccount = (await web3.eth.getAccounts())[0];
const computeEnvs = await ProviderInstance.getComputeEnvironments(
providerUrl
);
const computeEnv = computeEnvs[0].id;
const assets = [
{
documentId: resolvedDataDdo.id,
serviceId: resolvedDataDdo.services[0].id,
userdata: datasetInput
}
];
const dtAddressArray = [resolvedDataDdo.services[0].datatokenAddress];
const algo = {
documentId: resolvedAlgoDdo.id,
serviceId: resolvedAlgoDdo.services[0].id,
algocustomdata: algorithmInput
};
const mytime = new Date();
mytime.setMinutes(mytime.getMinutes() + 19);
const computeValidUntil = Math.floor(mytime.getTime() / 1000);
const providerInitializeComputeResults =
await ProviderInstance.initializeCompute(
assets,
algo,
computeEnv,
computeValidUntil,
providerUrl,
consumerAccount
);
// Pay for dataset
algo.transferTxId = await handleOrder(
web3,
providerInitializeComputeResults.algorithm,
resolvedAlgoDdo.services[0].datatokenAddress,
consumerAccount,
computeEnvs[0].consumerAddress,
0
);
assets[0].transferTxId = await handleOrder(
web3,
providerInitializeComputeResults.datasets[0],
resolvedDataDdo.services[0].datatokenAddress,
consumerAccount,
computeEnvs[0].consumerAddress,
0
);
const computeJobs = await computeStart(
providerUrl,
web3Instance,
consumerAccount,
computeEnv,
assets[0],
algo
);
console.log('compute jobs', computeJobs);
};
const getServiceEndpoints = async (providerEndpoint, endpoints) => {
const serviceEndpoints = [];
for (const i in endpoints.serviceEndpoints) {
const endpoint = {
serviceName: i,
method: endpoints.serviceEndpoints[i][0],
urlPath: providerEndpoint + endpoints.serviceEndpoints[i][1]
};
serviceEndpoints.push(endpoint);
}
return serviceEndpoints;
};
const signProviderRequest = async (web3, accountId, message, password) => {
const consumerMessage = web3.utils.soliditySha3({
t: 'bytes',
v: web3.utils.utf8ToHex(message)
});
const isMetaMask =
web3 && web3.currentProvider && web3.currentProvider.isMetaMask;
if (isMetaMask)
return await web3.eth.personal.sign(consumerMessage, accountId, password);
else
return await web3.eth.accounts.sign(
consumerMessage,
process.env.PRIVATE_KEY
);
};
const getData = async (url) => {
return fetch(url, {
method: 'GET',
headers: {
'Content-type': 'application/json'
}
});
};
const getEndpoints = async (providerUri) => {
try {
const endpoints = await getData(providerUri);
return await endpoints.json();
} catch (e) {
// LoggerInstance.error('Finding the service endpoints failed:', e);
console.error(e);
throw new Error('HTTP request failed calling Provider');
}
};
const computeStart = async (
providerUri,
web3,
consumerAddress,
computeEnv,
dataset,
algorithm,
signal,
additionalDatasets,
output
) => {
const providerEndpoints = await getEndpoints(providerUri);
const serviceEndpoints = await getServiceEndpoints(
providerUri,
providerEndpoints
);
const computeStartUrl = getEndpointURL(serviceEndpoints, 'computeStart')
? getEndpointURL(serviceEndpoints, 'computeStart').urlPath
: null;
const nonce = Date.now();
let signatureMessage = consumerAddress;
signatureMessage += dataset.documentId;
signatureMessage += nonce;
const signature = await signProviderRequest(
web3,
consumerAddress,
signatureMessage
);
const payload = Object();
payload.consumerAddress = consumerAddress;
payload.signature = signature['signature'];
payload.nonce = nonce;
payload.environment = computeEnv;
payload.dataset = dataset;
payload.algorithm = algorithm;
if (payload.additionalDatasets)
payload.additionalDatasets = additionalDatasets;
if (output) payload.output = output;
if (!computeStartUrl) return null;
try {
const response = await fetch(computeStartUrl, {
method: 'POST',
body: JSON.stringify(payload),
headers: { 'Content-Type': 'application/json' },
signal
});
if (response?.ok) {
const params = await response.json();
return params;
}
console.error('error', payload);
// LoggerInstance.error(
// 'Compute start failed: ',
// response.status,
// response.statusText,
// await response.json()
// );
// LoggerInstance.error('Payload was:', payload);
return null;
} catch (e) {
// LoggerInstance.error('Compute start failed:');
// LoggerInstance.error(e);
// LoggerInstance.error('Payload was:', payload);
console.error(e);
throw new Error('HTTP request failed calling Provider');
}
};
const getEndpointURL = (servicesEndpoints, serviceName) => {
if (!servicesEndpoints) return null;
return servicesEndpoints.find((s) => s.serviceName === serviceName);
};
const startCompute = async () => {
const datasetDid =
'did:op:b3ca139ac816cc0afc2484f33fc48d164786d64887c141a300d1896419d145b3';
const algoDid =
'did:op:dc01470e0ec34abdc469379628e08e9abc472af1845e0b70e92457883a0c392c';
const algorithmInput = {
view: 'compute-data',
'query-type': 'all',
'design-doc': 'brainstem'
};
const datasetInput = {
view: 'compute-data',
'query-type': 'all',
'design-doc': 'brainstem'
};
await startComputeJob(algoDid, datasetDid, datasetInput, algorithmInput);
};
(async () => {
try {
await startCompute();
process.exit();
} catch (e) {
console.error(e);
}
})();