Skip to content

Commit

Permalink
Merge pull request #12 from bcnmy/dev
Browse files Browse the repository at this point in the history
Optimizations
  • Loading branch information
ankurdubey521 authored Jun 27, 2023
2 parents f634460 + 67100cb commit ce43269
Show file tree
Hide file tree
Showing 11 changed files with 85 additions and 47 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ jobs:

- name: Run Forge tests
run: |
FOUNDRY_PROFILE=test forge test --ffi
FOUNDRY_PROFILE=test forge test -vvv --ffi
id: test
env:
FUJI_RPC_URL: https://api.avax-test.network/ext/bc/C/rpc
Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,5 @@ artifacts
.DS_Store
ScratchPad.t.sol
metrics/
*.bak
*.bak
.gas*
2 changes: 1 addition & 1 deletion hardhat/simulation/metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ export class Metrics {
await config.transactionAllocator.calculateMinimumTranasctionsForLiveness(
relayerStake,
totalStake,
totalTransactions.mul(BigNumber.from(10).pow(24)),
totalTransactions,
z
)
).div(BigNumber.from(10).pow(24));
Expand Down
2 changes: 1 addition & 1 deletion hardhat/testnet/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ const config = {
wormholeCoreAddress: addresses[targetChain].WormholeCore,
wormholeRelayerAddress: addresses[targetChain].WormholeRelayer,
fundingWallet: new ethers.Wallet(process.env.PRIVATE_KEY!, providers[targetChain].httpProvider),
fundingAmount: ethers.utils.parseEther('0.01'),
fundingAmount: ethers.utils.parseEther('0.5'),
taDeploymentBlock: 23333519,
...providers[targetChain],
bondToken: ERC20FreeMint__factory.connect(
Expand Down
19 changes: 11 additions & 8 deletions hardhat/testnet/hashToRelayerState.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,19 @@
"cdf": [10000],
"relayers": ["0x5Fb1684D707Eb68d18808aaAECbc3A4B2ba50DAD"]
},
"0xf118253c45653b6a25705224f89f95967ff113b93427e576a689f5060e51c394": [
[5000, 10000],
["0x5Fb1684D707Eb68d18808aaAECbc3A4B2ba50DAD", "0x6d009bc5fa151f1c45531DcDB38dF1F695d57EEE"]
],
"0x6c42cc44012848d078e58582e518367d0fb7bf81e7f689bafbe9822ec817aadb": [
[2500, 5000, 10000],
[
"0xf118253c45653b6a25705224f89f95967ff113b93427e576a689f5060e51c394": {
"cdf": [5000, 10000],
"relayers": [
"0x5Fb1684D707Eb68d18808aaAECbc3A4B2ba50DAD",
"0x6d009bc5fa151f1c45531DcDB38dF1F695d57EEE"
]
},
"0x6c42cc44012848d078e58582e518367d0fb7bf81e7f689bafbe9822ec817aadb": {
"cdf": [2500, 5000, 10000],
"relayers": [
"0x5Fb1684D707Eb68d18808aaAECbc3A4B2ba50DAD",
"0x6d009bc5fa151f1c45531DcDB38dF1F695d57EEE",
"0x5327b604d67af0AB6754965E671C4db4D6e2bFd1"
]
]
}
}
3 changes: 3 additions & 0 deletions hardhat/testnet/mempool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,13 @@ export class Mempool {
hashes = [];

public async init() {
// Generate new VAA transactions
await this.generateTransaction();
setInterval(async () => {
await this.generateTransaction();
}, config.generationIntervalSec * 1000);

// Process Existing VAAs
// this.processMockWormholeReceiverSourceTransactionReceipts(
// await Promise.all(
// this.hashes.map(async (hash) => config.sourceChain.httpProvider.getTransactionReceipt(hash))
Expand Down
1 change: 1 addition & 0 deletions hardhat/testnet/relayer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ export class Relayer {
// Delete transactions from mempool
console.log(`Relayer ${this.wallet.address}: Deleting transactions from mempool`);
} catch (e) {
console.log(e);
process.exit(1);
}

Expand Down
5 changes: 4 additions & 1 deletion hardhat/testnet/state-tracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ transactionAllocatorWs.on(
'NewRelayerState',
(latestHash: string, latestRelayerState: RelayerStateStruct) => {
console.log(`State Tracker: Received NewRelayerState event with hash: ${latestHash}`);
hashToRelayerState[latestHash] = latestRelayerState;
hashToRelayerState[latestHash] = {
cdf: latestRelayerState.cdf,
relayers: latestRelayerState.relayers,
};

// Write hashToRelayerState to a file
fs.writeFileSync(hashToRelayerStatePath, JSON.stringify(hashToRelayerState));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import "./interfaces/ITATransactionAllocation.sol";
import "./TATransactionAllocationStorage.sol";
import "ta-common/TAHelpers.sol";

import "forge-std/console2.sol";

contract TATransactionAllocation is ITATransactionAllocation, TAHelpers, TATransactionAllocationStorage {
using SafeCast for uint256;
using FixedPointTypeHelper for FixedPointType;
Expand Down Expand Up @@ -263,7 +265,8 @@ contract TATransactionAllocation is ITATransactionAllocation, TAHelpers, TATrans
uint256 epochEndTimestamp;
uint256 updatedUnpaidProtocolRewards;
uint256 stakeThresholdForJailing;
FixedPointType totalTransactionsInEpoch;
uint256 totalTransactionsInEpoch;
FixedPointType zScoreSquared;
FixedPointType updatedSharePrice;
// State
uint256 activeRelayersJailedCount;
Expand All @@ -286,12 +289,14 @@ contract TATransactionAllocation is ITATransactionAllocation, TAHelpers, TATrans
state.epochEndTimestamp = ta.epochEndTimestamp;
state.updatedUnpaidProtocolRewards = _getLatestTotalUnpaidProtocolRewardsAndUpdateUpdatedTimestamp();
state.updatedSharePrice = _protocolRewardRelayerSharePrice(state.updatedUnpaidProtocolRewards);
state.totalTransactionsInEpoch = ta.totalTransactionsSubmitted[state.epochEndTimestamp].fp();
state.totalTransactionsInEpoch = ta.totalTransactionsSubmitted[state.epochEndTimestamp];
state.zScoreSquared = ta.livenessZParameter;
state.zScoreSquared = state.zScoreSquared * state.zScoreSquared;
state.stakeThresholdForJailing = ta.stakeThresholdForJailing;
delete ta.totalTransactionsSubmitted[state.epochEndTimestamp];

// If no transactions were submitted in the epoch, then no need to process liveness check
if (state.totalTransactionsInEpoch == FP_ZERO) {
if (state.totalTransactionsInEpoch == 0) {
emit NoTransactionsSubmittedInEpoch();
return;
}
Expand Down Expand Up @@ -321,7 +326,11 @@ contract TATransactionAllocation is ITATransactionAllocation, TAHelpers, TATrans
) internal {
if (
_verifyRelayerLiveness(
_activeRelayerState, _relayerIndex, _state.epochEndTimestamp, _state.totalTransactionsInEpoch
_activeRelayerState,
_relayerIndex,
_state.epochEndTimestamp,
_state.totalTransactionsInEpoch,
_state.zScoreSquared
)
) {
return;
Expand Down Expand Up @@ -499,21 +508,21 @@ contract TATransactionAllocation is ITATransactionAllocation, TAHelpers, TATrans
function calculateMinimumTranasctionsForLiveness(
uint256 _relayerStake,
uint256 _totalStake,
FixedPointType _totalTransactions,
uint256 _totalTransactions,
FixedPointType _zScore
) public pure override returns (FixedPointType) {
if (_totalTransactions == FP_ZERO) {
) external pure override returns (FixedPointType) {
if (_totalTransactions == 0) {
return FP_ZERO;
}

if (_totalStake == 0) {
revert NoRelayersRegistered();
}

FixedPointType p = _relayerStake.fp() / _totalStake.fp();
FixedPointType s = ((p * (FP_ONE - p)) * _totalTransactions).sqrt();
FixedPointType p = _relayerStake.fp().div(_totalStake);
FixedPointType s = ((p * (FP_ONE - p)) * _totalTransactions.fp()).sqrt();
FixedPointType d = _zScore * s;
FixedPointType e = p * _totalTransactions;
FixedPointType e = p * _totalTransactions.fp();
unchecked {
if (e > d) {
return e - d;
Expand All @@ -527,29 +536,49 @@ contract TATransactionAllocation is ITATransactionAllocation, TAHelpers, TATrans
RelayerState calldata _activeState,
uint256 _relayerIndex,
uint256 _epochEndTimestamp,
FixedPointType _totalTransactionsInEpoch
uint256 _totalTransactionsInEpoch,
FixedPointType _zScoreSquared
) internal returns (bool) {
TAStorage storage ts = getTAStorage();
FixedPointType minimumTransactions;
{
uint256 relayerStakeNormalized = _activeState.cdf[_relayerIndex];

if (_relayerIndex != 0) {
relayerStakeNormalized -= _activeState.cdf[_relayerIndex - 1];
}

minimumTransactions = calculateMinimumTranasctionsForLiveness(
relayerStakeNormalized,
_activeState.cdf[_activeState.cdf.length - 1],
_totalTransactionsInEpoch,
ts.livenessZParameter
);
}

RelayerAddress relayerAddress = _activeState.relayers[_relayerIndex];
uint256 transactionsProcessedByRelayer = ts.transactionsSubmitted[_epochEndTimestamp][relayerAddress];
delete ts.transactionsSubmitted[_epochEndTimestamp][relayerAddress];
return transactionsProcessedByRelayer.fp() >= minimumTransactions;

uint256 relayerStakeNormalized = _activeState.cdf[_relayerIndex];

if (_relayerIndex != 0) {
relayerStakeNormalized -= _activeState.cdf[_relayerIndex - 1];
}

return _checkRelayerLiveness(
relayerStakeNormalized,
_activeState.cdf[_activeState.cdf.length - 1],
transactionsProcessedByRelayer,
_totalTransactionsInEpoch,
_zScoreSquared
);
}

function _checkRelayerLiveness(
uint256 _relayerStake,
uint256 _totalStake,
uint256 _tranasctionsDoneByRelayer,
uint256 _totalTransactions,
FixedPointType _zScoreSquared
) internal pure returns (bool) {
FixedPointType p = _relayerStake.fp().div(_totalStake);
FixedPointType e = p.mul(_totalTransactions);
FixedPointType _tranasctionsDoneByRelayerFp = _tranasctionsDoneByRelayer.fp();
if (e <= _tranasctionsDoneByRelayerFp) {
return true;
}

FixedPointType lhs = _zScoreSquared * e * (FP_ONE - p);
FixedPointType rhs = e - _tranasctionsDoneByRelayerFp;
rhs = rhs * rhs;

return lhs >= rhs;
}

function _calculatePenalty(uint256 _stake) internal view returns (uint256) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ interface ITATransactionAllocation is ITATransactionAllocationEventsErrors {
function calculateMinimumTranasctionsForLiveness(
uint256 _relayerStake,
uint256 _totalStake,
FixedPointType _totalTransactions,
uint256 _totalTransactions,
FixedPointType _zScore
) external view returns (FixedPointType);

Expand Down
10 changes: 4 additions & 6 deletions test/core/RelayerLivenessAndJailing.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,12 @@ contract RelayerLivenessAndJailingTest is
}

function testMinimumTransactionForLivenessCalculation() external {
FixedPointType minTransactions = ta.calculateMinimumTranasctionsForLiveness(
10 ** 18, 2 * 10 ** 18, uint256(50).fp(), ta.livenessZParameter()
);
FixedPointType minTransactions =
ta.calculateMinimumTranasctionsForLiveness(10 ** 18, 2 * 10 ** 18, 50, ta.livenessZParameter());
assertEq(minTransactions.u256(), 13);

minTransactions = ta.calculateMinimumTranasctionsForLiveness(
10 ** 18, 5 * 10 ** 18, uint256(50).fp(), ta.livenessZParameter()
);
minTransactions =
ta.calculateMinimumTranasctionsForLiveness(10 ** 18, 5 * 10 ** 18, 50, ta.livenessZParameter());
assertEq(minTransactions.u256(), 0);
}

Expand Down

0 comments on commit ce43269

Please sign in to comment.