-
Notifications
You must be signed in to change notification settings - Fork 121
/
Copy path14_holograph_operator_tests.ts
1720 lines (1584 loc) · 76.5 KB
/
14_holograph_operator_tests.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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { expect, assert } from 'chai';
import { PreTest } from './utils';
import setup from './utils';
import { BytesLike, BigNumber, ContractFactory } from 'ethers';
import { TransactionReceipt, TransactionResponse } from '@ethersproject/abstract-provider';
import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers';
import {
Signature,
StrictECDSA,
zeroAddress,
functionHash,
randomHex,
generateInitCode,
generateErc20Config,
generateErc721Config,
remove0x,
KeyOf,
HASH,
sleep,
} from '../scripts/utils/helpers';
import {
HolographERC20Event,
HolographERC721Event,
HolographERC1155Event,
ConfigureEvents,
} from '../scripts/utils/events';
import { HolographERC20, HolographOperator, Mock } from '../typechain-types';
import { GasParametersStructOutput } from '../typechain-types/LayerZeroModule';
import { ONLY_ADMIN_ERROR_MSG } from './utils/error_constants';
const bnHEX = function (n: number, bytes: number, prepend: boolean = true): BytesLike {
return (prepend ? '0x' : '') + remove0x(BigNumber.from(n).toHexString()).padStart(bytes * 2, '0');
};
const BLOCKTIME: number = 60;
const GWEI: BigNumber = BigNumber.from('1000000000');
const TESTGASLIMIT: BigNumber = BigNumber.from('10000000');
const GASPRICE: BigNumber = BigNumber.from('1000000000');
function shuffleWallets(array: KeyOf<PreTest>[]) {
let currentIndex = array.length,
randomIndex;
// While there remain elements to shuffle.
while (currentIndex != 0) {
// Pick a remaining element.
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]];
}
return array;
}
describe('Holograph Operator Contract', async () => {
let chain1: PreTest;
let chain2: PreTest;
let HLGCHAIN1: HolographERC20;
let HLGCHAIN2: HolographERC20;
let MOCKCHAIN1: Mock;
let MOCKCHAIN2: Mock;
let gasParameters: GasParametersStructOutput;
let msgBaseGas: BigNumber;
let msgGasPerByte: BigNumber;
let jobBaseGas: BigNumber;
let jobGasPerByte: BigNumber;
let mockOperator: HolographOperator;
let wallets: KeyOf<PreTest>[];
let pickOperator = function (chain: PreTest, target: string, opposite: boolean = false): SignerWithAddress {
let operator: SignerWithAddress = chain.deployer;
let targetOperator = target.toLowerCase();
if (targetOperator != zeroAddress) {
let wallet: SignerWithAddress;
// shuffle
shuffleWallets(wallets);
for (let i = 0, l = wallets.length; i < l; i++) {
wallet = chain[wallets[i]] as SignerWithAddress;
if (
(!opposite && wallet.address.toLowerCase() == targetOperator) ||
(opposite && wallet.address.toLowerCase() != targetOperator)
) {
operator = wallet;
break;
}
}
}
return operator;
};
let getLzMsgGas = function (payload: string): BigNumber {
return msgBaseGas.add(BigNumber.from(Math.floor((payload.length - 2) / 2)).mul(msgGasPerByte));
};
let getHlgMsgGas = function (gasLimit: BigNmber, payload: string): BigNumber {
return gasLimit.add(jobBaseGas.add(BigNumber.from(Math.floor((payload.length - 2) / 2)).mul(jobGasPerByte)));
};
let getRequestPayload = async function (
chain1: PreTest,
chain2: PreTest,
target: string | BytesLike,
data: string | BytesLike
): Promise<BytesLike> {
let payload: BytesLike = await chain1.bridge
.connect(chain1.deployer)
.callStatic.getBridgeOutRequestPayload(
chain2.network.holographId,
target as string,
'0x' + 'ff'.repeat(32),
'0x' + 'ff'.repeat(32),
data as string
);
return payload;
};
let getEstimatedGas = async function (
chain1: PreTest,
chain2: PreTest,
target: string | BytesLike,
data: string | BytesLike,
payload: string | BytesLike
): Promise<{
payload: string;
estimatedGas: BigNumber;
fee: BigNumber;
hlgFee: BigNumber;
msgFee: BigNumber;
dstGasPrice: BigNumber;
}> {
let estimatedGas: BigNumber = TESTGASLIMIT.sub(
await chain2.operator.callStatic.jobEstimator(payload as string, {
gasPrice: GASPRICE,
gasLimit: TESTGASLIMIT,
})
);
payload = await chain1.bridge
.connect(chain1.deployer)
.callStatic.getBridgeOutRequestPayload(
chain2.network.holographId,
target as string,
estimatedGas,
GWEI,
data as string
);
let fees = await chain1.bridge.callStatic.getMessageFee(chain2.network.holographId, estimatedGas, GWEI, payload);
let total: BigNumber = fees[0].add(fees[1]);
estimatedGas = TESTGASLIMIT.sub(
await chain2.operator.callStatic.jobEstimator(payload as string, {
value: total,
gasPrice: GASPRICE,
gasLimit: TESTGASLIMIT,
})
);
estimatedGas = getHlgMsgGas(estimatedGas, payload);
return { payload, estimatedGas, fee: total, hlgFee: fees[0], msgFee: fees[1], dstGasPrice: fees[2] };
};
let availableJobs: string[] = [];
let zeroAddressJobs: string[] = [];
let availableJobsGas: BigNumber[] = [];
let zeroAddressJobsGas: BigNumber[] = [];
let operatorJobTokenId: number = 0;
let createOperatorJob = async function (
chain1: PreTest,
chain2: PreTest,
tokenId: number,
skipZeroAddressFallback: boolean = false
): Promise<boolean> {
if (tokenId > 1) {
await chain1.sampleErc721
.attach(chain1.sampleErc721Holographer.address)
.mint(chain1.deployer.address, bnHEX(tokenId, 32), 'IPFSURIHERE');
}
let originalMessagingModule = await chain2.operator.getMessagingModule();
let data: BytesLike = generateInitCode(
['address', 'address', 'uint256'],
[chain1.deployer.address, chain2.deployer.address, bnHEX(tokenId, 32)]
);
let payload: BytesLike = await getRequestPayload(chain1, chain2, chain1.sampleErc721Holographer.address, data);
let gasEstimates = await getEstimatedGas(chain1, chain2, chain1.sampleErc721Holographer.address, data, payload);
payload = gasEstimates.payload;
let payloadHash: string = HASH(payload);
// temporarily set MockLZEndpoint as messaging module, to allow for easy sending
await chain2.operator.setMessagingModule(chain2.mockLZEndpoint.address);
// make call with mockLZEndpoint AS messaging module
await chain2.mockLZEndpoint.crossChainMessage(chain2.operator.address, getLzMsgGas(payload), payload, {
gasLimit: TESTGASLIMIT,
});
// return messaging module back to original address
await chain2.operator.setMessagingModule(originalMessagingModule);
let operatorJob = await chain2.operator.getJobDetails(payloadHash);
let operator = (operatorJob[2] as string).toLowerCase();
if (operator == zeroAddress) {
zeroAddressJobs.push(payloadHash);
zeroAddressJobs.push(payload as string);
zeroAddressJobsGas.push(gasEstimates.estimatedGas);
return false;
} else {
if (skipZeroAddressFallback && operatorJob[5][0] == 0) {
// need to skip this one, since it will fail a fallback test
// execute job to leave operator bonded
await chain2.operator
.connect(pickOperator(chain2, operator))
.executeJob(payload, { gasLimit: gasEstimates.estimatedGas });
return false;
} else {
availableJobs.push(payloadHash);
availableJobs.push(payload as string);
availableJobsGas.push(gasEstimates.estimatedGas);
return true;
}
}
};
before(async function () {
chain1 = await setup();
chain2 = await setup(true);
HLGCHAIN1 = await chain1.holographErc20.attach(chain1.utilityTokenHolographer.address);
HLGCHAIN2 = await chain2.holographErc20.attach(chain2.utilityTokenHolographer.address);
MOCKCHAIN1 = (await (await chain1.hre.ethers.getContractFactory('Mock')).deploy()) as Mock;
await MOCKCHAIN1.deployed();
await MOCKCHAIN1.init(generateInitCode(['bytes32'], ['0x' + 'ff'.repeat(32)]));
await MOCKCHAIN1.setStorage(0, '0x' + remove0x(chain1.operator.address).padStart(64, '0'));
MOCKCHAIN2 = (await (await chain2.hre.ethers.getContractFactory('Mock')).deploy()) as Mock;
await MOCKCHAIN2.deployed();
await MOCKCHAIN2.init(generateInitCode(['bytes32'], ['0x' + 'ff'.repeat(32)]));
await MOCKCHAIN2.setStorage(0, '0x' + remove0x(chain2.operator.address).padStart(64, '0'));
gasParameters = await chain1.lzModule.getGasParameters(chain1.network.holographId);
msgBaseGas = gasParameters.msgBaseGas;
msgGasPerByte = gasParameters.msgGasPerByte;
jobBaseGas = gasParameters.jobBaseGas;
jobGasPerByte = gasParameters.jobGasPerByte;
wallets = [
'wallet1',
'wallet2',
'wallet3',
'wallet4',
'wallet5',
'wallet6',
'wallet7',
'wallet8',
'wallet9',
'wallet10',
];
await chain1.sampleErc721
.attach(chain1.sampleErc721Holographer.address)
.mint(chain1.deployer.address, bnHEX(1, 32), 'IPFSURIHERE');
// 0xfffffffd00000000000000000000000000000000000000000000000000000001
await chain2.sampleErc721
.attach(chain1.sampleErc721Holographer.address)
.mint(chain1.deployer.address, bnHEX(1, 32), 'IPFSURIHERE');
});
function testPrivateFunction(functionName: string, user?: SignerWithAddress) {
const sender = user ?? chain1.deployer;
const operator = chain1.operator.connect(sender) as any;
const method = operator[functionName];
expect(typeof method).to.equal('undefined');
expect(chain1.operator.connect(sender)).to.not.have.property(functionName);
}
after(async () => {});
beforeEach(async () => {});
afterEach(async () => {});
describe('Deploy cross-chain contracts', async function () {
describe('hToken', async function () {
it('deploy chain1 equivalent on chain2', async function () {
let { erc20Config, erc20ConfigHash, erc20ConfigHashBytes } = await generateErc20Config(
chain1.network,
chain1.deployer.address,
'hToken',
chain1.network.tokenName + ' (Holographed #' + chain1.network.holographId.toString() + ')',
'h' + chain1.network.tokenSymbol,
chain1.network.tokenName + ' (Holographed #' + chain1.network.holographId.toString() + ')',
'1',
18,
ConfigureEvents([]),
generateInitCode(['address', 'uint16'], [chain1.deployer.address, 0]),
chain1.salt
);
let hTokenErc20Address = await chain2.registry.getHolographedHashAddress(erc20ConfigHash);
expect(hTokenErc20Address).to.equal(zeroAddress);
hTokenErc20Address = await chain1.registry.getHolographedHashAddress(erc20ConfigHash);
let sig = await chain1.deployer.signMessage(erc20ConfigHashBytes);
let signature: Signature = StrictECDSA({
r: '0x' + sig.substring(2, 66),
s: '0x' + sig.substring(66, 130),
v: '0x' + sig.substring(130, 132),
} as Signature);
await expect(chain2.factory.deployHolographableContract(erc20Config, signature, chain1.deployer.address))
.to.emit(chain2.factory, 'BridgeableContractDeployed')
.withArgs(hTokenErc20Address, erc20ConfigHash);
});
it('deploy chain2 equivalent on chain1', async function () {
let { erc20Config, erc20ConfigHash, erc20ConfigHashBytes } = await generateErc20Config(
chain2.network,
chain2.deployer.address,
'hToken',
chain2.network.tokenName + ' (Holographed #' + chain2.network.holographId.toString() + ')',
'h' + chain2.network.tokenSymbol,
chain2.network.tokenName + ' (Holographed #' + chain2.network.holographId.toString() + ')',
'1',
18,
ConfigureEvents([]),
generateInitCode(['address', 'uint16'], [chain2.deployer.address, 0]),
chain2.salt
);
let hTokenErc20Address = await chain1.registry.getHolographedHashAddress(erc20ConfigHash);
expect(hTokenErc20Address).to.equal(zeroAddress);
hTokenErc20Address = await chain2.registry.getHolographedHashAddress(erc20ConfigHash);
let sig = await chain2.deployer.signMessage(erc20ConfigHashBytes);
let signature: Signature = StrictECDSA({
r: '0x' + sig.substring(2, 66),
s: '0x' + sig.substring(66, 130),
v: '0x' + sig.substring(130, 132),
} as Signature);
await expect(chain1.factory.deployHolographableContract(erc20Config, signature, chain2.deployer.address))
.to.emit(chain1.factory, 'BridgeableContractDeployed')
.withArgs(hTokenErc20Address, erc20ConfigHash);
});
});
});
describe('constructor', async () => {
it('should successfully deploy', async () => {
let operatorFactory: ContractFactory = await chain1.hre.ethers.getContractFactory('HolographOperator');
mockOperator = (await operatorFactory.deploy()) as HolographOperator;
await mockOperator.deployed();
assert(mockOperator.address != zeroAddress, 'zero address');
let deployedCode = await chain1.hre.ethers.provider.getCode(mockOperator.address);
assert(deployedCode != '0x' && deployedCode != '', 'code not deployed');
});
});
describe('init()', async () => {
it('should successfully be initialized once', async () => {
let initPayload = generateInitCode(
['address', 'address', 'address', 'address', 'address', 'uint256'],
[
await chain1.operator.getBridge(),
await chain1.operator.getHolograph(),
await chain1.operator.getInterfaces(),
await chain1.operator.getRegistry(),
await chain1.operator.getUtilityToken(),
await chain1.operator.getMinGasPrice(),
]
);
let tx = await mockOperator.init(initPayload);
await tx.wait();
expect(await mockOperator.getBridge()).to.equal(await chain1.operator.getBridge());
expect(await mockOperator.getHolograph()).to.equal(await chain1.operator.getHolograph());
expect(await mockOperator.getInterfaces()).to.equal(await chain1.operator.getInterfaces());
expect(await mockOperator.getRegistry()).to.equal(await chain1.operator.getRegistry());
expect(await mockOperator.getUtilityToken()).to.equal(await chain1.operator.getUtilityToken());
expect(await mockOperator.getMinGasPrice()).to.equal(await chain1.operator.getMinGasPrice());
});
it('should fail if already initialized', async () => {
let initPayload = generateInitCode(
['address', 'address', 'address', 'address', 'address', 'uint256'],
[zeroAddress, zeroAddress, zeroAddress, zeroAddress, zeroAddress, '0x' + '00'.repeat(32)]
);
await expect(mockOperator.init(initPayload)).to.be.revertedWith('HOLOGRAPH: already initialized');
});
it('Should allow external contract to call fn', async () => {
let initPayload = generateInitCode(
['address', 'address', 'address', 'address', 'address', 'uint256'],
[zeroAddress, zeroAddress, zeroAddress, zeroAddress, zeroAddress, '0x' + '00'.repeat(32)]
);
// temp set fallback to mockOperator
await MOCKCHAIN1.setStorage(0, '0x' + remove0x(mockOperator.address).padStart(64, '0'));
await expect(
MOCKCHAIN1.callStatic.mockCall(
mockOperator.address,
(
await mockOperator.populateTransaction.init(initPayload)
).data as string
)
).to.be.revertedWith('HOLOGRAPH: already initialized');
// return fallback to operator
await MOCKCHAIN1.setStorage(0, '0x' + remove0x(chain1.operator.address).padStart(64, '0'));
});
it.skip('should fail to allow inherited contract to call fn', async () => {});
});
describe('jobEstimator()', async () => {
it('should return expected estimated value', async () => {
// used this space go into more detail and breakdown what is actually happening behind the scenes
let bridgeInRequestPayload =
// this is the data that is sent to HolographOperator jobEstimator function
generateInitCode(
// bridgeInRequestPayload
['uint256', 'uint32', 'address', 'address', 'address', 'uint256', 'bool', 'bytes'],
[
0, // nonce
chain1.network.holographId, // fromChain
chain1.sampleErc721Holographer.address, // holographableContract
zeroAddress, // hToken
zeroAddress, // hTokenRecipient
0, // hTokenValue
true, // doNotRevert
// this is the data that is sent to HolographBridge (by operator) bridgeInRequest function
generateInitCode(
// bridgeInPayload
['uint32', 'bytes'],
[
chain1.network.holographId, // fromChain
// this is the data that is sent to HolographERC721 (enforcer) bridgeIn function
generateInitCode(
// payload
['address', 'address', 'uint256', 'bytes'],
[
chain1.deployer.address, // from
chain1.deployer.address, // to
bnHEX(1, 32), // tokenId
// this is init code that is sent to SampleERC721 (custom contract) bridgeIn function
generateInitCode(
// _data
['string'],
[
'IPFSURIHERE', // token URI
]
),
]
),
]
),
]
);
let functionSig = functionHash('bridgeInRequest(uint256,uint32,address,address,address,uint256,bool,bytes)'); // fuunction signature
let gasEstimation = await chain2.operator.callStatic.jobEstimator(functionSig + remove0x(bridgeInRequestPayload));
assert(gasEstimation.gt(BigNumber.from('0x5af3107a4000')), 'unexpectedly low gas estimation'); // 0.001 ETH
});
it('Should allow external contract to call fn', async () => {
let data: BytesLike = generateInitCode(
['address', 'address', 'uint256'],
[chain1.deployer.address, chain2.deployer.address, bnHEX(1, 32)]
);
let payload: BytesLike = await getRequestPayload(chain1, chain2, chain1.sampleErc721Holographer.address, data);
let estimatedGas: BigNumber = TESTGASLIMIT.sub(
await chain2.operator.callStatic.jobEstimator(payload, {
gasPrice: GASPRICE,
gasLimit: TESTGASLIMIT,
})
);
payload = await chain1.bridge
.connect(chain1.deployer)
.callStatic.getBridgeOutRequestPayload(
chain2.network.holographId,
chain1.sampleErc721Holographer.address,
estimatedGas,
GWEI,
data
);
let fees = await chain1.bridge.callStatic.getMessageFee(chain2.network.holographId, estimatedGas, GWEI, payload);
let total: BigNumber = fees[0].add(fees[1]);
let gasEstimation = await chain2.operator
.attach(MOCKCHAIN2.address)
.callStatic.jobEstimator(payload, { value: BigNumber.from('1000000000000000000') });
assert(gasEstimation.gt(BigNumber.from('0x38d7ea4c68000')), 'unexpectedly low gas estimation'); // 0.001 ETH
});
it.skip('should fail to allow inherited contract to call fn', async () => {});
it('should be payable', async () => {
let data: BytesLike = generateInitCode(
['address', 'address', 'uint256'],
[chain1.deployer.address, chain2.deployer.address, bnHEX(1, 32)]
);
let payload: BytesLike = await getRequestPayload(chain1, chain2, chain1.sampleErc721Holographer.address, data);
let gasEstimates = await getEstimatedGas(chain1, chain2, chain1.sampleErc721Holographer.address, data, payload); // returns: payload, gasLimit, nativeFee, hlgFee, msgFee
assert(gasEstimates.estimatedGas.gt(BigNumber.from('100000')), 'unexpectedly low gas estimation'); // 100k gas units
});
});
describe('getTotalPods()', async () => {
it('should return expected number of pods', async () => {
expect(await chain1.operator.getTotalPods()).to.equal(BigNumber.from('1'));
});
});
describe('getPodOperatorsLength()', async () => {
it('should return expected pod length', async () => {
expect(await chain1.operator.getPodOperatorsLength(1)).to.equal(BigNumber.from('1'));
});
it('should fail if pod does not exist', async () => {
await expect(chain1.operator.getPodOperatorsLength(2)).to.be.revertedWith('HOLOGRAPH: pod does not exist');
});
});
describe('getPodOperators(pod)', async () => {
it('should return expected operators for a valid pod', async () => {
let operators = await chain1.operator.callStatic['getPodOperators(uint256)'](1);
assert.deepEqual(operators, [zeroAddress]);
});
it('should fail to return operators for an INVALID pod', async () => {
await expect(chain1.operator['getPodOperators(uint256)'](2)).to.be.revertedWith('HOLOGRAPH: pod does not exist');
});
it('Should allow external contract to call fn', async () => {
let operators = await chain1.operator.attach(MOCKCHAIN1.address).callStatic['getPodOperators(uint256)'](1);
assert.deepEqual(operators, [zeroAddress]);
});
it.skip('should fail to allow inherited contract to call fn', async () => {});
});
describe('getPodOperators(pod, index, length)', async () => {
it('should return expected operators for a valid pod', async () => {
let operators = await chain1.operator.callStatic['getPodOperators(uint256,uint256,uint256)'](1, 0, 10);
assert.deepEqual(operators, [zeroAddress]);
});
it('should fail to return operators for an INVALID pod', async () => {
await expect(chain1.operator['getPodOperators(uint256,uint256,uint256)'](2, 0, 10)).to.be.revertedWith(
'HOLOGRAPH: pod does not exist'
);
});
it('should fail if index out of bounds', async () => {
await expect(chain1.operator['getPodOperators(uint256,uint256,uint256)'](1, 10, 10)).to.be.reverted;
});
// this will never fail because length is auto adjusted
//it.skip('should fail if length is out of bounds', async () => {});
it('Should allow external contract to call fn', async () => {
let operators = await chain1.operator
.attach(MOCKCHAIN1.address)
.callStatic['getPodOperators(uint256,uint256,uint256)'](1, 0, 10);
assert.deepEqual(operators, [zeroAddress]);
});
it.skip('should fail to allow inherited contract to call fn', async () => {});
});
describe('getPodBondAmounts(pod)', async () => {
it('should return expected base and current value', async () => {
let bondRequirements1: BigNumber[] = await chain1.operator.getPodBondAmounts(1);
assert.equal(bondRequirements1[0].toHexString(), '0x056bc75e2d63100000');
assert.equal(bondRequirements1[1].toHexString(), '0x056bc75e2d63100000');
let bondRequirements2: BigNumber[] = await chain1.operator.getPodBondAmounts(2);
assert.equal(bondRequirements2[0].toHexString(), '0x0ad78ebc5ac6200000');
assert.equal(bondRequirements2[1].toHexString(), '0x0ad78ebc5ac6200000');
});
it('Should allow external contract to call fn', async () => {
let bondRequirements1 = await chain1.operator.attach(MOCKCHAIN1.address).getPodBondAmounts(1);
assert.equal(bondRequirements1[0].toHexString(), '0x056bc75e2d63100000');
assert.equal(bondRequirements1[1].toHexString(), '0x056bc75e2d63100000');
});
it.skip('should fail to allow inherited contract to call fn', async () => {});
});
describe('bondUtilityToken()', async () => {
it('should successfully allow bonding', async () => {
let bondRequirements: BigNumber[] = await chain1.operator.getPodBondAmounts(1);
let currentBondAmount: BigNumber = bondRequirements[1];
await expect(chain1.operator.bondUtilityToken(chain1.deployer.address, currentBondAmount, 1))
.to.emit(HLGCHAIN1, 'Transfer')
.withArgs(chain1.deployer.address, chain1.operator.address, currentBondAmount);
expect(await chain1.operator.getBondedAmount(chain1.deployer.address)).to.equal(currentBondAmount);
expect(await chain1.operator.getBondedPod(chain1.deployer.address)).to.equal(BigNumber.from('1'));
});
it('should successfully allow bonding a contract', async () => {
let bondRequirements: BigNumber[] = await chain1.operator.getPodBondAmounts(1);
let currentBondAmount: BigNumber = bondRequirements[1];
// we will bond to SampleERC20 as an example
await expect(chain1.operator.bondUtilityToken(chain1.sampleErc20Holographer.address, currentBondAmount, 1))
.to.emit(HLGCHAIN1, 'Transfer')
.withArgs(chain1.deployer.address, chain1.operator.address, currentBondAmount);
expect(await chain1.operator.getBondedAmount(chain1.sampleErc20Holographer.address)).to.equal(currentBondAmount);
expect(await chain1.operator.getBondedPod(chain1.sampleErc20Holographer.address)).to.equal(BigNumber.from('1'));
});
it('should fail if the operator is already bonded', async () => {
let bondRequirements: BigNumber[] = await chain1.operator.getPodBondAmounts(1);
let currentBondAmount: BigNumber = bondRequirements[1];
await expect(chain1.operator.bondUtilityToken(chain1.deployer.address, currentBondAmount, 1)).to.be.revertedWith(
'HOLOGRAPH: operator is bonded'
);
bondRequirements = await chain1.operator.getPodBondAmounts(2);
currentBondAmount = bondRequirements[1];
await expect(chain1.operator.bondUtilityToken(chain1.deployer.address, currentBondAmount, 2)).to.be.revertedWith(
'HOLOGRAPH: operator is bonded'
);
});
it('Should fail if the provided bond amount is too low', async () => {
let bondRequirements: BigNumber[] = await chain1.operator.getPodBondAmounts(1);
let currentBondAmount: BigNumber = bondRequirements[1];
await expect(
chain1.operator.connect(chain1.wallet1).bondUtilityToken(chain1.wallet1.address, currentBondAmount, 2)
).to.be.revertedWith('HOLOGRAPH: bond amount too small');
});
it('Should fail if operator does not have enough utility tokens', async () => {
let bondRequirements: BigNumber[] = await chain1.operator.getPodBondAmounts(1);
let currentBondAmount: BigNumber = bondRequirements[1];
await expect(
chain1.operator.connect(chain1.wallet1).bondUtilityToken(chain1.wallet1.address, currentBondAmount, 1)
).to.be.revertedWith('ERC20: amount exceeds balance');
});
it('should fail if the token transfer failed', async () => {
let bondRequirements: BigNumber[] = await chain1.operator.getPodBondAmounts(1);
let currentBondAmount: BigNumber = bondRequirements[1];
await expect(
chain1.operator.connect(chain1.wallet1).bondUtilityToken(chain1.wallet2.address, currentBondAmount, 1)
).to.be.revertedWith('ERC20: amount exceeds balance');
});
/**
* @dev This one is impossible to do, pod operator limit is max value of uint16 (65535)
* Maybe do this as an entirely separate test/file where that many random wallets are assigned
* There might be an issue of not enough utility token being available for this to happen
*/
//it.skip('should fail if the pod operator limit has been reached', async () => {});
it('Should allow external contract to call fn', async () => {
let bondRequirements: BigNumber[] = await chain1.operator.getPodBondAmounts(1);
let currentBondAmount: BigNumber = bondRequirements[1];
await HLGCHAIN1.transfer(MOCKCHAIN1.address, currentBondAmount);
await expect(
chain1.operator.attach(MOCKCHAIN1.address).bondUtilityToken(MOCKCHAIN1.address, currentBondAmount, 1)
)
.to.emit(HLGCHAIN1, 'Transfer')
.withArgs(MOCKCHAIN1.address, chain1.operator.address, currentBondAmount);
expect(await chain1.operator.getBondedAmount(MOCKCHAIN1.address)).to.equal(currentBondAmount);
expect(await chain1.operator.getBondedPod(MOCKCHAIN1.address)).to.equal(BigNumber.from('1'));
});
it.skip('should fail to allow inherited contract to call fn', async () => {});
});
describe('topupUtilityToken()', async () => {
it('should fail if operator is not bonded', async () => {
let bondRequirements: BigNumber[] = await chain1.operator.getPodBondAmounts(1);
let currentBondAmount: BigNumber = bondRequirements[1];
expect(await chain1.operator.getBondedPod(chain1.wallet1.address)).to.equal(BigNumber.from('0'));
await expect(
chain1.operator.connect(chain1.wallet1).topupUtilityToken(chain1.wallet1.address, currentBondAmount)
).to.be.revertedWith('HOLOGRAPH: operator not bonded');
});
it('successfully top up utility tokens', async () => {
let bondRequirements: BigNumber[] = await chain1.operator.getPodBondAmounts(1);
let currentBondAmount: BigNumber = bondRequirements[1];
await HLGCHAIN1.transfer(chain1.wallet1.address, currentBondAmount);
expect(await chain1.operator.getBondedPod(chain1.deployer.address)).to.equal(BigNumber.from('1'));
await expect(
chain1.operator.connect(chain1.wallet1).topupUtilityToken(chain1.deployer.address, currentBondAmount)
)
.to.emit(HLGCHAIN1, 'Transfer')
.withArgs(chain1.wallet1.address, chain1.operator.address, currentBondAmount);
expect(await chain1.operator.getBondedAmount(chain1.deployer.address)).to.equal(
currentBondAmount.mul(BigNumber.from('2'))
);
});
});
describe('unbondUtilityToken()', async () => {
it('should fail if the operator has not bonded', async () => {
await expect(
chain1.operator.connect(chain1.wallet2).unbondUtilityToken(chain1.wallet2.address, chain1.wallet2.address)
).to.be.revertedWith('HOLOGRAPH: operator not bonded');
});
it('should fail if the operator is not sender, and operator is not contract', async () => {
await expect(
chain1.operator.connect(chain1.wallet1).unbondUtilityToken(chain1.deployer.address, chain1.wallet1.address)
).to.be.revertedWith('HOLOGRAPH: operator not contract');
});
it('Should succeed if operator is contract and owned by sender', async () => {
let currentBondAmount: BigNumber = await chain1.operator.getBondedAmount(chain1.sampleErc20Holographer.address);
await expect(chain1.operator.unbondUtilityToken(chain1.sampleErc20Holographer.address, chain1.deployer.address))
.to.emit(HLGCHAIN1, 'Transfer')
.withArgs(chain1.operator.address, chain1.deployer.address, currentBondAmount);
expect(await chain1.operator.getBondedAmount(chain1.sampleErc20Holographer.address)).to.equal(
BigNumber.from('0')
);
});
it('Should fail if operator is contract and not owned by sender', async () => {
let bondRequirements: BigNumber[] = await chain1.operator.getPodBondAmounts(1);
let currentBondAmount: BigNumber = bondRequirements[1];
// we will bond to SampleERC20 as an example
await expect(chain1.operator.bondUtilityToken(chain1.sampleErc20Holographer.address, currentBondAmount, 1))
.to.emit(HLGCHAIN1, 'Transfer')
.withArgs(chain1.deployer.address, chain1.operator.address, currentBondAmount);
expect(await chain1.operator.getBondedAmount(chain1.sampleErc20Holographer.address)).to.equal(currentBondAmount);
expect(await chain1.operator.getBondedPod(chain1.sampleErc20Holographer.address)).to.equal(BigNumber.from('1'));
await expect(
chain1.operator
.connect(chain1.wallet1)
.unbondUtilityToken(chain1.sampleErc20Holographer.address, chain1.deployer.address)
).to.be.revertedWith('HOLOGRAPH: sender not owner');
});
it('should fail if the token transfer failed', async () => {
let currentBalance: BigNumber = await HLGCHAIN1.balanceOf(chain1.operator.address);
await expect(
chain1.operator.adminCall(
HLGCHAIN1.address,
(
await HLGCHAIN1.populateTransaction.transfer(chain1.deployer.address, currentBalance)
).data as string
)
)
.to.emit(HLGCHAIN1, 'Transfer')
.withArgs(chain1.operator.address, chain1.deployer.address, currentBalance);
expect(await HLGCHAIN1.balanceOf(chain1.operator.address)).to.equal(BigNumber.from('0'));
await expect(
chain1.operator.unbondUtilityToken(chain1.deployer.address, chain1.deployer.address)
).to.be.revertedWith('ERC20: amount exceeds balance');
await HLGCHAIN1.transfer(chain1.operator.address, currentBalance);
});
it('should successfully allow unbonding', async () => {
let currentBondAmount: BigNumber = await chain1.operator.getBondedAmount(chain1.deployer.address);
await expect(chain1.operator.unbondUtilityToken(chain1.deployer.address, chain1.deployer.address))
.to.emit(HLGCHAIN1, 'Transfer')
.withArgs(chain1.operator.address, chain1.deployer.address, currentBondAmount);
expect(await chain1.operator.getBondedAmount(chain1.deployer.address)).to.equal(BigNumber.from('0'));
});
it('Should allow external contract to call fn', async () => {
let currentBondAmount: BigNumber = await chain1.operator.getBondedAmount(MOCKCHAIN1.address);
await expect(
chain1.operator.attach(MOCKCHAIN1.address).unbondUtilityToken(MOCKCHAIN1.address, chain1.deployer.address)
)
.to.emit(HLGCHAIN1, 'Transfer')
.withArgs(chain1.operator.address, chain1.deployer.address, currentBondAmount);
expect(await chain1.operator.getBondedAmount(MOCKCHAIN1.address)).to.equal(BigNumber.from('0'));
});
it.skip('should fail to allow inherited contract to call fn', async () => {});
});
describe('getBondedAmount()', async () => {
it('should return expected _bondedOperators', async () => {
let bondRequirements: BigNumber[] = await chain1.operator.getPodBondAmounts(1);
expect(await chain1.operator.getBondedAmount(chain1.sampleErc20Holographer.address)).to.equal(
bondRequirements[0]
);
});
it('Should allow external contract to call fn', async () => {
let bondRequirements: BigNumber[] = await chain1.operator.getPodBondAmounts(1);
expect(
await chain1.operator.attach(MOCKCHAIN1.address).getBondedAmount(chain1.sampleErc20Holographer.address)
).to.equal(bondRequirements[0]);
});
it.skip('should fail to allow inherited contract to call fn', async () => {});
});
describe('getBondedPod()', async () => {
it('should return expected _bondedOperators', async () => {
expect(await chain1.operator.getBondedPod(chain1.sampleErc20Holographer.address)).to.equal(BigNumber.from('1'));
});
it('Should allow external contract to call fn', async () => {
expect(
await chain1.operator.attach(MOCKCHAIN1.address).getBondedPod(chain1.sampleErc20Holographer.address)
).to.equal(BigNumber.from('1'));
// actually unbond afterwards
await chain1.operator.unbondUtilityToken(chain1.sampleErc20Holographer.address, chain1.deployer.address);
});
it.skip('should fail to allow inherited contract to call fn', async () => {});
});
describe('crossChainMessage()', async () => {
it('Should successfully allow messaging address to call fn', async () => {
let originalMessagingModule = await chain2.operator.getMessagingModule();
// generate payload
let data: BytesLike = generateInitCode(
['address', 'address', 'uint256'],
[chain1.deployer.address, chain2.deployer.address, bnHEX(1, 32)]
);
let payload: BytesLike = await getRequestPayload(chain1, chain2, chain1.sampleErc721Holographer.address, data);
let gasEstimates = await getEstimatedGas(chain1, chain2, chain1.sampleErc721Holographer.address, data, payload);
payload = gasEstimates.payload;
// this is to make sure it reverts
let search: string = remove0x(chain1.sampleErc721Holographer.address).toLowerCase();
let replace: string = remove0x(zeroAddress);
payload = payload.replace(search, replace);
let payloadHash: string = HASH(payload);
// temporarily set MockLZEndpoint as messaging module, to allow for easy sending
await chain2.operator.setMessagingModule(chain2.mockLZEndpoint.address);
// make call with mockLZEndpoint AS messaging module
await expect(
chain2.mockLZEndpoint.crossChainMessage(chain2.operator.address, getLzMsgGas(payload), payload, {
gasLimit: TESTGASLIMIT,
})
)
.to.emit(chain2.operator, 'AvailableOperatorJob')
.withArgs(payloadHash, payload);
availableJobs.push(payloadHash);
availableJobs.push(payload as string);
availableJobsGas.push(gasEstimates.estimatedGas);
// return messaging module back to original address
await chain2.operator.setMessagingModule(originalMessagingModule);
});
it('Should fail to allow admin address to call fn', async () => {
// just random bytes, along with gasPrice and gasLimit at the end
let payload: string =
randomHex(4) + randomHex(64, false) + bnHEX(1000000000, 32, false) + bnHEX(1000000, 32, false);
let payloadHash: string = HASH(payload);
await expect(chain1.operator.crossChainMessage(payload)).to.be.revertedWith('HOLOGRAPH: messaging only call');
});
it('Should fail to allow random address to call fn', async () => {
// just random bytes, along with gasPrice and gasLimit at the end
let payload: string =
randomHex(4) + randomHex(64, false) + bnHEX(1000000000, 32, false) + bnHEX(1000000, 32, false);
let payloadHash: string = HASH(payload);
await expect(chain1.operator.connect(chain1.wallet1).crossChainMessage(payload)).to.be.revertedWith(
'HOLOGRAPH: messaging only call'
);
});
});
describe('getJobDetails()', async () => {
it('should return expected operatorJob from valid jobHash', async () => {
let jobHash: string = availableJobs[0];
let operatorJob: string = JSON.stringify(await chain2.operator.getJobDetails(jobHash));
assert(
operatorJob !=
'[0,' +
BLOCKTIME +
',"0x0000000000000000000000000000000000000000",0,{"type":"BigNumber","hex":"0x00"},[0,0,0,0,0]]',
'valid job hash returns empty job details'
);
});
it('should return expected operatorJob from INVALID jobHash', async () => {
let jobHash: string = '0x' + '00'.repeat(32);
let operatorJob: string = JSON.stringify(await chain2.operator.getJobDetails(jobHash));
assert(
operatorJob ==
'[0,' +
BLOCKTIME +
',"0x0000000000000000000000000000000000000000",0,{"type":"BigNumber","hex":"0x00"},[0,0,0,0,0]]',
'invalid job hash returns non-empty job details'
);
});
});
describe('getPodOperatorsLength()', async () => {
it('should return expected pod length', async () => {
expect(await chain1.operator.getPodOperatorsLength(1)).to.equal(BigNumber.from('1'));
});
it('should fail if pod does not exist', async () => {
await expect(chain1.operator.getPodOperatorsLength(2)).to.be.revertedWith('HOLOGRAPH: pod does not exist');
});
});
describe('** bond test operators **', async () => {
it('should add 10 operator wallets on each chain', async function () {
let bondAmounts: BigNumber[] = await chain1.operator.getPodBondAmounts(1);
let bondAmount: BigNumber = bondAmounts[0];
for (let i = 0, l = wallets.length; i < l; i++) {
let chain1wallet: SignerWithAddress = chain1[wallets[i]] as SignerWithAddress;
let chain2wallet: SignerWithAddress = chain2[wallets[i]] as SignerWithAddress;
await HLGCHAIN1.connect(chain1wallet).approve(chain1.operator.address, bondAmount);
await expect(chain1.operator.bondUtilityToken(chain1wallet.address, bondAmount, 1)).to.not.be.reverted;
await expect(chain2.operator.bondUtilityToken(chain2wallet.address, bondAmount, 1)).to.not.be.reverted;
}
});
});
describe('SampleERC20', async function () {
it('deploy chain1 equivalent on chain2', async function () {
let { erc20Config, erc20ConfigHash, erc20ConfigHashBytes } = await generateErc20Config(
chain1.network,
chain1.deployer.address,
'SampleERC20',
'Sample ERC20 Token (' + chain1.hre.networkName + ')',
'SMPL',
'Sample ERC20 Token',
'1',
18,
ConfigureEvents([HolographERC20Event.bridgeIn, HolographERC20Event.bridgeOut]),
generateInitCode(['address', 'uint16'], [chain1.deployer.address, 0]),
chain1.salt
);
let sampleErc20Address = await chain2.registry.getHolographedHashAddress(erc20ConfigHash);
expect(sampleErc20Address).to.equal(zeroAddress);
sampleErc20Address = await chain1.registry.getHolographedHashAddress(erc20ConfigHash);
let sig = await chain1.deployer.signMessage(erc20ConfigHashBytes);
let signature: Signature = StrictECDSA({
r: '0x' + sig.substring(2, 66),
s: '0x' + sig.substring(66, 130),
v: '0x' + sig.substring(130, 132),
} as Signature);
let data: BytesLike = generateInitCode(
['tuple(bytes32,uint32,bytes32,bytes,bytes)', 'tuple(bytes32,bytes32,uint8)', 'address'],
[
[
erc20Config.contractType,
erc20Config.chainType,
erc20Config.salt,
erc20Config.byteCode,
erc20Config.initCode,
],
[signature.r, signature.s, signature.v],
chain1.deployer.address,
]
);
let originalMessagingModule = await chain2.operator.getMessagingModule();
let payload: BytesLike = await getRequestPayload(chain1, chain2, chain1.factory.address, data);
let gasEstimates = await getEstimatedGas(chain1, chain2, chain1.factory.address, data, payload);
payload = gasEstimates.payload;
let payloadHash: string = HASH(payload);
// temporarily set MockLZEndpoint as messaging module, to allow for easy sending
await chain2.operator.setMessagingModule(chain2.mockLZEndpoint.address);
// make call with mockLZEndpoint AS messaging module
await chain2.mockLZEndpoint.crossChainMessage(chain2.operator.address, getLzMsgGas(payload), payload, {
gasLimit: TESTGASLIMIT,
});
// return messaging module back to original address
await chain2.operator.setMessagingModule(originalMessagingModule);
let operatorJob = await chain2.operator.getJobDetails(payloadHash);
let operator = (operatorJob[2] as string).toLowerCase();
// execute job to leave operator bonded
await expect(
chain2.operator
.connect(pickOperator(chain2, operator))
.executeJob(payload, { gasLimit: gasEstimates.estimatedGas })
)
.to.emit(chain2.factory, 'BridgeableContractDeployed')
.withArgs(sampleErc20Address, erc20ConfigHash);
expect(await chain2.registry.getHolographedHashAddress(erc20ConfigHash)).to.equal(sampleErc20Address);
});
it('deploy chain2 equivalent on chain1', async function () {
let { erc20Config, erc20ConfigHash, erc20ConfigHashBytes } = await generateErc20Config(
chain2.network,
chain2.deployer.address,
'SampleERC20',
'Sample ERC20 Token (' + chain2.hre.networkName + ')',
'SMPL',
'Sample ERC20 Token',
'1',
18,
ConfigureEvents([HolographERC20Event.bridgeIn, HolographERC20Event.bridgeOut]),
generateInitCode(['address', 'uint16'], [chain1.deployer.address, 0]),
chain2.salt
);
let sampleErc20Address = await chain1.registry.getHolographedHashAddress(erc20ConfigHash);
expect(sampleErc20Address).to.equal(zeroAddress);
sampleErc20Address = await chain2.registry.getHolographedHashAddress(erc20ConfigHash);
let sig = await chain2.deployer.signMessage(erc20ConfigHashBytes);
let signature: Signature = StrictECDSA({
r: '0x' + sig.substring(2, 66),
s: '0x' + sig.substring(66, 130),
v: '0x' + sig.substring(130, 132),
} as Signature);
let data: BytesLike = generateInitCode(
['tuple(bytes32,uint32,bytes32,bytes,bytes)', 'tuple(bytes32,bytes32,uint8)', 'address'],
[
[
erc20Config.contractType,
erc20Config.chainType,
erc20Config.salt,
erc20Config.byteCode,
erc20Config.initCode,
],
[signature.r, signature.s, signature.v],
chain2.deployer.address,
]
);
let originalMessagingModule = await chain1.operator.getMessagingModule();
let payload: BytesLike = await getRequestPayload(chain2, chain1, chain2.factory.address, data);
let gasEstimates = await getEstimatedGas(chain2, chain1, chain2.factory.address, data, payload);
payload = gasEstimates.payload;
let payloadHash: string = HASH(payload);
// temporarily set MockLZEndpoint as messaging module, to allow for easy sending
await chain1.operator.setMessagingModule(chain1.mockLZEndpoint.address);