-
Notifications
You must be signed in to change notification settings - Fork 121
/
Copy pathHolographOperator.sol
1209 lines (1135 loc) · 41.8 KB
/
HolographOperator.sol
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
// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
import "./abstract/Admin.sol";
import "./abstract/Initializable.sol";
import "./abstract/SafeERC20.sol";
import "./interface/CrossChainMessageInterface.sol";
import "./interface/HolographBridgeInterface.sol";
import "./interface/HolographERC20Interface.sol";
import "./interface/HolographInterface.sol";
import "./interface/HolographOperatorInterface.sol";
import "./interface/HolographRegistryInterface.sol";
import "./interface/InitializableInterface.sol";
import "./interface/HolographInterfacesInterface.sol";
import "./interface/Ownable.sol";
import "./struct/OperatorJob.sol";
/**
* @title Holograph Operator
* @author https://github.com/holographxyz
* @notice Participate in the Holograph Protocol by becoming an Operator
* @dev This contract allows operators to bond utility tokens and help execute operator jobs
*/
contract HolographOperator is Admin, Initializable, HolographOperatorInterface {
/**
* @dev bytes32(uint256(keccak256('eip1967.Holograph.bridge')) - 1)
*/
bytes32 constant _bridgeSlot = 0xeb87cbb21687feb327e3d58c6c16d552231d12c7a0e8115042a4165fac8a77f9;
/**
* @dev bytes32(uint256(keccak256('eip1967.Holograph.holograph')) - 1)
*/
bytes32 constant _holographSlot = 0xb4107f746e9496e8452accc7de63d1c5e14c19f510932daa04077cd49e8bd77a;
/**
* @dev bytes32(uint256(keccak256('eip1967.Holograph.interfaces')) - 1)
*/
bytes32 constant _interfacesSlot = 0xbd3084b8c09da87ad159c247a60e209784196be2530cecbbd8f337fdd1848827;
/**
* @dev bytes32(uint256(keccak256('eip1967.Holograph.jobNonce')) - 1)
*/
bytes32 constant _jobNonceSlot = 0x1cda64803f3b43503042e00863791e8d996666552d5855a78d53ee1dd4b3286d;
/**
* @dev bytes32(uint256(keccak256('eip1967.Holograph.messagingModule')) - 1)
*/
bytes32 constant _messagingModuleSlot = 0x54176250282e65985d205704ffce44a59efe61f7afd99e29fda50f55b48c061a;
/**
* @dev bytes32(uint256(keccak256('eip1967.Holograph.registry')) - 1)
*/
bytes32 constant _registrySlot = 0xce8e75d5c5227ce29a4ee170160bb296e5dea6934b80a9bd723f7ef1e7c850e7;
/**
* @dev bytes32(uint256(keccak256('eip1967.Holograph.utilityToken')) - 1)
*/
bytes32 constant _utilityTokenSlot = 0xbf76518d46db472b71aa7677a0908b8016f3dee568415ffa24055f9a670f9c37;
/**
* @dev bytes32(uint256(keccak256('eip1967.Holograph.minGasPrice')) - 1)
*/
bytes32 constant _minGasPriceSlot = 0x264d744422f7427cd080572c35c848b6cd3a36da6b47519af89ef13098b12fc0;
/**
* @dev Internal number (in seconds), used for defining a window for operator to execute the job
*/
uint256 private _blockTime;
/**
* @dev Minimum amount of tokens needed for bonding
*/
uint256 private _baseBondAmount;
/**
* @dev The multiplier used for calculating bonding amount for pods
*/
uint256 private _podMultiplier;
/**
* @dev The threshold used for limiting number of operators in a pod
*/
uint256 private _operatorThreshold;
/**
* @dev The threshold step used for increasing bond amount once threshold is reached
*/
uint256 private _operatorThresholdStep;
/**
* @dev The threshold divisor used for increasing bond amount once threshold is reached
*/
uint256 private _operatorThresholdDivisor;
/**
* @dev Internal counter of all cross-chain messages received
*/
uint256 private _inboundMessageCounter;
/**
* @dev Internal mapping of operator job details for a specific job hash (version 1: deprecated)
*/
mapping(bytes32 => uint256) private _deprecatedOperatorJobs;
/**
* @dev Internal mapping of operator job details for a specific job hash (version1: deprecated)
*/
mapping(bytes32 => bool) private _deprecatedFailedJobs;
/**
* @dev Internal mapping of operator addresses, used for temp storage when defining an operator job
*/
mapping(uint256 => address) private _operatorTempStorage;
/**
* @dev Internal index used for storing/referencing operator temp storage
*/
uint32 private _operatorTempStorageCounter;
/**
* @dev Multi-dimensional array of available operators
*/
address[][] private _operatorPods;
/**
* @dev Internal mapping of bonded operators, to prevent double bonding
*/
mapping(address => uint256) private _bondedOperators;
/**
* @dev Internal mapping of bonded operators, to prevent double bonding
*/
mapping(address => uint256) private _operatorPodIndex;
/**
* @dev Internal mapping of bonded operator amounts
*/
mapping(address => uint256) private _bondedAmounts;
/**
* @dev Internal mapping of operator job details for a specific job hash (version 2)
*/
mapping(bytes32 => uint256) private _operatorJobsV2;
/**
* @dev Internal mapping of operator job details for a specific failed job hash (version 2)
*/
mapping(bytes32 => bool) private _failedJobsV2;
/**
* @dev Constructor is left empty and init is used instead
*/
constructor() {}
/**
* @notice Used internally to initialize the contract instead of through a constructor
* @dev This function is called by the deployer/factory when creating a contract
* @param initPayload abi encoded payload to use for contract initilaization
*/
function init(bytes memory initPayload) external override returns (bytes4) {
require(!_isInitialized(), "HOLOGRAPH: already initialized");
(
address bridge,
address holograph,
address interfaces,
address registry,
address utilityToken,
uint256 minGasPrice
) = abi.decode(initPayload, (address, address, address, address, address, uint256));
assembly {
sstore(_adminSlot, origin())
sstore(_bridgeSlot, bridge)
sstore(_holographSlot, holograph)
sstore(_interfacesSlot, interfaces)
sstore(_registrySlot, registry)
sstore(_utilityTokenSlot, utilityToken)
sstore(_minGasPriceSlot, minGasPrice)
}
_blockTime = 60; // 60 seconds allowed for execution
unchecked {
_baseBondAmount = 100 * (10 ** 18); // one single token unit * 100
}
// how much to increase bond amount per pod
_podMultiplier = 2; // 1, 4, 16, 64
// starting pod max amount
_operatorThreshold = 1000;
// how often to increase price per each operator
_operatorThresholdStep = 10;
// we want to multiply by decimals, but instead will have to divide
_operatorThresholdDivisor = 100; // == * 0.01
// set first operator for each pod as zero address
_operatorPods = [[address(0)]];
// mark zero address as bonded operator, to prevent abuse
_bondedOperators[address(0)] = 1;
_setInitialized();
return InitializableInterface.init.selector;
}
/**
* @dev Checks if an operator job exists.
* @param jobHash The hash of the job to check.
*/
function operatorJobExists(bytes32 jobHash) external view returns (bool) {
return _operatorJobsV2[jobHash] > 0;
}
/**
* @dev Checks if a failed job exists.
* @param jobHash The hash of the job to check.
*/
function failedJobExists(bytes32 jobHash) external view returns (bool) {
return _failedJobsV2[jobHash];
}
/**
* @notice Recover failed job
* @dev If a job fails, it can be manually recovered
* @param bridgeInRequestPayload the entire cross chain message payload
*/
function recoverJob(bytes calldata bridgeInRequestPayload) external payable onlyAdmin {
bytes32 hash = keccak256(bridgeInRequestPayload);
require(_failedJobsV2[hash], "HOLOGRAPH: invalid recovery job");
delete (_failedJobsV2[hash]);
(bool success, ) = _bridge().call{value: msg.value}(bridgeInRequestPayload);
require(success, "HOLOGRAPH: recovery failed");
}
/**
* @notice Execute an available operator job
* @dev When making this call, if operating criteria is not met, the call will revert
* @param bridgeInRequestPayload the entire cross chain message payload
*/
function executeJob(bytes calldata bridgeInRequestPayload) external payable {
/**
* @dev derive the payload hash for use in mappings
*/
bytes32 hash = keccak256(bridgeInRequestPayload);
/**
* @dev check that job exists
*/
require(_operatorJobsV2[hash] > 0, "HOLOGRAPH: invalid job");
uint256 gasLimit = 0;
uint256 gasPrice = 0;
assembly {
/**
* @dev extract gasLimit
*/
gasLimit := calldataload(sub(add(bridgeInRequestPayload.offset, bridgeInRequestPayload.length), 0x40))
/**
* @dev extract gasPrice
*/
gasPrice := calldataload(sub(add(bridgeInRequestPayload.offset, bridgeInRequestPayload.length), 0x20))
}
/**
* @dev unpack bitwise packed operator job details
*/
OperatorJob memory job = getJobDetails(hash);
/**
* @dev to prevent replay attacks, remove job from mapping
*/
delete _operatorJobsV2[hash];
/**
* @dev operators of last resort are allowed, but they will not receive HLG rewards of any sort
*/
bool isBonded = _bondedAmounts[msg.sender] != 0;
/**
* @dev check that a specific operator was selected for the job
*/
if (job.operator != address(0)) {
/**
* @dev switch pod to index based value
*/
uint256 pod = job.pod - 1;
/**
* @dev check if sender is not the selected primary operator
*/
if (job.operator != msg.sender) {
/**
* @dev sender is not selected operator, need to check if allowed to do job
*/
uint256 elapsedTime = block.timestamp - uint256(job.startTimestamp);
uint256 timeDifference = elapsedTime / job.blockTimes;
/**
* @dev validate that initial selected operator time slot is still active
*/
require(timeDifference > 0, "HOLOGRAPH: operator has time");
/**
* @dev check that the selected missed the time slot due to a gas spike
*/
require(gasPrice >= tx.gasprice, "HOLOGRAPH: gas spike detected");
/**
* @dev check if time is within fallback operator slots
*/
if (timeDifference < 6) {
uint256 podIndex = uint256(job.fallbackOperators[timeDifference - 1]);
/**
* @dev do a quick sanity check to make sure operator did not leave from index or is a zero address
*/
if (podIndex > 0 && podIndex < _operatorPods[pod].length) {
address fallbackOperator = _operatorPods[pod][podIndex];
/**
* @dev ensure that sender is currently valid backup operator
*/
require(fallbackOperator == msg.sender, "HOLOGRAPH: invalid fallback");
} else {
require(_bondedOperators[msg.sender] == job.pod, "HOLOGRAPH: pod only fallback");
}
}
/**
* @dev time to reward the current operator
*/
uint256 amount = _getBaseBondAmount(pod);
/**
* @dev select operator that failed to do the job, is slashed the pod base fee
*/
_bondedAmounts[job.operator] -= amount;
/**
* @dev Loading _utilityToken() into memory to save gas
*/
HolographERC20Interface utilityToken = _utilityToken();
/**
* @dev only allow HLG rewards to go to bonded operators
* if operator is bonded, the slashed amount is sent to current operator
* otherwise it's sent to HolographTreasury, can be burned or distributed from there
*/
SafeERC20.safeTransfer(utilityToken, (isBonded ? msg.sender : address(_holograph().getTreasury())), amount);
/**
* @dev check if slashed operator has enough tokens bonded to stay
*/
if (_bondedAmounts[job.operator] >= amount) {
/**
* @dev enough bond amount leftover, put operator back in
*/
_operatorPods[pod].push(job.operator);
_operatorPodIndex[job.operator] = _operatorPods[pod].length - 1;
_bondedOperators[job.operator] = job.pod;
} else {
/**
* @dev slashed operator does not have enough tokens bonded, return remaining tokens only
*/
uint256 leftovers = _bondedAmounts[job.operator];
if (leftovers > 0) {
_bondedAmounts[job.operator] = 0;
SafeERC20.safeTransfer(utilityToken, job.operator, leftovers);
}
}
} else {
/**
* @dev the selected operator is executing the job
*/
_operatorPods[pod].push(msg.sender);
_operatorPodIndex[job.operator] = _operatorPods[pod].length - 1;
_bondedOperators[msg.sender] = job.pod;
}
}
/**
* @dev every executed job (even if failed) increments total message counter by one
*/
++_inboundMessageCounter;
/**
* @dev reward operator (with HLG) for executing the job
* this is out of scope and is purposefully omitted from code
* currently no rewards are issued
*/
//_utilityToken().transfer((isBonded ? msg.sender : address(_utilityToken())), (10**18));
/**
* @dev always emit an event at end of job, this helps other operators keep track of job status
*/
emit FinishedOperatorJob(hash, msg.sender);
/**
* @dev ensure that there is enough has left for the job
*/
require(gasleft() > gasLimit, "HOLOGRAPH: not enough gas left");
/**
* @dev execute the job
*/
try
HolographOperatorInterface(address(this)).nonRevertingBridgeCall{value: msg.value}(
msg.sender,
bridgeInRequestPayload
)
{
/// @dev do nothing
} catch {
/// @dev return any payed funds in case of revert
payable(msg.sender).transfer(msg.value);
_failedJobsV2[hash] = true;
emit FailedOperatorJob(hash);
}
}
/*
* @dev Purposefully made to be external so that Operator can call it during executeJob function
* Check the executeJob function to understand it's implementation
*/
function nonRevertingBridgeCall(address msgSender, bytes calldata payload) external payable {
require(msg.sender == address(this), "HOLOGRAPH: operator only call");
assembly {
/**
* @dev remove gas price from end
*/
calldatacopy(0, payload.offset, sub(payload.length, 0x20))
/**
* @dev hToken recipient is injected right before making the call
*/
mstore(0x84, msgSender)
/**
* @dev make non-reverting call
*/
let result := call(
/// @dev gas limit is retrieved from last 32 bytes of payload in-memory value
mload(sub(payload.length, 0x40)),
/// @dev destination is bridge contract
sload(_bridgeSlot),
/// @dev any value is passed along
callvalue(),
/// @dev data is retrieved from 0 index memory position
0,
/// @dev everything except for last 32 bytes (gas limit) is sent
sub(payload.length, 0x40),
0,
0
)
if eq(result, 0) {
revert(0, 0)
}
return(0, 0)
}
}
/**
* @notice Receive a cross-chain message
* @dev This function is restricted for use by Holograph Messaging Module only
*/
function crossChainMessage(bytes calldata bridgeInRequestPayload) external payable {
require(msg.sender == address(_messagingModule()), "HOLOGRAPH: messaging only call");
uint256 gasPrice = 0;
assembly {
/**
* @dev extract gasPrice
*/
gasPrice := calldataload(sub(add(bridgeInRequestPayload.offset, bridgeInRequestPayload.length), 0x20))
}
bool underpriced = gasPrice < _minGasPrice();
unchecked {
bytes32 jobHash = keccak256(bridgeInRequestPayload);
/**
* @dev load and increment operator temp storage in one call
*/
++_operatorTempStorageCounter;
/**
* @dev use job hash, job nonce, block number, and block timestamp for generating a random number
*/
uint256 random = uint256(keccak256(abi.encodePacked(jobHash, _jobNonce(), block.number, block.timestamp)));
// use the left 128 bits of random number
uint256 random1 = uint256(random >> 128);
// use the right 128 bits of random number
uint256 random2 = uint256(uint128(random));
// combine the two new random numbers for use in additional pod operator selection logic
random = uint256(keccak256(abi.encodePacked(random1 + random2)));
/**
* @dev divide by total number of pods, use modulus/remainder
*/
uint256 pod = random1 % _operatorPods.length;
/**
* @dev identify the total number of available operators in pod
*/
uint256 podSize = _operatorPods[pod].length;
/**
* @dev select a primary operator
*/
uint256 operatorIndex = underpriced ? 0 : random2 % podSize;
/**
* @dev If operator index is 0, then it's open season! Anyone can execute this job. First come first serve
* pop operator to ensure that they cannot be selected for any other job until this one completes
* decrease pod size to accomodate popped operator
*/
_operatorTempStorage[_operatorTempStorageCounter] = _operatorPods[pod][operatorIndex];
_popOperator(pod, operatorIndex);
if (podSize > 1) {
podSize--;
}
_operatorJobsV2[jobHash] = uint256(
((pod + 1) << 248) |
(uint256(_operatorTempStorageCounter) << 216) |
(block.number << 176) |
((underpriced ? 0 : _randomBlockHash(random, podSize, 1)) << 160) |
((underpriced ? 0 : _randomBlockHash(random, podSize, 2)) << 144) |
((underpriced ? 0 : _randomBlockHash(random, podSize, 3)) << 128) |
((underpriced ? 0 : _randomBlockHash(random, podSize, 4)) << 112) |
((underpriced ? 0 : _randomBlockHash(random, podSize, 5)) << 96) |
(block.timestamp << 16) |
0
); // 80 next available bit position && so far 176 bits used with only 128 left
/**
* @dev emit event to signal to operators that a job has become available
*/
emit AvailableOperatorJob(jobHash, bridgeInRequestPayload);
}
}
/**
* @notice Calculate the amount of gas needed to execute a bridgeInRequest
* @dev Use this function to estimate the amount of gas that will be used by the bridgeInRequest function
* Set a specific gas limit when making this call, subtract return value, to get total gas used
* Only use this with a static call
* @param bridgeInRequestPayload abi encoded bytes making up the bridgeInRequest payload
* @return the gas amount remaining after the static call is returned
*/
function jobEstimator(bytes calldata bridgeInRequestPayload) external payable returns (uint256) {
assembly {
calldatacopy(0, bridgeInRequestPayload.offset, sub(bridgeInRequestPayload.length, 0x40))
/**
* @dev bridgeInRequest doNotRevert is purposefully set to false so a rever would happen
*/
mstore8(0xE3, 0x00)
let result := call(gas(), sload(_bridgeSlot), callvalue(), 0, sub(bridgeInRequestPayload.length, 0x40), 0, 0)
/**
* @dev if for some reason the call does not revert, it is force reverted
*/
if eq(result, 1) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
/**
* @dev remaining gas is set as the return value
*/
mstore(0x00, gas())
return(0x00, 0x20)
}
}
/**
* @notice Send cross chain bridge request message
* @dev This function is restricted to only be callable by Holograph Bridge
* @param gasLimit maximum amount of gas to spend for executing the beam on destination chain
* @param gasPrice maximum amount of gas price (in destination chain native gas token) to pay on destination chain
* @param toChain Holograph Chain ID where the beam is being sent to
* @param nonce incremented number used to ensure job hashes are unique
* @param holographableContract address of the contract for which the bridge request is being made
* @param bridgeOutPayload bytes made up of the bridgeOutRequest payload
*/
function send(
uint256 gasLimit,
uint256 gasPrice,
uint32 toChain,
address msgSender,
uint256 nonce,
address holographableContract,
bytes calldata bridgeOutPayload
) external payable {
require(msg.sender == _bridge(), "HOLOGRAPH: bridge only call");
CrossChainMessageInterface messagingModule = _messagingModule();
uint256 hlgFee = messagingModule.getHlgFee(toChain, gasLimit, gasPrice, bridgeOutPayload);
address hToken = _registry().getHToken(_holograph().getHolographChainId());
require(hlgFee < msg.value, "HOLOGRAPH: not enough value");
payable(hToken).transfer(hlgFee);
bytes memory encodedData = abi.encodeWithSelector(
HolographBridgeInterface.bridgeInRequest.selector,
/**
* @dev job nonce is an incremented value that is assigned to each bridge request to guarantee unique hashes
*/
nonce,
/**
* @dev including the current holograph chain id (origin chain)
*/
_holograph().getHolographChainId(),
/**
* @dev holographable contract have the same address across all chains, so our destination address will be the same
*/
holographableContract,
/**
* @dev get the current chain's hToken for native gas token
*/
hToken,
/**
* @dev recipient will be defined when operator picks up the job
*/
address(0),
/**
* @dev value is set to zero for now
*/
hlgFee,
/**
* @dev specify that function call should not revert
*/
true,
/**
* @dev attach actual holographableContract function call
*/
bridgeOutPayload
);
/**
* @dev add gas variables to the back for later extraction
*/
encodedData = abi.encodePacked(encodedData, gasLimit, gasPrice);
/**
* @dev Send the data to the current Holograph Messaging Module
* This will be changed to dynamically select which messaging module to use based on destination network
*/
messagingModule.send{value: msg.value - hlgFee}(
gasLimit,
gasPrice,
toChain,
msgSender,
msg.value - hlgFee,
encodedData
);
/**
* @dev for easy indexing, an event is emitted with the payload hash for status tracking
*/
emit CrossChainMessageSent(keccak256(encodedData));
}
/**
* @notice Get the fees associated with sending specific payload
* @dev Will provide exact costs on protocol and message side, combine the two to get total
* @dev @param toChain holograph chain id of destination chain for payload
* @dev @param gasLimit amount of gas to provide for executing payload on destination chain
* @dev @param gasPrice maximum amount to pay for gas price, can be set to 0 and will be chose automatically
* @dev @param crossChainPayload the entire packet being sent cross-chain
* @return hlgFee the amount (in wei) of native gas token that will cost for finalizing job on destiantion chain
* @return msgFee the amount (in wei) of native gas token that will cost for sending message to destiantion chain
* @return dstGasPrice the amount (in wei) that destination message maximum gas price will be
*/
function getMessageFee(uint32, uint256, uint256, bytes calldata) external view returns (uint256, uint256, uint256) {
assembly {
calldatacopy(0, 0, calldatasize())
let result := staticcall(gas(), sload(_messagingModuleSlot), 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @notice Get the details for an available operator job
* @dev The job hash is a keccak256 hash of the entire job payload
* @param jobHash keccak256 hash of the job
* @return an OperatorJob struct with details about a specific job
*/
function getJobDetails(bytes32 jobHash) public view returns (OperatorJob memory) {
uint256 packed = _operatorJobsV2[jobHash];
/**
* @dev The job is bitwise packed into a single 32 byte slot, this unpacks it before returning the struct
*/
return
OperatorJob(
uint8(packed >> 248),
uint16(_blockTime),
_operatorTempStorage[uint32(packed >> 216)],
uint40(packed >> 176),
// TODO: move the bit-shifting around to have it be sequential
uint64(packed >> 16),
[
uint16(packed >> 160),
uint16(packed >> 144),
uint16(packed >> 128),
uint16(packed >> 112),
uint16(packed >> 96)
]
);
}
/**
* @notice Get number of pods available
* @dev This returns number of pods that have been opened via bonding
*/
function getTotalPods() external view returns (uint256 totalPods) {
return _operatorPods.length;
}
/**
* @notice Get total number of operators in a pod
* @dev Use in conjunction with paginated getPodOperators function
* @param pod the pod to query
* @return total operators in a pod
*/
function getPodOperatorsLength(uint256 pod) external view returns (uint256) {
require(_operatorPods.length >= pod, "HOLOGRAPH: pod does not exist");
return _operatorPods[pod - 1].length;
}
/**
* @notice Get list of operators in a pod
* @dev Use paginated getPodOperators function instead if list gets too long
* @param pod the pod to query
* @return operators array list of operators in a pod
*/
function getPodOperators(uint256 pod) external view returns (address[] memory operators) {
require(_operatorPods.length >= pod, "HOLOGRAPH: pod does not exist");
operators = _operatorPods[pod - 1];
}
/**
* @notice Get paginated list of operators in a pod
* @dev Use in conjunction with getPodOperatorsLength to know the total length of results
* @param pod the pod to query
* @param index the array index to start from
* @param length the length of result set to be (will be shorter if reached end of array)
* @return operators a paginated array of operators
*/
function getPodOperators(
uint256 pod,
uint256 index,
uint256 length
) external view returns (address[] memory operators) {
require(_operatorPods.length >= pod, "HOLOGRAPH: pod does not exist");
/**
* @dev if pod 0 is selected, this will create a revert
*/
pod--;
/**
* @dev get total length of pod operators
*/
uint256 supply = _operatorPods[pod].length;
/**
* @dev check if length is out of bounds for this result set
*/
if (index + length > supply) {
/**
* @dev adjust length to return remainder of the results
*/
length = supply - index;
}
/**
* @dev create in-memory array
*/
operators = new address[](length);
/**
* @dev add operators to result set
*/
for (uint256 i = 0; i < length; i++) {
operators[i] = _operatorPods[pod][index + i];
}
}
/**
* @notice Check the base and current price for bonding to a particular pod
* @dev Useful for understanding what is required for bonding to a pod
* @param pod the pod to get bonding amounts for
* @return base the base bond amount required for a pod
* @return current the current bond amount required for a pod
*/
function getPodBondAmounts(uint256 pod) external view returns (uint256 base, uint256 current) {
base = _getBaseBondAmount(pod - 1);
current = _getCurrentBondAmount(pod - 1);
}
/**
* @notice Get an operator's currently bonded amount
* @dev Useful for checking how much an operator has bonded
* @param operator address of operator to check
* @return amount total number of utility token bonded
*/
function getBondedAmount(address operator) external view returns (uint256 amount) {
return _bondedAmounts[operator];
}
/**
* @notice Get an operator's currently bonded pod
* @dev Useful for checking if an operator is currently bonded
* @param operator address of operator to check
* @return pod number that operator is bonded on, returns zero if not bonded or selected for job
*/
function getBondedPod(address operator) external view returns (uint256 pod) {
return _bondedOperators[operator];
}
/**
* @notice Get an operator's currently bonded pod index
* @dev Useful for checking if an operator is a fallback for active job
* @param operator address of operator to check
* @return index currently bonded pod's operator index, returns zero if not in pod or moved out for active job
*/
function getBondedPodIndex(address operator) external view returns (uint256 index) {
return _operatorPodIndex[operator];
}
/**
* @notice Topup a bonded operator with more utility tokens
* @dev Useful function if an operator got slashed and wants to add a safety buffer to not get unbonded
* This function will not work if operator has currently been selected for a job
* @param operator address of operator to topup
* @param amount utility token amount to add
*/
function topupUtilityToken(address operator, uint256 amount) external {
/**
* @dev check that an operator is currently bonded
*/
require(_bondedOperators[operator] != 0, "HOLOGRAPH: operator not bonded");
unchecked {
/**
* @dev add the additional amount to operator
*/
_bondedAmounts[operator] += amount;
}
/**
* @dev transfer tokens last, to prevent reentrancy attacks
*/
SafeERC20.safeTransferFrom(_utilityToken(), msg.sender, address(this), amount);
}
/**
* @notice Bond utility tokens and become an operator
* @dev An operator can only bond to one pod at a time, per network
* @param operator address of operator to bond (can be an ownable smart contract)
* @param amount utility token amount to bond (can be greater than minimum)
* @param pod number of pod to bond to (can be for one that does not exist yet)
*/
function bondUtilityToken(address operator, uint256 amount, uint256 pod) external {
/**
* @dev an operator can only bond to one pod at any give time per network
*/
require(_bondedOperators[operator] == 0 && _bondedAmounts[operator] == 0, "HOLOGRAPH: operator is bonded");
if (_isContract(operator)) {
require(Ownable(operator).owner() != address(0), "HOLOGRAPH: contract not ownable");
}
unchecked {
/**
* @dev get the current bonding minimum for selected pod
*/
uint256 current = _getCurrentBondAmount(pod - 1);
require(current <= amount, "HOLOGRAPH: bond amount too small");
/**
* @dev check if selected pod is greater than currently existing pods
*/
if (_operatorPods.length < pod) {
/**
* @dev activate pod(s) up until the selected pod
*/
for (uint256 i = _operatorPods.length; i < pod; i++) {
/**
* @dev add zero address into pod to mitigate empty pod issues
*/
_operatorPods.push([address(0)]);
}
}
/**
* @dev prevent bonding to a pod with more than uint16 max value
*/
require(_operatorPods[pod - 1].length < type(uint16).max, "HOLOGRAPH: too many operators");
_operatorPods[pod - 1].push(operator);
_operatorPodIndex[operator] = _operatorPods[pod - 1].length - 1;
_bondedOperators[operator] = pod;
_bondedAmounts[operator] = amount;
/**
* @dev transfer tokens last, to prevent reentrancy attacks
*/
SafeERC20.safeTransferFrom(_utilityToken(), msg.sender, address(this), amount);
}
}
/**
* @notice Unbond HLG utility tokens and stop being an operator
* @dev A bonded operator selected for a job cannot unbond until they complete the job, or are slashed
* @param operator address of operator to unbond
* @param recipient address where to send the bonded tokens
*/
function unbondUtilityToken(address operator, address recipient) external {
/**
* @dev validate that operator is currently bonded
*/
require(_bondedOperators[operator] != 0, "HOLOGRAPH: operator not bonded");
/**
* @dev check if sender is not actual operator
*/
if (msg.sender != operator) {
/**
* @dev check if operator is a smart contract
*/
require(_isContract(operator), "HOLOGRAPH: operator not contract");
/**
* @dev check if smart contract is owned by sender
*/
require(Ownable(operator).owner() == msg.sender, "HOLOGRAPH: sender not owner");
}
/**
* @dev get current bonded amount by operator
*/
uint256 amount = _bondedAmounts[operator];
/**
* @dev unset operator bond amount before making a transfer
*/
_bondedAmounts[operator] = 0;
/**
* @dev remove all operator references
*/
_popOperator(_bondedOperators[operator] - 1, _operatorPodIndex[operator]);
/**
* @dev transfer tokens to recipient
*/
SafeERC20.safeTransfer(_utilityToken(), recipient, amount);
}
/**
* @notice Get the address of the Holograph Bridge module
* @dev Used for beaming holographable assets cross-chain
*/
function getBridge() external view returns (address bridge) {
assembly {
bridge := sload(_bridgeSlot)
}
}
/**
* @notice Update the Holograph Bridge module address
* @param bridge address of the Holograph Bridge smart contract to use
*/
function setBridge(address bridge) external onlyAdmin {
assembly {
sstore(_bridgeSlot, bridge)
}
}
/**
* @notice Get the Holograph Protocol contract
* @dev Used for storing a reference to all the primary modules and variables of the protocol
*/
function getHolograph() external view returns (address holograph) {
assembly {
holograph := sload(_holographSlot)
}
}
/**
* @notice Update the Holograph Protocol contract address
* @param holograph address of the Holograph Protocol smart contract to use
*/
function setHolograph(address holograph) external onlyAdmin {
assembly {
sstore(_holographSlot, holograph)
}
}
/**
* @notice Get the address of the Holograph Interfaces module
* @dev Holograph uses this contract to store data that needs to be accessed by a large portion of the modules
*/
function getInterfaces() external view returns (address interfaces) {
assembly {
interfaces := sload(_interfacesSlot)
}
}
/**
* @notice Update the Holograph Interfaces module address
* @param interfaces address of the Holograph Interfaces smart contract to use
*/
function setInterfaces(address interfaces) external onlyAdmin {
assembly {
sstore(_interfacesSlot, interfaces)
}
}
/**
* @notice Get the address of the Holograph Messaging Module
* @dev All cross-chain message requests will get forwarded to this adress
*/
function getMessagingModule() external view returns (address messagingModule) {
assembly {
messagingModule := sload(_messagingModuleSlot)
}
}
/**
* @notice Update the Holograph Messaging Module address
* @param messagingModule address of the LayerZero Endpoint to use
*/
function setMessagingModule(address messagingModule) external onlyAdmin {
assembly {
sstore(_messagingModuleSlot, messagingModule)
}
}
/**
* @notice Get the Holograph Registry module
* @dev This module stores a reference for all deployed holographable smart contracts
*/
function getRegistry() external view returns (address registry) {
assembly {
registry := sload(_registrySlot)
}
}
/**
* @notice Update the Holograph Registry module address
* @param registry address of the Holograph Registry smart contract to use
*/
function setRegistry(address registry) external onlyAdmin {
assembly {
sstore(_registrySlot, registry)
}
}
/**
* @notice Get the Holograph Utility Token address
* @dev This is the official utility token of the Holograph Protocol
*/