-
Notifications
You must be signed in to change notification settings - Fork 272
/
deploy-contract-from-json.test.ts
492 lines (448 loc) · 15.6 KB
/
deploy-contract-from-json.test.ts
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
import test, { Test } from "tape-promise/tape";
import { v4 as uuidv4 } from "uuid";
import { Server as SocketIoServer } from "socket.io";
import { PluginRegistry } from "@hyperledger/cactus-core";
import {
EthContractInvocationType,
Web3SigningCredentialType,
PluginLedgerConnectorBesu,
PluginFactoryLedgerConnector,
Web3SigningCredentialCactusKeychainRef,
ReceiptType,
BesuApiClient,
WatchBlocksV1Progress,
Web3BlockHeader,
} from "../../../../../main/typescript/public-api";
import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory";
import {
BesuTestLedger,
pruneDockerAllIfGithubAction,
} from "@hyperledger/cactus-test-tooling";
import {
LogLevelDesc,
IListenOptions,
Servers,
} from "@hyperledger/cactus-common";
import HelloWorldContractJson from "../../../../solidity/hello-world-contract/HelloWorld.json";
import Web3 from "web3";
import { Constants, PluginImportType } from "@hyperledger/cactus-core-api";
import express from "express";
import bodyParser from "body-parser";
import http from "http";
import { AddressInfo } from "net";
import { K_CACTUS_BESU_TOTAL_TX_COUNT } from "../../../../../main/typescript/prometheus-exporter/metrics";
import { BesuApiClientOptions } from "../../../../../main/typescript/api-client/besu-api-client";
const testCase = "deploys contract via .json file";
const logLevel: LogLevelDesc = "TRACE";
test("BEFORE " + testCase, async (t: Test) => {
const pruning = pruneDockerAllIfGithubAction({ logLevel });
await t.doesNotReject(pruning, "Pruning didn't throw OK");
t.end();
});
test(testCase, async (t: Test) => {
const besuTestLedger = new BesuTestLedger();
await besuTestLedger.start();
test.onFinish(async () => {
await besuTestLedger.stop();
await besuTestLedger.destroy();
await pruneDockerAllIfGithubAction({ logLevel });
});
const rpcApiHttpHost = await besuTestLedger.getRpcApiHttpHost();
const rpcApiWsHost = await besuTestLedger.getRpcApiWsHost();
/**
* Constant defining the standard 'dev' Besu genesis.json contents.
*
* @see https://github.com/hyperledger/besu/blob/1.5.1/config/src/main/resources/dev.json
*/
const firstHighNetWorthAccount = besuTestLedger.getGenesisAccountPubKey();
const besuKeyPair = {
privateKey: besuTestLedger.getGenesisAccountPrivKey(),
};
const web3 = new Web3(rpcApiHttpHost);
const testEthAccount = web3.eth.accounts.create(uuidv4());
const keychainEntryKey = uuidv4();
const keychainEntryValue = testEthAccount.privateKey;
const keychainPlugin = new PluginKeychainMemory({
instanceId: uuidv4(),
keychainId: uuidv4(),
// pre-provision keychain with mock backend holding the private key of the
// test account that we'll reference while sending requests with the
// signing credential pointing to this keychain entry.
backend: new Map([[keychainEntryKey, keychainEntryValue]]),
logLevel,
});
keychainPlugin.set(
HelloWorldContractJson.contractName,
JSON.stringify(HelloWorldContractJson),
);
const factory = new PluginFactoryLedgerConnector({
pluginImportType: PluginImportType.Local,
});
const connector: PluginLedgerConnectorBesu = await factory.create({
rpcApiHttpHost,
rpcApiWsHost,
logLevel,
instanceId: uuidv4(),
pluginRegistry: new PluginRegistry({ plugins: [keychainPlugin] }),
});
const expressApp = express();
expressApp.use(bodyParser.json({ limit: "250mb" }));
const server = http.createServer(expressApp);
const wsApi = new SocketIoServer(server, {
path: Constants.SocketIoConnectionPathV1,
});
const listenOptions: IListenOptions = {
hostname: "localhost",
port: 0,
server,
};
const addressInfo = (await Servers.listen(listenOptions)) as AddressInfo;
test.onFinish(async () => await Servers.shutdown(server));
const { address, port } = addressInfo;
const apiHost = `http://${address}:${port}`;
t.comment(
`Metrics URL: ${apiHost}/api/v1/plugins/@hyperledger/cactus-plugin-ledger-connector-besu/get-prometheus-exporter-metrics`,
);
const wsBasePath = apiHost + Constants.SocketIoConnectionPathV1;
t.comment("WS base path: " + wsBasePath);
const besuApiClientOptions = new BesuApiClientOptions({ basePath: apiHost });
const apiClient = new BesuApiClient(besuApiClientOptions);
await connector.getOrCreateWebServices();
await connector.registerWebServices(expressApp, wsApi);
await connector.transact({
web3SigningCredential: {
ethAccount: firstHighNetWorthAccount,
secret: besuKeyPair.privateKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
transactionConfig: {
from: firstHighNetWorthAccount,
to: testEthAccount.address,
value: 10e9,
gas: 1000000,
},
consistencyStrategy: {
blockConfirmations: 0,
receiptType: ReceiptType.NodeTxPoolAck,
timeoutMs: 60000,
},
});
const blocks = await apiClient.watchBlocksV1();
const aBlockHeader = await new Promise<Web3BlockHeader>((resolve, reject) => {
let done = false;
const timerId = setTimeout(() => {
if (!done) {
reject("Waiting for block header notification to arrive timed out");
}
}, 10000);
const subscription = blocks.subscribe((res: WatchBlocksV1Progress) => {
subscription.unsubscribe();
done = true;
clearTimeout(timerId);
resolve(res.blockHeader);
});
});
t.ok(aBlockHeader, "Web3BlockHeader truthy OK");
const balance = await web3.eth.getBalance(testEthAccount.address);
t.ok(balance, "Retrieved balance of test account OK");
t.equals(parseInt(balance, 10), 10e9, "Balance of test account is OK");
let contractAddress: string;
test("deploys contract via .json file", async (t2: Test) => {
const deployOut = await connector.deployContract({
keychainId: keychainPlugin.getKeychainId(),
contractName: HelloWorldContractJson.contractName,
contractAbi: HelloWorldContractJson.abi,
constructorArgs: [],
web3SigningCredential: {
ethAccount: firstHighNetWorthAccount,
secret: besuKeyPair.privateKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
bytecode: HelloWorldContractJson.bytecode,
gas: 1000000,
});
t2.ok(deployOut, "deployContract() output is truthy OK");
t2.ok(
deployOut.transactionReceipt,
"deployContract() output.transactionReceipt is truthy OK",
);
t2.ok(
deployOut.transactionReceipt.contractAddress,
"deployContract() output.transactionReceipt.contractAddress is truthy OK",
);
contractAddress = deployOut.transactionReceipt.contractAddress as string;
t2.ok(
typeof contractAddress === "string",
"contractAddress typeof string OK",
);
const { callOutput: helloMsg } = await connector.invokeContract({
contractName: HelloWorldContractJson.contractName,
contractAbi: HelloWorldContractJson.abi,
contractAddress,
invocationType: EthContractInvocationType.Call,
methodName: "sayHello",
params: [],
signingCredential: {
ethAccount: firstHighNetWorthAccount,
secret: besuKeyPair.privateKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
});
t2.ok(helloMsg, "sayHello() output is truthy");
t2.true(
typeof helloMsg === "string",
"sayHello() output is type of string",
);
});
test("invoke Web3SigningCredentialType.NONE", async (t2: Test) => {
const testEthAccount2 = web3.eth.accounts.create(uuidv4());
const { rawTransaction } = await web3.eth.accounts.signTransaction(
{
from: testEthAccount.address,
to: testEthAccount2.address,
value: 10e6,
gas: 1000000,
},
testEthAccount.privateKey,
);
await connector.transact({
web3SigningCredential: {
type: Web3SigningCredentialType.None,
},
transactionConfig: {
rawTransaction,
},
consistencyStrategy: {
blockConfirmations: 0,
receiptType: ReceiptType.NodeTxPoolAck,
timeoutMs: 60000,
},
});
const balance2 = await web3.eth.getBalance(testEthAccount2.address);
t2.ok(balance2, "Retrieved balance of test account 2 OK");
t2.equals(parseInt(balance2, 10), 10e6, "Balance of test account2 is OK");
t2.end();
});
test("invoke Web3SigningCredentialType.PrivateKeyHex", async (t2: Test) => {
const newName = `DrCactus${uuidv4()}`;
const setNameOut = await connector.invokeContract({
contractName: HelloWorldContractJson.contractName,
contractAbi: HelloWorldContractJson.abi,
contractAddress,
invocationType: EthContractInvocationType.Send,
methodName: "setName",
params: [newName],
signingCredential: {
ethAccount: testEthAccount.address,
secret: testEthAccount.privateKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
nonce: 1,
});
t2.ok(setNameOut, "setName() invocation #1 output is truthy OK");
try {
const setNameOutInvalid = await connector.invokeContract({
contractName: HelloWorldContractJson.contractName,
contractAbi: HelloWorldContractJson.abi,
contractAddress,
invocationType: EthContractInvocationType.Send,
methodName: "setName",
params: [newName],
gas: 1000000,
signingCredential: {
ethAccount: testEthAccount.address,
secret: testEthAccount.privateKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
nonce: 1,
});
t2.ifError(setNameOutInvalid);
} catch (error) {
t2.notStrictEqual(
error,
"Nonce too low",
"setName() invocation with invalid nonce",
);
}
const { callOutput: getNameOut } = await connector.invokeContract({
contractName: HelloWorldContractJson.contractName,
contractAbi: HelloWorldContractJson.abi,
contractAddress,
invocationType: EthContractInvocationType.Call,
methodName: "getName",
params: [],
gas: 1000000,
signingCredential: {
ethAccount: testEthAccount.address,
secret: testEthAccount.privateKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
});
t2.equal(getNameOut, newName, `getName() output reflects the update OK`);
const getNameOut2 = await connector.invokeContract({
contractName: HelloWorldContractJson.contractName,
contractAbi: HelloWorldContractJson.abi,
contractAddress,
invocationType: EthContractInvocationType.Send,
methodName: "getName",
params: [],
gas: 1000000,
signingCredential: {
ethAccount: testEthAccount.address,
secret: testEthAccount.privateKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
});
t2.ok(getNameOut2, "getName() invocation #2 output is truthy OK");
const response = await connector.invokeContract({
contractName: HelloWorldContractJson.contractName,
contractAbi: HelloWorldContractJson.abi,
contractAddress,
invocationType: EthContractInvocationType.Send,
methodName: "deposit",
params: [],
gas: 1000000,
signingCredential: {
ethAccount: testEthAccount.address,
secret: testEthAccount.privateKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
value: 10,
});
t2.ok(response, "deposit() payable invocation output is truthy OK");
const { callOutput } = await connector.invokeContract({
contractName: HelloWorldContractJson.contractName,
contractAbi: HelloWorldContractJson.abi,
contractAddress,
invocationType: EthContractInvocationType.Call,
methodName: "getNameByIndex",
params: [0],
gas: 1000000,
signingCredential: {
ethAccount: testEthAccount.address,
secret: testEthAccount.privateKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
});
t2.equal(
callOutput,
newName,
`getNameByIndex() output reflects the update OK`,
);
t2.end();
});
test("invoke Web3SigningCredentialType.CactusKeychainRef", async (t2: Test) => {
const newName = `DrCactus${uuidv4()}`;
const signingCredential: Web3SigningCredentialCactusKeychainRef = {
ethAccount: testEthAccount.address,
keychainEntryKey,
keychainId: keychainPlugin.getKeychainId(),
type: Web3SigningCredentialType.CactusKeychainRef,
};
const setNameOut = await connector.invokeContract({
contractName: HelloWorldContractJson.contractName,
contractAbi: HelloWorldContractJson.abi,
contractAddress,
invocationType: EthContractInvocationType.Send,
methodName: "setName",
params: [newName],
gas: 1000000,
signingCredential,
nonce: 4,
});
t2.ok(setNameOut, "setName() invocation #1 output is truthy OK");
try {
const setNameOutInvalid = await connector.invokeContract({
contractName: HelloWorldContractJson.contractName,
contractAbi: HelloWorldContractJson.abi,
contractAddress,
invocationType: EthContractInvocationType.Send,
methodName: "setName",
params: [newName],
gas: 1000000,
signingCredential,
nonce: 4,
});
t2.ifError(setNameOutInvalid);
} catch (error) {
t2.notStrictEqual(
error,
"Nonce too low",
"setName() invocation with invalid nonce",
);
}
const { callOutput: getNameOut } = await connector.invokeContract({
contractName: HelloWorldContractJson.contractName,
contractAbi: HelloWorldContractJson.abi,
contractAddress,
invocationType: EthContractInvocationType.Call,
methodName: "getName",
params: [],
gas: 1000000,
signingCredential,
});
t2.equal(getNameOut, newName, `getName() output reflects the update OK`);
const getNameOut2 = await connector.invokeContract({
contractName: HelloWorldContractJson.contractName,
contractAbi: HelloWorldContractJson.abi,
contractAddress,
invocationType: EthContractInvocationType.Send,
methodName: "getName",
params: [],
gas: 1000000,
signingCredential,
});
t2.ok(getNameOut2, "getName() invocation #2 output is truthy OK");
const response = await connector.invokeContract({
contractName: HelloWorldContractJson.contractName,
contractAbi: HelloWorldContractJson.abi,
contractAddress,
invocationType: EthContractInvocationType.Send,
methodName: "deposit",
params: [],
gas: 1000000,
signingCredential,
value: 10,
});
t2.ok(response, "deposit() payable invocation output is truthy OK");
const { callOutput } = await connector.invokeContract({
contractName: HelloWorldContractJson.contractName,
contractAbi: HelloWorldContractJson.abi,
contractAddress,
invocationType: EthContractInvocationType.Call,
methodName: "getNameByIndex",
params: [1],
gas: 1000000,
signingCredential,
});
t2.equal(
callOutput,
newName,
`getNameByIndex() output reflects the update OK`,
);
t2.end();
});
test("get prometheus exporter metrics", async (t2: Test) => {
const res = await apiClient.getPrometheusMetricsV1();
const promMetricsOutput =
"# HELP " +
K_CACTUS_BESU_TOTAL_TX_COUNT +
" Total transactions executed\n" +
"# TYPE " +
K_CACTUS_BESU_TOTAL_TX_COUNT +
" gauge\n" +
K_CACTUS_BESU_TOTAL_TX_COUNT +
'{type="' +
K_CACTUS_BESU_TOTAL_TX_COUNT +
'"} 9';
t2.ok(res, "Response truthy OK");
t2.ok(res.data);
t2.equal(res.status, 200);
t2.true(
res.data.includes(promMetricsOutput),
"Total Transaction Count equals 9 OK.",
);
t2.end();
});
t.end();
});