-
Notifications
You must be signed in to change notification settings - Fork 60
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
feat: fastlane #174
Merged
Merged
feat: fastlane #174
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
271 changes: 271 additions & 0 deletions
271
packages/executor/src/services/BundlingService/relayers/fastlane.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,271 @@ | ||
import { providers } from "ethers"; | ||
import { Logger } from "types/lib"; | ||
import { PerChainMetrics } from "monitoring/lib"; | ||
import { IEntryPoint__factory } from "types/lib/executor/contracts"; | ||
import { chainsWithoutEIP1559 } from "params/lib"; | ||
import { AccessList } from "ethers/lib/utils"; | ||
import { MempoolEntryStatus } from "types/lib/executor"; | ||
import { Relayer } from "../interfaces"; | ||
import { Config } from "../../../config"; | ||
import { Bundle, NetworkConfig, StorageMap } from "../../../interfaces"; | ||
import { MempoolService } from "../../MempoolService"; | ||
import { estimateBundleGasLimit } from "../utils"; | ||
import { ReputationService } from "../../ReputationService"; | ||
import { BaseRelayer } from "./base"; | ||
import { now } from "../../../utils"; | ||
|
||
export class FastlaneRelayer extends BaseRelayer { | ||
private submitTimeout = 10 * 60 * 1000; // 10 minutes | ||
|
||
constructor( | ||
logger: Logger, | ||
chainId: number, | ||
provider: providers.JsonRpcProvider, | ||
config: Config, | ||
networkConfig: NetworkConfig, | ||
mempoolService: MempoolService, | ||
reputationService: ReputationService, | ||
metrics: PerChainMetrics | null | ||
) { | ||
super( | ||
logger, | ||
chainId, | ||
provider, | ||
config, | ||
networkConfig, | ||
mempoolService, | ||
reputationService, | ||
metrics | ||
); | ||
if (!this.networkConfig.conditionalTransactions) { | ||
throw new Error("Fastlane: You must enable conditional transactions"); | ||
} | ||
if (!this.networkConfig.rpcEndpointSubmit) { | ||
throw new Error("Fastlane: You must set rpcEndpointSubmit"); | ||
} | ||
} | ||
|
||
async sendBundle(bundle: Bundle): Promise<void> { | ||
const availableIndex = this.getAvailableRelayerIndex(); | ||
if (availableIndex == null) { | ||
this.logger.error("Fastlane: No available relayers"); | ||
return; | ||
} | ||
const relayer = this.relayers[availableIndex]; | ||
const mutex = this.mutexes[availableIndex]; | ||
|
||
const { entries, storageMap } = bundle; | ||
if (!bundle.entries.length) { | ||
this.logger.error("Fastlane: Bundle is empty"); | ||
return; | ||
} | ||
|
||
await mutex.runExclusive(async (): Promise<void> => { | ||
const beneficiary = await this.selectBeneficiary(relayer); | ||
const entryPoint = entries[0]!.entryPoint; | ||
const entryPointContract = IEntryPoint__factory.connect( | ||
entryPoint, | ||
this.provider | ||
); | ||
|
||
const txRequest = entryPointContract.interface.encodeFunctionData( | ||
"handleOps", | ||
[entries.map((entry) => entry.userOp), beneficiary] | ||
); | ||
|
||
const transactionRequest: providers.TransactionRequest = { | ||
to: entryPoint, | ||
data: txRequest, | ||
type: 2, | ||
maxPriorityFeePerGas: bundle.maxPriorityFeePerGas, | ||
maxFeePerGas: bundle.maxFeePerGas, | ||
}; | ||
|
||
if (this.networkConfig.eip2930) { | ||
const { storageMap } = bundle; | ||
const addresses = Object.keys(storageMap); | ||
if (addresses.length) { | ||
const accessList: AccessList = []; | ||
for (const address of addresses) { | ||
const storageKeys = storageMap[address]; | ||
if (typeof storageKeys == "object") { | ||
accessList.push({ | ||
address, | ||
storageKeys: Object.keys(storageKeys), | ||
}); | ||
} | ||
} | ||
transactionRequest.accessList = accessList; | ||
} | ||
} | ||
|
||
if ( | ||
chainsWithoutEIP1559.some((chainId: number) => chainId === this.chainId) | ||
) { | ||
transactionRequest.gasPrice = bundle.maxFeePerGas; | ||
delete transactionRequest.maxPriorityFeePerGas; | ||
delete transactionRequest.maxFeePerGas; | ||
delete transactionRequest.type; | ||
delete transactionRequest.accessList; | ||
} | ||
|
||
const transaction = { | ||
...transactionRequest, | ||
gasLimit: estimateBundleGasLimit( | ||
this.networkConfig.bundleGasLimitMarkup, | ||
bundle.entries | ||
), | ||
chainId: this.provider._network.chainId, | ||
nonce: await relayer.getTransactionCount(), | ||
}; | ||
|
||
if (!this.networkConfig.skipBundleValidation) { | ||
try { | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
const { gasLimit, ...txWithoutGasLimit } = transactionRequest; | ||
// some chains, like Bifrost, don't allow setting gasLimit in estimateGas | ||
await relayer.estimateGas(txWithoutGasLimit); | ||
} catch (err) { | ||
this.logger.debug( | ||
`${entries | ||
.map((entry) => entry.userOpHash) | ||
.join("; ")} failed on chain estimation. deleting...` | ||
); | ||
this.logger.error(err); | ||
await this.mempoolService.removeAll(entries); | ||
this.reportFailedBundle(); | ||
return; | ||
} | ||
} | ||
|
||
this.logger.debug( | ||
`Fastlane: Trying to submit userops: ${bundle.entries | ||
.map((entry) => entry.userOpHash) | ||
.join(", ")}` | ||
); | ||
|
||
await this.submitTransaction(relayer, transaction, storageMap) | ||
.then(async (txHash: string) => { | ||
this.logger.debug(`Fastlane: Bundle submitted: ${txHash}`); | ||
this.logger.debug( | ||
`Fastlane: User op hashes ${entries.map( | ||
(entry) => entry.userOpHash | ||
)}` | ||
); | ||
await this.mempoolService.setStatus( | ||
entries, | ||
MempoolEntryStatus.Submitted, | ||
txHash | ||
); | ||
|
||
await this.waitForEntries(entries).catch((err) => | ||
this.logger.error(err, "Fastlane: Could not find transaction") | ||
); | ||
this.reportSubmittedUserops(txHash, bundle); | ||
}) | ||
.catch(async (err: any) => { | ||
this.reportFailedBundle(); | ||
// Put all userops back to the mempool | ||
// if some userop failed, it will be deleted inside handleUserOpFail() | ||
await this.mempoolService.setStatus(entries, MempoolEntryStatus.New); | ||
await this.handleUserOpFail(entries, err); | ||
}); | ||
}); | ||
} | ||
|
||
async canSubmitBundle(): Promise<boolean> { | ||
try { | ||
const provider = new providers.JsonRpcProvider( | ||
"https://rpc-mainnet.maticvigil.com" | ||
); | ||
const validators = await provider.send("bor_getCurrentValidators", []); | ||
for (let fastlane of this.networkConfig.fastlaneValidators) { | ||
fastlane = fastlane.toLowerCase(); | ||
if ( | ||
validators.some( | ||
(validator: { signer: string }) => | ||
validator.signer.toLowerCase() == fastlane | ||
) | ||
) { | ||
return true; | ||
} | ||
} | ||
} catch (err) { | ||
this.logger.error(err, "Fastlane: error on bor_getCurrentValidators"); | ||
} | ||
return false; | ||
} | ||
|
||
/** | ||
* signs & sends a transaction | ||
* @param relayer wallet | ||
* @param transaction transaction request | ||
* @param storageMap storage map | ||
* @returns transaction hash | ||
*/ | ||
private async submitTransaction( | ||
relayer: Relayer, | ||
transaction: providers.TransactionRequest, | ||
storageMap: StorageMap | ||
): Promise<string> { | ||
const signedRawTx = await relayer.signTransaction(transaction); | ||
const method = "pfl_sendRawTransactionConditional"; | ||
|
||
const provider = new providers.JsonRpcProvider( | ||
this.networkConfig.rpcEndpointSubmit | ||
); | ||
const submitStart = now(); | ||
return new Promise((resolve, reject) => { | ||
let lock = false; | ||
const handler = async (blockNumber: number): Promise<void> => { | ||
if (now() - submitStart > this.submitTimeout) return reject("timeout"); | ||
if (lock) return; | ||
lock = true; | ||
|
||
const block = await relayer.provider.getBlock("latest"); | ||
const params = [ | ||
signedRawTx, | ||
{ | ||
knownAccounts: storageMap, | ||
blockNumberMin: block.number, | ||
blockNumberMax: block.number + 180, // ~10 minutes | ||
timestampMin: block.timestamp, | ||
timestampMax: block.timestamp + 420, // 15 minutes | ||
}, | ||
]; | ||
|
||
this.logger.debug({ | ||
method, | ||
...transaction, | ||
params, | ||
}); | ||
|
||
this.logger.debug(`Fastlane: Trying to submit...`); | ||
|
||
try { | ||
const hash = await provider.send(method, params); | ||
this.logger.debug(`Fastlane: Sent new bundle ${hash}`); | ||
this.provider.removeListener("block", handler); | ||
return resolve(hash); | ||
} catch (err: any) { | ||
console.log(JSON.stringify(err, undefined, 2)); | ||
if ( | ||
!err || | ||
!err.body || | ||
!err.body.match(/is not participating in FastLane protocol/) | ||
) { | ||
// some other error happened | ||
this.provider.removeListener("block", handler); | ||
return reject(err); | ||
} | ||
this.logger.debug( | ||
`Fastlane: Validator is not participating in FastLane protocol. Trying again...` | ||
); | ||
} finally { | ||
lock = false; | ||
} | ||
}; | ||
this.provider.on("block", handler); | ||
}); | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This in theory will be used only during the testing phase, no?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
yes, that's correct