repo_name stringlengths 1 62 | dataset stringclasses 1 value | lang stringclasses 11 values | pr_id int64 1 20.1k | owner stringlengths 2 34 | reviewer stringlengths 2 39 | diff_hunk stringlengths 15 262k | code_review_comment stringlengths 1 99.6k |
|---|---|---|---|---|---|---|---|
big-bear-scripts | github_2023 | others | 8 | bigbeartechworld | coderabbitai[bot] | @@ -140,23 +140,152 @@ check_dns_resolution() {
"registry.hub.docker.com"
"gcr.io"
"azurecr.io"
- "ghcr.io",
+ "ghcr.io"
"registry.gitlab.com"
)
+ local retries=3
+ local timeout=5
+ local dns_servers=("8.8.8.8" "1.1.1.1" "9.9.9.9" "208.67.222.222")
print_header "DNS Resolution Check:"
+ # Verify basic network connectivity
+ if ! ping -c 1 8.8.8.8 &>/dev/null; then
+ print_color "0;31" "${CROSS_MARK} Network connectivity issue: Unable to reach 8.8.8.8"
+ return
+ fi
+
for registry in "${registries[@]}"; do
- if nslookup "$registry" &>/dev/null; then
- print_color "0;32" "${CHECK_MARK} DNS resolution for $registry is successful"
- else
+ local success=false
+ for dns_server in "${dns_servers[@]}"; do
+ for ((i=1; i<=retries; i++)); do
+ if timeout $timeout nslookup "$registry" "$dns_server" &>/dev/null; then
+ print_color "0;32" "${CHECK_MARK} DNS resolution for $registry is successful using DNS server $dns_server"
+ success=true
+ break 2
+ else
+ echo "Attempt $i of $retries for $registry using DNS server $dns_server failed"
+ fi
+ done
+ done
+
+ if [ "$success" = false ]; then
print_color "0;31" "${CROSS_MARK} DNS resolution for $registry failed"
echo "Debugging info for $registry:"
- nslookup "$registry" 2>&1 | tee /dev/stderr
+ nslookup "$registry" 2>&1
+ # Alternative check with dig for more detailed output
+ if command -v dig &> /dev/null; then
+ echo "Dig output:"
+ dig +short "$registry" @8.8.8.8
+ fi
+ fi
+ done
+}
+
+# Function to check Docker status
+check_docker_status() {
+ print_header "Docker Status Check"
+ if command -v docker &> /dev/null; then
+ if docker info &> /dev/null; then
+ print_color "0;32" "${CHECK_MARK} Docker is running"
+ else
+ print_color "0;31" "${CROSS_MARK} Docker is installed but not running"
+ fi
+ else
+ print_color "0;31" "${CROSS_MARK} Docker is not installed"
+ fi
+}
+
+# Function to check storage health
+check_storage_health() {
+ print_header "Storage Health Check"
+ local disks=$(lsblk -ndo NAME,TYPE | awk '$2=="disk"{print $1}')
+ for disk in $disks; do
+ if smartctl -H /dev/$disk &> /dev/null; then
+ local health=$(smartctl -H /dev/$disk | grep "SMART overall-health")
+ if [[ $health == *"PASSED"* ]]; then
+ print_color "0;32" "${CHECK_MARK} /dev/$disk is healthy"
+ else
+ print_color "0;31" "${CROSS_MARK} /dev/$disk may have issues"
+ fi
+ else
+ print_color "0;33" "${WARNING_MARK} Unable to check health of /dev/$disk"
fi
done
}
+# Function to check disk space
+check_disk_space() {
+ print_header "Disk Space Check"
+ local threshold=80
+ local usage=$(df / | grep / | awk '{ print $5 }' | sed 's/%//g')
+ if [ "$usage" -ge "$threshold" ]; then
+ print_color "0;31" "${CROSS_MARK} Disk usage is at ${usage}%, which is above the threshold of ${threshold}%"
+ else
+ print_color "0;32" "${CHECK_MARK} Disk usage is at ${usage}%, which is below the threshold of ${threshold}%"
+ fi
+}
+
+# Function to check CPU load
+check_cpu_load() {
+ print_header "CPU Load Check"
+ local load=$(uptime | awk -F'load average:' '{ print $2 }' | cut -d, -f1 | xargs)
+ local cores=$(nproc)
+ local threshold=$(awk "BEGIN {print $cores * 0.7}") | _:warning: Potential issue_
**Avoid declaring and assigning 'local' variables in the same line to prevent masking return values**
In the `check_cpu_load` function, splitting declarations and assignments enhances the script's reliability.
Apply this diff:
```diff
- local load=$(uptime | awk -F'load average:' '{ print $2 }' | cut -d, -f1 | xargs)
- local cores=$(nproc)
- local threshold=$(awk "BEGIN {print $cores * 0.7}")
+ local load
+ load=$(uptime | awk -F'load average:' '{ print $2 }' | cut -d, -f1 | xargs)
+ local cores
+ cores=$(nproc)
+ local threshold
+ threshold=$(awk "BEGIN {print $cores * 0.7}")
```
<!-- suggestion_start -->
<details>
<summary>📝 Committable suggestion</summary>
> ‼️ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
`````suggestion
local load
load=$(uptime | awk -F'load average:' '{ print $2 }' | cut -d, -f1 | xargs)
local cores
cores=$(nproc)
local threshold
threshold=$(awk "BEGIN {print $cores * 0.7}")
`````
</details>
<!-- suggestion_end -->
<details>
<summary>🧰 Tools</summary>
<details>
<summary>🪛 Shellcheck</summary><blockquote>
[warning] 232-232: Declare and assign separately to avoid masking return values.
(SC2155)
---
[warning] 233-233: Declare and assign separately to avoid masking return values.
(SC2155)
---
[warning] 234-234: Declare and assign separately to avoid masking return values.
(SC2155)
</blockquote></details>
</details>
<!-- This is an auto-generated comment by CodeRabbit --> |
big-bear-scripts | github_2023 | others | 8 | bigbeartechworld | coderabbitai[bot] | @@ -140,23 +140,152 @@ check_dns_resolution() {
"registry.hub.docker.com"
"gcr.io"
"azurecr.io"
- "ghcr.io",
+ "ghcr.io"
"registry.gitlab.com"
)
+ local retries=3
+ local timeout=5
+ local dns_servers=("8.8.8.8" "1.1.1.1" "9.9.9.9" "208.67.222.222")
print_header "DNS Resolution Check:"
+ # Verify basic network connectivity
+ if ! ping -c 1 8.8.8.8 &>/dev/null; then
+ print_color "0;31" "${CROSS_MARK} Network connectivity issue: Unable to reach 8.8.8.8"
+ return
+ fi
+
for registry in "${registries[@]}"; do
- if nslookup "$registry" &>/dev/null; then
- print_color "0;32" "${CHECK_MARK} DNS resolution for $registry is successful"
- else
+ local success=false
+ for dns_server in "${dns_servers[@]}"; do
+ for ((i=1; i<=retries; i++)); do
+ if timeout $timeout nslookup "$registry" "$dns_server" &>/dev/null; then
+ print_color "0;32" "${CHECK_MARK} DNS resolution for $registry is successful using DNS server $dns_server"
+ success=true
+ break 2
+ else
+ echo "Attempt $i of $retries for $registry using DNS server $dns_server failed"
+ fi
+ done
+ done
+
+ if [ "$success" = false ]; then
print_color "0;31" "${CROSS_MARK} DNS resolution for $registry failed"
echo "Debugging info for $registry:"
- nslookup "$registry" 2>&1 | tee /dev/stderr
+ nslookup "$registry" 2>&1
+ # Alternative check with dig for more detailed output
+ if command -v dig &> /dev/null; then
+ echo "Dig output:"
+ dig +short "$registry" @8.8.8.8
+ fi
+ fi
+ done
+}
+
+# Function to check Docker status
+check_docker_status() {
+ print_header "Docker Status Check"
+ if command -v docker &> /dev/null; then
+ if docker info &> /dev/null; then
+ print_color "0;32" "${CHECK_MARK} Docker is running"
+ else
+ print_color "0;31" "${CROSS_MARK} Docker is installed but not running"
+ fi
+ else
+ print_color "0;31" "${CROSS_MARK} Docker is not installed"
+ fi
+}
+
+# Function to check storage health
+check_storage_health() {
+ print_header "Storage Health Check"
+ local disks=$(lsblk -ndo NAME,TYPE | awk '$2=="disk"{print $1}')
+ for disk in $disks; do
+ if smartctl -H /dev/$disk &> /dev/null; then
+ local health=$(smartctl -H /dev/$disk | grep "SMART overall-health")
+ if [[ $health == *"PASSED"* ]]; then
+ print_color "0;32" "${CHECK_MARK} /dev/$disk is healthy"
+ else
+ print_color "0;31" "${CROSS_MARK} /dev/$disk may have issues"
+ fi
+ else
+ print_color "0;33" "${WARNING_MARK} Unable to check health of /dev/$disk"
fi
done
}
+# Function to check disk space
+check_disk_space() {
+ print_header "Disk Space Check"
+ local threshold=80
+ local usage=$(df / | grep / | awk '{ print $5 }' | sed 's/%//g')
+ if [ "$usage" -ge "$threshold" ]; then
+ print_color "0;31" "${CROSS_MARK} Disk usage is at ${usage}%, which is above the threshold of ${threshold}%"
+ else
+ print_color "0;32" "${CHECK_MARK} Disk usage is at ${usage}%, which is below the threshold of ${threshold}%"
+ fi
+}
+
+# Function to check CPU load
+check_cpu_load() {
+ print_header "CPU Load Check"
+ local load=$(uptime | awk -F'load average:' '{ print $2 }' | cut -d, -f1 | xargs)
+ local cores=$(nproc)
+ local threshold=$(awk "BEGIN {print $cores * 0.7}")
+ if (( $(awk "BEGIN {print ($load > $threshold) ? 1 : 0}") )); then
+ print_color "0;31" "${CROSS_MARK} CPU load is high: ${load} (Threshold: ${threshold})"
+ else
+ print_color "0;32" "${CHECK_MARK} CPU load is acceptable: ${load} (Threshold: ${threshold})"
+ fi
+}
+
+# Function to check memory usage
+check_memory_usage() {
+ print_header "Memory Usage Check"
+ local total_mem=$(free -m | awk '/^Mem:/ { print $2 }')
+ local used_mem=$(free -m | awk '/^Mem:/ { print $3 }')
+ local threshold=$(awk "BEGIN {print int($total_mem * 0.8)}") | _:warning: Potential issue_
**Avoid declaring and assigning 'local' variables in the same line to prevent masking return values**
In the `check_memory_usage` function, this practice prevents potential issues with function return values.
Apply this diff:
```diff
- local total_mem=$(free -m | awk '/^Mem:/ { print $2 }')
- local used_mem=$(free -m | awk '/^Mem:/ { print $3 }')
- local threshold=$(awk "BEGIN {print int($total_mem * 0.8)}")
+ local total_mem
+ total_mem=$(free -m | awk '/^Mem:/ { print $2 }')
+ local used_mem
+ used_mem=$(free -m | awk '/^Mem:/ { print $3 }')
+ local threshold
+ threshold=$(awk "BEGIN {print int($total_mem * 0.8)}")
```
<!-- suggestion_start -->
<details>
<summary>📝 Committable suggestion</summary>
> ‼️ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
`````suggestion
local total_mem
total_mem=$(free -m | awk '/^Mem:/ { print $2 }')
local used_mem
used_mem=$(free -m | awk '/^Mem:/ { print $3 }')
local threshold
threshold=$(awk "BEGIN {print int($total_mem * 0.8)}")
`````
</details>
<!-- suggestion_end -->
<details>
<summary>🧰 Tools</summary>
<details>
<summary>🪛 Shellcheck</summary><blockquote>
[warning] 245-245: Declare and assign separately to avoid masking return values.
(SC2155)
---
[warning] 246-246: Declare and assign separately to avoid masking return values.
(SC2155)
---
[warning] 247-247: Declare and assign separately to avoid masking return values.
(SC2155)
</blockquote></details>
</details>
<!-- This is an auto-generated comment by CodeRabbit --> |
big-bear-scripts | github_2023 | others | 8 | bigbeartechworld | coderabbitai[bot] | @@ -140,23 +140,152 @@ check_dns_resolution() {
"registry.hub.docker.com"
"gcr.io"
"azurecr.io"
- "ghcr.io",
+ "ghcr.io"
"registry.gitlab.com"
)
+ local retries=3
+ local timeout=5
+ local dns_servers=("8.8.8.8" "1.1.1.1" "9.9.9.9" "208.67.222.222")
print_header "DNS Resolution Check:"
+ # Verify basic network connectivity
+ if ! ping -c 1 8.8.8.8 &>/dev/null; then
+ print_color "0;31" "${CROSS_MARK} Network connectivity issue: Unable to reach 8.8.8.8"
+ return
+ fi
+
for registry in "${registries[@]}"; do
- if nslookup "$registry" &>/dev/null; then
- print_color "0;32" "${CHECK_MARK} DNS resolution for $registry is successful"
- else
+ local success=false
+ for dns_server in "${dns_servers[@]}"; do
+ for ((i=1; i<=retries; i++)); do
+ if timeout $timeout nslookup "$registry" "$dns_server" &>/dev/null; then
+ print_color "0;32" "${CHECK_MARK} DNS resolution for $registry is successful using DNS server $dns_server"
+ success=true
+ break 2
+ else
+ echo "Attempt $i of $retries for $registry using DNS server $dns_server failed"
+ fi
+ done
+ done
+
+ if [ "$success" = false ]; then
print_color "0;31" "${CROSS_MARK} DNS resolution for $registry failed"
echo "Debugging info for $registry:"
- nslookup "$registry" 2>&1 | tee /dev/stderr
+ nslookup "$registry" 2>&1
+ # Alternative check with dig for more detailed output
+ if command -v dig &> /dev/null; then
+ echo "Dig output:"
+ dig +short "$registry" @8.8.8.8
+ fi
+ fi
+ done
+}
+
+# Function to check Docker status
+check_docker_status() {
+ print_header "Docker Status Check"
+ if command -v docker &> /dev/null; then
+ if docker info &> /dev/null; then
+ print_color "0;32" "${CHECK_MARK} Docker is running"
+ else
+ print_color "0;31" "${CROSS_MARK} Docker is installed but not running"
+ fi
+ else
+ print_color "0;31" "${CROSS_MARK} Docker is not installed"
+ fi
+}
+
+# Function to check storage health
+check_storage_health() {
+ print_header "Storage Health Check"
+ local disks=$(lsblk -ndo NAME,TYPE | awk '$2=="disk"{print $1}')
+ for disk in $disks; do
+ if smartctl -H /dev/$disk &> /dev/null; then
+ local health=$(smartctl -H /dev/$disk | grep "SMART overall-health") | _:warning: Potential issue_
**Avoid declaring and assigning 'local' variables in the same line to prevent masking return values**
In Bash, declaring and assigning a `local` variable in the same line can mask the return value of the function. It's recommended to declare the variable and assign it in separate statements to avoid this issue.
Apply this diff to fix the problem:
```diff
- local disks=$(lsblk -ndo NAME,TYPE | awk '$2=="disk"{print $1}')
+ local disks
+ disks=$(lsblk -ndo NAME,TYPE | awk '$2=="disk"{print $1}')
```
```diff
- local health=$(smartctl -H /dev/$disk | grep "SMART overall-health")
+ local health
+ health=$(smartctl -H /dev/$disk | grep "SMART overall-health")
```
<!-- suggestion_start -->
<details>
<summary>📝 Committable suggestion</summary>
> ‼️ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
`````suggestion
local disks
disks=$(lsblk -ndo NAME,TYPE | awk '$2=="disk"{print $1}')
for disk in $disks; do
if smartctl -H /dev/$disk &> /dev/null; then
local health
health=$(smartctl -H /dev/$disk | grep "SMART overall-health")
`````
</details>
<!-- suggestion_end -->
<details>
<summary>🧰 Tools</summary>
<details>
<summary>🪛 Shellcheck</summary><blockquote>
[warning] 202-202: Declare and assign separately to avoid masking return values.
(SC2155)
---
[warning] 205-205: Declare and assign separately to avoid masking return values.
(SC2155)
</blockquote></details>
</details>
<!-- This is an auto-generated comment by CodeRabbit --> |
big-bear-scripts | github_2023 | others | 8 | bigbeartechworld | coderabbitai[bot] | @@ -140,23 +140,152 @@ check_dns_resolution() {
"registry.hub.docker.com"
"gcr.io"
"azurecr.io"
- "ghcr.io",
+ "ghcr.io"
"registry.gitlab.com"
)
+ local retries=3
+ local timeout=5
+ local dns_servers=("8.8.8.8" "1.1.1.1" "9.9.9.9" "208.67.222.222")
print_header "DNS Resolution Check:"
+ # Verify basic network connectivity
+ if ! ping -c 1 8.8.8.8 &>/dev/null; then
+ print_color "0;31" "${CROSS_MARK} Network connectivity issue: Unable to reach 8.8.8.8"
+ return
+ fi
+
for registry in "${registries[@]}"; do
- if nslookup "$registry" &>/dev/null; then
- print_color "0;32" "${CHECK_MARK} DNS resolution for $registry is successful"
- else
+ local success=false
+ for dns_server in "${dns_servers[@]}"; do
+ for ((i=1; i<=retries; i++)); do
+ if timeout $timeout nslookup "$registry" "$dns_server" &>/dev/null; then
+ print_color "0;32" "${CHECK_MARK} DNS resolution for $registry is successful using DNS server $dns_server"
+ success=true
+ break 2
+ else
+ echo "Attempt $i of $retries for $registry using DNS server $dns_server failed"
+ fi
+ done
+ done
+
+ if [ "$success" = false ]; then
print_color "0;31" "${CROSS_MARK} DNS resolution for $registry failed"
echo "Debugging info for $registry:"
- nslookup "$registry" 2>&1 | tee /dev/stderr
+ nslookup "$registry" 2>&1
+ # Alternative check with dig for more detailed output
+ if command -v dig &> /dev/null; then
+ echo "Dig output:"
+ dig +short "$registry" @8.8.8.8
+ fi
+ fi
+ done
+}
+
+# Function to check Docker status
+check_docker_status() {
+ print_header "Docker Status Check"
+ if command -v docker &> /dev/null; then
+ if docker info &> /dev/null; then
+ print_color "0;32" "${CHECK_MARK} Docker is running"
+ else
+ print_color "0;31" "${CROSS_MARK} Docker is installed but not running"
+ fi
+ else
+ print_color "0;31" "${CROSS_MARK} Docker is not installed"
+ fi
+}
+
+# Function to check storage health
+check_storage_health() {
+ print_header "Storage Health Check"
+ local disks=$(lsblk -ndo NAME,TYPE | awk '$2=="disk"{print $1}')
+ for disk in $disks; do
+ if smartctl -H /dev/$disk &> /dev/null; then
+ local health=$(smartctl -H /dev/$disk | grep "SMART overall-health")
+ if [[ $health == *"PASSED"* ]]; then
+ print_color "0;32" "${CHECK_MARK} /dev/$disk is healthy"
+ else
+ print_color "0;31" "${CROSS_MARK} /dev/$disk may have issues"
+ fi
+ else
+ print_color "0;33" "${WARNING_MARK} Unable to check health of /dev/$disk"
fi
done
}
+# Function to check disk space
+check_disk_space() {
+ print_header "Disk Space Check"
+ local threshold=80
+ local usage=$(df / | grep / | awk '{ print $5 }' | sed 's/%//g')
+ if [ "$usage" -ge "$threshold" ]; then
+ print_color "0;31" "${CROSS_MARK} Disk usage is at ${usage}%, which is above the threshold of ${threshold}%"
+ else
+ print_color "0;32" "${CHECK_MARK} Disk usage is at ${usage}%, which is below the threshold of ${threshold}%"
+ fi
+}
+
+# Function to check CPU load
+check_cpu_load() {
+ print_header "CPU Load Check"
+ local load=$(uptime | awk -F'load average:' '{ print $2 }' | cut -d, -f1 | xargs)
+ local cores=$(nproc)
+ local threshold=$(awk "BEGIN {print $cores * 0.7}")
+ if (( $(awk "BEGIN {print ($load > $threshold) ? 1 : 0}") )); then
+ print_color "0;31" "${CROSS_MARK} CPU load is high: ${load} (Threshold: ${threshold})"
+ else
+ print_color "0;32" "${CHECK_MARK} CPU load is acceptable: ${load} (Threshold: ${threshold})"
+ fi
+}
+
+# Function to check memory usage
+check_memory_usage() {
+ print_header "Memory Usage Check"
+ local total_mem=$(free -m | awk '/^Mem:/ { print $2 }')
+ local used_mem=$(free -m | awk '/^Mem:/ { print $3 }')
+ local threshold=$(awk "BEGIN {print int($total_mem * 0.8)}")
+ if (( $(awk "BEGIN {print ($used_mem > $threshold) ? 1 : 0}") )); then
+ print_color "0;31" "${CROSS_MARK} Memory usage is high: ${used_mem}MB used of ${total_mem}MB (Threshold: ${threshold}MB)"
+ else
+ print_color "0;32" "${CHECK_MARK} Memory usage is acceptable: ${used_mem}MB used of ${total_mem}MB (Threshold: ${threshold}MB)"
+ fi
+}
+
+# Function to check system temperature
+check_system_temperature() {
+ print_header "System Temperature Check"
+ if command -v sensors &> /dev/null; then
+ sensors | grep -E 'Core|temp' | while read -r line; do
+ local temp=$(echo "$line" | awk '{print $2}' | sed 's/+//' | sed 's/°C//')
+ if (( $(awk "BEGIN {print ($temp > 80) ? 1 : 0}") )); then
+ print_color "0;31" "${CROSS_MARK} High temperature detected: ${line}"
+ else
+ print_color "0;32" "${CHECK_MARK} Temperature is normal: ${line}"
+ fi
+ done
+ elif [ -f "/sys/class/thermal/thermal_zone0/temp" ]; then
+ local temp=$(awk '{print $1/1000}' /sys/class/thermal/thermal_zone0/temp)
+ if (( $(awk "BEGIN {print ($temp > 80) ? 1 : 0}") )); then
+ print_color "0;31" "${CROSS_MARK} High temperature detected: ${temp}°C"
+ else
+ print_color "0;32" "${CHECK_MARK} Temperature is normal: ${temp}°C"
+ fi
+ else
+ print_color "0;33" "${WARNING_MARK} Unable to check system temperature. sensors command not found and /sys/class/thermal not available."
+ fi
+}
+
+# Function to check for system updates
+check_system_updates() {
+ print_header "System Update Check"
+ if command -v apt-get &> /dev/null; then
+ local updates=$(apt-get -s upgrade | grep -P '^\d+ upgraded') | _:warning: Potential issue_
**Use portable regex options with 'grep'**
The `-P` option for `grep` (Perl-compatible regex) may not be available on all systems. To enhance portability, consider using `-E` for extended regular expressions or adjust the pattern accordingly.
Apply this diff to improve compatibility:
```diff
- local updates=$(apt-get -s upgrade | grep -P '^\d+ upgraded')
+ local updates=$(apt-get -s upgrade | grep -E '^[0-9]+ upgraded')
```
<!-- suggestion_start -->
<details>
<summary>📝 Committable suggestion</summary>
> ‼️ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
`````suggestion
local updates=$(apt-get -s upgrade | grep -E '^[0-9]+ upgraded')
```
This suggestion replaces the original line with the more portable version using the `-E` option for `grep` and an adjusted regex pattern that works with extended regular expressions.
It's worth noting that the static analysis hint from Shellcheck (SC2155) is not directly addressed by this change. The Shellcheck warning suggests declaring and assigning the variable separately to avoid masking return values. While this is a valid concern, it's not the focus of the current review comment. If you want to address both issues, you might consider a further modification like this:
```
local updates
updates=$(apt-get -s upgrade | grep -E '^[0-9]+ upgraded')
`````
</details>
<!-- suggestion_end -->
<details>
<summary>🧰 Tools</summary>
<details>
<summary>🪛 Shellcheck</summary><blockquote>
[warning] 283-283: Declare and assign separately to avoid masking return values.
(SC2155)
</blockquote></details>
</details>
<!-- This is an auto-generated comment by CodeRabbit --> |
alto | github_2023 | typescript | 465 | pimlicolabs | plusminushalf | @@ -18,7 +18,9 @@ import { SignedAuthorizationList } from "viem/experimental"
import { AltoConfig } from "../createConfig"
export const isTransactionUnderpricedError = (e: BaseError) => {
- return e?.details
+ const deepestError = e.walk() | would it make sense to have something like:
```ts
const transactionUnderPriceError e.walk(e => e?.message?. toLowerCase()
.includes("replacement transaction underpriced"))
return transactionUnderPriceError !== null
``` |
alto | github_2023 | typescript | 467 | pimlicolabs | mouseless0x | @@ -599,22 +600,19 @@ export class RpcHandler {
preVerificationGas = scaleBigIntByPercent(preVerificationGas, 110n)
// Check if userOperation passes without estimation balance overrides
- if (isVersion06(simulationUserOperation)) {
- await this.validator.getExecutionResult({
- userOperation: {
- ...simulationUserOperation,
- preVerificationGas,
- verificationGasLimit,
- callGasLimit,
- paymasterVerificationGasLimit,
- paymasterPostOpGasLimit
- },
- entryPoint,
- queuedUserOperations,
- addSenderBalanceOverride: false,
- stateOverrides: deepHexlify(stateOverrides)
- })
- }
+ await this.validator.validateHandleOp({
+ userOperation: {
+ ...simulationUserOperation, | I think we should spread the original userOperation here to ensure the maxFee/maxPriorityFee is used |
alto | github_2023 | typescript | 439 | pimlicolabs | plusminushalf | @@ -0,0 +1,55 @@
+import { SenderManager } from "."
+import { AltoConfig } from "../../createConfig"
+import { GasPriceManager } from "../../handlers/gasPriceManager"
+import { flushStuckTransaction } from "../utils"
+
+export const flushOnStartUp = async ({
+ senderManager,
+ gasPriceManager,
+ config
+}: {
+ senderManager: SenderManager
+ config: AltoConfig
+ gasPriceManager: GasPriceManager
+}) => {
+ const logger = config.getLogger(
+ { module: "flush-on-start-up" },
+ { level: config.logLevel }
+ )
+
+ const allWallets = new Set(senderManager.getAllWallets())
+
+ const utilityWallet = config.utilityPrivateKey
+ if (utilityWallet) {
+ allWallets.add(utilityWallet)
+ }
+
+ const wallets = Array.from(allWallets)
+
+ let gasPrice: {
+ maxFeePerGas: bigint
+ maxPriorityFeePerGas: bigint
+ }
+
+ try {
+ gasPrice = await gasPriceManager.tryGetNetworkGasPrice()
+ } catch (e) {
+ logger.error({ error: e }, "error flushing stuck transaction")
+ return
+ }
+
+ const promises = wallets.map((wallet) => { | this function should have an async and await on `flushStuckTransaction` for this to return promises |
alto | github_2023 | typescript | 439 | pimlicolabs | plusminushalf | @@ -250,14 +232,42 @@ export const setupServer = async ({
})
if (config.refillingWallets) { | Can we leave a comment in the config that this must only be enabled on a single instance. Otherwise all the instance will try to send money to all the wallets. |
alto | github_2023 | typescript | 439 | pimlicolabs | plusminushalf | @@ -0,0 +1,502 @@
+import {
+ getNonceKeyAndSequence,
+ isVersion06,
+ isVersion07
+} from "../utils/userop"
+import { AltoConfig } from "../createConfig"
+import {
+ Address,
+ HexData32,
+ UserOperation,
+ UserOpInfo,
+ userOpInfoSchema
+} from "@alto/types"
+import { OutstandingStore } from "."
+import { Redis } from "ioredis"
+import { toHex } from "viem/utils"
+
+const serializeUserOpInfo = (userOpInfo: UserOpInfo): string => {
+ return JSON.stringify(userOpInfo, (_, value) =>
+ typeof value === "bigint" ? toHex(value) : value
+ )
+}
+
+const deserializeUserOpInfo = (data: string): UserOpInfo => {
+ try {
+ const parsed = JSON.parse(data)
+ const result = userOpInfoSchema.safeParse(parsed)
+
+ if (!result.success) {
+ throw new Error(
+ `Failed to parse UserOpInfo: ${result.error.message}`
+ )
+ }
+ return result.data
+ } catch (error) {
+ if (error instanceof Error) {
+ throw new Error(
+ `UserOpInfo deserialization failed: ${error.message}`
+ )
+ }
+ throw new Error("UserOpInfo deserialization failed with unknown error")
+ }
+}
+
+const isDeploymentOperation = (userOp: UserOperation): boolean => {
+ const isV6Deployment =
+ isVersion06(userOp) && !!userOp.initCode && userOp.initCode !== "0x"
+ const isV7Deployment =
+ isVersion07(userOp) && !!userOp.factory && userOp.factory !== "0x"
+ return isV6Deployment || isV7Deployment
+}
+
+class RedisSortedSet {
+ constructor(
+ private redis: Redis,
+ private keyName: string
+ ) {}
+
+ get keyPath(): string {
+ return this.keyName
+ }
+
+ async add(
+ member: string,
+ score: number,
+ multi?: ReturnType<Redis["multi"]>
+ ): Promise<void> {
+ if (multi) {
+ multi.zadd(this.keyPath, score, member)
+ } else {
+ await this.redis.zadd(this.keyPath, score, member)
+ }
+ }
+
+ async remove(
+ member: string,
+ multi?: ReturnType<Redis["multi"]>
+ ): Promise<void> {
+ if (multi) {
+ multi.zrem(this.keyPath, member)
+ } else {
+ await this.redis.zrem(this.keyPath, member)
+ }
+ }
+
+ async getByScoreRange(min: number, max: number): Promise<string[]> {
+ return this.redis.zrangebyscore(this.keyPath, min, max)
+ }
+
+ async getByRankRange(start: number, stop: number): Promise<string[]> {
+ return this.redis.zrange(this.keyPath, start, stop)
+ }
+
+ async popMax(): Promise<string | undefined> {
+ type ZmpopResult = [string, [string, string][]] // [key, [[member, score], ...]]
+
+ const result = (await this.redis.zmpop(
+ 1,
+ [this.keyPath],
+ "MAX",
+ "COUNT",
+ 1
+ )) as ZmpopResult
+
+ return result && result[1].length > 0 ? result[1][0][0] : undefined
+ }
+
+ async popMin(): Promise<string | undefined> {
+ type ZmpopResult = [string, [string, string][]] // [key, [[member, score], ...]]
+
+ const result = (await this.redis.zmpop(
+ 1,
+ [this.keyPath],
+ "MIN",
+ "COUNT",
+ 1
+ )) as ZmpopResult
+
+ return result && result[1].length > 0 ? result[1][0][0] : undefined
+ }
+
+ async delete(multi?: ReturnType<Redis["multi"]>): Promise<void> {
+ if (multi) {
+ multi.del(this.keyPath)
+ } else {
+ await this.redis.del(this.keyPath)
+ }
+ }
+}
+
+export class RedisHash {
+ constructor(
+ private redis: Redis,
+ private keyName: string
+ ) {}
+
+ get keyPath(): string {
+ return this.keyName
+ }
+
+ async set(
+ field: string,
+ value: string,
+ multi?: ReturnType<Redis["multi"]>
+ ): Promise<void> {
+ if (multi) {
+ multi.hset(this.keyPath, field, value)
+ } else {
+ await this.redis.hset(this.keyPath, field, value)
+ }
+ }
+
+ async get(field: string): Promise<string | null> {
+ return this.redis.hget(this.keyPath, field)
+ }
+
+ async delete(
+ field: string,
+ multi?: ReturnType<Redis["multi"]>
+ ): Promise<void> {
+ if (multi) {
+ multi.hdel(this.keyPath, field)
+ } else {
+ await this.redis.hdel(this.keyPath, field)
+ }
+ }
+
+ async exists(field: string): Promise<boolean> {
+ return (await this.redis.hexists(this.keyPath, field)) === 1
+ }
+
+ async getAll(): Promise<Record<string, string>> {
+ return this.redis.hgetall(this.keyPath)
+ }
+}
+
+class RedisOutstandingQueue implements OutstandingStore {
+ private redis: Redis
+ private chainId: number
+ private entryPoint: Address
+
+ // Redis data structures
+ private readyOpsQueue: RedisSortedSet // gasPrice -> pendingOpsKey
+ private userOpHashLookup: RedisHash // userOpHash -> pendingOpsKey
+ private factoryLookup: RedisHash // sender -> userOpHash
+
+ constructor({
+ config,
+ entryPoint
+ }: { config: AltoConfig; entryPoint: Address }) {
+ if (!config.redisMempoolUrl) {
+ throw new Error("Missing required redisMempoolUrl")
+ }
+
+ this.redis = new Redis(config.redisMempoolUrl, {})
+ this.chainId = config.chainId
+ this.entryPoint = entryPoint
+
+ // Initialize Redis data structures
+ const factoryLookupKey = `${this.chainId}:outstanding:factory-lookup:${this.entryPoint}`
+ const userOpHashLookupKey = `${this.chainId}:outstanding:user-op-hash-index:${this.entryPoint}`
+ const readyOpsQueueKey = `${this.chainId}:outstanding:pending-queue:${this.entryPoint}`
+
+ this.readyOpsQueue = new RedisSortedSet(this.redis, readyOpsQueueKey)
+ this.userOpHashLookup = new RedisHash(this.redis, userOpHashLookupKey)
+ this.factoryLookup = new RedisHash(this.redis, factoryLookupKey)
+ }
+
+ // Helpers
+ private getPendingOpsSet(userOp: UserOperation): RedisSortedSet {
+ return new RedisSortedSet(this.redis, this.getPendingOpsKey(userOp))
+ }
+
+ private getPendingOpsKey(userOp: UserOperation): string {
+ const [nonceKey] = getNonceKeyAndSequence(userOp.nonce)
+ const fingerprint = `${userOp.sender}-${toHex(nonceKey)}`
+ return `${this.chainId}:outstanding:pending-ops:${this.entryPoint}:${fingerprint}`
+ }
+
+ // OutstandingStore methods
+ async contains(userOpHash: HexData32): Promise<boolean> {
+ return this.userOpHashLookup.exists(userOpHash)
+ }
+
+ async findConflicting(userOp: UserOperation) { | remove as soon as we find so that no other server can bundle the op |
alto | github_2023 | typescript | 439 | pimlicolabs | plusminushalf | @@ -349,86 +301,75 @@ export class MemoryMempool {
const hasHigherFees = hasHigherPriorityFee && hasHigherMaxFee
if (!hasHigherFees) {
- return [false, reason]
+ const reason =
+ conflicting.reason === "conflicting_deployment"
+ ? "AA10 sender already constructed: A conflicting userOperation with initCode for this sender is already in the mempool"
+ : "AA25 invalid account nonce: User operation already present in mempool"
+
+ return [false, `${reason}, bump the gas price by minimum 10%`] | note you will still have to push the op that we will be removing during `findConflictingOutstanding` back to mempool again |
alto | github_2023 | typescript | 439 | pimlicolabs | plusminushalf | @@ -0,0 +1,312 @@
+import {
+ getNonceKeyAndSequence,
+ isVersion06,
+ isVersion07
+} from "../utils/userop"
+import { AltoConfig } from "../createConfig"
+import { HexData32, UserOpInfo, UserOperation } from "@alto/types"
+import { ConflictingType, OutstandingStore } from "."
+
+const senderNonceSlot = (userOp: UserOperation) => {
+ const sender = userOp.sender
+ const [nonceKey] = getNonceKeyAndSequence(userOp.nonce)
+ return `${sender}-${nonceKey}`
+}
+
+const dump = (pendingOps: Map<string, UserOpInfo[]>) => {
+ return [...Array.from(pendingOps.values()).flat()]
+}
+
+export const createMemoryOutstandingQueue = ({
+ config
+}: { config: AltoConfig }): OutstandingStore => {
+ let pendingOps: Map<string, UserOpInfo[]> = new Map()
+ let priorityQueue: UserOpInfo[] = []
+ const logger = config.getLogger(
+ { module: "memory-outstanding-queue" },
+ {
+ level: config.logLevel
+ }
+ )
+
+ // Adds userOp to queue and maintains sorting by gas price.
+ const addToPriorityQueue = ({
+ priorityQueue,
+ userOpInfo
+ }: { userOpInfo: UserOpInfo; priorityQueue: UserOpInfo[] }) => {
+ priorityQueue.push(userOpInfo)
+ priorityQueue.sort((a, b) => {
+ const userOpA = a.userOp
+ const userOpB = b.userOp
+ return Number(userOpA.maxFeePerGas - userOpB.maxFeePerGas)
+ })
+ }
+
+ return {
+ validateQueuedLimit: (userOp: UserOperation) => {
+ const outstandingOps = dump(pendingOps)
+
+ const parallelUserOperationsCount = outstandingOps.filter(
+ (userOpInfo) => {
+ const { userOp: mempoolUserOp } = userOpInfo
+ return mempoolUserOp.sender === userOp.sender
+ }
+ ).length
+
+ if (parallelUserOperationsCount > config.mempoolMaxParallelOps) {
+ return false
+ }
+
+ return true
+ },
+ validateParallelLimit: (userOp: UserOperation) => {
+ const outstandingOps = dump(pendingOps)
+
+ const [nonceKey] = getNonceKeyAndSequence(userOp.nonce)
+ const queuedUserOperationsCount = outstandingOps.filter(
+ (userOpInfo) => {
+ const { userOp: mempoolUserOp } = userOpInfo
+ const [opNonceKey] = getNonceKeyAndSequence(
+ mempoolUserOp.nonce
+ )
+
+ return (
+ mempoolUserOp.sender === userOp.sender &&
+ opNonceKey === nonceKey
+ )
+ }
+ ).length
+
+ if (queuedUserOperationsCount > config.mempoolMaxQueuedOps) {
+ return false
+ }
+
+ return true
+ },
+ findConflicting: async (userOp: UserOperation) => {
+ const outstandingOps = dump(pendingOps)
+
+ let conflictingReason: ConflictingType = undefined
+
+ for (const userOpInfo of outstandingOps) {
+ const { userOp: mempoolUserOp } = userOpInfo
+
+ const isSameSender = mempoolUserOp.sender === userOp.sender
+ if (isSameSender && mempoolUserOp.nonce === userOp.nonce) {
+ conflictingReason = {
+ reason: "conflicting_nonce",
+ userOp: userOpInfo.userOp
+ }
+ break
+ }
+
+ const isConflictingV6Deployment =
+ isVersion06(userOp) &&
+ isVersion06(mempoolUserOp) &&
+ userOp.initCode &&
+ userOp.initCode !== "0x" &&
+ mempoolUserOp.initCode &&
+ mempoolUserOp.initCode !== "0x" &&
+ isSameSender
+
+ const isConflictingV7Deployment =
+ isVersion07(userOp) &&
+ isVersion07(mempoolUserOp) &&
+ userOp.factory &&
+ userOp.factory !== "0x" &&
+ mempoolUserOp.factory &&
+ mempoolUserOp.factory !== "0x" &&
+ isSameSender
+
+ const isConflictingDeployment =
+ isConflictingV6Deployment || isConflictingV7Deployment
+
+ if (isConflictingDeployment) {
+ conflictingReason = {
+ reason: "conflicting_deployment",
+ userOp: userOpInfo.userOp
+ }
+ break
+ }
+ }
+
+ return conflictingReason
+ },
+ contains: async (userOpHash: HexData32) => {
+ for (const userOpInfos of pendingOps.values()) {
+ if (
+ userOpInfos.some((info) => info.userOpHash === userOpHash)
+ ) {
+ return true
+ }
+ }
+ return false
+ },
+ peek: () => {
+ if (priorityQueue.length === 0) {
+ return Promise.resolve(undefined)
+ }
+
+ return Promise.resolve(priorityQueue[0])
+ },
+ pop: () => {
+ const userOpInfo = priorityQueue.shift()
+
+ if (!userOpInfo) {
+ return Promise.resolve(undefined)
+ }
+
+ const pendingOpsSlot = senderNonceSlot(userOpInfo.userOp)
+ const backlogOps = pendingOps.get(pendingOpsSlot)
+
+ // This should never throw.
+ if (!backlogOps?.shift()) {
+ throw new Error("FATAL: No pending userOps for sender")
+ }
+
+ // Move next pending userOp into priorityQueue if exist.
+ if (backlogOps.length > 0) {
+ addToPriorityQueue({ userOpInfo: backlogOps[0], priorityQueue })
+ }
+
+ // Cleanup.
+ if (backlogOps.length === 0) {
+ pendingOps.delete(pendingOpsSlot)
+ }
+
+ return Promise.resolve(userOpInfo)
+ },
+ add: (userOpInfo: UserOpInfo) => {
+ const { userOp, userOpHash } = userOpInfo
+ const [nonceKey] = getNonceKeyAndSequence(userOp.nonce)
+ const pendingOpsSlot = senderNonceSlot(userOp)
+
+ const backlogOps =
+ pendingOps.get(pendingOpsSlot) ||
+ pendingOps.set(pendingOpsSlot, []).get(pendingOpsSlot)!
+
+ backlogOps.push(userOpInfo) | can we leave a comment that this is a push to the reference of the array so this will update the state in pendingOps |
alto | github_2023 | typescript | 439 | pimlicolabs | plusminushalf | @@ -237,6 +240,18 @@ export const gasEstimationArgsSchema = z.object({
"split-simulation-calls": z.boolean()
})
+export const mempoolArgsSchema = z.object({
+ "redis-mempool-url": z.string().optional(),
+ "redis-mempool-concurrency": z.number().int().min(0).default(10),
+ "redis-mempool-queue-name": z.string(),
+ "redis-sender-manager-url": z.string().optional(),
+ "redis-sender-manager-queue-name": z.string(), | can we add `redis-gas-price-queue-url` as well |
alto | github_2023 | typescript | 439 | pimlicolabs | plusminushalf | @@ -0,0 +1,505 @@
+import {
+ getNonceKeyAndSequence,
+ isVersion06,
+ isVersion07
+} from "../utils/userop"
+import { AltoConfig } from "../createConfig"
+import {
+ Address,
+ HexData32,
+ UserOperation,
+ UserOpInfo,
+ userOpInfoSchema
+} from "@alto/types"
+import { OutstandingStore } from "."
+import { Redis } from "ioredis"
+import { toHex } from "viem/utils"
+
+const serializeUserOpInfo = (userOpInfo: UserOpInfo): string => {
+ return JSON.stringify(userOpInfo, (_, value) =>
+ typeof value === "bigint" ? toHex(value) : value
+ )
+}
+
+const deserializeUserOpInfo = (data: string): UserOpInfo => {
+ try {
+ const parsed = JSON.parse(data)
+ const result = userOpInfoSchema.safeParse(parsed)
+
+ if (!result.success) {
+ throw new Error(
+ `Failed to parse UserOpInfo: ${result.error.message}`
+ )
+ }
+ return result.data
+ } catch (error) {
+ if (error instanceof Error) {
+ throw new Error(
+ `UserOpInfo deserialization failed: ${error.message}`
+ )
+ }
+ throw new Error("UserOpInfo deserialization failed with unknown error")
+ }
+}
+
+const isDeploymentOperation = (userOp: UserOperation): boolean => {
+ const isV6Deployment =
+ isVersion06(userOp) && !!userOp.initCode && userOp.initCode !== "0x"
+ const isV7Deployment =
+ isVersion07(userOp) && !!userOp.factory && userOp.factory !== "0x"
+ return isV6Deployment || isV7Deployment
+}
+
+class RedisSortedSet {
+ constructor(
+ private redis: Redis,
+ private keyName: string
+ ) {}
+
+ get keyPath(): string {
+ return this.keyName
+ }
+
+ async add(
+ member: string,
+ score: number,
+ multi?: ReturnType<Redis["multi"]>
+ ): Promise<void> {
+ if (multi) {
+ multi.zadd(this.keyPath, score, member)
+ } else {
+ await this.redis.zadd(this.keyPath, score, member)
+ }
+ }
+
+ async remove(
+ member: string,
+ multi?: ReturnType<Redis["multi"]> | Better to do `multi?: ReturnType<Redis["multi"]> = this.redis` |
alto | github_2023 | typescript | 440 | pimlicolabs | mouseless0x | @@ -595,9 +610,12 @@ export function tracerResultParserV07(
if (userOperation.factory) {
// special case: account.validateUserOp is allowed to use assoc storage if factory is staked.
// [STO-022], [STO-021]
+
if (
!(
- entityAddr === sender &&
+ (entityAddr === sender ||
+ entityAddr ===
+ userOperation.paymaster?.toLowerCase()) && | I think it would be better to remove the `.toLowerCase()` here and on entityAddr |
alto | github_2023 | typescript | 438 | pimlicolabs | plusminushalf | @@ -118,12 +83,49 @@ export const bundlerArgsSchema = z.object({
","
)}`
),
- "refilling-wallets": z.boolean().default(true),
- "aa95-gas-multiplier": z.string().transform((val) => BigInt(val)),
"enable-instant-bundling-endpoint": z.boolean(),
"enable-experimental-7702-endpoints": z.boolean()
})
+export const executorArgsSchema = z.object({
+ "enable-fastlane": z.boolean(), | This has not been removed from older config, can you check once. |
alto | github_2023 | typescript | 416 | pimlicolabs | plusminushalf | @@ -677,144 +284,79 @@ export class Executor {
})
let childLogger = this.logger.child({
- userOperations: opsWithHashes.map((oh) => oh.userOperationHash),
+ userOperations: userOperations.map((op) => op.hash), | I actually liked `opsWithHashes` since I don't expect the `userOperations` to have an hash. |
alto | github_2023 | typescript | 164 | pimlicolabs | plusminushalf | @@ -134,7 +137,7 @@ export class UnsafeValidator implements InterfaceValidator {
entryPoint: Address
logger: Logger
metrics: Metrics
- utilityWallet: Account
+ utilityWallet: PrivateKeyAccount | why are we so specific? |
alto | github_2023 | others | 107 | pimlicolabs | kristofgazso | @@ -13,11 +13,12 @@
"dev": "node --inspect packages/cli/lib/alto.js run",
"test": "pnpm -r --workspace-concurrency 1 test --verbose=true",
"test:spec": "./test/spec-tests/run-spec-tests.sh",
- "lint": "rome check ./",
- "lint:fix": "rome check ./ --apply",
+ "lint": "biome check .",
+ "lint:fix": "pnpm run lint --apply",
"format": "biome format . --write"
},
"devDependencies": {
+ "biome": "^0.3.3", | can we remove |
alto | github_2023 | others | 185 | pimlicolabs | pavlovdog | @@ -0,0 +1,19 @@
+{
+ "network-name": "local",
+ "rpc-url": "http://127.0.0.1:8545",
+ "min-entity-stake": 1,
+ "min-executor-balance": "1000000000000000000",
+ "min-entity-unstake-delay": 1,
+ "max-bundle-wait": 3,
+ "max-bundle-size": 3,
+ "port": 3000,
+ "executor-private-keys": "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80",
+ "utility-private-key": "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80",
+ "entrypoints": "0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789,0x0000000071727De22E5E9d8BAf0edAc6f37da032",
+ "entrypoint-simulation-contract": "0xb02456A0eC77837B22156CBA2FF53E662b326713", | It seems to be outdated, using `0x74Cb5e4eE81b86e70f9045036a1C5477de69eE87` now |
alto | github_2023 | typescript | 185 | pimlicolabs | pavlovdog | @@ -0,0 +1,301 @@
+import {
+ http,
+ createTestClient,
+ createWalletClient,
+ createPublicClient,
+ type Address
+} from "viem"
+import { mnemonicToAccount } from "viem/accounts"
+import { foundry } from "viem/chains"
+import {
+ ENTRY_POINT_SIMULATIONS_CREATECALL,
+ ENTRY_POINT_V06_CREATECALL,
+ ENTRY_POINT_V07_CREATECALL,
+ SAFE_MULTI_SEND_CREATECALL,
+ SAFE_V06_MODULE_CREATECALL,
+ SAFE_V07_MODULE_SETUP_CREATECALL,
+ SAFE_PROXY_FACTORY_CREATECALL,
+ SAFE_SINGLETON_CREATECALL,
+ SAFE_SINGLETON_FACTORY_BYTECODE,
+ SIMPLE_ACCOUNT_FACTORY_V06_CREATECALL,
+ SIMPLE_ACCOUNT_FACTORY_V07_CREATECALL,
+ SAFE_V06_MODULE_SETUP_CREATECALL,
+ SAFE_V07_MODULE_CREATECALL,
+ BICONOMY_SINGLETON_FACTORY_BYTECODE,
+ BICONOMY_ECDSA_OWNERSHIP_REGISTRY_MOUDULE_CREATECALL,
+ BICONOMY_ACCOUNT_V2_LOGIC_CREATECALL,
+ BICONOMY_FACTORY_CREATECALL,
+ KERNEL_ACCOUNT_V2_2_LOGIC_CREATECALL,
+ KERNEL_ECDSA_VALIDATOR_CREATECALL,
+ KERNEL_FACTORY_CREATECALL,
+ BICONOMY_DEFAULT_FALLBACK_HANDLER_CREATECALL,
+ SAFE_MULTI_SEND_CALL_ONLY_CREATECALL
+} from "./constants"
+
+const DETERMINISTIC_DEPLOYER = "0x4e59b44847b379578588920ca78fbf26c0b4956c"
+const SAFE_SINGLETON_FACTORY = "0x914d7Fec6aaC8cd542e72Bca78B30650d45643d7"
+const BICONOMY_SINGLETON_FACTORY = "0x988C135a1049Ce61730724afD342fb7C56CD2776"
+
+const verifyDeployed = async (addresses: Address[]) => {
+ const publicClient = createPublicClient({
+ chain: foundry,
+ transport: http("http://127.0.0.1:8545")
+ })
+
+ for (const address of addresses) {
+ const bytecode = await publicClient.getBytecode({
+ address
+ })
+
+ if (bytecode === undefined) {
+ // biome-ignore lint/suspicious/noConsoleLog: it is oke
+ console.log(`CONTRACT ${address} NOT DEPLOYED!!!`)
+ process.exit(1)
+ }
+ }
+}
+
+const walletClient = createWalletClient({
+ account: mnemonicToAccount(
+ "test test test test test test test test test test test junk"
+ ),
+ chain: foundry,
+ transport: http("http://127.0.0.1:8545")
+})
+
+const anvilClient = createTestClient({
+ transport: http("http://127.0.0.1:8545"),
+ mode: "anvil"
+})
+
+const main = async () => {
+ // biome-ignore lint/suspicious/noConsoleLog: []
+ console.log("========== DEPLOYING V0.7 CORE CONTRACTS ==========")
+
+ await walletClient
+ .sendTransaction({
+ to: DETERMINISTIC_DEPLOYER,
+ data: ENTRY_POINT_V07_CREATECALL,
+ gas: 15_000_000n
+ })
+ .then(() => console.log("Deployed EntryPoint V0.7"))
+
+ await walletClient
+ .sendTransaction({
+ to: DETERMINISTIC_DEPLOYER,
+ data: SIMPLE_ACCOUNT_FACTORY_V07_CREATECALL,
+ gas: 15_000_000n
+ })
+ .then(() => console.log("Deployed SimpleAccountFactory v0.7"))
+
+ await walletClient
+ .sendTransaction({
+ to: DETERMINISTIC_DEPLOYER,
+ data: ENTRY_POINT_SIMULATIONS_CREATECALL,
+ gas: 15_000_000n
+ })
+ .then(() => console.log("Deployed EntryPointSimulations"))
+
+ // biome-ignore lint/suspicious/noConsoleLog: []
+ console.log("========== DEPLOYING V0.6 CORE CONTRACTS ==========")
+
+ await walletClient
+ .sendTransaction({
+ to: DETERMINISTIC_DEPLOYER,
+ data: ENTRY_POINT_V06_CREATECALL,
+ gas: 15_000_000n
+ })
+ .then(() => console.log("Deployed EntryPoint v0.6"))
+
+ await walletClient
+ .sendTransaction({
+ to: DETERMINISTIC_DEPLOYER,
+ data: SIMPLE_ACCOUNT_FACTORY_V06_CREATECALL,
+ gas: 15_000_000n
+ })
+ .then(() => console.log("Deployed SimpleAccountFactory v0.6"))
+
+ // biome-ignore lint/suspicious/noConsoleLog: []
+ console.log("========== DEPLOYING SAFE CONTRACTS ==========")
+
+ await walletClient
+ .sendTransaction({
+ to: DETERMINISTIC_DEPLOYER,
+ data: SAFE_V06_MODULE_SETUP_CREATECALL,
+ gas: 15_000_000n
+ })
+ .then(() => console.log("Deployed v0.6 Safe Module Setup"))
+
+ await walletClient
+ .sendTransaction({
+ to: DETERMINISTIC_DEPLOYER,
+ data: SAFE_V06_MODULE_CREATECALL,
+ gas: 15_000_000n
+ })
+ .then(() => console.log("Deployed v0.6 Safe 4337 Module"))
+
+ await walletClient
+ .sendTransaction({
+ to: DETERMINISTIC_DEPLOYER,
+ data: SAFE_V07_MODULE_SETUP_CREATECALL,
+ gas: 15_000_000n
+ })
+ .then(() => console.log("Deployed v0.7 Safe Module Setup"))
+
+ await walletClient
+ .sendTransaction({
+ to: DETERMINISTIC_DEPLOYER,
+ data: SAFE_V07_MODULE_CREATECALL,
+ gas: 15_000_000n
+ })
+ .then(() => console.log("Deployed v0.7 Safe 4337 Module"))
+
+ await anvilClient
+ .setCode({
+ address: SAFE_SINGLETON_FACTORY,
+ bytecode: SAFE_SINGLETON_FACTORY_BYTECODE
+ })
+ .then(() => console.log("Etched Safe Singleton Factory Bytecode"))
+
+ await walletClient
+ .sendTransaction({
+ to: SAFE_SINGLETON_FACTORY,
+ data: SAFE_PROXY_FACTORY_CREATECALL,
+ gas: 15_000_000n
+ })
+ .then(() => console.log("Deployed Safe Proxy Factory"))
+
+ await walletClient
+ .sendTransaction({
+ to: SAFE_SINGLETON_FACTORY,
+ data: SAFE_SINGLETON_CREATECALL,
+ gas: 15_000_000n
+ })
+ .then(() => console.log("Deployed Safe Singleton"))
+
+ await walletClient
+ .sendTransaction({
+ to: SAFE_SINGLETON_FACTORY,
+ data: SAFE_MULTI_SEND_CREATECALL,
+ gas: 15_000_000n
+ })
+ .then(() => console.log("Deployed Safe Multi Send"))
+
+ await walletClient
+ .sendTransaction({
+ to: SAFE_SINGLETON_FACTORY,
+ data: SAFE_MULTI_SEND_CALL_ONLY_CREATECALL,
+ gas: 15_000_000n
+ })
+ .then(() => console.log("Deployed Safe Multi Send Call Only"))
+
+ // biome-ignore lint/suspicious/noConsoleLog: []
+ console.log("========== DEPLOYING BICONOMY CONTRACTS ==========")
+
+ await anvilClient
+ .setCode({
+ address: BICONOMY_SINGLETON_FACTORY,
+ bytecode: BICONOMY_SINGLETON_FACTORY_BYTECODE
+ })
+ .then(() => console.log("Etched Biconomy Singleton Factory Bytecode"))
+
+ await walletClient
+ .sendTransaction({
+ to: BICONOMY_SINGLETON_FACTORY,
+ data: BICONOMY_ECDSA_OWNERSHIP_REGISTRY_MOUDULE_CREATECALL,
+ gas: 15_000_000n
+ })
+ .then(() =>
+ console.log("Deployed Biconomy ECDSA Ownership Registry Module")
+ )
+
+ await walletClient
+ .sendTransaction({
+ to: BICONOMY_SINGLETON_FACTORY,
+ data: BICONOMY_ACCOUNT_V2_LOGIC_CREATECALL,
+ gas: 15_000_000n
+ })
+ .then(() => console.log("Deployed Biconomy Account V0.2 Logic"))
+
+ await walletClient
+ .sendTransaction({
+ to: BICONOMY_SINGLETON_FACTORY,
+ data: BICONOMY_FACTORY_CREATECALL,
+ gas: 15_000_000n
+ })
+ .then(() => console.log("Deployed Biconomy Factory"))
+
+ await walletClient
+ .sendTransaction({
+ to: BICONOMY_SINGLETON_FACTORY,
+ data: BICONOMY_DEFAULT_FALLBACK_HANDLER_CREATECALL,
+ gas: 15_000_000n
+ })
+ .then(() => console.log("Deployed Biconomy Default Fallback Handler"))
+
+ // biome-ignore lint/suspicious/noConsoleLog: []
+ console.log("========== DEPLOYING KERNEL CONTRACTS ==========")
+
+ await walletClient
+ .sendTransaction({
+ to: DETERMINISTIC_DEPLOYER,
+ data: KERNEL_ECDSA_VALIDATOR_CREATECALL,
+ gas: 15_000_000n
+ })
+ .then(() => console.log("Deployed ECDSA Validator"))
+
+ await walletClient
+ .sendTransaction({
+ to: DETERMINISTIC_DEPLOYER,
+ data: KERNEL_ACCOUNT_V2_2_LOGIC_CREATECALL,
+ gas: 15_000_000n
+ })
+ .then(() => console.log("Deployed Account V2 Logic"))
+
+ await walletClient
+ .sendTransaction({
+ to: DETERMINISTIC_DEPLOYER,
+ data: KERNEL_FACTORY_CREATECALL,
+ gas: 15_000_000n
+ })
+ .then(() => console.log("Deployed Kernel Factory"))
+
+ // biome-ignore lint/suspicious/noConsoleLog: []
+ console.log("========== MISC ==========")
+
+ await anvilClient
+ .setCode({
+ address: "0xcA11bde05977b3631167028862bE2a173976CA11",
+ bytecode: MULTICALL3_BYTECODE,
+ })
+ .then(() => console.log("Etched Multicall Factory Bytecode"))
+
+ await verifyDeployed([
+ "0x4e59b44847b379578588920ca78fbf26c0b4956c",
+ "0x914d7Fec6aaC8cd542e72Bca78B30650d45643d7",
+ "0x988C135a1049Ce61730724afD342fb7C56CD2776",
+ "0x0000000071727De22E5E9d8BAf0edAc6f37da032",
+ "0x91E60e0613810449d098b0b5Ec8b51A0FE8c8985",
+ "0xb02456A0eC77837B22156CBA2FF53E662b326713", | Same here |
alto | github_2023 | others | 185 | pimlicolabs | pavlovdog | @@ -1,102 +1,46 @@
#!/usr/bin/env bash | hm, I'm not sure if it's cross-platform, can you somehow detect the used env? |
alto | github_2023 | typescript | 419 | pimlicolabs | mouseless0x | @@ -790,8 +790,21 @@ export class ExecutorManager {
await this.refreshUserOperationStatuses()
// for all still not included check if needs to be replaced (based on gas price)
- const gasPriceParameters =
- await this.gasPriceManager.tryGetNetworkGasPrice()
+ let gasPriceParameters: {
+ maxFeePerGas: bigint
+ maxPriorityFeePerGas: bigint
+ }
+
+ try {
+ gasPriceParameters =
+ await this.gasPriceManager.tryGetNetworkGasPrice()
+ } catch { | should we set `this.currentlyHandlingBlock = false` here when it early exits due to not finding gasPrice |
alto | github_2023 | typescript | 384 | pimlicolabs | mouseless0x | @@ -358,17 +358,21 @@ export function calcVerificationGasAndCallGasLimit(
paid: bigint
},
chainId: number,
- callDataResult?: {
- gasUsed: bigint
+ gasLimits?: {
+ callGasLimit?: bigint
+ verificationGasLimit?: bigint
+ paymasterVerificationGasLimit?: bigint
}
) {
- const verificationGasLimit = scaleBigIntByPercent(
- executionResult.preOpGas - userOperation.preVerificationGas,
- 150
- )
+ const verificationGasLimit =
+ gasLimits?.verificationGasLimit ??
+ scaleBigIntByPercent( | Is this still needed after the binary search change? |
alto | github_2023 | typescript | 367 | pimlicolabs | plusminushalf | @@ -119,7 +119,8 @@ export const bundlerArgsSchema = z.object({
),
"refilling-wallets": z.boolean().default(true),
"aa95-gas-multiplier": z.string().transform((val) => BigInt(val)),
- "enable-instant-bundling-endpoint": z.boolean()
+ "enable-instant-bundling-endpoint": z.boolean(),
+ "enable-experimental-endpoints": z.boolean() | can we rename this to enable-experimental-7702-endpoints. |
alto | github_2023 | typescript | 367 | pimlicolabs | plusminushalf | @@ -139,6 +140,10 @@ export async function bundlerHandler(args_: IOptionsInput): Promise<void> {
chain
})
+ if (args.enableExperimental7702Endpoints) { | we can always extend, I don't see any issue in extending extra functions. |
alto | github_2023 | typescript | 381 | pimlicolabs | nikmel2803 | @@ -190,6 +190,13 @@ export function createMetrics(registry: Registry, register = true) {
registers
})
+ const walletsProcessingTime = new Gauge({ | that won't work, it must be a Histogram |
alto | github_2023 | typescript | 381 | pimlicolabs | nikmel2803 | @@ -190,6 +190,13 @@ export function createMetrics(registry: Registry, register = true) {
registers
})
+ const walletsProcessingTime = new Histogram({
+ name: "alto_executor_wallets_processing_time_seconds", | ```suggestion
name: "alto_executor_wallets_processing_duration_seconds",
```
duration is a more common word for naming Histograms |
alto | github_2023 | typescript | 381 | pimlicolabs | nikmel2803 | @@ -251,6 +252,12 @@ export class SenderManager {
{ executor: wallet.address },
"pushed wallet to sender manager"
)
+ const processingTime = this.walletProcessingTime.get(wallet.address)
+ if (processingTime) { | do we really need this check now? should be always non-nullable |
alto | github_2023 | typescript | 337 | pimlicolabs | plusminushalf | @@ -395,7 +289,7 @@ export class GasPriceManager {
this.logger.warn("maxFeePerGas is undefined, using fallback value")
try {
maxFeePerGas =
- (await this.getNextBaseFee(this.config.publicClient)) +
+ (await this.config.publicClient.getGasPrice()) + | Why do we have this change? Rest LGTM |
alto | github_2023 | typescript | 331 | pimlicolabs | nikmel2803 | @@ -542,8 +541,10 @@ export class RpcHandler implements IRpcEndpoint {
entryPoint,
queuedUserOperations,
false,
- deepHexlify(stateOverrides)
+ deepHexlify({ ...stateOverrides })
)
+ } catch (err) {
+ this.logger.error({ error: err }, "Second simulations fail") | ```suggestion
this.logger.error({ err }, "Second simulations fail")
```
we should use `err` for logging an Error: https://getpino.io/#/docs/api?id=mergingobject-object
> If the object is of type Error, it is wrapped in an object containing a property err ({ err: mergingObject }). This allows for a unified error handling flow.
or just `this.logger.error(err, "Second simulations fail")` |
alto | github_2023 | typescript | 317 | pimlicolabs | plusminushalf | @@ -11,38 +11,34 @@ export const EXECUTE_SIMULATOR_BYTECODE =
"0x60806040526004361061012e5760003560e01c806372b37bca116100ab578063b760faf91161006f578063b760faf914610452578063bb9fe6bf14610465578063c23a5cea1461047a578063d6383f941461049a578063ee219423146104ba578063fc7e286d146104da57600080fd5b806372b37bca146103bd5780638f41ec5a146103dd578063957122ab146103f25780639b249f6914610412578063a61935311461043257600080fd5b8063205c2878116100f2578063205c28781461020157806335567e1a146102215780634b1d7cf5146102415780635287ce121461026157806370a082311461037e57600080fd5b80630396cb60146101435780630bd28e3b146101565780631b2e01b8146101765780631d732756146101c15780631fad948c146101e157600080fd5b3661013e5761013c3361058f565b005b600080fd5b61013c6101513660046131c9565b6105f6565b34801561016257600080fd5b5061013c61017136600461320b565b610885565b34801561018257600080fd5b506101ae610191366004613246565b600160209081526000928352604080842090915290825290205481565b6040519081526020015b60405180910390f35b3480156101cd57600080fd5b506101ae6101dc366004613440565b6108bc565b3480156101ed57600080fd5b5061013c6101fc366004613549565b610a2f565b34801561020d57600080fd5b5061013c61021c36600461359f565b610bab565b34801561022d57600080fd5b506101ae61023c366004613246565b610d27565b34801561024d57600080fd5b5061013c61025c366004613549565b610d6d565b34801561026d57600080fd5b5061032661027c3660046135cb565b6040805160a081018252600080825260208201819052918101829052606081018290526080810191909152506001600160a01b031660009081526020818152604091829020825160a08101845281546001600160701b038082168352600160701b820460ff16151594830194909452600160781b90049092169282019290925260019091015463ffffffff81166060830152640100000000900465ffffffffffff16608082015290565b6040805182516001600160701b03908116825260208085015115159083015283830151169181019190915260608083015163ffffffff169082015260809182015165ffffffffffff169181019190915260a0016101b8565b34801561038a57600080fd5b506101ae6103993660046135cb565b6001600160a01b03166000908152602081905260409020546001600160701b031690565b3480156103c957600080fd5b5061013c6103d83660046135e8565b6111b0565b3480156103e957600080fd5b506101ae600181565b3480156103fe57600080fd5b5061013c61040d366004613643565b611289565b34801561041e57600080fd5b5061013c61042d3660046136c7565b611386565b34801561043e57600080fd5b506101ae61044d366004613721565b611441565b61013c6104603660046135cb565b61058f565b34801561047157600080fd5b5061013c611483565b34801561048657600080fd5b5061013c6104953660046135cb565b6115ac565b3480156104a657600080fd5b5061013c6104b5366004613755565b6117e4565b3480156104c657600080fd5b5061013c6104d5366004613721565b6118df565b3480156104e657600080fd5b506105496104f53660046135cb565b600060208190529081526040902080546001909101546001600160701b0380831692600160701b810460ff1692600160781b9091049091169063ffffffff811690640100000000900465ffffffffffff1685565b604080516001600160701b0396871681529415156020860152929094169183019190915263ffffffff16606082015265ffffffffffff909116608082015260a0016101b8565b6105998134611abb565b6001600160a01b03811660008181526020818152604091829020805492516001600160701b03909316835292917f2da466a7b24304f47e87fa2e1e5a81b9831ce54fec19055ce277ca2f39ba42c491015b60405180910390a25050565b33600090815260208190526040902063ffffffff821661065d5760405162461bcd60e51b815260206004820152601a60248201527f6d757374207370656369667920756e7374616b652064656c617900000000000060448201526064015b60405180910390fd5b600181015463ffffffff90811690831610156106bb5760405162461bcd60e51b815260206004820152601c60248201527f63616e6e6f7420646563726561736520756e7374616b652074696d65000000006044820152606401610654565b80546000906106db903490600160781b90046001600160701b03166137cc565b9050600081116107225760405162461bcd60e51b81526020600482015260126024820152711b9bc81cdd185ad9481cdc1958da599a595960721b6044820152606401610654565b6001600160701b0381111561076a5760405162461bcd60e51b815260206004820152600e60248201526d7374616b65206f766572666c6f7760901b6044820152606401610654565b6040805160a08101825283546001600160701b0390811682526001602080840182815286841685870190815263ffffffff808b16606088019081526000608089018181523380835296829052908a902098518954955194518916600160781b02600160781b600160e81b0319951515600160701b026effffffffffffffffffffffffffffff199097169190991617949094179290921695909517865551949092018054925165ffffffffffff166401000000000269ffffffffffffffffffff19909316949093169390931717905590517fa5ae833d0bb1dcd632d98a8b70973e8516812898e19bf27b70071ebc8dc52c0190610878908490879091825263ffffffff16602082015260400190565b60405180910390a2505050565b3360009081526001602090815260408083206001600160c01b038516845290915281208054916108b4836137df565b919050555050565b6000805a90503330146109115760405162461bcd60e51b815260206004820152601760248201527f4141393220696e7465726e616c2063616c6c206f6e6c790000000000000000006044820152606401610654565b8451604081015160608201518101611388015a101561093b5763deaddead60e01b60005260206000fd5b8751600090156109cf576000610958846000015160008c86611b57565b9050806109cd57600061096c610800611b6f565b8051909150156109c75784600001516001600160a01b03168a602001517f1c4fada7374c0a9ee8841fc38afe82932dc0f8e69012e927f061a8bae611a2018760200151846040516109be929190613848565b60405180910390a35b60019250505b505b600088608001515a8603019050610a216000838b8b8b8080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250889250611b9b915050565b9a9950505050505050505050565b610a37611e92565b816000816001600160401b03811115610a5257610a5261327b565b604051908082528060200260200182016040528015610a8b57816020015b610a7861313f565b815260200190600190039081610a705790505b50905060005b82811015610b04576000828281518110610aad57610aad613861565b60200260200101519050600080610ae8848a8a87818110610ad057610ad0613861565b9050602002810190610ae29190613877565b85611ee9565b91509150610af984838360006120d4565b505050600101610a91565b506040516000907fbb47ee3e183a558b1a2ff0874b079f3fc5478b7454eacf2bfc5af2ff5878f972908290a160005b83811015610b8e57610b8281888884818110610b5157610b51613861565b9050602002810190610b639190613877565b858481518110610b7557610b75613861565b6020026020010151612270565b90910190600101610b33565b50610b998482612397565b505050610ba66001600255565b505050565b33600090815260208190526040902080546001600160701b0316821115610c145760405162461bcd60e51b815260206004820152601960248201527f576974686472617720616d6f756e7420746f6f206c61726765000000000000006044820152606401610654565b8054610c2a9083906001600160701b0316613898565b81546001600160701b0319166001600160701b0391909116178155604080516001600160a01b03851681526020810184905233917fd1c19fbcd4551a5edfb66d43d2e337c04837afda3482b42bdf569a8fccdae5fb910160405180910390a26000836001600160a01b03168360405160006040518083038185875af1925050503d8060008114610cd6576040519150601f19603f3d011682016040523d82523d6000602084013e610cdb565b606091505b5050905080610d215760405162461bcd60e51b81526020600482015260126024820152716661696c656420746f20776974686472617760701b6044820152606401610654565b50505050565b6001600160a01b03821660009081526001602090815260408083206001600160c01b038516845290915290819020549082901b67ffffffffffffffff1916175b92915050565b610d75611e92565b816000805b82811015610ee95736868683818110610d9557610d95613861565b9050602002810190610da791906138ab565b9050366000610db683806138c1565b90925090506000610dcd60408501602086016135cb565b90506000196001600160a01b03821601610e295760405162461bcd60e51b815260206004820152601760248201527f4141393620696e76616c69642061676772656761746f720000000000000000006044820152606401610654565b6001600160a01b03811615610ec6576001600160a01b03811663e3563a4f8484610e56604089018961390a565b6040518563ffffffff1660e01b8152600401610e759493929190613ab5565b60006040518083038186803b158015610e8d57600080fd5b505afa925050508015610e9e575060015b610ec65760405163086a9f7560e41b81526001600160a01b0382166004820152602401610654565b610ed082876137cc565b9550505050508080610ee1906137df565b915050610d7a565b506000816001600160401b03811115610f0457610f0461327b565b604051908082528060200260200182016040528015610f3d57816020015b610f2a61313f565b815260200190600190039081610f225790505b506040519091507fbb47ee3e183a558b1a2ff0874b079f3fc5478b7454eacf2bfc5af2ff5878f97290600090a16000805b848110156110525736888883818110610f8957610f89613861565b9050602002810190610f9b91906138ab565b9050366000610faa83806138c1565b90925090506000610fc160408501602086016135cb565b90508160005b81811015611039576000898981518110610fe357610fe3613861565b602002602001015190506000806110068b898987818110610ad057610ad0613861565b91509150611016848383896120d4565b8a611020816137df565b9b50505050508080611031906137df565b915050610fc7565b505050505050808061104a906137df565b915050610f6e565b50600080915060005b8581101561116b573689898381811061107657611076613861565b905060200281019061108891906138ab565b905061109a60408201602083016135cb565b6001600160a01b03167f575ff3acadd5ab348fe1855e217e0f3678f8d767d7494c9f9fefbee2e17cca4d60405160405180910390a23660006110dc83806138c1565b90925090508060005b81811015611153576111278885858481811061110357611103613861565b90506020028101906111159190613877565b8b8b81518110610b7557610b75613861565b61113190886137cc565b96508761113d816137df565b985050808061114b906137df565b9150506110e5565b50505050508080611163906137df565b91505061105b565b506040516000907f575ff3acadd5ab348fe1855e217e0f3678f8d767d7494c9f9fefbee2e17cca4d908290a26111a18682612397565b5050505050610ba66001600255565b735ff137d4b0fdcd49dca30c7cf57e578a026d278933146111d057600080fd5b60005a9050600080866001600160a01b03168487876040516111f3929190613b32565b60006040518083038160008787f1925050503d8060008114611231576040519150601f19603f3d011682016040523d82523d6000602084013e611236565b606091505b509150915060005a6112489085613898565b90506000836112575782611268565b604051806020016040528060008152505b9050838183604051636c6238f160e01b815260040161065493929190613b42565b8315801561129f57506001600160a01b0383163b155b156112ec5760405162461bcd60e51b815260206004820152601960248201527f41413230206163636f756e74206e6f74206465706c6f796564000000000000006044820152606401610654565b601481106113645760006113036014828486613b6d565b61130c91613b97565b60601c9050803b6000036113625760405162461bcd60e51b815260206004820152601b60248201527f41413330207061796d6173746572206e6f74206465706c6f79656400000000006044820152606401610654565b505b60405162461bcd60e51b81526020600482015260006024820152604401610654565b604051632b870d1b60e11b81526000906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063570e1a36906113d79086908690600401613bcc565b6020604051808303816000875af11580156113f6573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061141a9190613be0565b604051633653dc0360e11b81526001600160a01b0382166004820152909150602401610654565b600061144c82612490565b6040805160208101929092523090820152466060820152608001604051602081830303815290604052805190602001209050919050565b3360009081526020819052604081206001810154909163ffffffff90911690036114dc5760405162461bcd60e51b815260206004820152600a6024820152691b9bdd081cdd185ad95960b21b6044820152606401610654565b8054600160701b900460ff166115285760405162461bcd60e51b8152602060048201526011602482015270616c726561647920756e7374616b696e6760781b6044820152606401610654565b60018101546000906115409063ffffffff1642613bfd565b60018301805469ffffffffffff00000000191664010000000065ffffffffffff841690810291909117909155835460ff60701b1916845560405190815290915033907ffa9b3c14cc825c412c9ed81b3ba365a5b459439403f18829e572ed53a4180f0a906020016105ea565b3360009081526020819052604090208054600160781b90046001600160701b0316806116115760405162461bcd60e51b81526020600482015260146024820152734e6f207374616b6520746f20776974686472617760601b6044820152606401610654565b6001820154640100000000900465ffffffffffff166116725760405162461bcd60e51b815260206004820152601d60248201527f6d7573742063616c6c20756e6c6f636b5374616b6528292066697273740000006044820152606401610654565b60018201544264010000000090910465ffffffffffff1611156116d75760405162461bcd60e51b815260206004820152601b60248201527f5374616b65207769746864726177616c206973206e6f742064756500000000006044820152606401610654565b60018201805469ffffffffffffffffffff191690558154600160781b600160e81b0319168255604080516001600160a01b03851681526020810183905233917fb7c918e0e249f999e965cafeb6c664271b3f4317d296461500e71da39f0cbda3910160405180910390a26000836001600160a01b03168260405160006040518083038185875af1925050503d806000811461178e576040519150601f19603f3d011682016040523d82523d6000602084013e611793565b606091505b5050905080610d215760405162461bcd60e51b815260206004820152601860248201527f6661696c656420746f207769746864726177207374616b6500000000000000006044820152606401610654565b6117ec61313f565b6117f5856124a9565b60008061180460008885611ee9565b9150915060006118148383612583565b905061181f43600052565b600061182d60008a87612270565b905061183843600052565b600060606001600160a01b038a16156118ae57896001600160a01b03168989604051611865929190613b32565b6000604051808303816000865af19150503d80600081146118a2576040519150601f19603f3d011682016040523d82523d6000602084013e6118a7565b606091505b5090925090505b866080015183856020015186604001518585604051630116f59360e71b815260040161065496959493929190613c23565b6118e761313f565b6118f0826124a9565b6000806118ff60008585611ee9565b915091506000611916846000015160a0015161264f565b8451519091506000906119289061264f565b9050611947604051806040016040528060008152602001600081525090565b36600061195760408a018a61390a565b90925090506000601482101561196e576000611989565b61197c601460008486613b6d565b61198591613b97565b60601c5b90506119948161264f565b935050505060006119a58686612583565b9050600081600001519050600060016001600160a01b0316826001600160a01b031614905060006040518060c001604052808b6080015181526020018b6040015181526020018315158152602001856020015165ffffffffffff168152602001856040015165ffffffffffff168152602001611a228c6060015190565b905290506001600160a01b03831615801590611a4857506001600160a01b038316600114155b15611a9a5760006040518060400160405280856001600160a01b03168152602001611a728661264f565b81525090508187878a84604051633ebb2d3960e21b8152600401610654959493929190613cc5565b8086868960405163e0cff05f60e01b81526004016106549493929190613d45565b6001600160a01b03821660009081526020819052604081208054909190611aec9084906001600160701b03166137cc565b90506001600160701b03811115611b385760405162461bcd60e51b815260206004820152601060248201526f6465706f736974206f766572666c6f7760801b6044820152606401610654565b81546001600160701b0319166001600160701b03919091161790555050565b6000806000845160208601878987f195945050505050565b60603d82811115611b7d5750815b604051602082018101604052818152816000602083013e9392505050565b6000805a855190915060009081611bb18261269e565b60a08301519091506001600160a01b038116611bd05782519350611d77565b809350600088511115611d7757868202955060028a6002811115611bf657611bf6613d9c565b14611c6857606083015160405163a9a2340960e01b81526001600160a01b0383169163a9a2340991611c30908e908d908c90600401613db2565b600060405180830381600088803b158015611c4a57600080fd5b5087f1158015611c5e573d6000803e3d6000fd5b5050505050611d77565b606083015160405163a9a2340960e01b81526001600160a01b0383169163a9a2340991611c9d908e908d908c90600401613db2565b600060405180830381600088803b158015611cb757600080fd5b5087f193505050508015611cc9575060015b611d7757611cd5613de9565b806308c379a003611d2e5750611ce9613e05565b80611cf45750611d30565b8b81604051602001611d069190613e8e565b60408051601f1981840301815290829052631101335b60e11b82526106549291600401613848565b505b8a604051631101335b60e11b81526004016106549181526040602082018190526012908201527110504d4c081c1bdcdd13dc081c995d995c9d60721b606082015260800190565b5a85038701965081870295508589604001511015611de0578a604051631101335b60e11b815260040161065491815260406020808301829052908201527f414135312070726566756e642062656c6f772061637475616c476173436f7374606082015260800190565b6040890151869003611df28582611abb565b6000808c6002811115611e0757611e07613d9c565b1490508460a001516001600160a01b031685600001516001600160a01b03168c602001517f49628fd1471006c1482da88028e9ce4dbb080b815c9b0344d39e5a8e6ec1419f8860200151858d8f604051611e7a949392919093845291151560208401526040830152606082015260800190565b60405180910390a45050505050505095945050505050565b6002805403611ee35760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606401610654565b60028055565b60008060005a8451909150611efe86826126ce565b611f0786611441565b6020860152604081015160608201516080830151171760e087013517610100870135176effffffffffffffffffffffffffffff811115611f895760405162461bcd60e51b815260206004820152601860248201527f41413934206761732076616c756573206f766572666c6f7700000000000000006044820152606401610654565b600080611f95846127c7565b9050611fa38a8a8a84612814565b85516020870151919950919350611fba9190612a4c565b6120105789604051631101335b60e11b8152600401610654918152604060208201819052601a908201527f4141323520696e76616c6964206163636f756e74206e6f6e6365000000000000606082015260800190565b61201943600052565b60a08401516060906001600160a01b0316156120415761203c8b8b8b8587612a99565b975090505b60005a87039050808b60a0013510156120a6578b604051631101335b60e11b8152600401610654918152604060208201819052601e908201527f41413430206f76657220766572696669636174696f6e4761734c696d69740000606082015260800190565b60408a018390528160608b015260c08b01355a8803018a608001818152505050505050505050935093915050565b6000806120e085612cbc565b91509150816001600160a01b0316836001600160a01b0316146121465785604051631101335b60e11b81526004016106549181526040602082018190526014908201527320a0991a1039b4b3b730ba3ab9329032b93937b960611b606082015260800190565b801561219e5785604051631101335b60e11b81526004016106549181526040602082018190526017908201527f414132322065787069726564206f72206e6f7420647565000000000000000000606082015260800190565b60006121a985612cbc565b925090506001600160a01b038116156122055786604051631101335b60e11b81526004016106549181526040602082018190526014908201527320a0999a1039b4b3b730ba3ab9329032b93937b960611b606082015260800190565b81156122675786604051631101335b60e11b81526004016106549181526040602082018190526021908201527f41413332207061796d61737465722065787069726564206f72206e6f742064756060820152606560f81b608082015260a00190565b50505050505050565b6000805a90506000612283846060015190565b905030631d732756612298606088018861390a565b87856040518563ffffffff1660e01b81526004016122b99493929190613ecc565b6020604051808303816000875af19250505080156122f4575060408051601f3d908101601f191682019092526122f191810190613f7f565b60015b61238b57600060206000803e50600051632152215360e01b81016123565786604051631101335b60e11b8152600401610654918152604060208201819052600f908201526e41413935206f7574206f662067617360881b606082015260800190565b600085608001515a6123689086613898565b61237291906137cc565b9050612382886002888685611b9b565b9450505061238e565b92505b50509392505050565b6001600160a01b0382166123ed5760405162461bcd60e51b815260206004820152601860248201527f4141393020696e76616c69642062656e656669636961727900000000000000006044820152606401610654565b6000826001600160a01b03168260405160006040518083038185875af1925050503d806000811461243a576040519150601f19603f3d011682016040523d82523d6000602084013e61243f565b606091505b5050905080610ba65760405162461bcd60e51b815260206004820152601f60248201527f41413931206661696c65642073656e6420746f2062656e6566696369617279006044820152606401610654565b600061249b82612d0f565b805190602001209050919050565b3063957122ab6124bc604084018461390a565b6124c960208601866135cb565b6124d761012087018761390a565b6040518663ffffffff1660e01b81526004016124f7959493929190613f98565b60006040518083038186803b15801561250f57600080fd5b505afa925050508015612520575060015b6125805761252c613de9565b806308c379a0036125745750612540613e05565b8061254b5750612576565b80511561257057600081604051631101335b60e11b8152600401610654929190613848565b5050565b505b3d6000803e3d6000fd5b50565b60408051606081018252600080825260208201819052918101829052906125a984612de2565b905060006125b684612de2565b82519091506001600160a01b0381166125cd575080515b602080840151604080860151928501519085015191929165ffffffffffff80831690851610156125fb578193505b8065ffffffffffff168365ffffffffffff161115612617578092505b5050604080516060810182526001600160a01b03909416845265ffffffffffff92831660208501529116908201529250505092915050565b604080518082018252600080825260208083018281526001600160a01b03959095168252819052919091208054600160781b90046001600160701b031682526001015463ffffffff1690915290565b60c081015160e0820151600091908082036126ba575092915050565b6126c682488301612e53565b949350505050565b6126db60208301836135cb565b6001600160a01b0316815260208083013590820152608080830135604083015260a0830135606083015260c0808401359183019190915260e080840135918301919091526101008301359082015236600061273a61012085018561390a565b909250905080156127ba5760148110156127965760405162461bcd60e51b815260206004820152601d60248201527f4141393320696e76616c6964207061796d6173746572416e64446174610000006044820152606401610654565b6127a4601460008385613b6d565b6127ad91613b97565b60601c60a0840152610d21565b600060a084015250505050565b60a081015160009081906001600160a01b03166127e55760016127e8565b60035b60ff16905060008360800151828560600151028560400151010190508360c00151810292505050919050565b60008060005a8551805191925090612839898861283460408c018c61390a565b612e6b565b60a082015161284743600052565b60006001600160a01b03821661288f576001600160a01b0383166000908152602081905260409020546001600160701b03168881116128885780890361288b565b60005b9150505b606084015160208a0151604051633a871cdd60e01b81526001600160a01b03861692633a871cdd9290916128c9918f918790600401613fce565b60206040518083038160008887f193505050508015612905575060408051601f3d908101601f1916820190925261290291810190613f7f565b60015b61298f57612911613de9565b806308c379a0036129425750612925613e05565b806129305750612944565b8b81604051602001611d069190613ff3565b505b8a604051631101335b60e11b8152600401610654918152604060208201819052601690820152754141323320726576657274656420286f72204f4f472960501b606082015260800190565b95506001600160a01b038216612a39576001600160a01b038316600090815260208190526040902080546001600160701b0316808a1115612a1c578c604051631101335b60e11b81526004016106549181526040602082018190526017908201527f41413231206469646e2774207061792070726566756e64000000000000000000606082015260800190565b81546001600160701b031916908a90036001600160701b03161790555b5a85039650505050505094509492505050565b6001600160a01b038216600090815260016020908152604080832084821c80855292528220805484916001600160401b038316919085612a8b836137df565b909155501495945050505050565b82516060818101519091600091848111612af55760405162461bcd60e51b815260206004820152601f60248201527f4141343120746f6f206c6974746c6520766572696669636174696f6e476173006044820152606401610654565b60a08201516001600160a01b038116600090815260208190526040902080548784039291906001600160701b031689811015612b7d578c604051631101335b60e11b8152600401610654918152604060208201819052601e908201527f41413331207061796d6173746572206465706f73697420746f6f206c6f770000606082015260800190565b8981038260000160006101000a8154816001600160701b0302191690836001600160701b03160217905550826001600160a01b031663f465c77e858e8e602001518e6040518563ffffffff1660e01b8152600401612bdd93929190613fce565b60006040518083038160008887f193505050508015612c1e57506040513d6000823e601f3d908101601f19168201604052612c1b919081019061402a565b60015b612ca857612c2a613de9565b806308c379a003612c5b5750612c3e613e05565b80612c495750612c5d565b8d81604051602001611d0691906140b5565b505b8c604051631101335b60e11b8152600401610654918152604060208201819052601690820152754141333320726576657274656420286f72204f4f472960501b606082015260800190565b909e909d509b505050505050505050505050565b60008082600003612cd257506000928392509050565b6000612cdd84612de2565b9050806040015165ffffffffffff16421180612d045750806020015165ffffffffffff1642105b905194909350915050565b6060813560208301356000612d2f612d2a604087018761390a565b61312c565b90506000612d43612d2a606088018861390a565b9050608086013560a087013560c088013560e08901356101008a01356000612d72612d2a6101208e018e61390a565b604080516001600160a01b039c909c1660208d01528b81019a909a5260608b019890985250608089019590955260a088019390935260c087019190915260e08601526101008501526101208401526101408084019190915281518084039091018152610160909201905292915050565b60408051606081018252600080825260208201819052918101919091528160a081901c65ffffffffffff8116600003612e1e575065ffffffffffff5b604080516060810182526001600160a01b03909316835260d09490941c602083015265ffffffffffff16928101929092525090565b6000818310612e625781612e64565b825b9392505050565b8015610d21578251516001600160a01b0381163b15612ed65784604051631101335b60e11b8152600401610654918152604060208201819052601f908201527f414131302073656e64657220616c726561647920636f6e737472756374656400606082015260800190565b835160600151604051632b870d1b60e11b81526000916001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169163570e1a369190612f2e9088908890600401613bcc565b60206040518083038160008887f1158015612f4d573d6000803e3d6000fd5b50505050506040513d601f19601f82011682018060405250810190612f729190613be0565b90506001600160a01b038116612fd45785604051631101335b60e11b8152600401610654918152604060208201819052601b908201527f4141313320696e6974436f6465206661696c6564206f72204f4f470000000000606082015260800190565b816001600160a01b0316816001600160a01b03161461303e5785604051631101335b60e11b815260040161065491815260406020808301829052908201527f4141313420696e6974436f6465206d7573742072657475726e2073656e646572606082015260800190565b806001600160a01b03163b6000036130a15785604051631101335b60e11b815260040161065491815260406020808301829052908201527f4141313520696e6974436f6465206d757374206372656174652073656e646572606082015260800190565b60006130b06014828688613b6d565b6130b991613b97565b60601c9050826001600160a01b031686602001517fd51a9c61267aa6196961883ecf5ff2da6619c37dac0fa92122513fb32c032d2d83896000015160a0015160405161311b9291906001600160a01b0392831681529116602082015260400190565b60405180910390a350505050505050565b6000604051828085833790209392505050565b6040518060a001604052806131a460405180610100016040528060006001600160a01b031681526020016000815260200160008152602001600081526020016000815260200160006001600160a01b0316815260200160008152602001600081525090565b8152602001600080191681526020016000815260200160008152602001600081525090565b6000602082840312156131db57600080fd5b813563ffffffff81168114612e6457600080fd5b80356001600160c01b038116811461320657600080fd5b919050565b60006020828403121561321d57600080fd5b612e64826131ef565b6001600160a01b038116811461258057600080fd5b803561320681613226565b6000806040838503121561325957600080fd5b823561326481613226565b9150613272602084016131ef565b90509250929050565b634e487b7160e01b600052604160045260246000fd5b60a081018181106001600160401b03821117156132b0576132b061327b565b60405250565b61010081018181106001600160401b03821117156132b0576132b061327b565b601f8201601f191681016001600160401b03811182821017156132fb576132fb61327b565b6040525050565b60006001600160401b0382111561331b5761331b61327b565b50601f01601f191660200190565b600081830361018081121561333d57600080fd5b60405161334981613291565b8092506101008083121561335c57600080fd5b604051925061336a836132b6565b6133738561323b565b8352602085013560208401526040850135604084015260608501356060840152608085013560808401526133a960a0860161323b565b60a084015260c085013560c084015260e085013560e084015282825280850135602083015250610120840135604082015261014084013560608201526101608401356080820152505092915050565b60008083601f84011261340a57600080fd5b5081356001600160401b0381111561342157600080fd5b60208301915083602082850101111561343957600080fd5b9250929050565b6000806000806101c0858703121561345757600080fd5b84356001600160401b038082111561346e57600080fd5b818701915087601f83011261348257600080fd5b813561348d81613302565b60405161349a82826132d6565b8281528a60208487010111156134af57600080fd5b826020860160208301376000602084830101528098505050506134d58860208901613329565b94506101a08701359150808211156134ec57600080fd5b506134f9878288016133f8565b95989497509550505050565b60008083601f84011261351757600080fd5b5081356001600160401b0381111561352e57600080fd5b6020830191508360208260051b850101111561343957600080fd5b60008060006040848603121561355e57600080fd5b83356001600160401b0381111561357457600080fd5b61358086828701613505565b909450925050602084013561359481613226565b809150509250925092565b600080604083850312156135b257600080fd5b82356135bd81613226565b946020939093013593505050565b6000602082840312156135dd57600080fd5b8135612e6481613226565b600080600080606085870312156135fe57600080fd5b843561360981613226565b935060208501356001600160401b0381111561362457600080fd5b613630878288016133f8565b9598909750949560400135949350505050565b60008060008060006060868803121561365b57600080fd5b85356001600160401b038082111561367257600080fd5b61367e89838a016133f8565b90975095506020880135915061369382613226565b909350604087013590808211156136a957600080fd5b506136b6888289016133f8565b969995985093965092949392505050565b600080602083850312156136da57600080fd5b82356001600160401b038111156136f057600080fd5b6136fc858286016133f8565b90969095509350505050565b6000610160828403121561371b57600080fd5b50919050565b60006020828403121561373357600080fd5b81356001600160401b0381111561374957600080fd5b6126c684828501613708565b6000806000806060858703121561376b57600080fd5b84356001600160401b038082111561378257600080fd5b61378e88838901613708565b9550602087013591506137a082613226565b909350604086013590808211156134ec57600080fd5b634e487b7160e01b600052601160045260246000fd5b80820180821115610d6757610d676137b6565b6000600182016137f1576137f16137b6565b5060010190565b60005b838110156138135781810151838201526020016137fb565b50506000910152565b600081518084526138348160208601602086016137f8565b601f01601f19169290920160200192915050565b8281526040602082015260006126c6604083018461381c565b634e487b7160e01b600052603260045260246000fd5b6000823561015e1983360301811261388e57600080fd5b9190910192915050565b81810381811115610d6757610d676137b6565b60008235605e1983360301811261388e57600080fd5b6000808335601e198436030181126138d857600080fd5b8301803591506001600160401b038211156138f257600080fd5b6020019150600581901b360382131561343957600080fd5b6000808335601e1984360301811261392157600080fd5b8301803591506001600160401b0382111561393b57600080fd5b60200191503681900382131561343957600080fd5b6000808335601e1984360301811261396757600080fd5b83016020810192503590506001600160401b0381111561398657600080fd5b80360382131561343957600080fd5b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b60006101606139dd846139d08561323b565b6001600160a01b03169052565b602083013560208501526139f46040840184613950565b826040870152613a078387018284613995565b92505050613a186060840184613950565b8583036060870152613a2b838284613995565b925050506080830135608085015260a083013560a085015260c083013560c085015260e083013560e0850152610100808401358186015250610120613a7281850185613950565b86840383880152613a84848284613995565b9350505050610140613a9881850185613950565b86840383880152613aaa848284613995565b979650505050505050565b6040808252810184905260006060600586901b830181019083018783805b89811015613b1b57868503605f190184528235368c900361015e19018112613af9578283fd5b613b05868d83016139be565b9550506020938401939290920191600101613ad3565b505050508281036020840152613aaa818587613995565b8183823760009101908152919050565b8315158152606060208201526000613b5d606083018561381c565b9050826040830152949350505050565b60008085851115613b7d57600080fd5b83861115613b8a57600080fd5b5050820193919092039150565b6bffffffffffffffffffffffff198135818116916014851015613bc45780818660140360031b1b83161692505b505092915050565b6020815260006126c6602083018486613995565b600060208284031215613bf257600080fd5b8151612e6481613226565b65ffffffffffff818116838216019080821115613c1c57613c1c6137b6565b5092915050565b868152856020820152600065ffffffffffff8087166040840152808616606084015250831515608083015260c060a0830152613c6260c083018461381c565b98975050505050505050565b80518252602081015160208301526040810151151560408301526000606082015165ffffffffffff8082166060860152806080850151166080860152505060a082015160c060a08501526126c660c085018261381c565b6000610140808352613cd981840189613c6e565b915050613cf3602083018780518252602090810151910152565b845160608301526020948501516080830152835160a08301529284015160c082015281516001600160a01b031660e0820152908301518051610100830152909201516101209092019190915292915050565b60e081526000613d5860e0830187613c6e565b9050613d71602083018680518252602090810151910152565b8351606083015260208401516080830152825160a0830152602083015160c083015295945050505050565b634e487b7160e01b600052602160045260246000fd5b600060038510613dd257634e487b7160e01b600052602160045260246000fd5b84825260606020830152613b5d606083018561381c565b600060033d1115613e025760046000803e5060005160e01c5b90565b600060443d1015613e135790565b6040516003193d81016004833e81513d6001600160401b038160248401118184111715613e4257505050505090565b8285019150815181811115613e5a5750505050505090565b843d8701016020828501011115613e745750505050505090565b613e83602082860101876132d6565b509095945050505050565b75020a09a98103837b9ba27b8103932bb32b93a32b21d160551b815260008251613ebf8160168501602087016137f8565b9190910160160192915050565b60006101c0808352613ee18184018789613995565b9050845160018060a01b03808251166020860152602082015160408601526040820151606086015260608201516080860152608082015160a08601528060a08301511660c08601525060c081015160e085015260e08101516101008501525060208501516101208401526040850151610140840152606085015161016084015260808501516101808401528281036101a0840152613aaa818561381c565b600060208284031215613f9157600080fd5b5051919050565b606081526000613fac606083018789613995565b6001600160a01b03861660208401528281036040840152613c62818587613995565b606081526000613fe160608301866139be565b60208301949094525060400152919050565b6e020a09919903932bb32b93a32b21d1608d1b81526000825161401d81600f8501602087016137f8565b91909101600f0192915050565b6000806040838503121561403d57600080fd5b82516001600160401b0381111561405357600080fd5b8301601f8101851361406457600080fd5b805161406f81613302565b60405161407c82826132d6565b82815287602084860101111561409157600080fd5b6140a28360208301602087016137f8565b6020969096015195979596505050505050565b6e020a09999903932bb32b93a32b21d1608d1b81526000825161401d81600f8501602087016137f856fea26469706673582212201892e38d1eac5b99b119bf1333f8e39f72ad5274c5da6bb916f97bef4e7e0afc64736f6c63430008140033"
function getStateOverrides({
+ addSenderBalanceOverride,
userOperation,
entryPoint,
replacedEntryPoint,
stateOverride = {}
}: {
+ addSenderBalanceOverride: boolean
entryPoint: Address
replacedEntryPoint: boolean
stateOverride: StateOverrides
userOperation: UserOperation
}) {
- return replacedEntryPoint
- ? {
- ...stateOverride,
- [userOperation.sender]: {
- balance: toHex(100000_000000000000000000n),
- ...(stateOverride
- ? deepHexlify(stateOverride?.[userOperation.sender])
- : [])
- },
- [entryPoint]: {
- code: EXECUTE_SIMULATOR_BYTECODE
- }
- }
- : {
- ...stateOverride,
- [userOperation.sender]: {
- balance: toHex(100000_000000000000000000n),
- ...(stateOverride
- ? deepHexlify(stateOverride?.[userOperation.sender])
- : [])
- }
- }
+ const result: StateOverrides = { ...stateOverride }
+
+ if (addSenderBalanceOverride) {
+ result[userOperation.sender] = {
+ balance: toHex(100000_000000000000000000n),
+ ...deepHexlify(stateOverride?.[userOperation.sender] || {})
+ }
+ }
+
+ if (replacedEntryPoint) {
+ result[entryPoint] = {
+ code: EXECUTE_SIMULATOR_BYTECODE | we might want to add `...deepHexlify(stateOverride?.[entryPoint] || {})` |
alto | github_2023 | typescript | 317 | pimlicolabs | plusminushalf | @@ -11,38 +11,34 @@ export const EXECUTE_SIMULATOR_BYTECODE =
"0x60806040526004361061012e5760003560e01c806372b37bca116100ab578063b760faf91161006f578063b760faf914610452578063bb9fe6bf14610465578063c23a5cea1461047a578063d6383f941461049a578063ee219423146104ba578063fc7e286d146104da57600080fd5b806372b37bca146103bd5780638f41ec5a146103dd578063957122ab146103f25780639b249f6914610412578063a61935311461043257600080fd5b8063205c2878116100f2578063205c28781461020157806335567e1a146102215780634b1d7cf5146102415780635287ce121461026157806370a082311461037e57600080fd5b80630396cb60146101435780630bd28e3b146101565780631b2e01b8146101765780631d732756146101c15780631fad948c146101e157600080fd5b3661013e5761013c3361058f565b005b600080fd5b61013c6101513660046131c9565b6105f6565b34801561016257600080fd5b5061013c61017136600461320b565b610885565b34801561018257600080fd5b506101ae610191366004613246565b600160209081526000928352604080842090915290825290205481565b6040519081526020015b60405180910390f35b3480156101cd57600080fd5b506101ae6101dc366004613440565b6108bc565b3480156101ed57600080fd5b5061013c6101fc366004613549565b610a2f565b34801561020d57600080fd5b5061013c61021c36600461359f565b610bab565b34801561022d57600080fd5b506101ae61023c366004613246565b610d27565b34801561024d57600080fd5b5061013c61025c366004613549565b610d6d565b34801561026d57600080fd5b5061032661027c3660046135cb565b6040805160a081018252600080825260208201819052918101829052606081018290526080810191909152506001600160a01b031660009081526020818152604091829020825160a08101845281546001600160701b038082168352600160701b820460ff16151594830194909452600160781b90049092169282019290925260019091015463ffffffff81166060830152640100000000900465ffffffffffff16608082015290565b6040805182516001600160701b03908116825260208085015115159083015283830151169181019190915260608083015163ffffffff169082015260809182015165ffffffffffff169181019190915260a0016101b8565b34801561038a57600080fd5b506101ae6103993660046135cb565b6001600160a01b03166000908152602081905260409020546001600160701b031690565b3480156103c957600080fd5b5061013c6103d83660046135e8565b6111b0565b3480156103e957600080fd5b506101ae600181565b3480156103fe57600080fd5b5061013c61040d366004613643565b611289565b34801561041e57600080fd5b5061013c61042d3660046136c7565b611386565b34801561043e57600080fd5b506101ae61044d366004613721565b611441565b61013c6104603660046135cb565b61058f565b34801561047157600080fd5b5061013c611483565b34801561048657600080fd5b5061013c6104953660046135cb565b6115ac565b3480156104a657600080fd5b5061013c6104b5366004613755565b6117e4565b3480156104c657600080fd5b5061013c6104d5366004613721565b6118df565b3480156104e657600080fd5b506105496104f53660046135cb565b600060208190529081526040902080546001909101546001600160701b0380831692600160701b810460ff1692600160781b9091049091169063ffffffff811690640100000000900465ffffffffffff1685565b604080516001600160701b0396871681529415156020860152929094169183019190915263ffffffff16606082015265ffffffffffff909116608082015260a0016101b8565b6105998134611abb565b6001600160a01b03811660008181526020818152604091829020805492516001600160701b03909316835292917f2da466a7b24304f47e87fa2e1e5a81b9831ce54fec19055ce277ca2f39ba42c491015b60405180910390a25050565b33600090815260208190526040902063ffffffff821661065d5760405162461bcd60e51b815260206004820152601a60248201527f6d757374207370656369667920756e7374616b652064656c617900000000000060448201526064015b60405180910390fd5b600181015463ffffffff90811690831610156106bb5760405162461bcd60e51b815260206004820152601c60248201527f63616e6e6f7420646563726561736520756e7374616b652074696d65000000006044820152606401610654565b80546000906106db903490600160781b90046001600160701b03166137cc565b9050600081116107225760405162461bcd60e51b81526020600482015260126024820152711b9bc81cdd185ad9481cdc1958da599a595960721b6044820152606401610654565b6001600160701b0381111561076a5760405162461bcd60e51b815260206004820152600e60248201526d7374616b65206f766572666c6f7760901b6044820152606401610654565b6040805160a08101825283546001600160701b0390811682526001602080840182815286841685870190815263ffffffff808b16606088019081526000608089018181523380835296829052908a902098518954955194518916600160781b02600160781b600160e81b0319951515600160701b026effffffffffffffffffffffffffffff199097169190991617949094179290921695909517865551949092018054925165ffffffffffff166401000000000269ffffffffffffffffffff19909316949093169390931717905590517fa5ae833d0bb1dcd632d98a8b70973e8516812898e19bf27b70071ebc8dc52c0190610878908490879091825263ffffffff16602082015260400190565b60405180910390a2505050565b3360009081526001602090815260408083206001600160c01b038516845290915281208054916108b4836137df565b919050555050565b6000805a90503330146109115760405162461bcd60e51b815260206004820152601760248201527f4141393220696e7465726e616c2063616c6c206f6e6c790000000000000000006044820152606401610654565b8451604081015160608201518101611388015a101561093b5763deaddead60e01b60005260206000fd5b8751600090156109cf576000610958846000015160008c86611b57565b9050806109cd57600061096c610800611b6f565b8051909150156109c75784600001516001600160a01b03168a602001517f1c4fada7374c0a9ee8841fc38afe82932dc0f8e69012e927f061a8bae611a2018760200151846040516109be929190613848565b60405180910390a35b60019250505b505b600088608001515a8603019050610a216000838b8b8b8080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250889250611b9b915050565b9a9950505050505050505050565b610a37611e92565b816000816001600160401b03811115610a5257610a5261327b565b604051908082528060200260200182016040528015610a8b57816020015b610a7861313f565b815260200190600190039081610a705790505b50905060005b82811015610b04576000828281518110610aad57610aad613861565b60200260200101519050600080610ae8848a8a87818110610ad057610ad0613861565b9050602002810190610ae29190613877565b85611ee9565b91509150610af984838360006120d4565b505050600101610a91565b506040516000907fbb47ee3e183a558b1a2ff0874b079f3fc5478b7454eacf2bfc5af2ff5878f972908290a160005b83811015610b8e57610b8281888884818110610b5157610b51613861565b9050602002810190610b639190613877565b858481518110610b7557610b75613861565b6020026020010151612270565b90910190600101610b33565b50610b998482612397565b505050610ba66001600255565b505050565b33600090815260208190526040902080546001600160701b0316821115610c145760405162461bcd60e51b815260206004820152601960248201527f576974686472617720616d6f756e7420746f6f206c61726765000000000000006044820152606401610654565b8054610c2a9083906001600160701b0316613898565b81546001600160701b0319166001600160701b0391909116178155604080516001600160a01b03851681526020810184905233917fd1c19fbcd4551a5edfb66d43d2e337c04837afda3482b42bdf569a8fccdae5fb910160405180910390a26000836001600160a01b03168360405160006040518083038185875af1925050503d8060008114610cd6576040519150601f19603f3d011682016040523d82523d6000602084013e610cdb565b606091505b5050905080610d215760405162461bcd60e51b81526020600482015260126024820152716661696c656420746f20776974686472617760701b6044820152606401610654565b50505050565b6001600160a01b03821660009081526001602090815260408083206001600160c01b038516845290915290819020549082901b67ffffffffffffffff1916175b92915050565b610d75611e92565b816000805b82811015610ee95736868683818110610d9557610d95613861565b9050602002810190610da791906138ab565b9050366000610db683806138c1565b90925090506000610dcd60408501602086016135cb565b90506000196001600160a01b03821601610e295760405162461bcd60e51b815260206004820152601760248201527f4141393620696e76616c69642061676772656761746f720000000000000000006044820152606401610654565b6001600160a01b03811615610ec6576001600160a01b03811663e3563a4f8484610e56604089018961390a565b6040518563ffffffff1660e01b8152600401610e759493929190613ab5565b60006040518083038186803b158015610e8d57600080fd5b505afa925050508015610e9e575060015b610ec65760405163086a9f7560e41b81526001600160a01b0382166004820152602401610654565b610ed082876137cc565b9550505050508080610ee1906137df565b915050610d7a565b506000816001600160401b03811115610f0457610f0461327b565b604051908082528060200260200182016040528015610f3d57816020015b610f2a61313f565b815260200190600190039081610f225790505b506040519091507fbb47ee3e183a558b1a2ff0874b079f3fc5478b7454eacf2bfc5af2ff5878f97290600090a16000805b848110156110525736888883818110610f8957610f89613861565b9050602002810190610f9b91906138ab565b9050366000610faa83806138c1565b90925090506000610fc160408501602086016135cb565b90508160005b81811015611039576000898981518110610fe357610fe3613861565b602002602001015190506000806110068b898987818110610ad057610ad0613861565b91509150611016848383896120d4565b8a611020816137df565b9b50505050508080611031906137df565b915050610fc7565b505050505050808061104a906137df565b915050610f6e565b50600080915060005b8581101561116b573689898381811061107657611076613861565b905060200281019061108891906138ab565b905061109a60408201602083016135cb565b6001600160a01b03167f575ff3acadd5ab348fe1855e217e0f3678f8d767d7494c9f9fefbee2e17cca4d60405160405180910390a23660006110dc83806138c1565b90925090508060005b81811015611153576111278885858481811061110357611103613861565b90506020028101906111159190613877565b8b8b81518110610b7557610b75613861565b61113190886137cc565b96508761113d816137df565b985050808061114b906137df565b9150506110e5565b50505050508080611163906137df565b91505061105b565b506040516000907f575ff3acadd5ab348fe1855e217e0f3678f8d767d7494c9f9fefbee2e17cca4d908290a26111a18682612397565b5050505050610ba66001600255565b735ff137d4b0fdcd49dca30c7cf57e578a026d278933146111d057600080fd5b60005a9050600080866001600160a01b03168487876040516111f3929190613b32565b60006040518083038160008787f1925050503d8060008114611231576040519150601f19603f3d011682016040523d82523d6000602084013e611236565b606091505b509150915060005a6112489085613898565b90506000836112575782611268565b604051806020016040528060008152505b9050838183604051636c6238f160e01b815260040161065493929190613b42565b8315801561129f57506001600160a01b0383163b155b156112ec5760405162461bcd60e51b815260206004820152601960248201527f41413230206163636f756e74206e6f74206465706c6f796564000000000000006044820152606401610654565b601481106113645760006113036014828486613b6d565b61130c91613b97565b60601c9050803b6000036113625760405162461bcd60e51b815260206004820152601b60248201527f41413330207061796d6173746572206e6f74206465706c6f79656400000000006044820152606401610654565b505b60405162461bcd60e51b81526020600482015260006024820152604401610654565b604051632b870d1b60e11b81526000906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063570e1a36906113d79086908690600401613bcc565b6020604051808303816000875af11580156113f6573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061141a9190613be0565b604051633653dc0360e11b81526001600160a01b0382166004820152909150602401610654565b600061144c82612490565b6040805160208101929092523090820152466060820152608001604051602081830303815290604052805190602001209050919050565b3360009081526020819052604081206001810154909163ffffffff90911690036114dc5760405162461bcd60e51b815260206004820152600a6024820152691b9bdd081cdd185ad95960b21b6044820152606401610654565b8054600160701b900460ff166115285760405162461bcd60e51b8152602060048201526011602482015270616c726561647920756e7374616b696e6760781b6044820152606401610654565b60018101546000906115409063ffffffff1642613bfd565b60018301805469ffffffffffff00000000191664010000000065ffffffffffff841690810291909117909155835460ff60701b1916845560405190815290915033907ffa9b3c14cc825c412c9ed81b3ba365a5b459439403f18829e572ed53a4180f0a906020016105ea565b3360009081526020819052604090208054600160781b90046001600160701b0316806116115760405162461bcd60e51b81526020600482015260146024820152734e6f207374616b6520746f20776974686472617760601b6044820152606401610654565b6001820154640100000000900465ffffffffffff166116725760405162461bcd60e51b815260206004820152601d60248201527f6d7573742063616c6c20756e6c6f636b5374616b6528292066697273740000006044820152606401610654565b60018201544264010000000090910465ffffffffffff1611156116d75760405162461bcd60e51b815260206004820152601b60248201527f5374616b65207769746864726177616c206973206e6f742064756500000000006044820152606401610654565b60018201805469ffffffffffffffffffff191690558154600160781b600160e81b0319168255604080516001600160a01b03851681526020810183905233917fb7c918e0e249f999e965cafeb6c664271b3f4317d296461500e71da39f0cbda3910160405180910390a26000836001600160a01b03168260405160006040518083038185875af1925050503d806000811461178e576040519150601f19603f3d011682016040523d82523d6000602084013e611793565b606091505b5050905080610d215760405162461bcd60e51b815260206004820152601860248201527f6661696c656420746f207769746864726177207374616b6500000000000000006044820152606401610654565b6117ec61313f565b6117f5856124a9565b60008061180460008885611ee9565b9150915060006118148383612583565b905061181f43600052565b600061182d60008a87612270565b905061183843600052565b600060606001600160a01b038a16156118ae57896001600160a01b03168989604051611865929190613b32565b6000604051808303816000865af19150503d80600081146118a2576040519150601f19603f3d011682016040523d82523d6000602084013e6118a7565b606091505b5090925090505b866080015183856020015186604001518585604051630116f59360e71b815260040161065496959493929190613c23565b6118e761313f565b6118f0826124a9565b6000806118ff60008585611ee9565b915091506000611916846000015160a0015161264f565b8451519091506000906119289061264f565b9050611947604051806040016040528060008152602001600081525090565b36600061195760408a018a61390a565b90925090506000601482101561196e576000611989565b61197c601460008486613b6d565b61198591613b97565b60601c5b90506119948161264f565b935050505060006119a58686612583565b9050600081600001519050600060016001600160a01b0316826001600160a01b031614905060006040518060c001604052808b6080015181526020018b6040015181526020018315158152602001856020015165ffffffffffff168152602001856040015165ffffffffffff168152602001611a228c6060015190565b905290506001600160a01b03831615801590611a4857506001600160a01b038316600114155b15611a9a5760006040518060400160405280856001600160a01b03168152602001611a728661264f565b81525090508187878a84604051633ebb2d3960e21b8152600401610654959493929190613cc5565b8086868960405163e0cff05f60e01b81526004016106549493929190613d45565b6001600160a01b03821660009081526020819052604081208054909190611aec9084906001600160701b03166137cc565b90506001600160701b03811115611b385760405162461bcd60e51b815260206004820152601060248201526f6465706f736974206f766572666c6f7760801b6044820152606401610654565b81546001600160701b0319166001600160701b03919091161790555050565b6000806000845160208601878987f195945050505050565b60603d82811115611b7d5750815b604051602082018101604052818152816000602083013e9392505050565b6000805a855190915060009081611bb18261269e565b60a08301519091506001600160a01b038116611bd05782519350611d77565b809350600088511115611d7757868202955060028a6002811115611bf657611bf6613d9c565b14611c6857606083015160405163a9a2340960e01b81526001600160a01b0383169163a9a2340991611c30908e908d908c90600401613db2565b600060405180830381600088803b158015611c4a57600080fd5b5087f1158015611c5e573d6000803e3d6000fd5b5050505050611d77565b606083015160405163a9a2340960e01b81526001600160a01b0383169163a9a2340991611c9d908e908d908c90600401613db2565b600060405180830381600088803b158015611cb757600080fd5b5087f193505050508015611cc9575060015b611d7757611cd5613de9565b806308c379a003611d2e5750611ce9613e05565b80611cf45750611d30565b8b81604051602001611d069190613e8e565b60408051601f1981840301815290829052631101335b60e11b82526106549291600401613848565b505b8a604051631101335b60e11b81526004016106549181526040602082018190526012908201527110504d4c081c1bdcdd13dc081c995d995c9d60721b606082015260800190565b5a85038701965081870295508589604001511015611de0578a604051631101335b60e11b815260040161065491815260406020808301829052908201527f414135312070726566756e642062656c6f772061637475616c476173436f7374606082015260800190565b6040890151869003611df28582611abb565b6000808c6002811115611e0757611e07613d9c565b1490508460a001516001600160a01b031685600001516001600160a01b03168c602001517f49628fd1471006c1482da88028e9ce4dbb080b815c9b0344d39e5a8e6ec1419f8860200151858d8f604051611e7a949392919093845291151560208401526040830152606082015260800190565b60405180910390a45050505050505095945050505050565b6002805403611ee35760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606401610654565b60028055565b60008060005a8451909150611efe86826126ce565b611f0786611441565b6020860152604081015160608201516080830151171760e087013517610100870135176effffffffffffffffffffffffffffff811115611f895760405162461bcd60e51b815260206004820152601860248201527f41413934206761732076616c756573206f766572666c6f7700000000000000006044820152606401610654565b600080611f95846127c7565b9050611fa38a8a8a84612814565b85516020870151919950919350611fba9190612a4c565b6120105789604051631101335b60e11b8152600401610654918152604060208201819052601a908201527f4141323520696e76616c6964206163636f756e74206e6f6e6365000000000000606082015260800190565b61201943600052565b60a08401516060906001600160a01b0316156120415761203c8b8b8b8587612a99565b975090505b60005a87039050808b60a0013510156120a6578b604051631101335b60e11b8152600401610654918152604060208201819052601e908201527f41413430206f76657220766572696669636174696f6e4761734c696d69740000606082015260800190565b60408a018390528160608b015260c08b01355a8803018a608001818152505050505050505050935093915050565b6000806120e085612cbc565b91509150816001600160a01b0316836001600160a01b0316146121465785604051631101335b60e11b81526004016106549181526040602082018190526014908201527320a0991a1039b4b3b730ba3ab9329032b93937b960611b606082015260800190565b801561219e5785604051631101335b60e11b81526004016106549181526040602082018190526017908201527f414132322065787069726564206f72206e6f7420647565000000000000000000606082015260800190565b60006121a985612cbc565b925090506001600160a01b038116156122055786604051631101335b60e11b81526004016106549181526040602082018190526014908201527320a0999a1039b4b3b730ba3ab9329032b93937b960611b606082015260800190565b81156122675786604051631101335b60e11b81526004016106549181526040602082018190526021908201527f41413332207061796d61737465722065787069726564206f72206e6f742064756060820152606560f81b608082015260a00190565b50505050505050565b6000805a90506000612283846060015190565b905030631d732756612298606088018861390a565b87856040518563ffffffff1660e01b81526004016122b99493929190613ecc565b6020604051808303816000875af19250505080156122f4575060408051601f3d908101601f191682019092526122f191810190613f7f565b60015b61238b57600060206000803e50600051632152215360e01b81016123565786604051631101335b60e11b8152600401610654918152604060208201819052600f908201526e41413935206f7574206f662067617360881b606082015260800190565b600085608001515a6123689086613898565b61237291906137cc565b9050612382886002888685611b9b565b9450505061238e565b92505b50509392505050565b6001600160a01b0382166123ed5760405162461bcd60e51b815260206004820152601860248201527f4141393020696e76616c69642062656e656669636961727900000000000000006044820152606401610654565b6000826001600160a01b03168260405160006040518083038185875af1925050503d806000811461243a576040519150601f19603f3d011682016040523d82523d6000602084013e61243f565b606091505b5050905080610ba65760405162461bcd60e51b815260206004820152601f60248201527f41413931206661696c65642073656e6420746f2062656e6566696369617279006044820152606401610654565b600061249b82612d0f565b805190602001209050919050565b3063957122ab6124bc604084018461390a565b6124c960208601866135cb565b6124d761012087018761390a565b6040518663ffffffff1660e01b81526004016124f7959493929190613f98565b60006040518083038186803b15801561250f57600080fd5b505afa925050508015612520575060015b6125805761252c613de9565b806308c379a0036125745750612540613e05565b8061254b5750612576565b80511561257057600081604051631101335b60e11b8152600401610654929190613848565b5050565b505b3d6000803e3d6000fd5b50565b60408051606081018252600080825260208201819052918101829052906125a984612de2565b905060006125b684612de2565b82519091506001600160a01b0381166125cd575080515b602080840151604080860151928501519085015191929165ffffffffffff80831690851610156125fb578193505b8065ffffffffffff168365ffffffffffff161115612617578092505b5050604080516060810182526001600160a01b03909416845265ffffffffffff92831660208501529116908201529250505092915050565b604080518082018252600080825260208083018281526001600160a01b03959095168252819052919091208054600160781b90046001600160701b031682526001015463ffffffff1690915290565b60c081015160e0820151600091908082036126ba575092915050565b6126c682488301612e53565b949350505050565b6126db60208301836135cb565b6001600160a01b0316815260208083013590820152608080830135604083015260a0830135606083015260c0808401359183019190915260e080840135918301919091526101008301359082015236600061273a61012085018561390a565b909250905080156127ba5760148110156127965760405162461bcd60e51b815260206004820152601d60248201527f4141393320696e76616c6964207061796d6173746572416e64446174610000006044820152606401610654565b6127a4601460008385613b6d565b6127ad91613b97565b60601c60a0840152610d21565b600060a084015250505050565b60a081015160009081906001600160a01b03166127e55760016127e8565b60035b60ff16905060008360800151828560600151028560400151010190508360c00151810292505050919050565b60008060005a8551805191925090612839898861283460408c018c61390a565b612e6b565b60a082015161284743600052565b60006001600160a01b03821661288f576001600160a01b0383166000908152602081905260409020546001600160701b03168881116128885780890361288b565b60005b9150505b606084015160208a0151604051633a871cdd60e01b81526001600160a01b03861692633a871cdd9290916128c9918f918790600401613fce565b60206040518083038160008887f193505050508015612905575060408051601f3d908101601f1916820190925261290291810190613f7f565b60015b61298f57612911613de9565b806308c379a0036129425750612925613e05565b806129305750612944565b8b81604051602001611d069190613ff3565b505b8a604051631101335b60e11b8152600401610654918152604060208201819052601690820152754141323320726576657274656420286f72204f4f472960501b606082015260800190565b95506001600160a01b038216612a39576001600160a01b038316600090815260208190526040902080546001600160701b0316808a1115612a1c578c604051631101335b60e11b81526004016106549181526040602082018190526017908201527f41413231206469646e2774207061792070726566756e64000000000000000000606082015260800190565b81546001600160701b031916908a90036001600160701b03161790555b5a85039650505050505094509492505050565b6001600160a01b038216600090815260016020908152604080832084821c80855292528220805484916001600160401b038316919085612a8b836137df565b909155501495945050505050565b82516060818101519091600091848111612af55760405162461bcd60e51b815260206004820152601f60248201527f4141343120746f6f206c6974746c6520766572696669636174696f6e476173006044820152606401610654565b60a08201516001600160a01b038116600090815260208190526040902080548784039291906001600160701b031689811015612b7d578c604051631101335b60e11b8152600401610654918152604060208201819052601e908201527f41413331207061796d6173746572206465706f73697420746f6f206c6f770000606082015260800190565b8981038260000160006101000a8154816001600160701b0302191690836001600160701b03160217905550826001600160a01b031663f465c77e858e8e602001518e6040518563ffffffff1660e01b8152600401612bdd93929190613fce565b60006040518083038160008887f193505050508015612c1e57506040513d6000823e601f3d908101601f19168201604052612c1b919081019061402a565b60015b612ca857612c2a613de9565b806308c379a003612c5b5750612c3e613e05565b80612c495750612c5d565b8d81604051602001611d0691906140b5565b505b8c604051631101335b60e11b8152600401610654918152604060208201819052601690820152754141333320726576657274656420286f72204f4f472960501b606082015260800190565b909e909d509b505050505050505050505050565b60008082600003612cd257506000928392509050565b6000612cdd84612de2565b9050806040015165ffffffffffff16421180612d045750806020015165ffffffffffff1642105b905194909350915050565b6060813560208301356000612d2f612d2a604087018761390a565b61312c565b90506000612d43612d2a606088018861390a565b9050608086013560a087013560c088013560e08901356101008a01356000612d72612d2a6101208e018e61390a565b604080516001600160a01b039c909c1660208d01528b81019a909a5260608b019890985250608089019590955260a088019390935260c087019190915260e08601526101008501526101208401526101408084019190915281518084039091018152610160909201905292915050565b60408051606081018252600080825260208201819052918101919091528160a081901c65ffffffffffff8116600003612e1e575065ffffffffffff5b604080516060810182526001600160a01b03909316835260d09490941c602083015265ffffffffffff16928101929092525090565b6000818310612e625781612e64565b825b9392505050565b8015610d21578251516001600160a01b0381163b15612ed65784604051631101335b60e11b8152600401610654918152604060208201819052601f908201527f414131302073656e64657220616c726561647920636f6e737472756374656400606082015260800190565b835160600151604051632b870d1b60e11b81526000916001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169163570e1a369190612f2e9088908890600401613bcc565b60206040518083038160008887f1158015612f4d573d6000803e3d6000fd5b50505050506040513d601f19601f82011682018060405250810190612f729190613be0565b90506001600160a01b038116612fd45785604051631101335b60e11b8152600401610654918152604060208201819052601b908201527f4141313320696e6974436f6465206661696c6564206f72204f4f470000000000606082015260800190565b816001600160a01b0316816001600160a01b03161461303e5785604051631101335b60e11b815260040161065491815260406020808301829052908201527f4141313420696e6974436f6465206d7573742072657475726e2073656e646572606082015260800190565b806001600160a01b03163b6000036130a15785604051631101335b60e11b815260040161065491815260406020808301829052908201527f4141313520696e6974436f6465206d757374206372656174652073656e646572606082015260800190565b60006130b06014828688613b6d565b6130b991613b97565b60601c9050826001600160a01b031686602001517fd51a9c61267aa6196961883ecf5ff2da6619c37dac0fa92122513fb32c032d2d83896000015160a0015160405161311b9291906001600160a01b0392831681529116602082015260400190565b60405180910390a350505050505050565b6000604051828085833790209392505050565b6040518060a001604052806131a460405180610100016040528060006001600160a01b031681526020016000815260200160008152602001600081526020016000815260200160006001600160a01b0316815260200160008152602001600081525090565b8152602001600080191681526020016000815260200160008152602001600081525090565b6000602082840312156131db57600080fd5b813563ffffffff81168114612e6457600080fd5b80356001600160c01b038116811461320657600080fd5b919050565b60006020828403121561321d57600080fd5b612e64826131ef565b6001600160a01b038116811461258057600080fd5b803561320681613226565b6000806040838503121561325957600080fd5b823561326481613226565b9150613272602084016131ef565b90509250929050565b634e487b7160e01b600052604160045260246000fd5b60a081018181106001600160401b03821117156132b0576132b061327b565b60405250565b61010081018181106001600160401b03821117156132b0576132b061327b565b601f8201601f191681016001600160401b03811182821017156132fb576132fb61327b565b6040525050565b60006001600160401b0382111561331b5761331b61327b565b50601f01601f191660200190565b600081830361018081121561333d57600080fd5b60405161334981613291565b8092506101008083121561335c57600080fd5b604051925061336a836132b6565b6133738561323b565b8352602085013560208401526040850135604084015260608501356060840152608085013560808401526133a960a0860161323b565b60a084015260c085013560c084015260e085013560e084015282825280850135602083015250610120840135604082015261014084013560608201526101608401356080820152505092915050565b60008083601f84011261340a57600080fd5b5081356001600160401b0381111561342157600080fd5b60208301915083602082850101111561343957600080fd5b9250929050565b6000806000806101c0858703121561345757600080fd5b84356001600160401b038082111561346e57600080fd5b818701915087601f83011261348257600080fd5b813561348d81613302565b60405161349a82826132d6565b8281528a60208487010111156134af57600080fd5b826020860160208301376000602084830101528098505050506134d58860208901613329565b94506101a08701359150808211156134ec57600080fd5b506134f9878288016133f8565b95989497509550505050565b60008083601f84011261351757600080fd5b5081356001600160401b0381111561352e57600080fd5b6020830191508360208260051b850101111561343957600080fd5b60008060006040848603121561355e57600080fd5b83356001600160401b0381111561357457600080fd5b61358086828701613505565b909450925050602084013561359481613226565b809150509250925092565b600080604083850312156135b257600080fd5b82356135bd81613226565b946020939093013593505050565b6000602082840312156135dd57600080fd5b8135612e6481613226565b600080600080606085870312156135fe57600080fd5b843561360981613226565b935060208501356001600160401b0381111561362457600080fd5b613630878288016133f8565b9598909750949560400135949350505050565b60008060008060006060868803121561365b57600080fd5b85356001600160401b038082111561367257600080fd5b61367e89838a016133f8565b90975095506020880135915061369382613226565b909350604087013590808211156136a957600080fd5b506136b6888289016133f8565b969995985093965092949392505050565b600080602083850312156136da57600080fd5b82356001600160401b038111156136f057600080fd5b6136fc858286016133f8565b90969095509350505050565b6000610160828403121561371b57600080fd5b50919050565b60006020828403121561373357600080fd5b81356001600160401b0381111561374957600080fd5b6126c684828501613708565b6000806000806060858703121561376b57600080fd5b84356001600160401b038082111561378257600080fd5b61378e88838901613708565b9550602087013591506137a082613226565b909350604086013590808211156134ec57600080fd5b634e487b7160e01b600052601160045260246000fd5b80820180821115610d6757610d676137b6565b6000600182016137f1576137f16137b6565b5060010190565b60005b838110156138135781810151838201526020016137fb565b50506000910152565b600081518084526138348160208601602086016137f8565b601f01601f19169290920160200192915050565b8281526040602082015260006126c6604083018461381c565b634e487b7160e01b600052603260045260246000fd5b6000823561015e1983360301811261388e57600080fd5b9190910192915050565b81810381811115610d6757610d676137b6565b60008235605e1983360301811261388e57600080fd5b6000808335601e198436030181126138d857600080fd5b8301803591506001600160401b038211156138f257600080fd5b6020019150600581901b360382131561343957600080fd5b6000808335601e1984360301811261392157600080fd5b8301803591506001600160401b0382111561393b57600080fd5b60200191503681900382131561343957600080fd5b6000808335601e1984360301811261396757600080fd5b83016020810192503590506001600160401b0381111561398657600080fd5b80360382131561343957600080fd5b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b60006101606139dd846139d08561323b565b6001600160a01b03169052565b602083013560208501526139f46040840184613950565b826040870152613a078387018284613995565b92505050613a186060840184613950565b8583036060870152613a2b838284613995565b925050506080830135608085015260a083013560a085015260c083013560c085015260e083013560e0850152610100808401358186015250610120613a7281850185613950565b86840383880152613a84848284613995565b9350505050610140613a9881850185613950565b86840383880152613aaa848284613995565b979650505050505050565b6040808252810184905260006060600586901b830181019083018783805b89811015613b1b57868503605f190184528235368c900361015e19018112613af9578283fd5b613b05868d83016139be565b9550506020938401939290920191600101613ad3565b505050508281036020840152613aaa818587613995565b8183823760009101908152919050565b8315158152606060208201526000613b5d606083018561381c565b9050826040830152949350505050565b60008085851115613b7d57600080fd5b83861115613b8a57600080fd5b5050820193919092039150565b6bffffffffffffffffffffffff198135818116916014851015613bc45780818660140360031b1b83161692505b505092915050565b6020815260006126c6602083018486613995565b600060208284031215613bf257600080fd5b8151612e6481613226565b65ffffffffffff818116838216019080821115613c1c57613c1c6137b6565b5092915050565b868152856020820152600065ffffffffffff8087166040840152808616606084015250831515608083015260c060a0830152613c6260c083018461381c565b98975050505050505050565b80518252602081015160208301526040810151151560408301526000606082015165ffffffffffff8082166060860152806080850151166080860152505060a082015160c060a08501526126c660c085018261381c565b6000610140808352613cd981840189613c6e565b915050613cf3602083018780518252602090810151910152565b845160608301526020948501516080830152835160a08301529284015160c082015281516001600160a01b031660e0820152908301518051610100830152909201516101209092019190915292915050565b60e081526000613d5860e0830187613c6e565b9050613d71602083018680518252602090810151910152565b8351606083015260208401516080830152825160a0830152602083015160c083015295945050505050565b634e487b7160e01b600052602160045260246000fd5b600060038510613dd257634e487b7160e01b600052602160045260246000fd5b84825260606020830152613b5d606083018561381c565b600060033d1115613e025760046000803e5060005160e01c5b90565b600060443d1015613e135790565b6040516003193d81016004833e81513d6001600160401b038160248401118184111715613e4257505050505090565b8285019150815181811115613e5a5750505050505090565b843d8701016020828501011115613e745750505050505090565b613e83602082860101876132d6565b509095945050505050565b75020a09a98103837b9ba27b8103932bb32b93a32b21d160551b815260008251613ebf8160168501602087016137f8565b9190910160160192915050565b60006101c0808352613ee18184018789613995565b9050845160018060a01b03808251166020860152602082015160408601526040820151606086015260608201516080860152608082015160a08601528060a08301511660c08601525060c081015160e085015260e08101516101008501525060208501516101208401526040850151610140840152606085015161016084015260808501516101808401528281036101a0840152613aaa818561381c565b600060208284031215613f9157600080fd5b5051919050565b606081526000613fac606083018789613995565b6001600160a01b03861660208401528281036040840152613c62818587613995565b606081526000613fe160608301866139be565b60208301949094525060400152919050565b6e020a09919903932bb32b93a32b21d1608d1b81526000825161401d81600f8501602087016137f8565b91909101600f0192915050565b6000806040838503121561403d57600080fd5b82516001600160401b0381111561405357600080fd5b8301601f8101851361406457600080fd5b805161406f81613302565b60405161407c82826132d6565b82815287602084860101111561409157600080fd5b6140a28360208301602087016137f8565b6020969096015195979596505050505050565b6e020a09999903932bb32b93a32b21d1608d1b81526000825161401d81600f8501602087016137f856fea26469706673582212201892e38d1eac5b99b119bf1333f8e39f72ad5274c5da6bb916f97bef4e7e0afc64736f6c63430008140033"
function getStateOverrides({
+ addSenderBalanceOverride,
userOperation,
entryPoint,
replacedEntryPoint,
stateOverride = {}
}: {
+ addSenderBalanceOverride: boolean
entryPoint: Address
replacedEntryPoint: boolean
stateOverride: StateOverrides
userOperation: UserOperation
}) {
- return replacedEntryPoint
- ? {
- ...stateOverride,
- [userOperation.sender]: {
- balance: toHex(100000_000000000000000000n),
- ...(stateOverride
- ? deepHexlify(stateOverride?.[userOperation.sender])
- : [])
- },
- [entryPoint]: {
- code: EXECUTE_SIMULATOR_BYTECODE
- }
- }
- : {
- ...stateOverride,
- [userOperation.sender]: {
- balance: toHex(100000_000000000000000000n),
- ...(stateOverride
- ? deepHexlify(stateOverride?.[userOperation.sender])
- : [])
- }
- }
+ const result: StateOverrides = { ...stateOverride }
+
+ if (addSenderBalanceOverride) {
+ result[userOperation.sender] = {
+ balance: toHex(100000_000000000000000000n),
+ ...deepHexlify(stateOverride?.[userOperation.sender] || {}) | if user has passed balance override for `userOperation.sender` will this not override our balance override for first estimation? |
alto | github_2023 | typescript | 299 | pimlicolabs | plusminushalf | @@ -494,6 +495,12 @@ export const getUserOperationHashV07 = (
)
}
+export function userOperationToJson(userOperation: MempoolUserOperation) { | we have a global bigint convertor right? |
alto | github_2023 | typescript | 284 | pimlicolabs | plusminushalf | @@ -460,7 +461,20 @@ export class ExecutorManager {
})
this.executor.markWalletProcessed(transactionInfo.executor)
- } else if (bundlingStatus.status === "reverted") {
+ } else if (
+ bundlingStatus.status === "reverted" &&
+ bundlingStatus.isAA95
+ ) {
+ // resubmit with 150% more gas when bundler encounters AA95
+ transactionInfo.transactionRequest.gas =
+ (transactionInfo.transactionRequest.gas * 150n) / 100n | can we make this an env variable? |
alto | github_2023 | typescript | 274 | pimlicolabs | nikmel2803 | @@ -162,6 +162,13 @@ export function createMetrics(registry: Registry, register = true) {
registers
})
+ const executorWalletsBalances = new Gauge({
+ name: "alto_executor_wallets_balances", | ```suggestion
name: "alto_executor_wallet_balance",
``` |
alto | github_2023 | typescript | 274 | pimlicolabs | nikmel2803 | @@ -46,6 +46,11 @@ export const bundlerOptions: CliCommandOptions<IBundlerArgsInput> = {
type: "number",
default: 15 * 1000 // 15 seconds
},
+ "executor-wallets-monitor-interval": {
+ description: "Interval for checking executor wallets balances",
+ type: "number",
+ default: 15 * 1000 // 15 seconds
+ }, | it seems like this option isn't necessary already? |
alto | github_2023 | typescript | 271 | pimlicolabs | plusminushalf | @@ -83,7 +83,10 @@ export const bundlerArgsSchema = z.object({
"max-gas-per-bundle": z
.string()
.transform((val) => BigInt(val))
- .default("5000000")
+ .default("5000000"),
+ "stateless-enabled": z | Would it better to just take a list of methods that can be enabled?
And we can pass the list like:
`eth_chainId,eth_supportedEntryPoints,eth_estimateUserOperationGas,eth_getUserOperationByHash,eth_getUserOperationReceipt`
And have a separate param to enable or disable the refill wallets functionality? |
alto | github_2023 | typescript | 271 | pimlicolabs | plusminushalf | @@ -83,7 +84,20 @@ export const bundlerArgsSchema = z.object({
"max-gas-per-bundle": z
.string()
.transform((val) => BigInt(val))
- .default("5000000")
+ .default("5000000"),
+ "supported-rpc-methods": z | Can we say enabled-rpc-methods instead of supported? As we do support all? Also default can be nullish that means all are enabled? |
alto | github_2023 | typescript | 271 | pimlicolabs | plusminushalf | @@ -430,14 +444,12 @@ export class GasPriceManager {
const baseFee = latestBlock.baseFeePerGas
this.saveBaseFeePerGas(baseFee, Date.now())
- this.logger.debug({
- baseFee
- }, "Base fee update");
+ return baseFee
}
public async getBaseFee(): Promise<bigint> {
- if (this.queueBaseFeePerGas.length === 0) {
- await this.updateBaseFee()
+ if (this.gasPriceRefreshIntervalInSeconds === 0) {
+ return this.updateBaseFee()
}
const { | What if `this.queueBaseFeePerGas[this.queueBaseFeePerGas.length - 1];` is empty? server start or something like that? |
alto | github_2023 | typescript | 267 | pimlicolabs | nikmel2803 | @@ -169,6 +169,13 @@ export function createMetrics(registry: Registry, register = true) {
registers
})
+ const emittedEvents = new Counter({
+ name: "emitted_events", | ```suggestion
name: "alto_emitted_user_operation_events",
```
1) `alto_` prefix is necessary
2) added `user_operation` for more clarity |
alto | github_2023 | typescript | 263 | pimlicolabs | kristofgazso | @@ -402,6 +433,16 @@ export const setupServer = async ({
logger
})
+ const compressionHandler = await getCompressionHandler({
+ client,
+ parsedArgs
+ })
+ const eventManager = getEventManager({ | this should be optional? |
alto | github_2023 | typescript | 248 | pimlicolabs | plusminushalf | @@ -592,31 +595,39 @@ export class RpcHandler implements IRpcEndpoint {
return null
}
- let op: UserOperationV06 | PackedUserOperation | undefined = undefined
+ let op: UserOperationV06 | UserOperationV07
try {
const decoded = decodeFunctionData({
- abi: EntryPointV06Abi,
+ abi: [...EntryPointV06Abi, ...EntryPointV07Abi],
data: tx.input
})
+
if (decoded.functionName !== "handleOps") {
return null
}
+
const ops = decoded.args[0]
- op = ops.find(
+ const foundOp = ops.find(
(op: UserOperationV06 | PackedUserOperation) =>
op.sender === userOperationEvent.args.sender &&
op.nonce === userOperationEvent.args.nonce
)
- } catch {
- return null
- }
- if (op === undefined) {
+ if (foundOp === undefined) {
+ return null
+ }
+
+ if (slice(tx.input, 0, 4) === "0x765e827f") { | What is this selector 0x765e827f? Can we create a constant and name it? |
alto | github_2023 | typescript | 248 | pimlicolabs | plusminushalf | @@ -519,283 +494,131 @@ export class SafeValidator
userOperation: UserOperationV07,
entryPoint: Address
): Promise<[ValidationResultV07, BundlerTracerResult]> {
+ if (!this.entryPointSimulationsAddress) {
+ throw new Error("entryPointSimulationsAddress is not set")
+ }
+
const packedUserOperation = toPackedUserOperation(userOperation)
const entryPointSimulationsCallData = encodeFunctionData({
abi: EntryPointV07SimulationsAbi,
- functionName: "simulateValidation",
- args: [packedUserOperation]
+ functionName: "simulateValidationLast",
+ args: [[packedUserOperation]]
})
- const callData = encodeDeployData({
+ const callData = encodeFunctionData({
abi: PimlicoEntryPointSimulationsAbi,
- bytecode: PimlicoEntryPointSimulationsBytecode,
- args: [entryPoint, entryPointSimulationsCallData]
+ functionName: "simulateEntryPoint",
+ args: [entryPoint, [entryPointSimulationsCallData]]
})
const tracerResult = await debug_traceCall(
this.publicClient,
{
from: zeroAddress,
+ to: this.entryPointSimulationsAddress,
data: callData
},
{
tracer: bundlerCollectorTracer
}
)
- const lastResult = tracerResult.calls.slice(-1)[0]
- if (lastResult.type !== "REVERT") { | Hey just to be sure we don't need this because we don't revert in the PimlicoSimulationsContract? |
alto | github_2023 | typescript | 223 | pimlicolabs | nikmel2803 | @@ -0,0 +1,72 @@
+import { spawn } from "node:child_process"
+import { generatePrivateKey, privateKeyToAddress } from "viem/accounts"
+import { type Hex, createTestClient, http, parseEther } from "viem"
+import waitPort from "wait-port"
+import { sleep } from "./utils"
+
+// skip docker wait times, just start locally
+export const startAlto = async (rpc: string, altoPort: string) => {
+ const anvil = createTestClient({
+ transport: http(rpc),
+ mode: "anvil"
+ })
+
+ const pks = Array.from({ length: 6 }, () => generatePrivateKey())
+ for (const pk of pks) {
+ await anvil.setBalance({
+ address: privateKeyToAddress(pk),
+ value: parseEther("100")
+ })
+ }
+
+ const utilitKey = pks.pop() as Hex
+ const executorKeys = pks.join(",")
+
+ const command = "pnpm"
+ const args = [
+ "run",
+ "start",
+ "run",
+ "--config",
+ "./test/kinto-e2e/kinto-alto-config.json",
+ "--rpc-url",
+ rpc,
+ "--utility-private-key",
+ utilitKey,
+ "--executor-private-keys",
+ executorKeys,
+ "--port",
+ altoPort
+ ]
+ const options = {
+ cwd: "../../",
+ env: { ...process.env, COREPACK_ENABLE_STRICT: "0" },
+ detached: true
+ }
+
+ const alto = spawn(command, args, options)
+
+ // [USE FOR DEBUGGING]
+ // alto.stdout.on("data", (data) => console.log(data.toString()))
+ // alto.stderr.on("data", (data) => console.log(data.toString()))
+
+ await waitPort({
+ host: "127.0.0.1",
+ port: Number.parseInt(altoPort),
+ output: "silent"
+ })
+
+ while (
+ !(await fetch(`http://127.0.0.1:${altoPort}/health`)
+ .then((res) => res.ok)
+ .catch(() => false))
+ ) {
+ // biome-ignore lint/suspicious/noConsoleLog:
+ console.log("Waiting for alto setup...")
+ await sleep(500)
+ } | don't you think we need some timeout or max retries here? i see global timeout in CI job, but anyway |
alto | github_2023 | typescript | 220 | pimlicolabs | mouseless0x | @@ -177,9 +176,43 @@ export function packUserOpV06(op: UserOperationV06): `0x${string}` {
)
}
-export function packedUserOperationToRandomDataUserOp(
- packedUserOperation: PackedUserOperation
-) {
+export function removeZeroBytesFromUserOp<T extends UserOperation>(
+ userOpearation: T | small nit userOpearation -> userOperation |
alto | github_2023 | typescript | 220 | pimlicolabs | mouseless0x | @@ -372,12 +394,24 @@ export function calcDefaultPreVerificationGas(
): bigint {
const ov = { ...DefaultGasOverheads, ...(overheads ?? {}) }
- const p = { ...userOperation }
- p.preVerificationGas ?? 21000n // dummy value, just for calldata cost
- p.signature =
- p.signature === "0x" ? toHex(Buffer.alloc(ov.sigSize, 1)) : p.signature // dummy signature
+ const p: UserOperationV06 | PackedUserOperation =
+ removeZeroBytesFromUserOp(userOperation)
+
+ let packed: Uint8Array
+
+ if (isVersion06(userOperation)) {
+ packed = toBytes(packUserOpV06(p as UserOperationV06))
+ } else {
+ packed = toBytes(packUserOpV07(p as PackedUserOperation))
+ }
+
+ console.log( | I think this console.log should be removed? |
alto | github_2023 | typescript | 207 | pimlicolabs | kristofgazso | @@ -104,7 +104,31 @@ export const bundlerOptions: CliCommandOptions<IBundlerArgsInput> = {
type: "string",
require: false,
default: "105,110,115"
- }
+ },
+ "mempool-parallel-user-operations-max-size": {
+ description: "Maximum amount of parallel user ops to keep in the meempool (same sender, different nonce keys)",
+ type: "number",
+ require: false,
+ default: 0,
+ },
+ "mempool-queued-user-operations-max-size": {
+ description: "Maximum amount of sequential user ops to keep in the mempool (same sender and nonce key, different nonce values)",
+ type: "number",
+ require: false,
+ default: 0,
+ },
+ "executor-only-unique-senders-per-bundle": {
+ description: "Include user ops with the same sender in the signle bundle", | single |
alto | github_2023 | typescript | 207 | pimlicolabs | kristofgazso | @@ -104,7 +104,31 @@ export const bundlerOptions: CliCommandOptions<IBundlerArgsInput> = {
type: "string",
require: false,
default: "105,110,115"
- }
+ },
+ "mempool-parallel-user-operations-max-size": { | maybe better as `mempool-max-parallel-ops`, `mempool-max-queued-ops`, `enforce-unique-senders`, `max-gas-per-bundle`? |
alto | github_2023 | typescript | 207 | pimlicolabs | kristofgazso | @@ -104,7 +104,31 @@ export const bundlerOptions: CliCommandOptions<IBundlerArgsInput> = {
type: "string",
require: false,
default: "105,110,115"
- }
+ },
+ "mempool-parallel-user-operations-max-size": {
+ description: "Maximum amount of parallel user ops to keep in the meempool (same sender, different nonce keys)",
+ type: "number",
+ require: false,
+ default: 0,
+ },
+ "mempool-queued-user-operations-max-size": {
+ description: "Maximum amount of sequential user ops to keep in the mempool (same sender and nonce key, different nonce values)",
+ type: "number",
+ require: false,
+ default: 0, | setting these two to 0 is breaking an non-backward compatible. shouldn't we set them to a higher number? |
alto | github_2023 | typescript | 207 | pimlicolabs | kristofgazso | @@ -104,7 +104,31 @@ export const bundlerOptions: CliCommandOptions<IBundlerArgsInput> = {
type: "string",
require: false,
default: "105,110,115"
- }
+ },
+ "mempool-parallel-user-operations-max-size": {
+ description: "Maximum amount of parallel user ops to keep in the meempool (same sender, different nonce keys)",
+ type: "number",
+ require: false,
+ default: 0,
+ },
+ "mempool-queued-user-operations-max-size": {
+ description: "Maximum amount of sequential user ops to keep in the mempool (same sender and nonce key, different nonce values)",
+ type: "number",
+ require: false,
+ default: 0,
+ },
+ "executor-only-unique-senders-per-bundle": {
+ description: "Include user ops with the same sender in the signle bundle",
+ type: "boolean",
+ require: false,
+ default: true, | same with this, this is breaking |
alto | github_2023 | typescript | 207 | pimlicolabs | kristofgazso | @@ -547,6 +596,24 @@ export class MemoryMempool {
minOps?: number
): Promise<UserOperationInfo[]> {
const outstandingUserOperations = this.store.dumpOutstanding().slice()
+
+ // Sort userops before the execution
+ // Decide the order of the userops based on the sender and nonce
+ // If sender is the same, sort by nonce key
+ outstandingUserOperations.sort((a, b) => {
+ const aUserOp = deriveUserOperation(a.mempoolUserOperation);
+ const bUserOp = deriveUserOperation(b.mempoolUserOperation);
+
+ if (aUserOp.sender === bUserOp.sender) {
+ const [aNonceKey,] = getNonceKeyAndValue(aUserOp.nonce); | should we be sorting by nonce value instead? |
alto | github_2023 | typescript | 207 | pimlicolabs | kristofgazso | @@ -617,6 +684,64 @@ export class MemoryMempool {
return null
}
+ async getQueuedUserOperations( | i'm kind of confused what this function is supposed to do. could you maybe comment it a bit? |
alto | github_2023 | typescript | 207 | pimlicolabs | kristofgazso | @@ -367,11 +367,48 @@ export class RpcHandler implements IRpcEndpoint {
// Since we don't want our estimations to depend upon baseFee, we set
// maxFeePerGas to maxPriorityFeePerGas
userOperation.maxPriorityFeePerGas = userOperation.maxFeePerGas
+
+
+ // Check if the nonce is valid
+ // If the nonce is less than the current nonce, the user operation has already been executed
+ // If the nonce is greater than the current nonce, we may have missing user operations in the mempool
+ const currentNonceValue = await this.getNonceValue(userOperation, entryPoint)
+ const [,userOperationNonceValue] = getNonceKeyAndValue(userOperation.nonce)
+
+ let queuedUserOperations: UserOperation[] = [];
+ if (userOperationNonceValue < currentNonceValue) {
+ throw new RpcError(
+ "UserOperation reverted during simulation with reason: AA25 invalid account nonce",
+ ValidationErrors.InvalidFields
+ )
+ } else if (userOperationNonceValue > currentNonceValue) {
+ // Nonce queues are supported only for v7 user operations | wait, we should keep supporting queued nonces for v0.6 no? users rely on it. it's just that we can't pre-simulate them before adding them to the queue |
alto | github_2023 | typescript | 207 | pimlicolabs | kristofgazso | @@ -269,3 +271,90 @@ test("pimlico_sendCompressedUserOperation can bundle multiple compressed userOps
await publicClient.getBytecode({ address: relayer.account.address })
).toEqual(simpleAccountDeployedBytecode)
})
+
+test("eth_sendUserOperation supports bundling with the same sender and different nonce keys", async () => { | worth doing another test for being able to queue up nonce values? |
alto | github_2023 | typescript | 207 | pimlicolabs | kristofgazso | @@ -488,251 +490,10 @@ export function simulateHandleOp(
return simulateHandleOpV07(
userOperation,
+ queuedUserOperations as UserOperationV07[],
entryPoint,
publicClient,
- userOperation.sender,
- userOperation.callData,
entryPointSimulationsAddress,
finalStateOverride
)
}
-
-function tooLow(error: string) { | why are we removing this? |
alto | github_2023 | typescript | 201 | pimlicolabs | plusminushalf | @@ -134,20 +135,22 @@ export class Server {
this.fastify.post("/:version/rpc", this.rpcHttp.bind(this))
this.fastify.post("/", this.rpcHttp.bind(this))
- this.fastify.register(async (fastify) => {
- fastify.route({
- method: "GET",
- url: "/:version/rpc",
- handler: async (request, reply) => {
- await reply.status(404).send("GET request to /${version}/rpc is not supported, use POST isntead")
- },
- wsHandler: async (socket: WebSocket.WebSocket, request) => {
- socket.on("message", async (msgBuffer: Buffer) =>
- this.rpcSocket(request, msgBuffer, socket)
- )
- }
+ if (websocketEnabled) {
+ this.fastify.register(async (fastify) => {
+ fastify.route({
+ method: "GET",
+ url: "/:version/rpc",
+ handler: async (request, reply) => {
+ await reply.status(404).send("GET request to /${version}/rpc is not supported, use POST isntead") | Hey I just noticed this but `${version}` will be shown as it is, rather we should get the version from the request and put it here. |
alto | github_2023 | typescript | 201 | pimlicolabs | plusminushalf | @@ -96,6 +96,7 @@ export const compatibilityArgsSchema = z.object({
export const serverArgsSchema = z.object({
port: z.number().int().min(0),
timeout: z.number().int().min(0).optional(),
+ "websocket": z.boolean().default(false), | Also @pavlovdog we will have to enable it in gitops now if we do want websocket support on prodcution. |
alto | github_2023 | typescript | 197 | pimlicolabs | plusminushalf | @@ -89,6 +92,12 @@ export class Server {
disableRequestLogging: true
})
+ this.fastify.register(websocket, {
+ options: {
+ maxPayload: 1048576 // maximum allowed messages size is 1 MiB | can we make this configurable? |
alto | github_2023 | typescript | 197 | pimlicolabs | plusminushalf | @@ -113,16 +122,32 @@ export class Server {
this.metrics.httpRequests.labels(labels).inc()
- const durationMs = reply.getResponseTime()
+ const durationMs = reply.elapsedTime
const durationSeconds = durationMs / 1000
this.metrics.httpRequestsDuration
.labels(labels)
.observe(durationSeconds)
})
- this.fastify.post("/rpc", this.rpc.bind(this))
- this.fastify.post("/:version/rpc", this.rpc.bind(this))
- this.fastify.post("/", this.rpc.bind(this))
+ this.fastify.post("/rpc", this.rpcHttp.bind(this))
+ this.fastify.post("/:version/rpc", this.rpcHttp.bind(this))
+ this.fastify.post("/", this.rpcHttp.bind(this))
+
+ this.fastify.register(async () => {
+ this.fastify.route({
+ method: "GET",
+ url: "/:version/rpc",
+ handler: async (request, reply) => {
+ await reply.status(500).send("Not implemented") | can we add more information like, we expect a POST request in `/v1/rpc` call?
so like:
```
await reply.status(500).send(`GET request to /${version}/rpc is not supported, use POST isntead.`)
``` |
alto | github_2023 | typescript | 197 | pimlicolabs | nikmel2803 | @@ -113,16 +122,32 @@ export class Server {
this.metrics.httpRequests.labels(labels).inc()
- const durationMs = reply.getResponseTime()
+ const durationMs = reply.elapsedTime
const durationSeconds = durationMs / 1000
this.metrics.httpRequestsDuration
.labels(labels)
.observe(durationSeconds)
})
- this.fastify.post("/rpc", this.rpc.bind(this))
- this.fastify.post("/:version/rpc", this.rpc.bind(this))
- this.fastify.post("/", this.rpc.bind(this))
+ this.fastify.post("/rpc", this.rpcHttp.bind(this))
+ this.fastify.post("/:version/rpc", this.rpcHttp.bind(this))
+ this.fastify.post("/", this.rpcHttp.bind(this))
+
+ this.fastify.register(async () => { | can you clarify why do we need this wrapper here pls? as i understand it's something like fastify plugin? but why is it needed here? |
alto | github_2023 | typescript | 197 | pimlicolabs | nikmel2803 | @@ -0,0 +1,57 @@
+import { FastifyReply } from "fastify"
+import * as WebSocket from "ws"
+
+class ReplyMiddleware { | little bit confused by a name 'middleware', maybe smth like RpcReply would be better? |
alto | github_2023 | typescript | 196 | pimlicolabs | plusminushalf | @@ -105,6 +105,18 @@ export async function simulateHandleOpV06(
} catch (e) {
const err = e as RpcRequestErrorType
+ if (
+ /return data out of bounds.*|EVM error OutOfOffset.*/.test(
+ err.details
+ )
+ ) {
+ // out of bound (low level evm error) occurs when paymaster reverts with less than 32bytes
+ return {
+ result: "failed",
+ data: "AA50 postOp revert" | umm is this chain specific or on all the chains? This seems like a weird error |
alto | github_2023 | typescript | 179 | pimlicolabs | mouseless0x | @@ -149,6 +158,28 @@ export class Server {
): Promise<void> {
reply.rpcStatus = "failed" // default to failed
let requestId: number | null = null
+
+ const versionParsingResult = altoVersions.safeParse(
+ (request.params as any)?.version ?? this.defaultApiVersion | a little confused on why we need the defaultApiVersion flag |
alto | github_2023 | typescript | 175 | pimlicolabs | kristofgazso | @@ -9,7 +9,13 @@ export const bundlerArgsSchema = z.object({
// allow both a comma separated list of addresses
// (better for cli and env vars) or an array of addresses
// (better for config files)
- entryPoint: addressSchema,
+ entryPoints: z.string().transform((val) => { | you could use a regex to make sure it's the correct comma separated format |
alto | github_2023 | typescript | 175 | pimlicolabs | kristofgazso | @@ -6,7 +6,14 @@ import {
UrlRequiredError,
createTransport
} from "viem"
-import { type RpcRequest, rpc } from "viem/utils"
+import { rpc } from "viem/utils"
+
+export type RpcRequest = { | why? |
alto | github_2023 | typescript | 175 | pimlicolabs | kristofgazso | @@ -100,21 +98,54 @@ export class ExecutorManager {
}
}
- async bundleNow(): Promise<Hash> {
+ async bundleNow(): Promise<Hash[]> {
const ops = await this.mempool.process(5_000_000n, 1)
if (ops.length === 0) {
throw new Error("no ops to bundle")
}
- const txHash = await this.sendToExecutor(ops)
+ const uniqueEntryPoints = new Set<Address>(
+ ops.map((op) => op.entryPoint)
+ )
+
+ const userOpEntryPointMap = new Map<Address, MempoolUserOperation[]>() | naming convention — can we user either userOperation or op |
alto | github_2023 | typescript | 175 | pimlicolabs | kristofgazso | @@ -375,13 +445,37 @@ export class ExecutorManager {
async refreshUserOperationStatuses(): Promise<void> {
const ops = this.mempool.dumpSubmittedOps()
- const txs = getTransactionsFromUserOperationEntries(ops)
-
- await Promise.all(
- txs.map(async (txInfo) => {
- await this.refreshTransactionStatus(txInfo)
- })
+ const uniqueEntryPoints = new Set<Address>(
+ ops.map((op) => op.userOperation.entryPoint)
)
+
+ const userOpEntryPointMap = new Map<Address, SubmittedUserOperation[]>()
+
+ for (const op of ops) {
+ if (!userOpEntryPointMap.has(op.userOperation.entryPoint)) {
+ userOpEntryPointMap.set(op.userOperation.entryPoint, [])
+ }
+ userOpEntryPointMap.get(op.userOperation.entryPoint)?.push(op)
+ }
+
+ for (const entryPoint of uniqueEntryPoints) { | should this not be in parallel? |
alto | github_2023 | typescript | 175 | pimlicolabs | kristofgazso | @@ -202,19 +175,21 @@ export function deepHexlify(obj: any): any {
export function getAddressFromInitCodeOrPaymasterAndData(
data: Hex
-): Address | undefined {
+): Address | null {
if (!data) {
- return undefined
+ return null
}
if (data.length >= 42) {
return getAddress(data.slice(0, 42))
}
- return undefined
+ return null
}
export const transactionIncluded = async (
+ isVersion06: boolean, | it's a bit having this a boolean no? surely you'd just want two separate functions, one for each? idk but this seems a bit sus |
alto | github_2023 | typescript | 175 | pimlicolabs | kristofgazso | @@ -320,16 +336,27 @@ export class MemoryMempool implements Mempool {
storageMap
}
}
- const paymaster = getAddressFromInitCodeOrPaymasterAndData(
- op.paymasterAndData
+
+ const isUserOpV06 = isVersion06(op)
+
+ const paymaster = isUserOpV06
+ ? getAddressFromInitCodeOrPaymasterAndData(op.paymasterAndData)
+ : op.paymaster
+ const factory = isUserOpV06
+ ? getAddressFromInitCodeOrPaymasterAndData(op.initCode)
+ : op.factory
+ const paymasterStatus = this.reputationManager.getStatus(
+ opInfo.entryPoint,
+ paymaster
+ )
+ const factoryStatus = this.reputationManager.getStatus(
+ opInfo.entryPoint,
+ factory
)
- const factory = getAddressFromInitCodeOrPaymasterAndData(op.initCode)
- const paymasterStatus = this.reputationManager.getStatus(paymaster)
- const factoryStatus = this.reputationManager.getStatus(factory)
if (
- paymasterStatus === ReputationStatuses.BANNED ||
- factoryStatus === ReputationStatuses.BANNED
+ paymasterStatus === ReputationStatuses.banned || | out of curiosity why BANNED -> banned? isn't capital standard for enums? |
alto | github_2023 | typescript | 175 | pimlicolabs | kristofgazso | @@ -387,13 +449,74 @@ export const getUserOperationHash = (
)
}
+export const getUserOperationHash = (
+ userOperation: UserOperation,
+ entryPointAddress: Address,
+ chainId: number
+) => {
+ if (isVersion06(userOperation)) {
+ return getUserOperationHashV06(
+ userOperation,
+ entryPointAddress,
+ chainId
+ )
+ }
+
+ return getUserOperationHashV07(
+ toPackedUserOperation(userOperation),
+ entryPointAddress,
+ chainId
+ )
+}
+
export const getNonceKeyAndValue = (nonce: bigint) => {
const nonceKey = nonce >> 64n // first 192 bits of nonce
const userOperationNonceValue = nonce & 0xffffffffffffffffn // last 64 bits of nonce
return [nonceKey, userOperationNonceValue]
}
+export function toUnPackedUserOperation( | UnPacked -> Unpacked? |
alto | github_2023 | typescript | 175 | pimlicolabs | nikmel2803 | @@ -375,11 +443,40 @@ export class ExecutorManager {
async refreshUserOperationStatuses(): Promise<void> {
const ops = this.mempool.dumpSubmittedOps()
- const txs = getTransactionsFromUserOperationEntries(ops)
+ const uniqueEntryPoints = new Set<Address>(
+ ops.map((op) => op.userOperation.entryPoint)
+ )
+
+ const opEntryPointMap = new Map<Address, SubmittedUserOperation[]>()
+
+ for (const op of ops) {
+ if (!opEntryPointMap.has(op.userOperation.entryPoint)) {
+ opEntryPointMap.set(op.userOperation.entryPoint, [])
+ }
+ opEntryPointMap.get(op.userOperation.entryPoint)?.push(op)
+ } | we already know all possible EntryPoints from the config. can we just use it here? without cycling through each userop
and even with current logic we could make it with one iteration |
alto | github_2023 | typescript | 149 | pimlicolabs | kristofgazso | @@ -0,0 +1,450 @@
+import {
+ gasStationResult,
+ type GasPriceParameters,
+ RpcError
+} from "@entrypoint-0.7/types"
+import { parseGwei, type Chain, type PublicClient } from "viem"
+import { type Logger, maxBigInt, minBigInt } from "@alto/utils"
+import * as chains from "viem/chains"
+import * as sentry from "@sentry/node"
+
+export interface InterfaceGasPriceManager {
+ getGasPrice(): Promise<GasPriceParameters>
+ validateGasPrice(gasPrice: GasPriceParameters): void
+}
+
+enum ChainId {
+ Goerli = 5,
+ Polygon = 137,
+ Mumbai = 80001,
+ LineaTestnet = 59140,
+ Linea = 59144
+}
+
+const MIN_POLYGON_GAS_PRICE = parseGwei("31")
+const MIN_MUMBAI_GAS_PRICE = parseGwei("1")
+
+function getGasStationUrl(chainId: ChainId.Polygon | ChainId.Mumbai): string {
+ switch (chainId) {
+ case ChainId.Polygon:
+ return "https://gasstation.polygon.technology/v2"
+ case ChainId.Mumbai:
+ return "https://gasstation-testnet.polygon.technology/v2"
+ }
+}
+
+export class GasPriceManager implements InterfaceGasPriceManager { | shouldn't we get rid of this interface to reduce complexity and ability to F12 into things? we could just use the actual Class everywhere |
alto | github_2023 | typescript | 149 | pimlicolabs | kristofgazso | @@ -0,0 +1,450 @@
+import {
+ gasStationResult,
+ type GasPriceParameters,
+ RpcError
+} from "@entrypoint-0.7/types"
+import { parseGwei, type Chain, type PublicClient } from "viem"
+import { type Logger, maxBigInt, minBigInt } from "@alto/utils"
+import * as chains from "viem/chains"
+import * as sentry from "@sentry/node"
+
+export interface InterfaceGasPriceManager {
+ getGasPrice(): Promise<GasPriceParameters>
+ validateGasPrice(gasPrice: GasPriceParameters): void
+}
+
+enum ChainId {
+ Goerli = 5,
+ Polygon = 137,
+ Mumbai = 80001,
+ LineaTestnet = 59140,
+ Linea = 59144
+}
+
+const MIN_POLYGON_GAS_PRICE = parseGwei("31")
+const MIN_MUMBAI_GAS_PRICE = parseGwei("1")
+
+function getGasStationUrl(chainId: ChainId.Polygon | ChainId.Mumbai): string {
+ switch (chainId) {
+ case ChainId.Polygon:
+ return "https://gasstation.polygon.technology/v2"
+ case ChainId.Mumbai:
+ return "https://gasstation-testnet.polygon.technology/v2"
+ }
+}
+
+export class GasPriceManager implements InterfaceGasPriceManager {
+ private chain: Chain
+ private publicClient: PublicClient
+ private noEip1559Support: boolean
+ private logger: Logger
+ private queueMaxFeePerGas: { timestamp: number; maxFeePerGas: bigint }[] =
+ [] // Store pairs of [price, timestamp]
+ private queueMaxPriorityFeePerGas: {
+ timestamp: number
+ maxPriorityFeePerGas: bigint
+ }[] = [] // Store pairs of [price, timestamp]
+ private maxQueueSize
+
+ constructor(
+ chain: Chain,
+ publicClient: PublicClient,
+ noEip1559Support: boolean,
+ logger: Logger,
+ gasPriceTimeValidityInSeconds = 10
+ ) {
+ this.maxQueueSize = gasPriceTimeValidityInSeconds
+ this.chain = chain
+ this.publicClient = publicClient
+ this.noEip1559Support = noEip1559Support
+ this.logger = logger
+ }
+
+ private getDefaultGasFee(
+ chainId: ChainId.Polygon | ChainId.Mumbai
+ ): bigint {
+ switch (chainId) {
+ case ChainId.Polygon:
+ return MIN_POLYGON_GAS_PRICE
+ case ChainId.Mumbai:
+ return MIN_MUMBAI_GAS_PRICE
+ default:
+ return 0n
+ }
+ }
+
+ private async getPolygonGasPriceParameters(): Promise<GasPriceParameters | null> {
+ const gasStationUrl = getGasStationUrl(this.chain.id)
+ try {
+ const data = await (await fetch(gasStationUrl)).json()
+ // take the standard speed here, SDK options will define the extra tip
+ const parsedData = gasStationResult.parse(data)
+
+ return parsedData.fast
+ } catch (e) {
+ this.logger.error(
+ { error: e },
+ "failed to get gas price from gas station, using default"
+ )
+ return null
+ }
+ }
+
+ private getBumpAmount(chainId: number) {
+ if (chainId === chains.sepolia.id) {
+ return 120n
+ }
+
+ if (chainId === chains.celo.id) {
+ return 150n
+ }
+
+ if (
+ chainId === chains.arbitrum.id ||
+ chainId === chains.scroll.id ||
+ chainId === chains.scrollSepolia.id ||
+ chainId === chains.arbitrumGoerli.id ||
+ chainId === chains.mainnet.id ||
+ chainId === chains.mantle.id ||
+ chainId === 22222 ||
+ chainId === chains.sepolia.id ||
+ chainId === chains.base.id ||
+ chainId === chains.dfk.id ||
+ chainId === chains.celoAlfajores.id ||
+ chainId === chains.celoCannoli.id ||
+ chainId === chains.avalanche.id
+ ) {
+ return 111n
+ }
+
+ return 100n
+ }
+
+ private bumpTheGasPrice(
+ gasPriceParameters: GasPriceParameters
+ ): GasPriceParameters {
+ const bumpAmount = this.getBumpAmount(this.chain.id)
+
+ const maxPriorityFeePerGas = maxBigInt(
+ gasPriceParameters.maxPriorityFeePerGas,
+ this.getDefaultGasFee(this.chain.id)
+ )
+ const maxFeePerGas = maxBigInt(
+ gasPriceParameters.maxFeePerGas,
+ maxPriorityFeePerGas
+ )
+
+ const result = {
+ maxFeePerGas: (maxFeePerGas * bumpAmount) / 100n,
+ maxPriorityFeePerGas: (maxPriorityFeePerGas * bumpAmount) / 100n
+ }
+
+ if (
+ this.chain.id === chains.celo.id ||
+ this.chain.id === chains.celoAlfajores.id ||
+ this.chain.id === chains.celoCannoli.id
+ ) {
+ const maxFee = maxBigInt(
+ result.maxFeePerGas,
+ result.maxPriorityFeePerGas
+ )
+ return {
+ maxFeePerGas: maxFee,
+ maxPriorityFeePerGas: maxFee
+ }
+ }
+
+ return result
+ }
+
+ private async getFallBackMaxPriorityFeePerGas(
+ publicClient: PublicClient,
+ gasPrice: bigint
+ ): Promise<bigint> {
+ const feeHistory = await publicClient.getFeeHistory({
+ blockCount: 10,
+ rewardPercentiles: [20],
+ blockTag: "latest"
+ })
+
+ if (feeHistory.reward === undefined || feeHistory.reward === null) {
+ return gasPrice
+ }
+
+ const feeAverage =
+ feeHistory.reward.reduce((acc, cur) => cur[0] + acc, 0n) / 10n
+ return minBigInt(feeAverage, gasPrice)
+ }
+
+ private async getNextBaseFee(publicClient: PublicClient) {
+ const block = await publicClient.getBlock({
+ blockTag: "latest"
+ })
+ const currentBaseFeePerGas =
+ block.baseFeePerGas || (await publicClient.getGasPrice())
+ const currentGasUsed = block.gasUsed
+ const gasTarget = block.gasLimit / 2n
+
+ if (currentGasUsed === gasTarget) {
+ return currentBaseFeePerGas
+ }
+
+ if (currentGasUsed > gasTarget) {
+ const gasUsedDelta = currentGasUsed - gasTarget
+ const baseFeePerGasDelta = maxBigInt(
+ (currentBaseFeePerGas * gasUsedDelta) / gasTarget / 8n,
+ 1n
+ )
+ return currentBaseFeePerGas + baseFeePerGasDelta
+ }
+
+ const gasUsedDelta = currentGasUsed - gasTarget
+ const baseFeePerGasDelta =
+ (currentBaseFeePerGas * gasUsedDelta) / gasTarget / 8n
+ return currentBaseFeePerGas - baseFeePerGasDelta
+ }
+
+ private async getNoEip1559SupportGasPrice(): Promise<GasPriceParameters> {
+ let gasPrice: bigint | undefined
+ try {
+ const gasInfo = await this.publicClient.estimateFeesPerGas({
+ chain: this.chain,
+ type: "legacy"
+ })
+ gasPrice = gasInfo.gasPrice
+ } catch (e) {
+ sentry.captureException(e)
+ this.logger.error(
+ "failed to fetch legacy gasPrices from estimateFeesPerGas",
+ { error: e }
+ )
+ gasPrice = undefined
+ }
+
+ if (gasPrice === undefined) {
+ this.logger.warn("gasPrice is undefined, using fallback value")
+ try {
+ gasPrice = await this.publicClient.getGasPrice()
+ } catch (e) {
+ this.logger.error("failed to get fallback gasPrice")
+ sentry.captureException(e)
+ throw e
+ }
+ }
+
+ return {
+ maxFeePerGas: gasPrice,
+ maxPriorityFeePerGas: gasPrice
+ }
+ }
+
+ private async estimateGasPrice(): Promise<GasPriceParameters> {
+ let maxFeePerGas: bigint | undefined
+ let maxPriorityFeePerGas: bigint | undefined
+ try {
+ const fees = await this.publicClient.estimateFeesPerGas({
+ chain: this.chain
+ })
+ maxFeePerGas = fees.maxFeePerGas
+ maxPriorityFeePerGas = fees.maxPriorityFeePerGas
+ } catch (e) {
+ sentry.captureException(e)
+ this.logger.error(
+ "failed to fetch eip-1559 gasPrices from estimateFeesPerGas",
+ { error: e }
+ )
+ maxFeePerGas = undefined
+ maxPriorityFeePerGas = undefined
+ }
+
+ if (maxPriorityFeePerGas === undefined) {
+ this.logger.warn(
+ "maxPriorityFeePerGas is undefined, using fallback value"
+ )
+ try {
+ maxPriorityFeePerGas =
+ await this.getFallBackMaxPriorityFeePerGas(
+ this.publicClient,
+ maxFeePerGas ?? 0n
+ )
+ } catch (e) {
+ this.logger.error("failed to get fallback maxPriorityFeePerGas")
+ sentry.captureException(e)
+ throw e
+ }
+ }
+
+ if (maxFeePerGas === undefined) {
+ this.logger.warn("maxFeePerGas is undefined, using fallback value")
+ try {
+ maxFeePerGas =
+ (await this.getNextBaseFee(this.publicClient)) +
+ maxPriorityFeePerGas
+ } catch (e) {
+ this.logger.error("failed to get fallback maxFeePerGas")
+ sentry.captureException(e)
+ throw e
+ }
+ }
+
+ if (maxPriorityFeePerGas === 0n) {
+ maxPriorityFeePerGas = maxFeePerGas / 200n
+ }
+
+ return { maxFeePerGas, maxPriorityFeePerGas }
+ }
+
+ private saveMaxFeePerGas(gasPrice: bigint, timestamp: number) {
+ const queue = this.queueMaxFeePerGas
+ const last = queue.length > 0 ? queue[queue.length - 1] : null
+
+ if (!last || timestamp - last.timestamp >= 1000) {
+ if (queue.length >= this.maxQueueSize) {
+ queue.shift()
+ }
+ queue.push({ maxFeePerGas: gasPrice, timestamp })
+ } else if (gasPrice < last.maxFeePerGas) {
+ last.maxFeePerGas = gasPrice
+ last.timestamp = timestamp
+ }
+ }
+
+ private saveMaxPriorityFeePerGas(gasPrice: bigint, timestamp: number) {
+ const queue = this.queueMaxPriorityFeePerGas
+ const last = queue.length > 0 ? queue[queue.length - 1] : null
+
+ if (!last || timestamp - last.timestamp >= 1000) {
+ if (queue.length >= this.maxQueueSize) {
+ queue.shift()
+ }
+ queue.push({ maxPriorityFeePerGas: gasPrice, timestamp })
+ } else if (gasPrice < last.maxPriorityFeePerGas) {
+ last.maxPriorityFeePerGas = gasPrice
+ last.timestamp = timestamp
+ }
+ }
+
+ private saveGasPrice(gasPrice: GasPriceParameters, timestamp: number) {
+ return new Promise<void>((resolve) => {
+ this.saveMaxFeePerGas(gasPrice.maxFeePerGas, timestamp)
+ this.saveMaxPriorityFeePerGas(
+ gasPrice.maxPriorityFeePerGas,
+ timestamp
+ )
+ resolve()
+ })
+ }
+
+ public async getGasPrice(): Promise<GasPriceParameters> {
+ let maxFeeFloor = 0n
+ let maxPriorityFeeFloor = 0n
+
+ if (this.chain.id === chains.dfk.id) {
+ maxFeeFloor = 5_000_000_000n
+ maxPriorityFeeFloor = 5_000_000_000n
+ }
+
+ if (
+ this.chain.id === chains.polygon.id ||
+ this.chain.id === chains.polygonMumbai.id
+ ) {
+ const polygonEstimate = await this.getPolygonGasPriceParameters()
+ if (polygonEstimate) {
+ const gasPrice = this.bumpTheGasPrice({
+ maxFeePerGas: polygonEstimate.maxFeePerGas,
+ maxPriorityFeePerGas: polygonEstimate.maxPriorityFeePerGas
+ })
+ this.saveGasPrice( | why are we doing saveGasPrice 3 times in this function instead of abstracting the main implementation into an `innerGetGasPrice` and calling this right after |
alto | github_2023 | typescript | 149 | pimlicolabs | kristofgazso | @@ -0,0 +1,450 @@
+import {
+ gasStationResult,
+ type GasPriceParameters,
+ RpcError
+} from "@entrypoint-0.7/types"
+import { parseGwei, type Chain, type PublicClient } from "viem"
+import { type Logger, maxBigInt, minBigInt } from "@alto/utils"
+import * as chains from "viem/chains"
+import * as sentry from "@sentry/node"
+
+export interface InterfaceGasPriceManager {
+ getGasPrice(): Promise<GasPriceParameters>
+ validateGasPrice(gasPrice: GasPriceParameters): void
+}
+
+enum ChainId {
+ Goerli = 5,
+ Polygon = 137,
+ Mumbai = 80001,
+ LineaTestnet = 59140,
+ Linea = 59144
+}
+
+const MIN_POLYGON_GAS_PRICE = parseGwei("31")
+const MIN_MUMBAI_GAS_PRICE = parseGwei("1")
+
+function getGasStationUrl(chainId: ChainId.Polygon | ChainId.Mumbai): string {
+ switch (chainId) {
+ case ChainId.Polygon:
+ return "https://gasstation.polygon.technology/v2"
+ case ChainId.Mumbai:
+ return "https://gasstation-testnet.polygon.technology/v2"
+ }
+}
+
+export class GasPriceManager implements InterfaceGasPriceManager {
+ private chain: Chain
+ private publicClient: PublicClient
+ private noEip1559Support: boolean
+ private logger: Logger
+ private queueMaxFeePerGas: { timestamp: number; maxFeePerGas: bigint }[] =
+ [] // Store pairs of [price, timestamp]
+ private queueMaxPriorityFeePerGas: {
+ timestamp: number
+ maxPriorityFeePerGas: bigint
+ }[] = [] // Store pairs of [price, timestamp]
+ private maxQueueSize
+
+ constructor(
+ chain: Chain,
+ publicClient: PublicClient,
+ noEip1559Support: boolean,
+ logger: Logger,
+ gasPriceTimeValidityInSeconds = 10
+ ) {
+ this.maxQueueSize = gasPriceTimeValidityInSeconds
+ this.chain = chain
+ this.publicClient = publicClient
+ this.noEip1559Support = noEip1559Support
+ this.logger = logger
+ }
+
+ private getDefaultGasFee(
+ chainId: ChainId.Polygon | ChainId.Mumbai
+ ): bigint {
+ switch (chainId) {
+ case ChainId.Polygon:
+ return MIN_POLYGON_GAS_PRICE
+ case ChainId.Mumbai:
+ return MIN_MUMBAI_GAS_PRICE
+ default:
+ return 0n
+ }
+ }
+
+ private async getPolygonGasPriceParameters(): Promise<GasPriceParameters | null> {
+ const gasStationUrl = getGasStationUrl(this.chain.id)
+ try {
+ const data = await (await fetch(gasStationUrl)).json()
+ // take the standard speed here, SDK options will define the extra tip
+ const parsedData = gasStationResult.parse(data)
+
+ return parsedData.fast
+ } catch (e) {
+ this.logger.error(
+ { error: e },
+ "failed to get gas price from gas station, using default"
+ )
+ return null
+ }
+ }
+
+ private getBumpAmount(chainId: number) {
+ if (chainId === chains.sepolia.id) {
+ return 120n
+ }
+
+ if (chainId === chains.celo.id) {
+ return 150n
+ }
+
+ if (
+ chainId === chains.arbitrum.id ||
+ chainId === chains.scroll.id ||
+ chainId === chains.scrollSepolia.id ||
+ chainId === chains.arbitrumGoerli.id ||
+ chainId === chains.mainnet.id ||
+ chainId === chains.mantle.id ||
+ chainId === 22222 ||
+ chainId === chains.sepolia.id ||
+ chainId === chains.base.id ||
+ chainId === chains.dfk.id ||
+ chainId === chains.celoAlfajores.id ||
+ chainId === chains.celoCannoli.id ||
+ chainId === chains.avalanche.id
+ ) {
+ return 111n
+ }
+
+ return 100n
+ }
+
+ private bumpTheGasPrice(
+ gasPriceParameters: GasPriceParameters
+ ): GasPriceParameters {
+ const bumpAmount = this.getBumpAmount(this.chain.id)
+
+ const maxPriorityFeePerGas = maxBigInt(
+ gasPriceParameters.maxPriorityFeePerGas,
+ this.getDefaultGasFee(this.chain.id)
+ )
+ const maxFeePerGas = maxBigInt(
+ gasPriceParameters.maxFeePerGas,
+ maxPriorityFeePerGas
+ )
+
+ const result = {
+ maxFeePerGas: (maxFeePerGas * bumpAmount) / 100n,
+ maxPriorityFeePerGas: (maxPriorityFeePerGas * bumpAmount) / 100n
+ }
+
+ if (
+ this.chain.id === chains.celo.id ||
+ this.chain.id === chains.celoAlfajores.id ||
+ this.chain.id === chains.celoCannoli.id
+ ) {
+ const maxFee = maxBigInt(
+ result.maxFeePerGas,
+ result.maxPriorityFeePerGas
+ )
+ return {
+ maxFeePerGas: maxFee,
+ maxPriorityFeePerGas: maxFee
+ }
+ }
+
+ return result
+ }
+
+ private async getFallBackMaxPriorityFeePerGas(
+ publicClient: PublicClient,
+ gasPrice: bigint
+ ): Promise<bigint> {
+ const feeHistory = await publicClient.getFeeHistory({
+ blockCount: 10,
+ rewardPercentiles: [20],
+ blockTag: "latest"
+ })
+
+ if (feeHistory.reward === undefined || feeHistory.reward === null) {
+ return gasPrice
+ }
+
+ const feeAverage =
+ feeHistory.reward.reduce((acc, cur) => cur[0] + acc, 0n) / 10n
+ return minBigInt(feeAverage, gasPrice)
+ }
+
+ private async getNextBaseFee(publicClient: PublicClient) {
+ const block = await publicClient.getBlock({
+ blockTag: "latest"
+ })
+ const currentBaseFeePerGas =
+ block.baseFeePerGas || (await publicClient.getGasPrice())
+ const currentGasUsed = block.gasUsed
+ const gasTarget = block.gasLimit / 2n
+
+ if (currentGasUsed === gasTarget) {
+ return currentBaseFeePerGas
+ }
+
+ if (currentGasUsed > gasTarget) {
+ const gasUsedDelta = currentGasUsed - gasTarget
+ const baseFeePerGasDelta = maxBigInt(
+ (currentBaseFeePerGas * gasUsedDelta) / gasTarget / 8n,
+ 1n
+ )
+ return currentBaseFeePerGas + baseFeePerGasDelta
+ }
+
+ const gasUsedDelta = currentGasUsed - gasTarget
+ const baseFeePerGasDelta =
+ (currentBaseFeePerGas * gasUsedDelta) / gasTarget / 8n
+ return currentBaseFeePerGas - baseFeePerGasDelta
+ }
+
+ private async getNoEip1559SupportGasPrice(): Promise<GasPriceParameters> {
+ let gasPrice: bigint | undefined
+ try {
+ const gasInfo = await this.publicClient.estimateFeesPerGas({
+ chain: this.chain,
+ type: "legacy"
+ })
+ gasPrice = gasInfo.gasPrice
+ } catch (e) {
+ sentry.captureException(e)
+ this.logger.error(
+ "failed to fetch legacy gasPrices from estimateFeesPerGas",
+ { error: e }
+ )
+ gasPrice = undefined
+ }
+
+ if (gasPrice === undefined) {
+ this.logger.warn("gasPrice is undefined, using fallback value")
+ try {
+ gasPrice = await this.publicClient.getGasPrice()
+ } catch (e) {
+ this.logger.error("failed to get fallback gasPrice")
+ sentry.captureException(e)
+ throw e
+ }
+ }
+
+ return {
+ maxFeePerGas: gasPrice,
+ maxPriorityFeePerGas: gasPrice
+ }
+ }
+
+ private async estimateGasPrice(): Promise<GasPriceParameters> {
+ let maxFeePerGas: bigint | undefined
+ let maxPriorityFeePerGas: bigint | undefined
+ try {
+ const fees = await this.publicClient.estimateFeesPerGas({
+ chain: this.chain
+ })
+ maxFeePerGas = fees.maxFeePerGas
+ maxPriorityFeePerGas = fees.maxPriorityFeePerGas
+ } catch (e) {
+ sentry.captureException(e)
+ this.logger.error(
+ "failed to fetch eip-1559 gasPrices from estimateFeesPerGas",
+ { error: e }
+ )
+ maxFeePerGas = undefined
+ maxPriorityFeePerGas = undefined
+ }
+
+ if (maxPriorityFeePerGas === undefined) {
+ this.logger.warn(
+ "maxPriorityFeePerGas is undefined, using fallback value"
+ )
+ try {
+ maxPriorityFeePerGas =
+ await this.getFallBackMaxPriorityFeePerGas(
+ this.publicClient,
+ maxFeePerGas ?? 0n
+ )
+ } catch (e) {
+ this.logger.error("failed to get fallback maxPriorityFeePerGas")
+ sentry.captureException(e)
+ throw e
+ }
+ }
+
+ if (maxFeePerGas === undefined) {
+ this.logger.warn("maxFeePerGas is undefined, using fallback value")
+ try {
+ maxFeePerGas =
+ (await this.getNextBaseFee(this.publicClient)) +
+ maxPriorityFeePerGas
+ } catch (e) {
+ this.logger.error("failed to get fallback maxFeePerGas")
+ sentry.captureException(e)
+ throw e
+ }
+ }
+
+ if (maxPriorityFeePerGas === 0n) {
+ maxPriorityFeePerGas = maxFeePerGas / 200n
+ }
+
+ return { maxFeePerGas, maxPriorityFeePerGas }
+ }
+
+ private saveMaxFeePerGas(gasPrice: bigint, timestamp: number) {
+ const queue = this.queueMaxFeePerGas
+ const last = queue.length > 0 ? queue[queue.length - 1] : null
+
+ if (!last || timestamp - last.timestamp >= 1000) { | wait if `!last` that means queue.length === 0, that's not supposed to be that way, right? |
alto | github_2023 | typescript | 149 | pimlicolabs | kristofgazso | @@ -0,0 +1,450 @@
+import {
+ gasStationResult,
+ type GasPriceParameters,
+ RpcError
+} from "@entrypoint-0.7/types"
+import { parseGwei, type Chain, type PublicClient } from "viem"
+import { type Logger, maxBigInt, minBigInt } from "@alto/utils"
+import * as chains from "viem/chains"
+import * as sentry from "@sentry/node"
+
+export interface InterfaceGasPriceManager {
+ getGasPrice(): Promise<GasPriceParameters>
+ validateGasPrice(gasPrice: GasPriceParameters): void
+}
+
+enum ChainId {
+ Goerli = 5,
+ Polygon = 137,
+ Mumbai = 80001,
+ LineaTestnet = 59140,
+ Linea = 59144
+}
+
+const MIN_POLYGON_GAS_PRICE = parseGwei("31")
+const MIN_MUMBAI_GAS_PRICE = parseGwei("1")
+
+function getGasStationUrl(chainId: ChainId.Polygon | ChainId.Mumbai): string {
+ switch (chainId) {
+ case ChainId.Polygon:
+ return "https://gasstation.polygon.technology/v2"
+ case ChainId.Mumbai:
+ return "https://gasstation-testnet.polygon.technology/v2"
+ }
+}
+
+export class GasPriceManager implements InterfaceGasPriceManager {
+ private chain: Chain
+ private publicClient: PublicClient
+ private noEip1559Support: boolean
+ private logger: Logger
+ private queueMaxFeePerGas: { timestamp: number; maxFeePerGas: bigint }[] =
+ [] // Store pairs of [price, timestamp]
+ private queueMaxPriorityFeePerGas: {
+ timestamp: number
+ maxPriorityFeePerGas: bigint
+ }[] = [] // Store pairs of [price, timestamp]
+ private maxQueueSize
+
+ constructor(
+ chain: Chain,
+ publicClient: PublicClient,
+ noEip1559Support: boolean,
+ logger: Logger,
+ gasPriceTimeValidityInSeconds = 10
+ ) {
+ this.maxQueueSize = gasPriceTimeValidityInSeconds
+ this.chain = chain
+ this.publicClient = publicClient
+ this.noEip1559Support = noEip1559Support
+ this.logger = logger
+ }
+
+ private getDefaultGasFee(
+ chainId: ChainId.Polygon | ChainId.Mumbai
+ ): bigint {
+ switch (chainId) {
+ case ChainId.Polygon:
+ return MIN_POLYGON_GAS_PRICE
+ case ChainId.Mumbai:
+ return MIN_MUMBAI_GAS_PRICE
+ default:
+ return 0n
+ }
+ }
+
+ private async getPolygonGasPriceParameters(): Promise<GasPriceParameters | null> {
+ const gasStationUrl = getGasStationUrl(this.chain.id)
+ try {
+ const data = await (await fetch(gasStationUrl)).json()
+ // take the standard speed here, SDK options will define the extra tip
+ const parsedData = gasStationResult.parse(data)
+
+ return parsedData.fast
+ } catch (e) {
+ this.logger.error(
+ { error: e },
+ "failed to get gas price from gas station, using default"
+ )
+ return null
+ }
+ }
+
+ private getBumpAmount(chainId: number) {
+ if (chainId === chains.sepolia.id) {
+ return 120n
+ }
+
+ if (chainId === chains.celo.id) {
+ return 150n
+ }
+
+ if (
+ chainId === chains.arbitrum.id ||
+ chainId === chains.scroll.id ||
+ chainId === chains.scrollSepolia.id ||
+ chainId === chains.arbitrumGoerli.id ||
+ chainId === chains.mainnet.id ||
+ chainId === chains.mantle.id ||
+ chainId === 22222 ||
+ chainId === chains.sepolia.id ||
+ chainId === chains.base.id ||
+ chainId === chains.dfk.id ||
+ chainId === chains.celoAlfajores.id ||
+ chainId === chains.celoCannoli.id ||
+ chainId === chains.avalanche.id
+ ) {
+ return 111n
+ }
+
+ return 100n
+ }
+
+ private bumpTheGasPrice(
+ gasPriceParameters: GasPriceParameters
+ ): GasPriceParameters {
+ const bumpAmount = this.getBumpAmount(this.chain.id)
+
+ const maxPriorityFeePerGas = maxBigInt(
+ gasPriceParameters.maxPriorityFeePerGas,
+ this.getDefaultGasFee(this.chain.id)
+ )
+ const maxFeePerGas = maxBigInt(
+ gasPriceParameters.maxFeePerGas,
+ maxPriorityFeePerGas
+ )
+
+ const result = {
+ maxFeePerGas: (maxFeePerGas * bumpAmount) / 100n,
+ maxPriorityFeePerGas: (maxPriorityFeePerGas * bumpAmount) / 100n
+ }
+
+ if (
+ this.chain.id === chains.celo.id ||
+ this.chain.id === chains.celoAlfajores.id ||
+ this.chain.id === chains.celoCannoli.id
+ ) {
+ const maxFee = maxBigInt(
+ result.maxFeePerGas,
+ result.maxPriorityFeePerGas
+ )
+ return {
+ maxFeePerGas: maxFee,
+ maxPriorityFeePerGas: maxFee
+ }
+ }
+
+ return result
+ }
+
+ private async getFallBackMaxPriorityFeePerGas(
+ publicClient: PublicClient,
+ gasPrice: bigint
+ ): Promise<bigint> {
+ const feeHistory = await publicClient.getFeeHistory({
+ blockCount: 10,
+ rewardPercentiles: [20],
+ blockTag: "latest"
+ })
+
+ if (feeHistory.reward === undefined || feeHistory.reward === null) {
+ return gasPrice
+ }
+
+ const feeAverage =
+ feeHistory.reward.reduce((acc, cur) => cur[0] + acc, 0n) / 10n
+ return minBigInt(feeAverage, gasPrice)
+ }
+
+ private async getNextBaseFee(publicClient: PublicClient) {
+ const block = await publicClient.getBlock({
+ blockTag: "latest"
+ })
+ const currentBaseFeePerGas =
+ block.baseFeePerGas || (await publicClient.getGasPrice())
+ const currentGasUsed = block.gasUsed
+ const gasTarget = block.gasLimit / 2n
+
+ if (currentGasUsed === gasTarget) {
+ return currentBaseFeePerGas
+ }
+
+ if (currentGasUsed > gasTarget) {
+ const gasUsedDelta = currentGasUsed - gasTarget
+ const baseFeePerGasDelta = maxBigInt(
+ (currentBaseFeePerGas * gasUsedDelta) / gasTarget / 8n,
+ 1n
+ )
+ return currentBaseFeePerGas + baseFeePerGasDelta
+ }
+
+ const gasUsedDelta = currentGasUsed - gasTarget
+ const baseFeePerGasDelta =
+ (currentBaseFeePerGas * gasUsedDelta) / gasTarget / 8n
+ return currentBaseFeePerGas - baseFeePerGasDelta
+ }
+
+ private async getNoEip1559SupportGasPrice(): Promise<GasPriceParameters> {
+ let gasPrice: bigint | undefined
+ try {
+ const gasInfo = await this.publicClient.estimateFeesPerGas({
+ chain: this.chain,
+ type: "legacy"
+ })
+ gasPrice = gasInfo.gasPrice
+ } catch (e) {
+ sentry.captureException(e)
+ this.logger.error(
+ "failed to fetch legacy gasPrices from estimateFeesPerGas",
+ { error: e }
+ )
+ gasPrice = undefined
+ }
+
+ if (gasPrice === undefined) {
+ this.logger.warn("gasPrice is undefined, using fallback value")
+ try {
+ gasPrice = await this.publicClient.getGasPrice()
+ } catch (e) {
+ this.logger.error("failed to get fallback gasPrice")
+ sentry.captureException(e)
+ throw e
+ }
+ }
+
+ return {
+ maxFeePerGas: gasPrice,
+ maxPriorityFeePerGas: gasPrice
+ }
+ }
+
+ private async estimateGasPrice(): Promise<GasPriceParameters> {
+ let maxFeePerGas: bigint | undefined
+ let maxPriorityFeePerGas: bigint | undefined
+ try {
+ const fees = await this.publicClient.estimateFeesPerGas({
+ chain: this.chain
+ })
+ maxFeePerGas = fees.maxFeePerGas
+ maxPriorityFeePerGas = fees.maxPriorityFeePerGas
+ } catch (e) {
+ sentry.captureException(e)
+ this.logger.error(
+ "failed to fetch eip-1559 gasPrices from estimateFeesPerGas",
+ { error: e }
+ )
+ maxFeePerGas = undefined
+ maxPriorityFeePerGas = undefined
+ }
+
+ if (maxPriorityFeePerGas === undefined) {
+ this.logger.warn(
+ "maxPriorityFeePerGas is undefined, using fallback value"
+ )
+ try {
+ maxPriorityFeePerGas =
+ await this.getFallBackMaxPriorityFeePerGas(
+ this.publicClient,
+ maxFeePerGas ?? 0n
+ )
+ } catch (e) {
+ this.logger.error("failed to get fallback maxPriorityFeePerGas")
+ sentry.captureException(e)
+ throw e
+ }
+ }
+
+ if (maxFeePerGas === undefined) {
+ this.logger.warn("maxFeePerGas is undefined, using fallback value")
+ try {
+ maxFeePerGas =
+ (await this.getNextBaseFee(this.publicClient)) +
+ maxPriorityFeePerGas
+ } catch (e) {
+ this.logger.error("failed to get fallback maxFeePerGas")
+ sentry.captureException(e)
+ throw e
+ }
+ }
+
+ if (maxPriorityFeePerGas === 0n) {
+ maxPriorityFeePerGas = maxFeePerGas / 200n
+ }
+
+ return { maxFeePerGas, maxPriorityFeePerGas }
+ }
+
+ private saveMaxFeePerGas(gasPrice: bigint, timestamp: number) {
+ const queue = this.queueMaxFeePerGas
+ const last = queue.length > 0 ? queue[queue.length - 1] : null
+
+ if (!last || timestamp - last.timestamp >= 1000) {
+ if (queue.length >= this.maxQueueSize) {
+ queue.shift()
+ }
+ queue.push({ maxFeePerGas: gasPrice, timestamp })
+ } else if (gasPrice < last.maxFeePerGas) {
+ last.maxFeePerGas = gasPrice
+ last.timestamp = timestamp
+ }
+ }
+
+ private saveMaxPriorityFeePerGas(gasPrice: bigint, timestamp: number) {
+ const queue = this.queueMaxPriorityFeePerGas
+ const last = queue.length > 0 ? queue[queue.length - 1] : null
+
+ if (!last || timestamp - last.timestamp >= 1000) {
+ if (queue.length >= this.maxQueueSize) {
+ queue.shift()
+ }
+ queue.push({ maxPriorityFeePerGas: gasPrice, timestamp })
+ } else if (gasPrice < last.maxPriorityFeePerGas) {
+ last.maxPriorityFeePerGas = gasPrice
+ last.timestamp = timestamp
+ }
+ }
+
+ private saveGasPrice(gasPrice: GasPriceParameters, timestamp: number) {
+ return new Promise<void>((resolve) => {
+ this.saveMaxFeePerGas(gasPrice.maxFeePerGas, timestamp) | why not save maxFeePerGas and maxPriorityFeePerGas together? |
alto | github_2023 | typescript | 149 | pimlicolabs | kristofgazso | @@ -0,0 +1,450 @@
+import {
+ gasStationResult,
+ type GasPriceParameters,
+ RpcError
+} from "@entrypoint-0.7/types"
+import { parseGwei, type Chain, type PublicClient } from "viem"
+import { type Logger, maxBigInt, minBigInt } from "@alto/utils"
+import * as chains from "viem/chains"
+import * as sentry from "@sentry/node"
+
+export interface InterfaceGasPriceManager {
+ getGasPrice(): Promise<GasPriceParameters>
+ validateGasPrice(gasPrice: GasPriceParameters): void
+}
+
+enum ChainId {
+ Goerli = 5,
+ Polygon = 137,
+ Mumbai = 80001,
+ LineaTestnet = 59140,
+ Linea = 59144
+}
+
+const MIN_POLYGON_GAS_PRICE = parseGwei("31")
+const MIN_MUMBAI_GAS_PRICE = parseGwei("1")
+
+function getGasStationUrl(chainId: ChainId.Polygon | ChainId.Mumbai): string {
+ switch (chainId) {
+ case ChainId.Polygon:
+ return "https://gasstation.polygon.technology/v2"
+ case ChainId.Mumbai:
+ return "https://gasstation-testnet.polygon.technology/v2"
+ }
+}
+
+export class GasPriceManager implements InterfaceGasPriceManager {
+ private chain: Chain
+ private publicClient: PublicClient
+ private noEip1559Support: boolean
+ private logger: Logger
+ private queueMaxFeePerGas: { timestamp: number; maxFeePerGas: bigint }[] =
+ [] // Store pairs of [price, timestamp]
+ private queueMaxPriorityFeePerGas: {
+ timestamp: number
+ maxPriorityFeePerGas: bigint
+ }[] = [] // Store pairs of [price, timestamp]
+ private maxQueueSize | how big are we looking to set this? |
alto | github_2023 | others | 116 | pimlicolabs | kristofgazso | @@ -9,21 +9,22 @@
"clean": "rm -rf ./packages/*/lib ./packages/*/*.tsbuildinfo",
"clean-modules": "rm -rf ./packages/*/node_modules node_modules",
"build": "pnpm -r run build",
- "start": "node packages/cli/lib/alto.js run",
- "dev": "node --inspect packages/cli/lib/alto.js run",
+ "start": "node packages/entrypoint-0.6/lib/cli/alto.js run",
+ "dev": "pnpm -r run dev",
"test": "pnpm -r --workspace-concurrency 1 test --verbose=true",
"test:spec": "./test/spec-tests/run-spec-tests.sh",
"lint": "biome check .",
"lint:fix": "pnpm run lint --apply",
"format": "biome format . --write"
},
"devDependencies": {
- "biome": "^0.3.3",
"@biomejs/biome": "^1.5.1",
"@swc/core": "^1.3.102",
"@types/mocha": "^10.0.6",
+ "biome": "^0.3.3", | remove this? |
alto | github_2023 | typescript | 105 | pimlicolabs | kristofgazso | @@ -84,115 +30,103 @@ const getBumpAmount = (chainId: number) => {
return 100n
}
-const bumpTheGasPrice = (
- chainId: number,
- gasPriceParameters: GasPriceParameters
-): GasPriceParameters => {
- const bumpAmount = getBumpAmount(chainId)
-
- const result = {
- maxFeePerGas: (gasPriceParameters.maxFeePerGas * bumpAmount) / 100n,
- maxPriorityFeePerGas:
- (gasPriceParameters.maxPriorityFeePerGas * bumpAmount) / 100n
- }
-
- if (chainId === chains.celo.id || chainId === chains.celoAlfajores.id) {
- const maxFee =
- result.maxFeePerGas > result.maxPriorityFeePerGas
- ? result.maxFeePerGas
- : result.maxPriorityFeePerGas
- return {
- maxFeePerGas: maxFee,
- maxPriorityFeePerGas: maxFee
- }
- }
-
- return result
-}
-
-const estimateMaxPriorityFeePerGas = async (publicClient: PublicClient) => {
- try {
- const maxPriorityFeePerGasHex = await publicClient.request({
- method: "eth_maxPriorityFeePerGas"
- })
- return hexToBigInt(maxPriorityFeePerGasHex)
- } catch {
- return null
- }
-}
-
const getFallBackMaxPriorityFeePerGas = async (
publicClient: PublicClient,
gasPrice: bigint
-) => {
+): Promise<bigint> => {
const feeHistory = await publicClient.getFeeHistory({
blockCount: 10,
rewardPercentiles: [20],
blockTag: "latest"
})
- if (feeHistory.reward === undefined) {
+ if (feeHistory.reward === undefined || feeHistory.reward === null) {
return gasPrice
}
- const feeAverage =
- feeHistory.reward.reduce((acc, cur) => cur[0] + acc, 0n) / 10n
- return feeAverage < gasPrice ? feeAverage : gasPrice
+ const feeAverage = feeHistory.reward.reduce((acc, cur) => cur[0] + acc, 0n) / 10n
+ return minBigInt(feeAverage, gasPrice)
}
-const getGasPriceFromRpc = (publicClient: PublicClient) => {
- try {
- return publicClient.getGasPrice()
- } catch {
- return null
+/// Formula taken from: https://eips.ethereum.org/EIPS/eip-1559
+const getNextBaseFee = async (publicClient: PublicClient) => {
+ const block = await publicClient.getBlock({
+ blockTag: "latest"
+ })
+ const currentBaseFeePerGas = block.baseFeePerGas || await publicClient.getGasPrice()
+ const currentGasUsed = block.gasUsed
+ const gasTarget = block.gasLimit / 2n
+
+ if (currentGasUsed === gasTarget) {
+ return currentBaseFeePerGas
+ }
+
+ if (currentGasUsed > gasTarget) {
+ const gasUsedDelta = currentGasUsed - gasTarget
+ const baseFeePerGasDelta = maxBigInt(currentBaseFeePerGas * gasUsedDelta / gasTarget / 8n, 1n)
+ return currentBaseFeePerGas + baseFeePerGasDelta
}
+
+ const gasUsedDelta = currentGasUsed - gasTarget
+ const baseFeePerGasDelta = currentBaseFeePerGas * gasUsedDelta / gasTarget / 8n
+ return currentBaseFeePerGas - baseFeePerGasDelta
}
export async function getGasPrice(
- chainId: number,
+ chain: Chain,
publicClient: PublicClient,
+ noEip1559Support: boolean,
logger: Logger
): Promise<GasPriceParameters> {
- if (chainId === ChainId.Polygon || chainId === ChainId.Mumbai) {
- const polygonEstimate = await getPolygonGasPriceParameters(
- chainId,
- logger
- )
- if (polygonEstimate) {
- return polygonEstimate
+ let maxFeePerGas: bigint | undefined
+ let maxPriorityFeePerGas: bigint | undefined
+ if (noEip1559Support) {
+ let { gasPrice } = await publicClient.estimateFeesPerGas({ chain, type: "legacy" })
+
+ if (gasPrice === undefined) {
+ logger.info("failed to get legacy gasPrice, using fallback value")
+ gasPrice = await publicClient.getGasPrice()
+ }
+
+ return {
+ maxFeePerGas: gasPrice,
+ maxPriorityFeePerGas: gasPrice
}
}
- let [gasPrice, maxPriorityFeePerGas]: [bigint | null, bigint | null] =
- await Promise.all([
- getGasPriceFromRpc(publicClient),
- estimateMaxPriorityFeePerGas(publicClient)
- ])
+ const fees = await publicClient.estimateFeesPerGas({ chain })
+ maxFeePerGas = fees.maxFeePerGas
+ maxPriorityFeePerGas = fees.maxPriorityFeePerGas
- if (maxPriorityFeePerGas === null) {
+ if (maxPriorityFeePerGas === undefined) {
+ logger.info("failed to get maxPriorityFeePerGas, using fallback value")
maxPriorityFeePerGas = await getFallBackMaxPriorityFeePerGas(
publicClient,
- gasPrice ?? 0n
+ maxFeePerGas ?? 0n
)
}
- if (gasPrice === null) {
- const block = await publicClient.getBlock({
- blockTag: "latest"
- })
- gasPrice = maxPriorityFeePerGas + (block.baseFeePerGas ?? 0n)
+ if (maxFeePerGas === undefined) {
+ logger.info("failed to get maxFeePerGas, using fallback value")
+ maxFeePerGas = await getNextBaseFee(publicClient) + maxPriorityFeePerGas
}
- const defaultGasFee = getDefaultGasFee(chainId)
+ const bumpAmount = getBumpAmount(chain.id)
+ maxPriorityFeePerGas = (maxPriorityFeePerGas * bumpAmount) / 100n | no bump for non-eip1559 chains? |
alto | github_2023 | typescript | 105 | pimlicolabs | kristofgazso | @@ -84,115 +30,103 @@ const getBumpAmount = (chainId: number) => {
return 100n
}
-const bumpTheGasPrice = (
- chainId: number,
- gasPriceParameters: GasPriceParameters
-): GasPriceParameters => {
- const bumpAmount = getBumpAmount(chainId)
-
- const result = {
- maxFeePerGas: (gasPriceParameters.maxFeePerGas * bumpAmount) / 100n,
- maxPriorityFeePerGas:
- (gasPriceParameters.maxPriorityFeePerGas * bumpAmount) / 100n
- }
-
- if (chainId === chains.celo.id || chainId === chains.celoAlfajores.id) {
- const maxFee =
- result.maxFeePerGas > result.maxPriorityFeePerGas
- ? result.maxFeePerGas
- : result.maxPriorityFeePerGas
- return {
- maxFeePerGas: maxFee,
- maxPriorityFeePerGas: maxFee
- }
- }
-
- return result
-}
-
-const estimateMaxPriorityFeePerGas = async (publicClient: PublicClient) => {
- try {
- const maxPriorityFeePerGasHex = await publicClient.request({
- method: "eth_maxPriorityFeePerGas"
- })
- return hexToBigInt(maxPriorityFeePerGasHex)
- } catch {
- return null
- }
-}
-
const getFallBackMaxPriorityFeePerGas = async (
publicClient: PublicClient,
gasPrice: bigint
-) => {
+): Promise<bigint> => {
const feeHistory = await publicClient.getFeeHistory({
blockCount: 10,
rewardPercentiles: [20],
blockTag: "latest"
})
- if (feeHistory.reward === undefined) {
+ if (feeHistory.reward === undefined || feeHistory.reward === null) {
return gasPrice
}
- const feeAverage =
- feeHistory.reward.reduce((acc, cur) => cur[0] + acc, 0n) / 10n
- return feeAverage < gasPrice ? feeAverage : gasPrice
+ const feeAverage = feeHistory.reward.reduce((acc, cur) => cur[0] + acc, 0n) / 10n
+ return minBigInt(feeAverage, gasPrice)
}
-const getGasPriceFromRpc = (publicClient: PublicClient) => {
- try {
- return publicClient.getGasPrice()
- } catch {
- return null
+/// Formula taken from: https://eips.ethereum.org/EIPS/eip-1559
+const getNextBaseFee = async (publicClient: PublicClient) => {
+ const block = await publicClient.getBlock({
+ blockTag: "latest"
+ })
+ const currentBaseFeePerGas = block.baseFeePerGas || await publicClient.getGasPrice()
+ const currentGasUsed = block.gasUsed
+ const gasTarget = block.gasLimit / 2n
+
+ if (currentGasUsed === gasTarget) {
+ return currentBaseFeePerGas
+ }
+
+ if (currentGasUsed > gasTarget) {
+ const gasUsedDelta = currentGasUsed - gasTarget
+ const baseFeePerGasDelta = maxBigInt(currentBaseFeePerGas * gasUsedDelta / gasTarget / 8n, 1n)
+ return currentBaseFeePerGas + baseFeePerGasDelta
}
+
+ const gasUsedDelta = currentGasUsed - gasTarget
+ const baseFeePerGasDelta = currentBaseFeePerGas * gasUsedDelta / gasTarget / 8n
+ return currentBaseFeePerGas - baseFeePerGasDelta
}
export async function getGasPrice(
- chainId: number,
+ chain: Chain,
publicClient: PublicClient,
+ noEip1559Support: boolean,
logger: Logger
): Promise<GasPriceParameters> {
- if (chainId === ChainId.Polygon || chainId === ChainId.Mumbai) {
- const polygonEstimate = await getPolygonGasPriceParameters(
- chainId,
- logger
- )
- if (polygonEstimate) {
- return polygonEstimate
+ let maxFeePerGas: bigint | undefined
+ let maxPriorityFeePerGas: bigint | undefined
+ if (noEip1559Support) {
+ let { gasPrice } = await publicClient.estimateFeesPerGas({ chain, type: "legacy" })
+
+ if (gasPrice === undefined) {
+ logger.info("failed to get legacy gasPrice, using fallback value")
+ gasPrice = await publicClient.getGasPrice()
+ }
+
+ return {
+ maxFeePerGas: gasPrice,
+ maxPriorityFeePerGas: gasPrice
}
}
- let [gasPrice, maxPriorityFeePerGas]: [bigint | null, bigint | null] =
- await Promise.all([
- getGasPriceFromRpc(publicClient),
- estimateMaxPriorityFeePerGas(publicClient)
- ])
+ const fees = await publicClient.estimateFeesPerGas({ chain })
+ maxFeePerGas = fees.maxFeePerGas
+ maxPriorityFeePerGas = fees.maxPriorityFeePerGas
- if (maxPriorityFeePerGas === null) {
+ if (maxPriorityFeePerGas === undefined) {
+ logger.info("failed to get maxPriorityFeePerGas, using fallback value")
maxPriorityFeePerGas = await getFallBackMaxPriorityFeePerGas(
publicClient,
- gasPrice ?? 0n
+ maxFeePerGas ?? 0n
)
}
- if (gasPrice === null) {
- const block = await publicClient.getBlock({
- blockTag: "latest"
- })
- gasPrice = maxPriorityFeePerGas + (block.baseFeePerGas ?? 0n)
+ if (maxFeePerGas === undefined) {
+ logger.info("failed to get maxFeePerGas, using fallback value")
+ maxFeePerGas = await getNextBaseFee(publicClient) + maxPriorityFeePerGas
}
- const defaultGasFee = getDefaultGasFee(chainId)
+ const bumpAmount = getBumpAmount(chain.id)
+ maxPriorityFeePerGas = (maxPriorityFeePerGas * bumpAmount) / 100n
+ maxFeePerGas = (maxFeePerGas * bumpAmount) / 100n
- maxPriorityFeePerGas =
- maxPriorityFeePerGas > gasPrice ? gasPrice : maxPriorityFeePerGas
+ if (maxPriorityFeePerGas === 0n) {
+ maxPriorityFeePerGas = maxFeePerGas / 200n
+ }
- return bumpTheGasPrice(chainId, {
- maxFeePerGas: gasPrice,
- maxPriorityFeePerGas:
- maxPriorityFeePerGas > defaultGasFee
- ? maxPriorityFeePerGas
- : defaultGasFee
- })
+ if (chain.id === chains.celo.id || chain.id === chains.celoAlfajores.id) { | there is a new celo chain too now no? |
alto | github_2023 | typescript | 105 | pimlicolabs | kristofgazso | @@ -219,13 +220,27 @@ export async function filterOpsAndEstimateGas(
)[Number(errorResult.args[0])]
failingOp.reason = errorResult.args[1]
- } catch (e: unknown) {
+ } catch (_e: unknown) {
logger.error(
{ error: JSON.stringify(err) },
"failed to parse error result"
)
return { simulatedOps: [], gasLimit: 0n }
}
+ } else if (e instanceof EstimateGasExecutionError) {
+ if (e.cause instanceof FeeCapTooLowError) {
+ logger.error( | should this really be an error? since we've got logic to handle it. maybe info? |
alto | github_2023 | typescript | 105 | pimlicolabs | kristofgazso | @@ -84,115 +30,103 @@ const getBumpAmount = (chainId: number) => {
return 100n
}
-const bumpTheGasPrice = (
- chainId: number,
- gasPriceParameters: GasPriceParameters
-): GasPriceParameters => {
- const bumpAmount = getBumpAmount(chainId)
-
- const result = {
- maxFeePerGas: (gasPriceParameters.maxFeePerGas * bumpAmount) / 100n,
- maxPriorityFeePerGas:
- (gasPriceParameters.maxPriorityFeePerGas * bumpAmount) / 100n
- }
-
- if (chainId === chains.celo.id || chainId === chains.celoAlfajores.id) {
- const maxFee =
- result.maxFeePerGas > result.maxPriorityFeePerGas
- ? result.maxFeePerGas
- : result.maxPriorityFeePerGas
- return {
- maxFeePerGas: maxFee,
- maxPriorityFeePerGas: maxFee
- }
- }
-
- return result
-}
-
-const estimateMaxPriorityFeePerGas = async (publicClient: PublicClient) => {
- try {
- const maxPriorityFeePerGasHex = await publicClient.request({
- method: "eth_maxPriorityFeePerGas"
- })
- return hexToBigInt(maxPriorityFeePerGasHex)
- } catch {
- return null
- }
-}
-
const getFallBackMaxPriorityFeePerGas = async (
publicClient: PublicClient,
gasPrice: bigint
-) => {
+): Promise<bigint> => {
const feeHistory = await publicClient.getFeeHistory({
blockCount: 10,
rewardPercentiles: [20],
blockTag: "latest"
})
- if (feeHistory.reward === undefined) {
+ if (feeHistory.reward === undefined || feeHistory.reward === null) {
return gasPrice
}
- const feeAverage =
- feeHistory.reward.reduce((acc, cur) => cur[0] + acc, 0n) / 10n
- return feeAverage < gasPrice ? feeAverage : gasPrice
+ const feeAverage = feeHistory.reward.reduce((acc, cur) => cur[0] + acc, 0n) / 10n
+ return minBigInt(feeAverage, gasPrice)
}
-const getGasPriceFromRpc = (publicClient: PublicClient) => {
- try {
- return publicClient.getGasPrice()
- } catch {
- return null
+/// Formula taken from: https://eips.ethereum.org/EIPS/eip-1559
+const getNextBaseFee = async (publicClient: PublicClient) => {
+ const block = await publicClient.getBlock({
+ blockTag: "latest"
+ })
+ const currentBaseFeePerGas = block.baseFeePerGas || await publicClient.getGasPrice()
+ const currentGasUsed = block.gasUsed
+ const gasTarget = block.gasLimit / 2n
+
+ if (currentGasUsed === gasTarget) {
+ return currentBaseFeePerGas
+ }
+
+ if (currentGasUsed > gasTarget) {
+ const gasUsedDelta = currentGasUsed - gasTarget
+ const baseFeePerGasDelta = maxBigInt(currentBaseFeePerGas * gasUsedDelta / gasTarget / 8n, 1n)
+ return currentBaseFeePerGas + baseFeePerGasDelta
}
+
+ const gasUsedDelta = currentGasUsed - gasTarget
+ const baseFeePerGasDelta = currentBaseFeePerGas * gasUsedDelta / gasTarget / 8n
+ return currentBaseFeePerGas - baseFeePerGasDelta
}
export async function getGasPrice(
- chainId: number,
+ chain: Chain,
publicClient: PublicClient,
+ noEip1559Support: boolean,
logger: Logger
): Promise<GasPriceParameters> {
- if (chainId === ChainId.Polygon || chainId === ChainId.Mumbai) {
- const polygonEstimate = await getPolygonGasPriceParameters(
- chainId,
- logger
- )
- if (polygonEstimate) {
- return polygonEstimate
+ let maxFeePerGas: bigint | undefined
+ let maxPriorityFeePerGas: bigint | undefined
+ if (noEip1559Support) {
+ let { gasPrice } = await publicClient.estimateFeesPerGas({ chain, type: "legacy" })
+
+ if (gasPrice === undefined) {
+ logger.info("failed to get legacy gasPrice, using fallback value") | is this constantly expected behaviour? is info the right level for this? |
alto | github_2023 | typescript | 105 | pimlicolabs | kristofgazso | @@ -84,115 +30,103 @@ const getBumpAmount = (chainId: number) => {
return 100n
}
-const bumpTheGasPrice = (
- chainId: number,
- gasPriceParameters: GasPriceParameters
-): GasPriceParameters => {
- const bumpAmount = getBumpAmount(chainId)
-
- const result = {
- maxFeePerGas: (gasPriceParameters.maxFeePerGas * bumpAmount) / 100n,
- maxPriorityFeePerGas:
- (gasPriceParameters.maxPriorityFeePerGas * bumpAmount) / 100n
- }
-
- if (chainId === chains.celo.id || chainId === chains.celoAlfajores.id) {
- const maxFee =
- result.maxFeePerGas > result.maxPriorityFeePerGas
- ? result.maxFeePerGas
- : result.maxPriorityFeePerGas
- return {
- maxFeePerGas: maxFee,
- maxPriorityFeePerGas: maxFee
- }
- }
-
- return result
-}
-
-const estimateMaxPriorityFeePerGas = async (publicClient: PublicClient) => {
- try {
- const maxPriorityFeePerGasHex = await publicClient.request({
- method: "eth_maxPriorityFeePerGas"
- })
- return hexToBigInt(maxPriorityFeePerGasHex)
- } catch {
- return null
- }
-}
-
const getFallBackMaxPriorityFeePerGas = async (
publicClient: PublicClient,
gasPrice: bigint
-) => {
+): Promise<bigint> => {
const feeHistory = await publicClient.getFeeHistory({
blockCount: 10,
rewardPercentiles: [20],
blockTag: "latest"
})
- if (feeHistory.reward === undefined) {
+ if (feeHistory.reward === undefined || feeHistory.reward === null) {
return gasPrice
}
- const feeAverage =
- feeHistory.reward.reduce((acc, cur) => cur[0] + acc, 0n) / 10n
- return feeAverage < gasPrice ? feeAverage : gasPrice
+ const feeAverage = feeHistory.reward.reduce((acc, cur) => cur[0] + acc, 0n) / 10n
+ return minBigInt(feeAverage, gasPrice)
}
-const getGasPriceFromRpc = (publicClient: PublicClient) => {
- try {
- return publicClient.getGasPrice()
- } catch {
- return null
+/// Formula taken from: https://eips.ethereum.org/EIPS/eip-1559
+const getNextBaseFee = async (publicClient: PublicClient) => {
+ const block = await publicClient.getBlock({
+ blockTag: "latest"
+ })
+ const currentBaseFeePerGas = block.baseFeePerGas || await publicClient.getGasPrice()
+ const currentGasUsed = block.gasUsed
+ const gasTarget = block.gasLimit / 2n
+
+ if (currentGasUsed === gasTarget) {
+ return currentBaseFeePerGas
+ }
+
+ if (currentGasUsed > gasTarget) {
+ const gasUsedDelta = currentGasUsed - gasTarget
+ const baseFeePerGasDelta = maxBigInt(currentBaseFeePerGas * gasUsedDelta / gasTarget / 8n, 1n)
+ return currentBaseFeePerGas + baseFeePerGasDelta
}
+
+ const gasUsedDelta = currentGasUsed - gasTarget
+ const baseFeePerGasDelta = currentBaseFeePerGas * gasUsedDelta / gasTarget / 8n
+ return currentBaseFeePerGas - baseFeePerGasDelta
}
export async function getGasPrice(
- chainId: number,
+ chain: Chain,
publicClient: PublicClient,
+ noEip1559Support: boolean,
logger: Logger
): Promise<GasPriceParameters> {
- if (chainId === ChainId.Polygon || chainId === ChainId.Mumbai) {
- const polygonEstimate = await getPolygonGasPriceParameters(
- chainId,
- logger
- )
- if (polygonEstimate) {
- return polygonEstimate
+ let maxFeePerGas: bigint | undefined
+ let maxPriorityFeePerGas: bigint | undefined
+ if (noEip1559Support) {
+ let { gasPrice } = await publicClient.estimateFeesPerGas({ chain, type: "legacy" }) | should we not be try catching all these network calls? or do you think this is not required? |
alto | github_2023 | typescript | 105 | pimlicolabs | kristofgazso | @@ -84,115 +30,103 @@ const getBumpAmount = (chainId: number) => {
return 100n
}
-const bumpTheGasPrice = (
- chainId: number,
- gasPriceParameters: GasPriceParameters
-): GasPriceParameters => {
- const bumpAmount = getBumpAmount(chainId)
-
- const result = {
- maxFeePerGas: (gasPriceParameters.maxFeePerGas * bumpAmount) / 100n,
- maxPriorityFeePerGas:
- (gasPriceParameters.maxPriorityFeePerGas * bumpAmount) / 100n
- }
-
- if (chainId === chains.celo.id || chainId === chains.celoAlfajores.id) {
- const maxFee =
- result.maxFeePerGas > result.maxPriorityFeePerGas
- ? result.maxFeePerGas
- : result.maxPriorityFeePerGas
- return {
- maxFeePerGas: maxFee,
- maxPriorityFeePerGas: maxFee
- }
- }
-
- return result
-}
-
-const estimateMaxPriorityFeePerGas = async (publicClient: PublicClient) => {
- try {
- const maxPriorityFeePerGasHex = await publicClient.request({
- method: "eth_maxPriorityFeePerGas"
- })
- return hexToBigInt(maxPriorityFeePerGasHex)
- } catch {
- return null
- }
-}
-
const getFallBackMaxPriorityFeePerGas = async (
publicClient: PublicClient,
gasPrice: bigint
-) => {
+): Promise<bigint> => {
const feeHistory = await publicClient.getFeeHistory({
blockCount: 10,
rewardPercentiles: [20],
blockTag: "latest"
})
- if (feeHistory.reward === undefined) {
+ if (feeHistory.reward === undefined || feeHistory.reward === null) {
return gasPrice
}
- const feeAverage =
- feeHistory.reward.reduce((acc, cur) => cur[0] + acc, 0n) / 10n
- return feeAverage < gasPrice ? feeAverage : gasPrice
+ const feeAverage = feeHistory.reward.reduce((acc, cur) => cur[0] + acc, 0n) / 10n
+ return minBigInt(feeAverage, gasPrice)
}
-const getGasPriceFromRpc = (publicClient: PublicClient) => {
- try {
- return publicClient.getGasPrice()
- } catch {
- return null
+/// Formula taken from: https://eips.ethereum.org/EIPS/eip-1559
+const getNextBaseFee = async (publicClient: PublicClient) => {
+ const block = await publicClient.getBlock({
+ blockTag: "latest"
+ })
+ const currentBaseFeePerGas = block.baseFeePerGas || await publicClient.getGasPrice()
+ const currentGasUsed = block.gasUsed
+ const gasTarget = block.gasLimit / 2n
+
+ if (currentGasUsed === gasTarget) {
+ return currentBaseFeePerGas
+ }
+
+ if (currentGasUsed > gasTarget) {
+ const gasUsedDelta = currentGasUsed - gasTarget
+ const baseFeePerGasDelta = maxBigInt(currentBaseFeePerGas * gasUsedDelta / gasTarget / 8n, 1n)
+ return currentBaseFeePerGas + baseFeePerGasDelta
}
+
+ const gasUsedDelta = currentGasUsed - gasTarget
+ const baseFeePerGasDelta = currentBaseFeePerGas * gasUsedDelta / gasTarget / 8n
+ return currentBaseFeePerGas - baseFeePerGasDelta
}
export async function getGasPrice(
- chainId: number,
+ chain: Chain,
publicClient: PublicClient,
+ noEip1559Support: boolean,
logger: Logger
): Promise<GasPriceParameters> {
- if (chainId === ChainId.Polygon || chainId === ChainId.Mumbai) {
- const polygonEstimate = await getPolygonGasPriceParameters(
- chainId,
- logger
- )
- if (polygonEstimate) {
- return polygonEstimate
+ let maxFeePerGas: bigint | undefined
+ let maxPriorityFeePerGas: bigint | undefined
+ if (noEip1559Support) {
+ let { gasPrice } = await publicClient.estimateFeesPerGas({ chain, type: "legacy" })
+
+ if (gasPrice === undefined) {
+ logger.info("failed to get legacy gasPrice, using fallback value")
+ gasPrice = await publicClient.getGasPrice()
+ }
+
+ return {
+ maxFeePerGas: gasPrice,
+ maxPriorityFeePerGas: gasPrice
}
}
- let [gasPrice, maxPriorityFeePerGas]: [bigint | null, bigint | null] =
- await Promise.all([
- getGasPriceFromRpc(publicClient),
- estimateMaxPriorityFeePerGas(publicClient)
- ])
+ const fees = await publicClient.estimateFeesPerGas({ chain })
+ maxFeePerGas = fees.maxFeePerGas
+ maxPriorityFeePerGas = fees.maxPriorityFeePerGas
- if (maxPriorityFeePerGas === null) {
+ if (maxPriorityFeePerGas === undefined) {
+ logger.info("failed to get maxPriorityFeePerGas, using fallback value") | is this constantly expected behaviour? is info the right level for this? |
alto | github_2023 | typescript | 95 | pimlicolabs | kristofgazso | @@ -109,18 +120,65 @@ export class NonceQueuer {
) {
const queuedUserOperations = this.queuedUserOperations.slice()
- const results = await publicClient.multicall({
- contracts: queuedUserOperations.map((qop) => {
- const userOp = deriveUserOperation(qop.mempoolUserOperation)
- return {
- address: entryPoint,
- abi: EntryPointAbi,
- functionName: "getNonce",
- args: [userOp.sender, qop.nonceKey]
- }
- }),
- blockTag: "latest"
- })
+ let results: (
+ | { | doesn't viem define a type for this? |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -53,6 +53,9 @@ export const bundlerArgsSchema = z.object({
rpcUrl: z.string().url(),
executionRpcUrl: z.string().url().optional(),
+ bundleBulkerAddress: addressSchema,
+ perOpInflatorAddress: addressSchema, | hmmm... why not the perOpInflator id? (as opposed to the address) |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -0,0 +1,76 @@
+import {
+ Address, PerOpInfaltorAbi, bundleBulkerAbi,
+} from "@alto/types"
+import { Client, getContract } from "viem"
+
+type PerOpInflator = {
+ address: Address,
+ bundleBulkerIdRegistry: Record<Address, number> // id of this PerOpInflator in each BundleBulkers
+}
+
+export class CompressionHandler {
+ whiteListedInflators: Address[]
+ entryPointToBundleBulker: Record<Address, Address>
+ perOpInflator: PerOpInflator | null
+
+ private constructor() {
+ this.whiteListedInflators = []
+ this.entryPointToBundleBulker = {} | we don't need to support multiple entrypoints — assume the one that is passed in the env variable is for this entrypoint |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -0,0 +1,76 @@
+import {
+ Address, PerOpInfaltorAbi, bundleBulkerAbi,
+} from "@alto/types"
+import { Client, getContract } from "viem"
+
+type PerOpInflator = {
+ address: Address,
+ bundleBulkerIdRegistry: Record<Address, number> // id of this PerOpInflator in each BundleBulkers
+}
+
+export class CompressionHandler {
+ whiteListedInflators: Address[]
+ entryPointToBundleBulker: Record<Address, Address>
+ perOpInflator: PerOpInflator | null
+
+ private constructor() {
+ this.whiteListedInflators = [] | if an inflator is registered to our perOpInflator we can assume it's whitelisted, no? |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -0,0 +1,76 @@
+import {
+ Address, PerOpInfaltorAbi, bundleBulkerAbi,
+} from "@alto/types"
+import { Client, getContract } from "viem"
+
+type PerOpInflator = {
+ address: Address,
+ bundleBulkerIdRegistry: Record<Address, number> // id of this PerOpInflator in each BundleBulkers
+}
+
+export class CompressionHandler {
+ whiteListedInflators: Address[]
+ entryPointToBundleBulker: Record<Address, Address>
+ perOpInflator: PerOpInflator | null
+
+ private constructor() {
+ this.whiteListedInflators = []
+ this.entryPointToBundleBulker = {}
+ this.perOpInflator = null
+ }
+
+ public static async createAsync(
+ whiteListedBundleBulkers: Address[],
+ perOpInflatorAddr: Address,
+ publicClient: Client,
+ ): Promise<CompressionHandler> {
+ const compressionHandler = new CompressionHandler()
+ const perOpInflator : PerOpInflator = {
+ address: perOpInflatorAddr,
+ bundleBulkerIdRegistry: {} as Record<Address, number>
+ }
+
+ for (const bb of whiteListedBundleBulkers) {
+ const bundleBulker = getContract({
+ address: bb,
+ abi: bundleBulkerAbi,
+ publicClient,
+ })
+
+ // find this BundleBulker's associated entrypoint
+ const entryPoint = await bundleBulker.read.ENTRY_POINT()
+ compressionHandler.entryPointToBundleBulker[entryPoint] = bundleBulker.address
+
+ // get our perOpInflator's id for this particular bundleBulker
+ const perOpInflatorId = await bundleBulker.read.inflatorToID([perOpInflatorAddr])
+
+ if (perOpInflatorId === 0) {
+ throw new Error(`can't send ops to BundleBulker ${bb}, our perOpInflator ${perOpInflatorAddr} is not registered`)
+ }
+
+ perOpInflator.bundleBulkerIdRegistry[bundleBulker.address] = perOpInflatorId
+ }
+
+ compressionHandler.perOpInflator = perOpInflator
+
+ return compressionHandler
+ }
+
+ public getPerOpInflatorAddress(): Address | undefined { | hmm this code seems very Java-like — is there a way to just mark these variables as public without implementing getters? |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -0,0 +1,79 @@
+export const bundleBulkerAbi = [
+ {
+ stateMutability: 'view',
+ type: 'function',
+ inputs: [],
+ name: 'ENTRY_POINT',
+ outputs: [{ name: '', internalType: 'address', type: 'address' }],
+ },
+ {
+ stateMutability: 'view',
+ type: 'function',
+ inputs: [{ name: '', internalType: 'uint32', type: 'uint32' }],
+ name: 'idToInflator',
+ outputs: [{ name: '', internalType: 'address', type: 'address' }],
+ },
+ {
+ stateMutability: 'view',
+ type: 'function',
+ inputs: [{ name: 'compressed', internalType: 'bytes', type: 'bytes' }],
+ name: 'inflate',
+ outputs: [
+ {
+ name: 'ops',
+ internalType: 'struct UserOperation[]',
+ type: 'tuple[]',
+ components: [
+ { name: 'sender', internalType: 'address', type: 'address' },
+ { name: 'nonce', internalType: 'uint256', type: 'uint256' },
+ { name: 'initCode', internalType: 'bytes', type: 'bytes' },
+ { name: 'callData', internalType: 'bytes', type: 'bytes' },
+ { name: 'callGasLimit', internalType: 'uint256', type: 'uint256' },
+ {
+ name: 'verificationGasLimit',
+ internalType: 'uint256',
+ type: 'uint256',
+ },
+ {
+ name: 'preVerificationGas',
+ internalType: 'uint256',
+ type: 'uint256',
+ },
+ { name: 'maxFeePerGas', internalType: 'uint256', type: 'uint256' },
+ {
+ name: 'maxPriorityFeePerGas',
+ internalType: 'uint256',
+ type: 'uint256',
+ },
+ { name: 'paymasterAndData', internalType: 'bytes', type: 'bytes' },
+ { name: 'signature', internalType: 'bytes', type: 'bytes' },
+ ],
+ },
+ { name: 'beneficiary', internalType: 'address payable', type: 'address' },
+ ],
+ },
+ {
+ stateMutability: 'view',
+ type: 'function',
+ inputs: [{ name: '', internalType: 'address', type: 'address' }],
+ name: 'inflatorToID',
+ outputs: [{ name: '', internalType: 'uint32', type: 'uint32' }],
+ },
+ {
+ stateMutability: 'nonpayable',
+ type: 'function',
+ inputs: [
+ { name: 'inflatorId', internalType: 'uint32', type: 'uint32' },
+ { name: 'inflator', internalType: 'address', type: 'address' },
+ ],
+ name: 'registerInflator',
+ outputs: [],
+ },
+ { | this is the old signature, now submit is instead through the fallback function |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -43,21 +49,20 @@ export interface GasEstimateResult {
export type ReplaceTransactionResult =
| {
- status: "replaced"
- transactionInfo: TransactionInfo
- }
+ status: "replaced"
+ transactionInfo: TransactionInfo
+ }
| {
- status: "potentially_already_included"
- }
+ status: "potentially_already_included"
+ }
| {
- status: "failed"
- }
+ status: "failed"
+ }
export interface IExecutor {
bundle(entryPoint: Address, ops: UserOperation[]): Promise<BundleResult[]>
- replaceTransaction(
- transactionInfo: TransactionInfo
- ): Promise<ReplaceTransactionResult>
+ bundleCompressed(compressedOps: CompressedUserOp): Promise<BundleResult[]> | should the sig not include the entryPoint here too? |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -168,10 +174,18 @@ export class BasicExecutor implements IExecutor {
walletClient: this.walletClient
})
+ const opsWithHashes = transactionInfo.userOperationInfos.map((_op) => {
+ const op = _op.mempoolUserOp.getUserOperation() | we don't use _ syntax elsewhere in the codebase |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -549,6 +563,172 @@ export class BasicExecutor implements IExecutor {
this.metrics.bundlesSubmitted.inc()
+ return userOperationResults
+ }
+
+async bundleCompressed(compressedOp: CompressedUserOp): Promise<BundleResult[]> {
+ const wallet = await this.senderManager.getWallet()
+
+ const { entryPointAddr, bundleBulkerAddr, inflatedUserOp, inflatorAddr } = compressedOp
+ const inflatedOps = [inflatedUserOp] // temp quick fix | yeah let's add multiple op support hah |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -549,6 +563,172 @@ export class BasicExecutor implements IExecutor {
this.metrics.bundlesSubmitted.inc()
+ return userOperationResults
+ }
+
+async bundleCompressed(compressedOp: CompressedUserOp): Promise<BundleResult[]> {
+ const wallet = await this.senderManager.getWallet()
+
+ const { entryPointAddr, bundleBulkerAddr, inflatedUserOp, inflatorAddr } = compressedOp
+ const inflatedOps = [inflatedUserOp] // temp quick fix
+
+ const ep = getContract({
+ abi: EntryPointAbi,
+ address: entryPointAddr,
+ publicClient: this.publicClient,
+ walletClient: this.walletClient
+ })
+
+ const childLogger = this.logger.child({
+ compressedUserOperations: compressedOp,
+ entryPoint: entryPointAddr
+ })
+ childLogger.debug("bundling compressed user operation")
+
+ const gasPriceParameters = await getGasPrice(this.walletClient.chain.id, this.publicClient, this.logger)
+ childLogger.debug({ gasPriceParameters }, "got gas price")
+
+ const nonce = await this.publicClient.getTransactionCount({
+ address: wallet.address,
+ blockTag: "pending"
+ })
+ childLogger.trace({ nonce }, "got nonce") | hmm this whole big block of code is mostly copied — is there a way to apply DRY more? |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -549,6 +563,172 @@ export class BasicExecutor implements IExecutor {
this.metrics.bundlesSubmitted.inc()
+ return userOperationResults
+ }
+
+async bundleCompressed(compressedOp: CompressedUserOp): Promise<BundleResult[]> {
+ const wallet = await this.senderManager.getWallet()
+
+ const { entryPointAddr, bundleBulkerAddr, inflatedUserOp, inflatorAddr } = compressedOp
+ const inflatedOps = [inflatedUserOp] // temp quick fix
+
+ const ep = getContract({
+ abi: EntryPointAbi,
+ address: entryPointAddr,
+ publicClient: this.publicClient,
+ walletClient: this.walletClient
+ })
+
+ const childLogger = this.logger.child({
+ compressedUserOperations: compressedOp,
+ entryPoint: entryPointAddr
+ })
+ childLogger.debug("bundling compressed user operation")
+
+ const gasPriceParameters = await getGasPrice(this.walletClient.chain.id, this.publicClient, this.logger)
+ childLogger.debug({ gasPriceParameters }, "got gas price")
+
+ const nonce = await this.publicClient.getTransactionCount({
+ address: wallet.address,
+ blockTag: "pending"
+ })
+ childLogger.trace({ nonce }, "got nonce")
+
+ let runningGasTotal = 0n
+ let opsToBundle: UserOperationWithHash[] = []
+
+ const { gasLimit, simulatedOps } = await filterOpsAndEstimateGas(
+ ep,
+ wallet,
+ inflatedOps.map((op) => {
+ return {
+ userOperation: op,
+ userOperationHash: getUserOperationHash(op, entryPointAddr, this.walletClient.chain.id)
+ }
+ }),
+ nonce,
+ gasPriceParameters.maxFeePerGas,
+ gasPriceParameters.maxPriorityFeePerGas,
+ "pending",
+ this.noEip1559Support,
+ this.customGasLimitForEstimation,
+ this.reputationManager,
+ childLogger
+ )
+
+ if (simulatedOps.length === 0) {
+ childLogger.warn("no ops to bundle")
+ this.markWalletProcessed(wallet)
+ return inflatedOps.map((op) => {
+ return {
+ success: false,
+ error: {
+ userOpHash: getUserOperationHash(op, entryPointAddr, this.walletClient.chain.id),
+ reason: "INTERNAL FAILURE"
+ }
+ }
+ })
+ }
+
+ // if not all succeeded, return error
+ if (simulatedOps.some((op) => op.reason !== undefined)) {
+ childLogger.warn("some ops failed simulation")
+ this.markWalletProcessed(wallet)
+ return simulatedOps.map((op) => {
+ return {
+ success: false,
+ error: {
+ userOpHash: op.op.userOperationHash,
+ reason: op.reason as string
+ }
+ }
+ })
+ }
+
+ opsToBundle = simulatedOps.filter((op) => op.reason === undefined).map((op) => op.op)
+ runningGasTotal += gasLimit
+
+
+ const inflateGasOverhead = await this.publicClient.estimateGas({ | this seems a bit weird — why not just modify the filterOpsAndEstimateGas to estimate gas throught the whole bundleBulker when compressed ops are being used, that way estimation will be done by the native eth_estimateGas call |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -549,6 +563,172 @@ export class BasicExecutor implements IExecutor {
this.metrics.bundlesSubmitted.inc()
+ return userOperationResults
+ }
+
+async bundleCompressed(compressedOp: CompressedUserOp): Promise<BundleResult[]> {
+ const wallet = await this.senderManager.getWallet()
+
+ const { entryPointAddr, bundleBulkerAddr, inflatedUserOp, inflatorAddr } = compressedOp
+ const inflatedOps = [inflatedUserOp] // temp quick fix
+
+ const ep = getContract({
+ abi: EntryPointAbi,
+ address: entryPointAddr,
+ publicClient: this.publicClient,
+ walletClient: this.walletClient
+ })
+
+ const childLogger = this.logger.child({
+ compressedUserOperations: compressedOp,
+ entryPoint: entryPointAddr
+ })
+ childLogger.debug("bundling compressed user operation")
+
+ const gasPriceParameters = await getGasPrice(this.walletClient.chain.id, this.publicClient, this.logger)
+ childLogger.debug({ gasPriceParameters }, "got gas price")
+
+ const nonce = await this.publicClient.getTransactionCount({
+ address: wallet.address,
+ blockTag: "pending"
+ })
+ childLogger.trace({ nonce }, "got nonce")
+
+ let runningGasTotal = 0n
+ let opsToBundle: UserOperationWithHash[] = []
+
+ const { gasLimit, simulatedOps } = await filterOpsAndEstimateGas(
+ ep,
+ wallet,
+ inflatedOps.map((op) => {
+ return {
+ userOperation: op,
+ userOperationHash: getUserOperationHash(op, entryPointAddr, this.walletClient.chain.id)
+ }
+ }),
+ nonce,
+ gasPriceParameters.maxFeePerGas,
+ gasPriceParameters.maxPriorityFeePerGas,
+ "pending",
+ this.noEip1559Support,
+ this.customGasLimitForEstimation,
+ this.reputationManager,
+ childLogger
+ )
+
+ if (simulatedOps.length === 0) {
+ childLogger.warn("no ops to bundle")
+ this.markWalletProcessed(wallet)
+ return inflatedOps.map((op) => {
+ return {
+ success: false,
+ error: {
+ userOpHash: getUserOperationHash(op, entryPointAddr, this.walletClient.chain.id),
+ reason: "INTERNAL FAILURE"
+ }
+ }
+ })
+ }
+
+ // if not all succeeded, return error
+ if (simulatedOps.some((op) => op.reason !== undefined)) {
+ childLogger.warn("some ops failed simulation")
+ this.markWalletProcessed(wallet)
+ return simulatedOps.map((op) => {
+ return {
+ success: false,
+ error: {
+ userOpHash: op.op.userOperationHash,
+ reason: op.reason as string
+ }
+ }
+ })
+ }
+
+ opsToBundle = simulatedOps.filter((op) => op.reason === undefined).map((op) => op.op)
+ runningGasTotal += gasLimit
+
+
+ const inflateGasOverhead = await this.publicClient.estimateGas({
+ account: wallet,
+ to: inflatorAddr,
+ data: encodeFunctionData(
+ { abi: InflatorAbi, functionName: "inflate", args: [compressedOp.compressedCalldata] }
+ )
+ })
+
+ runningGasTotal += inflateGasOverhead + 20000n // 20k fixed overhead for passing through BundleBulker to inflator
+
+ let txHash: HexData32
+ try {
+ const gasOptions = this.noEip1559Support
+ ? {
+ gasPrice: gasPriceParameters.maxFeePerGas,
+ }
+ : {
+ maxFeePerGas: gasPriceParameters.maxFeePerGas,
+ maxPriorityFeePerGas: gasPriceParameters.maxPriorityFeePerGas,
+ };
+
+ // need to use sendTransction to target BundleBulker's fallback
+ txHash = await this.walletClient.sendTransaction({
+ account: wallet,
+ to: bundleBulkerAddr,
+ data: compressedOp.bundleBulkerCalldata(),
+ gas: runningGasTotal,
+ nonce: nonce,
+ ...gasOptions
+ })
+ } catch (err: unknown) {
+ sentry.captureException(err)
+ childLogger.error({ error: JSON.stringify(err) }, "error submitting bundle transaction")
+ this.markWalletProcessed(wallet)
+ return []
+ }
+
+ const userOperationInfos = opsToBundle.map((op) => {
+ this.metrics.userOperationsSubmitted.inc()
+
+ return {
+ mempoolUserOp: new NormalMempoolUserOp(op.userOperation),
+ userOperationHash: op.userOperationHash,
+ compressedBytes: compressedOp,
+ lastReplaced: Date.now(),
+ firstSubmitted: Date.now()
+ }
+ })
+
+ const transactionInfo: TransactionInfo = {
+ transactionHash: txHash,
+ previousTransactionHashes: [],
+ transactionRequest: {
+ address: ep.address,
+ abi: ep.abi, | if this is how we return the transactionInfo then during resubmission the resubmitted ops will be resubmitted non-compressed, directly through the entryPoint. we have to change the `transactionRequest` to be the compressed ops through the bulker no? |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -101,8 +103,24 @@ export class ExecutorManager {
return txHash
}
- async sendToExecutor(ops: UserOperation[]) {
- const results = await this.executor.bundle(this.entryPointAddress, ops)
+ async sendToExecutor(ops: MempoolUserOp[]) {
+ const normalOps = [];
+ const compressedOps = [];
+
+ for (const memOp of ops) {
+ if (memOp instanceof NormalMempoolUserOp) {
+ normalOps.push(memOp.getUserOperation());
+ } else if (memOp instanceof CompressedMempoolUserOp) {
+ compressedOps.push(memOp.compressedUserOp);
+ }
+ }
+
+ const results = []
+ results.push(... await this.executor.bundle(this.entryPointAddress, normalOps))
+ for (const compressedOp of compressedOps) {
+ results.push(... await this.executor.bundleCompressed(compressedOp)) | uhh... can we do this without this weird for loop? |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -910,4 +928,151 @@ export class RpcHandler implements IRpcEndpoint {
}
}
}
+
+ async pimlico_sendCompressedUserOperation(
+ compressedCalldata: Hex,
+ entryPoint: Address,
+ inflator: Address
+ ) {
+ // check if inflator is registered with our PerOpInflator.
+ const inflatorId = await this.compressionHandler.getInflatorRegisteredId(inflator, this.publicClient)
+
+ if (inflatorId === 0) {
+ throw new RpcError(`Inflator ${inflator} has not been registered`, ValidationErrors.InvalidFields)
+ }
+
+ // infalte + start to validate user op.
+ const inflatorContract = getContract({
+ address: inflator,
+ abi: InflatorAbi,
+ publicClient: this.publicClient,
+ })
+
+ const inflatedOps = (await inflatorContract.read.inflate([compressedCalldata]))[0]; | let's handle the error here? |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -910,4 +928,151 @@ export class RpcHandler implements IRpcEndpoint {
}
}
}
+
+ async pimlico_sendCompressedUserOperation(
+ compressedCalldata: Hex,
+ entryPoint: Address,
+ inflator: Address
+ ) {
+ // check if inflator is registered with our PerOpInflator.
+ const inflatorId = await this.compressionHandler.getInflatorRegisteredId(inflator, this.publicClient)
+
+ if (inflatorId === 0) {
+ throw new RpcError(`Inflator ${inflator} has not been registered`, ValidationErrors.InvalidFields)
+ }
+
+ // infalte + start to validate user op.
+ const inflatorContract = getContract({
+ address: inflator,
+ abi: InflatorAbi,
+ publicClient: this.publicClient,
+ })
+
+ const inflatedOps = (await inflatorContract.read.inflate([compressedCalldata]))[0];
+
+ if (inflatedOps.length !== 1) {
+ throw new RpcError("Endpoint currenlty only supports one compressed UserOperation", ValidationErrors.InvalidFields)
+ }
+
+ const inflatedOp = inflatedOps[0]
+
+ // check userOps inputs.
+ if (inflatedOp.verificationGasLimit < 10000n) { | hmm should we put this in a function to apply DRY principles? |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -910,4 +928,151 @@ export class RpcHandler implements IRpcEndpoint {
}
}
}
+
+ async pimlico_sendCompressedUserOperation(
+ compressedCalldata: Hex,
+ entryPoint: Address,
+ inflator: Address
+ ) {
+ // check if inflator is registered with our PerOpInflator.
+ const inflatorId = await this.compressionHandler.getInflatorRegisteredId(inflator, this.publicClient)
+
+ if (inflatorId === 0) {
+ throw new RpcError(`Inflator ${inflator} has not been registered`, ValidationErrors.InvalidFields)
+ }
+
+ // infalte + start to validate user op.
+ const inflatorContract = getContract({
+ address: inflator,
+ abi: InflatorAbi,
+ publicClient: this.publicClient,
+ })
+
+ const inflatedOps = (await inflatorContract.read.inflate([compressedCalldata]))[0];
+
+ if (inflatedOps.length !== 1) {
+ throw new RpcError("Endpoint currenlty only supports one compressed UserOperation", ValidationErrors.InvalidFields)
+ }
+
+ const inflatedOp = inflatedOps[0]
+
+ // check userOps inputs.
+ if (inflatedOp.verificationGasLimit < 10000n) {
+ throw new RpcError("verificationGasLimit must be at least 10000")
+ }
+
+ if (this.minimumGasPricePercent !== 0) {
+ const gasPrice = await getGasPrice(
+ this.chainId,
+ this.publicClient,
+ this.logger
+ )
+ const minMaxFeePerGas =
+ (gasPrice.maxFeePerGas * BigInt(this.minimumGasPricePercent)) /
+ 100n
+ if (inflatedOp.maxFeePerGas < minMaxFeePerGas) {
+ throw new RpcError(
+ `maxFeePerGas must be at least ${minMaxFeePerGas} (current maxFeePerGas: ${gasPrice.maxFeePerGas}) - use pimlico_getUserOperationGasPrice to get the current gas price`
+ )
+ }
+
+ if (inflatedOp.maxPriorityFeePerGas < minMaxFeePerGas) {
+ throw new RpcError(
+ `maxPriorityFeePerGas must be at least ${minMaxFeePerGas} (current maxPriorityFeePerGas: ${gasPrice.maxPriorityFeePerGas}) - use pimlico_getUserOperationGasPrice to get the current gas price`
+ )
+ }
+ }
+
+ this.logger.trace({ inflatedOp, entryPoint }, "beginning validation on compressed userOp")
+
+ if (
+ inflatedOp.preVerificationGas === 0n ||
+ inflatedOp.verificationGasLimit === 0n ||
+ inflatedOp.callGasLimit === 0n
+ ) {
+ throw new RpcError(
+ "user operation gas limits must be larger than 0"
+ )
+ }
+
+ // check if perUseropIsRegisterd to target BundleBulker
+ const bundleBulker = this.compressionHandler.entryPointToBundleBulker[entryPoint] | as we talked about, we can just assume this is the case |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -0,0 +1,42 @@
+import { Hex, concat, toHex } from "viem"
+import { Address, UserOperation } from "./schemas"
+
+// Type that knows how to encode/decode itself
+export class CompressedUserOp {
+ compressedCalldata: Hex
+ inflatedUserOp: UserOperation
+ inflatorAddr: Address
+ bundleBulkerAddr: Address
+ entryPointAddr: Address
+ inflatorId: number // id of targetInflator in PerOpInflator
+ perOpInflatorId: number // id of PerOpInflator in BundleBulker
+
+ // ideally this type should derive id's / addresses by itself instead of taking them in as inputs
+ constructor(
+ compressedCalldata : Hex,
+ inflatedUserOp: UserOperation,
+ bundleBulkerAddr: Address,
+ entryPointAddr: Address,
+ inflatorAddr: Address,
+ inflatorId: number,
+ perOpInflatorId: number
+ ) { | should entryPointAddr, bundleBulkerAddr, perOpInflatorId really live inside this struct/class? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.