Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

merge from dev #83

Merged
merged 5 commits into from
Mar 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions packages/batch-submitter/src/batch-submitter/batch-submitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ export abstract class BatchSubmitter {
readonly minBalanceEther: number,
readonly blockOffset: number,
readonly logger: Logger,
readonly defaultMetrics: Metrics
readonly defaultMetrics: Metrics,
readonly useMpc: boolean
) {
this.metrics = this._registerMetrics(defaultMetrics)
}
Expand All @@ -71,14 +72,20 @@ export abstract class BatchSubmitter {
public abstract _onSync(): Promise<TransactionReceipt>
public abstract _getBatchStartAndEnd(): Promise<BlockRange>
public abstract _updateChainInfo(): Promise<void>
public abstract _mpcBalanceCheck(): Promise<boolean>

public async submitNextBatch(): Promise<TransactionReceipt> {
if (typeof this.l2ChainId === 'undefined') {
this.l2ChainId = await this._getL2ChainId()
}
await this._updateChainInfo()

if (!(await this._hasEnoughETHToCoverGasCosts())) {
if (!this.useMpc && !(await this._hasEnoughETHToCoverGasCosts())) {
await sleep(this.resubmissionTimeout)
return
}

if (this.useMpc && !(await this._mpcBalanceCheck())) {
await sleep(this.resubmissionTimeout)
return
}
Expand Down Expand Up @@ -107,9 +114,17 @@ export abstract class BatchSubmitter {
)
}

protected async _hasEnoughETHToCoverGasCosts(): Promise<boolean> {
const address = await this.signer.getAddress()
const balance = await this.signer.getBalance()
protected async _hasEnoughETHToCoverGasCosts(
mpcAddress?: string
): Promise<boolean> {
const mpcAddressEnabled =
mpcAddress && mpcAddress.length === 42 && mpcAddress.startsWith('0x')
const address = mpcAddressEnabled
? mpcAddress
: await this.signer.getAddress()
const balance = mpcAddressEnabled
? await this.signer.provider.getBalance(mpcAddress)
: await this.signer.getBalance()
const ether = utils.formatEther(balance)
const num = parseFloat(ether)

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
/* External Imports */
import { Promise as bPromise } from 'bluebird'
import { Contract, ethers, Signer, providers, BigNumber } from 'ethers'
import {
Contract,
ethers,
Signer,
providers,
BigNumber,
PopulatedTransaction,
} from 'ethers'
import { TransactionReceipt } from '@ethersproject/abstract-provider'
import { getContractFactory } from '@metis.io/contracts'
import { L2Block, RollupInfo, Bytes32, remove0x } from '@metis.io/core-utils'
Expand Down Expand Up @@ -64,7 +71,8 @@ export class StateBatchSubmitter extends BatchSubmitter {
minBalanceEther,
blockOffset,
logger,
metrics
metrics,
mpcUrl.length > 0
)
this.fraudSubmissionAddress = fraudSubmissionAddress
this.transactionSubmitter = transactionSubmitter
Expand Down Expand Up @@ -269,24 +277,30 @@ export class StateBatchSubmitter extends BatchSubmitter {
if (!mpcInfo || !mpcInfo.mpc_address) {
throw new Error('MPC 1 info get failed')
}
const txUnsign: PopulatedTransaction = {
to: tx.to,
data: tx.data,
value: ethers.utils.parseEther('0'),
}
const mpcAddress = mpcInfo.mpc_address
tx.nonce = await this.signer.provider.getTransactionCount(mpcAddress)
tx.gasLimit = await this.signer.provider.estimateGas({
txUnsign.nonce = await this.signer.provider.getTransactionCount(
mpcAddress
)
txUnsign.gasLimit = await this.signer.provider.estimateGas({
to: tx.to,
from: mpcAddress,
data: tx.data,
})
tx.value = ethers.utils.parseEther('0')
tx.chainId = (await this.signer.provider.getNetwork()).chainId
txUnsign.chainId = (await this.signer.provider.getNetwork()).chainId
// mpc model can use ynatm
// tx.gasPrice = gasPrice

const submitSignedTransaction = (): Promise<TransactionReceipt> => {
return this.transactionSubmitter.submitSignedTransaction(
tx,
txUnsign,
async (gasPrice) => {
tx.gasPrice = gasPrice
const signedTx = await mpcClient.signTx(tx, mpcInfo.mpc_id)
txUnsign.gasPrice = gasPrice
const signedTx = await mpcClient.signTx(txUnsign, mpcInfo.mpc_id)
return signedTx
},
this._makeHooks('appendSequencerBatch')
Expand Down Expand Up @@ -314,6 +328,20 @@ export class StateBatchSubmitter extends BatchSubmitter {
)
}

public async _mpcBalanceCheck(): Promise<boolean> {
if (!this.useMpc) {
return true
}
this.logger.info('MPC model balance check of state batch submitter...')
const mpcClient = new MpcClient(this.mpcUrl)
const mpcInfo = await mpcClient.getLatestMpc('1')
if (!mpcInfo || !mpcInfo.mpc_address) {
this.logger.error('MPC 1 info get failed')
return false
}
return this._hasEnoughETHToCoverGasCosts(mpcInfo.mpc_address)
}

/*********************
* Private Functions *
********************/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,8 @@ export class TransactionBatchSubmitter extends BatchSubmitter {
minBalanceEther,
blockOffset,
logger,
metrics
metrics,
mpcUrl.length > 0
)
this.validateBatch = validateBatch
this.autoFixBatchOptions = autoFixBatchOptions
Expand Down Expand Up @@ -466,6 +467,20 @@ export class TransactionBatchSubmitter extends BatchSubmitter {
return this.submitAppendSequencerBatch(batchParams)
}

public async _mpcBalanceCheck(): Promise<boolean> {
if (!this.useMpc) {
return true
}
this.logger.info('MPC model balance check of tx batch submitter...')
const mpcClient = new MpcClient(this.mpcUrl)
const mpcInfo = await mpcClient.getLatestMpc()
if (!mpcInfo || !mpcInfo.mpc_address) {
this.logger.error('MPC 0 info get failed')
return false
}
return this._hasEnoughETHToCoverGasCosts(mpcInfo.mpc_address)
}

/*********************
* Private Functions *
********************/
Expand Down
36 changes: 28 additions & 8 deletions packages/message-relayer/src/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -341,22 +341,41 @@ export class MessageRelayerService extends BaseService<MessageRelayerOptions> {
})
}

const l1ChainId = (await this.options.l1RpcProvider.getNetwork()).chainId
let startingBlock = this.state.lastQueriedL1Block
while (
startingBlock < (await this.options.l1RpcProvider.getBlockNumber())
) {
let sccContract = this.state.StateCommitmentChain
let endBlock = startingBlock + this.options.getLogsInterval
if (l1ChainId === 1) {
// changed address at 19439449
const setHeight1 = 19439449
if (endBlock > setHeight1 && startingBlock < setHeight1) {
endBlock = setHeight1
}
if (
(endBlock > setHeight1 && startingBlock < setHeight1) ||
endBlock <= setHeight1
) {
sccContract = loadContract(
'StateCommitmentChain',
'0xf209815E595Cdf3ed0aAF9665b1772e608AB9380',
this.options.l1RpcProvider
)
}
}
this.state.lastQueriedL1Block = startingBlock
this.logger.info('Querying events', {
startingBlock,
endBlock: startingBlock + this.options.getLogsInterval,
endBlock,
})

const events: ethers.Event[] =
await this.state.StateCommitmentChain.queryFilter(
this.state.StateCommitmentChain.filters.StateBatchAppended(),
startingBlock,
startingBlock + this.options.getLogsInterval
)
const events: ethers.Event[] = await sccContract.queryFilter(
sccContract.filters.StateBatchAppended(),
startingBlock,
endBlock
)
const filteredEvents = events.filter((event) => {
if (event != undefined) {
return event.args._chainId.toNumber() == this.options.l2ChainId
Expand All @@ -367,7 +386,8 @@ export class MessageRelayerService extends BaseService<MessageRelayerOptions> {

this.state.eventCache = this.state.eventCache.concat(filteredEvents)
//this.state.eventCache = this.state.eventCache.concat(events)
startingBlock += this.options.getLogsInterval
// startingBlock += this.options.getLogsInterval
startingBlock = endBlock

// We need to stop syncing early once we find the event we're looking for to avoid putting
// *all* events into memory at the same time. Otherwise we'll get OOM killed.
Expand Down
Loading