eth-compress 0.0.0-security → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +136 -0
- package/_cjs/index.cjs +3 -0
- package/_cjs/index.cjs.map +7 -0
- package/_cjs/index.node.cjs +3 -0
- package/_cjs/index.node.cjs.map +7 -0
- package/_cjs/jit-compressor.cjs +6 -0
- package/_cjs/jit-compressor.cjs.map +7 -0
- package/_esm/index.js +3 -0
- package/_esm/index.js.map +7 -0
- package/_esm/index.node.js +3 -0
- package/_esm/index.node.js.map +7 -0
- package/_esm/jit-compressor.js +6 -0
- package/_esm/jit-compressor.js.map +7 -0
- package/_types/index.d.ts +35 -0
- package/_types/index.d.ts.map +1 -0
- package/_types/index.node.d.ts +2 -0
- package/_types/index.node.d.ts.map +1 -0
- package/_types/jit-compressor.d.ts +30 -0
- package/_types/jit-compressor.d.ts.map +1 -0
- package/index.node.ts +61 -0
- package/index.ts +114 -0
- package/jit-compressor.ts +443 -0
- package/package.json +134 -12
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025, Tadpole Labs Ltd.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
OR
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
Apache License
|
|
28
|
+
Version 2.0, January 2004
|
|
29
|
+
http://www.apache.org/licenses/
|
|
30
|
+
|
|
31
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
32
|
+
|
|
33
|
+
1. Definitions.
|
|
34
|
+
|
|
35
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
36
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
37
|
+
|
|
38
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
39
|
+
the copyright owner that is granting the License.
|
|
40
|
+
|
|
41
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
42
|
+
other entities that control, are controlled by, or are under common
|
|
43
|
+
control with that entity. For the purposes of this definition,
|
|
44
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
45
|
+
direction or management of such entity, whether by contract or
|
|
46
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
47
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
48
|
+
|
|
49
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
50
|
+
exercising permissions granted by this License.
|
|
51
|
+
|
|
52
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
53
|
+
including but not limited to software source code, documentation
|
|
54
|
+
source, and configuration files.
|
|
55
|
+
|
|
56
|
+
"Object" form shall mean any form resulting from mechanical
|
|
57
|
+
transformation or translation of a Source form, including but
|
|
58
|
+
not limited to compiled object code, generated documentation,
|
|
59
|
+
and conversions to other media types.
|
|
60
|
+
|
|
61
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
62
|
+
Object form, made available under the License, as indicated by a
|
|
63
|
+
copyright notice that is included in or attached to the work
|
|
64
|
+
(an example is provided in the Appendix below).
|
|
65
|
+
|
|
66
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
67
|
+
form, that is based on (or derived from) the Work and for which the
|
|
68
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
69
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
70
|
+
of this License, Derivative Works shall not include works that remain
|
|
71
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
72
|
+
the Work and Derivative Works thereof.
|
|
73
|
+
|
|
74
|
+
"Contribution" shall mean any work of authorship, including
|
|
75
|
+
the original version of the Work and any modifications or additions
|
|
76
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
77
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
78
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
79
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
80
|
+
means any form of electronic, verbal, or written communication sent
|
|
81
|
+
to the Licensor or its representatives, including but not limited to
|
|
82
|
+
communication on electronic mailing lists, source code control systems,
|
|
83
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
84
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
85
|
+
excluding communication that is conspicuously marked or otherwise
|
|
86
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
87
|
+
|
|
88
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
89
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
90
|
+
subsequently incorporated within the Work.
|
|
91
|
+
|
|
92
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
93
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
94
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
95
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
96
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
97
|
+
Work and such Derivative Works in Source or Object form.
|
|
98
|
+
|
|
99
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
100
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
101
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
102
|
+
(except as stated in this section) patent license to make, have made,
|
|
103
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
104
|
+
where such license applies only to those patent claims licensable
|
|
105
|
+
by such Contributor that are necessarily infringed by their
|
|
106
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
107
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
108
|
+
institute patent litigation against any entity (including a
|
|
109
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
110
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
111
|
+
or contributory patent infringement, then any patent licenses
|
|
112
|
+
granted to You under this License for that Work shall terminate
|
|
113
|
+
as of the date such litigation is filed.
|
|
114
|
+
|
|
115
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
116
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
117
|
+
modifications, and in Source or Object form, provided that You
|
|
118
|
+
meet the following conditions:
|
|
119
|
+
|
|
120
|
+
(a) You must give any other recipients of the Work or
|
|
121
|
+
Derivative Works a copy of this License; and
|
|
122
|
+
|
|
123
|
+
(b) You must cause any modified files to carry prominent notices
|
|
124
|
+
stating that You changed the files; and
|
|
125
|
+
|
|
126
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
127
|
+
that You distribute, all copyright, patent, trademark, and
|
|
128
|
+
attribution notices from the Source form of the Work,
|
|
129
|
+
excluding those notices that do not pertain to any part of
|
|
130
|
+
the Derivative Works; and
|
|
131
|
+
|
|
132
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
133
|
+
distribution, then any Derivative Works that You distribute must
|
|
134
|
+
include a readable copy of the attribution notices contained
|
|
135
|
+
within such NOTICE file, excluding those notices that do not
|
|
136
|
+
pertain to any part of the Derivative Works, in at least one
|
|
137
|
+
of the following places: within a NOTICE text file distributed
|
|
138
|
+
as part of the Derivative Works; within the Source form or
|
|
139
|
+
documentation, if provided along with the Derivative Works; or,
|
|
140
|
+
within a display generated by the Derivative Works, if and
|
|
141
|
+
wherever such third-party notices normally appear. The contents
|
|
142
|
+
of the NOTICE file are for informational purposes only and
|
|
143
|
+
do not modify the License. You may add Your own attribution
|
|
144
|
+
notices within Derivative Works that You distribute, alongside
|
|
145
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
146
|
+
that such additional attribution notices cannot be construed
|
|
147
|
+
as modifying the License.
|
|
148
|
+
|
|
149
|
+
You may add Your own copyright statement to Your modifications and
|
|
150
|
+
may provide additional or different license terms and conditions
|
|
151
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
152
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
153
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
154
|
+
the conditions stated in this License.
|
|
155
|
+
|
|
156
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
157
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
158
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
159
|
+
this License, without any additional terms or conditions.
|
|
160
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
161
|
+
the terms of any separate license agreement you may have executed
|
|
162
|
+
with Licensor regarding such Contributions.
|
|
163
|
+
|
|
164
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
165
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
166
|
+
except as required for reasonable and customary use in describing the
|
|
167
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
168
|
+
|
|
169
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
170
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
171
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
172
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
173
|
+
implied, including, without limitation, any warranties or conditions
|
|
174
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
175
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
176
|
+
appropriateness of using or redistributing the Work and assume any
|
|
177
|
+
risks associated with Your exercise of permissions under this License.
|
|
178
|
+
|
|
179
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
180
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
181
|
+
unless required by applicable law (such as deliberate and grossly
|
|
182
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
183
|
+
liable to You for damages, including any direct, indirect, special,
|
|
184
|
+
incidental, or consequential damages of any character arising as a
|
|
185
|
+
result of this License or out of the use or inability to use the
|
|
186
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
187
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
188
|
+
other commercial damages or losses), even if such Contributor
|
|
189
|
+
has been advised of the possibility of such damages.
|
|
190
|
+
|
|
191
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
192
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
193
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
194
|
+
or other liability obligations and/or rights consistent with this
|
|
195
|
+
License. However, in accepting such obligations, You may act only
|
|
196
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
197
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
198
|
+
defend, and hold each Contributor harmless for any liability
|
|
199
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
200
|
+
of your accepting any such warranty or additional liability.
|
|
201
|
+
|
|
202
|
+
END OF TERMS AND CONDITIONS
|
package/README.md
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
## eth-compress
|
|
2
|
+
|
|
3
|
+
Compact client-side module for compressing Ethereum JSON-RPC requests, targeting **lower latency** and gas-efficient **read-only calls** with large calldata.
|
|
4
|
+
|
|
5
|
+
It combines [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110.html#section-12.5.3)-compliant negotiation for client-to-server compression, with optional JIT-compiled calldata compression for `eth_call`s.
|
|
6
|
+
|
|
7
|
+
_Plug'n Play with viem & with a simple API_
|
|
8
|
+
|
|
9
|
+
### Scope
|
|
10
|
+
- **Only read-only `eth_call`'s are considered**
|
|
11
|
+
- Compression is only attempted above a size threshold (currently 800 bytes), and only applied if it strictly reduces total request size.
|
|
12
|
+
- The transform re-targets the call through a decompressor contract and forwards calldata to the original `to` address.
|
|
13
|
+
- For reference: Large eth_call's >70kb at a <40% compression ratio result in roughly 30-40% latency reduction. (precise benefits largely depend on a variety of factors, non-the-less the said estimate is a sane projection for the average case)
|
|
14
|
+
|
|
15
|
+
### Installation
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm i eth-compress
|
|
19
|
+
```
|
|
20
|
+
---
|
|
21
|
+
### HTTP request compression
|
|
22
|
+
|
|
23
|
+
`eth-compress` exposes a `fetch`-compatible function that transparently compresses JSON-RPC request bodies using standard HTTP content-encoding.
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import { compressModule } from 'eth-compress';
|
|
27
|
+
|
|
28
|
+
const response = await compressModule('https://rpc.example.org', {
|
|
29
|
+
method: 'POST',
|
|
30
|
+
body: JSON.stringify({
|
|
31
|
+
jsonrpc: '2.0',
|
|
32
|
+
id: 1,
|
|
33
|
+
method: 'eth_call',
|
|
34
|
+
params: [/* ... */],
|
|
35
|
+
}),
|
|
36
|
+
});
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### How it works
|
|
40
|
+
|
|
41
|
+
- On the first request to a given RPC URL, inspects the `Accept-Encoding` response header to discover supported encodings, then compresses subsequent request bodies via
|
|
42
|
+
[`CompressionStreams API`](https://developer.mozilla.org/en-US/docs/Web/API/Compression_Streams_API)
|
|
43
|
+
(browser) or a [Node.js polyfill](https://github.com/tadpole-labs/eth-compress/blob/main/src/index.node.ts).
|
|
44
|
+
- Designed as the client-side piece for future client-to-server compression support in RPC nodes;
|
|
45
|
+
- Falls back to plain `fetch` & EVM-based compression if not supported by the RPC (see below).
|
|
46
|
+
|
|
47
|
+
<br>
|
|
48
|
+
|
|
49
|
+
----
|
|
50
|
+
### viem integration
|
|
51
|
+
|
|
52
|
+
`compressModule` and `compressModuleWithJIT` can be used as drop-in `fetchFn` modules for viem's `http` transport.
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
import { createPublicClient, http } from 'viem';
|
|
56
|
+
import { base } from 'viem/chains';
|
|
57
|
+
import { compressModule, compressModuleWithJIT } from 'eth-compress';
|
|
58
|
+
|
|
59
|
+
// HTTP compression only
|
|
60
|
+
const httpCompressedClient = createPublicClient({
|
|
61
|
+
chain: base,
|
|
62
|
+
transport: http(rpcUrl, {
|
|
63
|
+
fetchFn: compressModule,
|
|
64
|
+
}),
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
// HTTP compression + eth_call JIT calldata compression
|
|
68
|
+
const jitCompressedClient = createPublicClient({
|
|
69
|
+
chain: base,
|
|
70
|
+
transport: http(rpcUrl, {
|
|
71
|
+
fetchFn: compressModuleWithJIT,
|
|
72
|
+
}),
|
|
73
|
+
});
|
|
74
|
+
```
|
|
75
|
+
#### thats it.
|
|
76
|
+
----
|
|
77
|
+
### Compatibility
|
|
78
|
+
- Preserves viem semantics: responses and error handling are unchanged; only the request path is compressed.
|
|
79
|
+
- Works in Node and modern browsers that support the `CompressionStreams API` (Chrome/Edge ≥ 80, Firefox ≥ 113, Safari/iOS ≥ 16.4).
|
|
80
|
+
|
|
81
|
+
<br>
|
|
82
|
+
|
|
83
|
+
----
|
|
84
|
+
|
|
85
|
+
### eth_call JIT calldata compression
|
|
86
|
+
|
|
87
|
+
For backwards compatibility and immediate benefit, calldata compression is implemented on the application layer: requests are rewritten client-side and executed as usual by existing nodes.
|
|
88
|
+
The goal here is the same: **reduce request size -> latency** for large `eth_call` payloads, and secondarily to **stay under eth_call gas/memory limits** by reducing calldata size and gas footprint.
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
import { compress_call } from 'eth-compress/compressor';
|
|
92
|
+
|
|
93
|
+
const payload = {
|
|
94
|
+
method: 'eth_call',
|
|
95
|
+
params: [
|
|
96
|
+
{
|
|
97
|
+
to: '0x…',
|
|
98
|
+
data: '0x…', // potentially large calldata
|
|
99
|
+
},
|
|
100
|
+
'latest',
|
|
101
|
+
],
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
const compressedPayload = compress_call(payload); // safe to send instead of `payload`
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
`compress_call` can be used directly or via `compressModuleWithJIT` (which feeds it into `compressModule` as a payload transform).
|
|
108
|
+
For eligible `eth_call`s it chooses between:
|
|
109
|
+
|
|
110
|
+
- **JIT**: Compiles just-in-time, a one-off decompressor contract that reconstructs calldata to forward the call.
|
|
111
|
+
- **FLZ / CD**: Uses `LibZip.flzCompress` and `LibZip.cdCompress` from `solady` for fast LZ and calldata RLE compression.
|
|
112
|
+
|
|
113
|
+
Selection logic (subject to change, but current behaviour):
|
|
114
|
+
|
|
115
|
+
- **Size gating**:
|
|
116
|
+
- `< 1150 bytes`: no compression.
|
|
117
|
+
- `≥ 1150 bytes`: compression considered.
|
|
118
|
+
- `3000 ≥ 1150 bytes or > 8000`: JIT is preferred.
|
|
119
|
+
- `8000 ≥ size ≥ 3000`: FastLZ or RLE.
|
|
120
|
+
|
|
121
|
+
- **Algorithm choice**:
|
|
122
|
+
- For mid-sized payloads, FLZ and CD are tried and the smaller output is chosen.
|
|
123
|
+
- For larger payloads, JIT is used directly, focusing on gas-efficient decompression.
|
|
124
|
+
- The thresholds are chosen with consideration for request header overhead & latency,
|
|
125
|
+
aiming to keep the total request size within the [Ethernet MTU](https://en.wikipedia.org/wiki/Maximum_transmission_unit).
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
### Implementation notes & compression flavours
|
|
129
|
+
- **JIT calldata compiler (`compress_call` JIT mode)**: Views the calldata as a zero‑initialized memory image and synthesises bytecode that rebuilds it word-by-word in-place. In the first pass it walks the data in 32-byte slices, detects non-zero segments per word, and for each word chooses the cheapest of three strategies: store a literal tail, assemble segments using SHL/OR, or reuse an earlier word via MLOAD/MSTORE, under a rough opcode-count cost model. In the second pass it materialises this plan into concrete PUSH/MSTORE/SHL/OR/DUP opcodes, pre-seeds the stack with frequently used constants, and appends a small CALL/RETURNDATA stub that forwards the reconstructed calldata to the original `to` address. The execution is realized through a `stateDiff` passed together with the eth_call. The 4‑byte selector is right‑aligned in the first 32‑byte slot so that the rest of the calldata can be reconstructed on mostly word‑aligned boundaries, with the decompressor stateDiff being placed at `0x00000000000000000000000000000000000000e0` such that `0xe0` can be obtained from `ADDRESS` with a single opcode instead of an explicit literal. Achieves higher compression ratios compared to both FastLZ & Run-Length-Encoding (-10-15%) for smaller calldata <3kb, and roughly on par above 8kb (except in cases with deeply nested calls and types, minimally worse), at a fraction of the gas footprint (<5%).
|
|
130
|
+
|
|
131
|
+
- **FastLZ path (`LibZip.flzCompress` / `flzDecompress`)**: Implements a minimal LZ77-style compressor over raw bytes with a 3-byte rolling window. Each 24-bit chunk is hashed into a tiny table; repeated substrings within a bounded look-back distance are emitted as (length, distance) match tokens, and everything else is emitted as literal runs. Decompression is a simple loop over this stream that copies literals and then copies `length` bytes from `distance` bytes back in the already-produced output.
|
|
132
|
+
|
|
133
|
+
- **Calldata RLE path (`LibZip.cdCompress` / `cdDecompress`)**: Targets the two most common runs in calldata—long stretches of `0x00` and shorter stretches of `0xff`—and turns them into compact `[marker][control]` pairs, where the control byte encodes which value and how many repetitions to emit. Bytes that are not part of such runs are left verbatim, so the decoder can just scan the stream and either expand a run or forward a single byte.
|
|
134
|
+
|
|
135
|
+
Both the FastLZ and calldata-RLE forwarders are minimally adopted from Solady's [`LibZip.sol`](https://github.com/Vectorized/solady/blob/main/src/utils/LibZip.sol) and inlined as raw bytecode. To avoid Solidity's wrapper overhead the code is compiled from pure yul.
|
|
136
|
+
|
package/_cjs/index.cjs
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
var W=Object.defineProperty;var ht=Object.getOwnPropertyDescriptor;var xt=Object.getOwnPropertyNames;var yt=Object.prototype.hasOwnProperty;var wt=(e,n)=>()=>(e&&(n=e(e=0)),n);var st=(e,n)=>{for(var o in n)W(e,o,{get:n[o],enumerable:!0})},Mt=(e,n,o,a)=>{if(n&&typeof n=="object"||typeof n=="function")for(let u of xt(n))!yt.call(e,u)&&u!==o&&W(e,u,{get:()=>n[u],enumerable:!(a=ht(n,u))||a.enumerable});return e};var St=e=>Mt(W({},"__esModule",{value:!0}),e);var ut={};st(ut,{compress_call:()=>Ct,flzFwdBytecode:()=>it,jitBytecode:()=>At,rleFwdBytecode:()=>ct});var X,Rt,_,_t,rt,it,ct,At,ft,It,Z,ot,$,V,Ct,lt=wt(()=>{X=require("solady"),Rt=(1n<<128n)-1n,_=e=>e.replace(/^0x/,"").toLowerCase(),_t=e=>{let n=_(e),o=n.length,a=new Uint8Array(o/2);for(let u=0;u<o;u+=2)a[u/2]=Number.parseInt(n.slice(u,u+2),16);return a},rt=e=>{let n="";for(let o=0;o<e.length;o++)n+=e[o].toString(16).padStart(2,"0");return n};it=e=>`0x365f73${_(e)}815b838110602f575f80848134865af1503d5f803e3d5ff35b803590815f1a8060051c908115609857600190600783149285831a6007018118840218600201948383011a90601f1660081b0101808603906020811860208211021890815f5b80830151818a015201858110609257505050600201019201916018565b82906075565b6001929350829150019101925f5b82811060b3575001916018565b85851060c1575b60010160a6565b936001818192355f1a878501530194905060ba56`;ct=e=>`0x5f5f5b368110602d575f8083813473${_(e)}5af1503d5f803e3d5ff35b600180820192909160031981019035185f1a8015604c57815301906002565b505f19815282820192607f9060031981019035185f1a818111156072575b160101906002565b838101368437606a56`;At=function(e){return ft("0x"+_(e))},ft=function(e){let n=_(e),o=_t(n),a=28,u=new Uint8Array(a+o.length);u.set(o,a);let d=u.length,c=[],l=[],b=[],h=0,M=new Map,P=t=>{let s=b.lastIndexOf(t);return s===-1?-1:b.length-1-s},O=new Map,A=new Map,g=new Map,x=new Map,k=new Map,q=t=>t+31&-32,G=0,L=new Map,I=()=>[b.pop(),b.pop()],j=(1n<<256n)-1n,D=(t,s,r)=>t.set(s,(t.get(s)||0)+r),Q=(t,s)=>D(t,s,1),Y=(t,s)=>D(t,s,-1),z=t=>{c.push(t),Q(O,t)},N=t=>{l.push(t||null),Q(A,t||null)},y=(t,s=1)=>{b.push(t),D(g,t,s),++G,L.set(t,G)},v=(t,s)=>{h=q(t+s)},C=(t,s)=>{if(t===54)y(32n,0);else if(t===89)y(BigInt(h),0);else if(t===27){let[r,f]=I();c[c.length-1]==144&&(c.pop(),l.pop(),[r,f]=[f,r]),y(f<<BigInt(r)&j)}else if(t===23){let[r,f]=I();c[c.length-1]==144&&(c.pop(),l.pop()),y((r|f)&j)}else if(t>=96&&t<=127||t===95){let r=0n;for(let p of s||[])r=r<<8n|BigInt(p);if(r==224n){y(r),z(48),N(null);return}let f=P(r);if(f!==-1&&t!=95){let p=g.get(r)==0;if(f==0&&p){Y(g,r);return}if(f==1&&p){z(144);let[F,T]=I();b.push(T),b.push(F),N(null),Y(g,r);return}y(r,-1),z(128+f),N(null);return}y(r)}else if(t===81){let r=Number(b.pop());y(M.has(r)?M.get(r):0n)}else if(t===82){let[r,f]=I(),p=Number(r);M.set(p,f&j),v(p,32)}else if(t===83){let[r,f]=I();v(Number(r),1)}else t===243&&I();z(t),N(s||null)},pt=t=>b.includes(t)||t==224||t==32n,K=t=>C(t),S=t=>{if(t>0&&t===h)return C(89);if(t==32n)return C(54);if(!t)return C(95,void 0);let s=BigInt(t),r=[];for(;s;)r.unshift(Number(s&0xffn)),s>>=8n;return C(95+r.length,r)},tt=t=>C(95+t.length,Array.from(t)),gt=(t,s)=>(t.match(new RegExp(s,"g"))||[]).length,mt=t=>{let s=0,r=!0;for(let{s:f,e:p}of t)s+=1+p-f+1,31-p>0&&(s+=3),r||(s+=1),r=!1;return s},E=[],U=t=>(E.push({t:"num",v:t}),S(t)),H=t=>(E.push({t:"bytes",b:t}),tt(t)),B=t=>(E.push({t:"op",o:t}),K(t));S(1n);for(let t=0;t<d;t+=32){let s=new Uint8Array(32);s.set(u.slice(t,Math.min(t+32,d)),0);let r=[];for(let i=0;i<32;){for(;i<32&&s[i]===0;)++i;if(i>=32)break;let w=i;for(;i<32&&s[i]!==0;)++i;r.push({s:w,e:i-1})}if(!r.length)continue;let f=s.slice(r[0].s),p=1+f.length,F=0n;for(let i of f)F=F<<8n|BigInt(i);let T=Math.ceil(Math.log2(t+1)/8),R=rt(s);if(p>8){if(x.has(R)){if(p>k.get(R)+T){U(x.get(R)),B(81),U(t),B(82);continue}}else if(k.get(R)!=-1){let i=T+3,w=gt(n,R);k.set(R,w*32>w*i?i:-1),x.set(R,t)}}let dt=r.every(({s:i,e:w})=>i===w);if(pt(f))H(f);else if(dt){for(let{s:i}of r)U(s[i]),U(t+i),B(83);continue}else if(p<=mt(r))H(f);else{let i=!0;for(let{s:w,e:et}of r){let nt=31-et;H(s.slice(w,et+1)),nt>0&&(U(nt*8),B(27)),i||B(23),i=!1}}U(t),B(82)}c=[],l=[],b=[],h=0,M=new Map,Array.from(g.entries()).filter(([t,s])=>s>1&&t>1n&&t!==32n&&t!==224n).sort((t,s)=>L.get(s[0])-L.get(t[0])).filter(([t,s])=>typeof t=="number"?BigInt(t):t<=Rt).slice(0,13).forEach(([t,s])=>{S(t)}),S(1n);for(let t of E)t.t==="num"?S(t.v):t.t==="bytes"?tt(t.b):t.t==="op"&&K(t.o);K(95),K(95),S(o.length),S(a);let J=[];for(let t=0;t<c.length;++t)J.push(c[t]),c[t]>=96&&c[t]<=127&&l[t]&&J.push(...l[t]);return"0x"+rt(new Uint8Array(J))+"345f355af13d5f5f3e3d5ff3"},It=1150,Z="0x00000000000000000000000000000000000000e0",ot="jit",$="flz",V="cd";Ct=function(e,n){let o=e.params?.[0]?.method||e.method;if(o&&o!=="eth_call")return e;let a=e.params?.[0]||e,u=e.params?.[1]||"latest",d=e.params?.[2]||{},c=_(a.data||"0x"),l=(a.data||"0x").length;if(l<It||d[Z])return e;let b=a.to||"",h="0x"+c,M=!n&&l<1150,P=n===$||M?X.LibZip.flzCompress(h):null,O=n===V||M?X.LibZip.cdCompress(h):null,A=n;A||(A=l>=1150&&(l<3e3||l>=8e3)?ot:l>=3e3&&l<8e3&&P.length<O.length?$:V);let g,x;if(A===ot)g=ft(h),x="0x"+_(b).padStart(64,"0");else{let q=A===$;x=q?P:O,g=q?it(b):ct(b)}return g.length+x.length>=l?e:{...e,params:[{...a,to:Z,data:x},u,{...d,[Z]:{code:g}}]}}});var Pt={};st(Pt,{compressModule:()=>bt,compressModuleWithJIT:()=>Bt});module.exports=St(Pt);var at=new Map,Ut=["deflate-raw","deflate","gzip"],m=typeof CompressionStream>"u"?-1:null;async function bt(e,n,o){let a=typeof e=="string"?e:e instanceof URL?e.toString():e.url,u=at.get(a);if(m=m===-1||u===-1?-1:u?.[0]??null,o&&n?.body&&typeof n.body=="string"&&(m===-1||m===null))try{let c=JSON.parse(n.body),l=o(c);l!==void 0&&(n={...n,body:JSON.stringify(l)})}catch{}if(m&&m!==-1&&n?.body){let c=await new Response(new Blob([n.body]).stream().pipeThrough(new CompressionStream(m))).blob();n={...n,body:c,headers:{...n&&n.headers,"Content-Encoding":m}}}let d=await fetch(a,n);if(m===null){let c=d.headers.get("Accept-Encoding")?.split(",").filter(l=>Ut.includes(l));at.set(a,c?.length?c:-1)}return d}var Bt=(e,n)=>Promise.resolve().then(()=>(lt(),ut)).then(({compress_call:o})=>bt(e,n,o));0&&(module.exports={compressModule,compressModuleWithJIT});
|
|
2
|
+
//! @__PURE__
|
|
3
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/jit-compressor.ts", "../../src/index.ts"],
|
|
4
|
+
"sourcesContent": ["import { LibZip } from 'solady';\n\nconst MAX_160_BIT = (1n << 128n) - 1n;\n\nconst _normHex = (hex: string): string => hex.replace(/^0x/, '').toLowerCase();\n\nconst _hexToUint8Array = (hex: string): Uint8Array => {\n const normalized = _normHex(hex);\n const len = normalized.length;\n const bytes = new Uint8Array(len / 2);\n for (let i = 0; i < len; i += 2) {\n bytes[i / 2] = Number.parseInt(normalized.slice(i, i + 2), 16);\n }\n return bytes;\n};\n\nconst _uint8ArrayToHex = (bytes: Uint8Array): string => {\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += bytes[i].toString(16).padStart(2, '0');\n }\n return hex;\n};\n\n/**\n * Generates FastLZ (LZ77) decompressor bytecode. The generated code decompresses incoming calldata and forwards it to the target address.\n * @param address - Target contract address\n * @see {@link https://github.com/Vectorized/solady/blob/main/src/utils/LibZip.sol}\n * @pure\n */\n//! @__PURE__\nexport const flzFwdBytecode = (address: string): string =>\n `0x365f73${_normHex(address)}815b838110602f575f80848134865af1503d5f803e3d5ff35b803590815f1a8060051c908115609857600190600783149285831a6007018118840218600201948383011a90601f1660081b0101808603906020811860208211021890815f5b80830151818a015201858110609257505050600201019201916018565b82906075565b6001929350829150019101925f5b82811060b3575001916018565b85851060c1575b60010160a6565b936001818192355f1a878501530194905060ba56`;\n\n/**\n * Generates RLE (run-length encoded) decompressor bytecode. The generated code decompresses incoming calldata and forwards it to the target address.\n * @param address - Target contract address\n * @see {@link https://github.com/Vectorized/solady/blob/main/src/utils/LibZip.sol}\n * @pure\n */\n//! @__PURE__\nexport const rleFwdBytecode = (address: string): string =>\n `0x5f5f5b368110602d575f8083813473${_normHex(address)}5af1503d5f803e3d5ff35b600180820192909160031981019035185f1a8015604c57815301906002565b505f19815282820192607f9060031981019035185f1a818111156072575b160101906002565b838101368437606a56`;\n\n/**\n * JIT Compiles decompressor bytecode\n * @param calldata - Calldata to compress\n * @pure\n */\n//! @__PURE__\nexport const jitBytecode = function (calldata: string): string {\n return _jitDecompressor('0x' + _normHex(calldata));\n};\n\nconst _jitDecompressor = function (calldata: string): string {\n const hex = _normHex(calldata);\n const originalBuf = _hexToUint8Array(hex);\n\n // Right\u2011align the 4\u2011byte selector in the first 32\u2011byte slot (offset 28),\n // so that everything after the selector is reconstructed on mostly\n // word\u2011aligned boundaries. This keeps the ABI words (and therefore most\n // calldata reconstruction) 32\u2011byte aligned in memory.\n // That way we avoid encoding offsets for writes (most of the time),\n const padding = 28;\n const buf = new Uint8Array(padding + originalBuf.length);\n buf.set(originalBuf, padding);\n\n const n = buf.length;\n\n let ops: number[] = [];\n let data: (number[] | null)[] = [];\n let stack: bigint[] = [];\n let trackedMemSize = 0;\n let mem = new Map<number, bigint>();\n const getStackIdx = (val: bigint): number => {\n const idx = stack.lastIndexOf(val);\n return idx === -1 ? -1 : stack.length - 1 - idx;\n };\n\n const opFreq = new Map<number, number>();\n const dataFreq = new Map<number[] | null, number>();\n const stackFreq = new Map<bigint, number>();\n const wordCache = new Map<string, number>();\n const wordCacheCost = new Map<string, number>();\n const roundUp32 = (x: number) => (x + 31) & ~31;\n\n let pushCounter = 0;\n const stackCnt = new Map<bigint, number>();\n\n const pop2 = (): [bigint, bigint] => [stack.pop()!, stack.pop()!];\n const MASK32 = (1n << 256n) - 1n;\n\n const ctr = <K>(m: Map<K, number>, k: K, delta: number) => m.set(k, (m.get(k) || 0) + delta);\n const inc = <K>(m: Map<K, number>, k: K) => ctr(m, k, 1);\n const dec = <K>(m: Map<K, number>, k: K) => ctr(m, k, -1);\n const pushOp = (op: number) => {\n ops.push(op);\n inc(opFreq, op);\n };\n const pushD = (d: number[] | null) => {\n data.push(d || null);\n inc(dataFreq, d || null);\n };\n const pushS = (v: bigint, freq: number = 1) => {\n stack.push(v);\n ctr(stackFreq, v, freq);\n ++pushCounter;\n stackCnt.set(v, pushCounter);\n };\n\n const trackMem = (offset: number, size: number) => {\n trackedMemSize = roundUp32(offset + size);\n };\n\n const addOp = (op: number, imm?: number[]) => {\n if (op === 0x36) {\n pushS(32n, 0);\n } else if (op === 0x59) {\n pushS(BigInt(trackedMemSize), 0);\n } else if (op === 0x1b) {\n let [shift, val] = pop2();\n if (ops[ops.length - 1] == 144) {\n ops.pop();\n data.pop();\n [shift, val] = [val, shift];\n }\n pushS((val << BigInt(shift)) & MASK32);\n } else if (op === 0x17) {\n // OR\n const [a, b] = pop2();\n if (ops[ops.length - 1] == 144) {\n ops.pop();\n data.pop();\n }\n pushS((a | b) & MASK32);\n } else if ((op >= 0x60 && op <= 0x7f) || op === 0x5f) {\n // PUSH\n let v = 0n;\n for (const b of imm || []) v = (v << 8n) | BigInt(b);\n if (v == 224n) {\n // Special\u2011case the literal 0xe0 (224):\n // the decompressor is always deployed at 0x...00e0, so the final\n // byte of ADDRESS is exactly 0xe0. Since we must send our own\n // address with the eth_call anyway, we can synthesize this value\n // with a single opcode instead of encoding a literal, effectively\n // giving us one more hot constant slot on the stack.\n pushS(v);\n pushOp(0x30); // ADDRESS\n pushD(null);\n return;\n }\n const idx = getStackIdx(v);\n if (idx !== -1 && op != 0x5f) {\n const last = stackFreq.get(v) == 0;\n if (idx == 0 && last) {\n dec(stackFreq, v);\n return;\n }\n if (idx == 1 && last) {\n pushOp(144);\n const [a, b] = pop2();\n stack.push(b);\n stack.push(a);\n pushD(null);\n dec(stackFreq, v);\n return;\n }\n pushS(v, -1);\n pushOp(128 + idx);\n pushD(null);\n return;\n }\n pushS(v);\n } else if (op === 0x51) {\n // MLOAD\n const k = Number(stack.pop()!);\n pushS(mem.has(k) ? mem.get(k)! : 0n);\n } else if (op === 0x52) {\n // MSTORE\n const [offset, value] = pop2();\n const k = Number(offset);\n mem.set(k, value & MASK32);\n trackMem(k, 32);\n } else if (op === 0x53) {\n // MSTORE8\n const [offset, _] = pop2();\n trackMem(Number(offset), 1);\n } else if (op === 0xf3) {\n // RETURN\n pop2();\n }\n pushOp(op);\n pushD(imm || null);\n };\n const isInStack = (w) => stack.includes(w) || w == 0xe0 || w == 32n;\n const op = (opcode: number) => addOp(opcode);\n const pushN = (value: number | bigint) => {\n if (value > 0 && value === trackedMemSize) return addOp(0x59);\n if (value == 32n) return addOp(0x36);\n if (!value) return addOp(0x5f, undefined); // PUSH0\n let v = BigInt(value);\n let bytes: number[] = [];\n while (v) {\n bytes.unshift(Number(v & 0xffn));\n v >>= 8n;\n }\n return addOp(0x5f + bytes.length, bytes);\n };\n const pushB = (buf: Uint8Array) => addOp(0x5f + buf.length, Array.from(buf));\n const cntWords = (hex: string, wordHex: string) =>\n (hex.match(new RegExp(wordHex, 'g')) || []).length;\n\n // Rough cost model\n const estShlCost = (seg: Array<{ s: number; e: number }>) => {\n let cost = 0;\n let first = true;\n for (const { s, e } of seg) {\n cost += 1 + e - s + 1; // PUSH segLen bytes\n if (31 - e > 0) cost += 1 /* PUSH1 */ + 1 /* shift byte */ + 1 /* SHL */;\n if (!first) cost += 1; // OR\n first = false;\n }\n return cost;\n };\n\n type PlanStep =\n | { t: 'num'; v: number | bigint }\n | { t: 'bytes'; b: Uint8Array }\n | { t: 'op'; o: number };\n\n const plan: PlanStep[] = [];\n const emitPushN = (v: number | bigint) => (plan.push({ t: 'num', v }), pushN(v));\n const emitPushB = (b: Uint8Array) => (plan.push({ t: 'bytes', b }), pushB(b));\n const emitOp = (o: number) => (plan.push({ t: 'op', o }), op(o));\n pushN(1n);\n // First pass: decide how to build each 32-byte word without emitting bytecode\n for (let base = 0; base < n; base += 32) {\n const word = new Uint8Array(32);\n word.set(buf.slice(base, Math.min(base + 32, n)), 0);\n\n const seg: Array<{ s: number; e: number }> = [];\n for (let i = 0; i < 32; ) {\n while (i < 32 && word[i] === 0) ++i;\n if (i >= 32) break;\n const s = i;\n while (i < 32 && word[i] !== 0) ++i;\n seg.push({ s, e: i - 1 });\n }\n\n if (!seg.length) continue;\n\n // Decide whether to build this word via SHL/OR or as a single literal word\n const literal = word.slice(seg[0].s);\n const literalCost = 1 + literal.length;\n let literalVal = 0n;\n for (const b of literal) literalVal = (literalVal << 8n) | BigInt(b);\n const baseBytes = Math.ceil(Math.log2(base + 1) / 8);\n const wordHex = _uint8ArrayToHex(word);\n if (literalCost > 8) {\n if (wordCache.has(wordHex)) {\n if (literalCost > wordCacheCost.get(wordHex)! + baseBytes) {\n emitPushN(wordCache.get(wordHex)!);\n emitOp(0x51);\n emitPushN(base);\n emitOp(0x52); // MSTORE\n continue;\n }\n } else if (wordCacheCost.get(wordHex) != -1) {\n const reuseCost = baseBytes + 3;\n const freq = cntWords(hex, wordHex);\n wordCacheCost.set(wordHex, freq * 32 > freq * reuseCost ? reuseCost : -1);\n wordCache.set(wordHex, base);\n }\n }\n\n // Convert literal bytes to bigint for stack comparison\n\n const byte8s = seg.every(({ s, e }) => s === e);\n if (isInStack(literal)) {\n emitPushB(literal);\n } else if (byte8s) {\n for (const { s } of seg) {\n emitPushN(word[s]);\n emitPushN(base + s);\n emitOp(0x53); // MSTORE8\n }\n continue;\n } else if (literalCost <= estShlCost(seg)) {\n emitPushB(literal);\n } else {\n let first = true;\n for (const { s, e } of seg) {\n const suffix0s = 31 - e;\n emitPushB(word.slice(s, e + 1));\n if (suffix0s > 0) {\n emitPushN(suffix0s * 8);\n emitOp(0x1b); // SHL\n }\n if (!first) emitOp(0x17); // OR\n first = false;\n }\n }\n emitPushN(base);\n emitOp(0x52); // MSTORE\n }\n\n ops = [];\n data = [];\n stack = [];\n trackedMemSize = 0;\n mem = new Map();\n // Pre 2nd pass. Push most frequent literals into stack.\n Array.from(stackFreq.entries())\n .filter(([val, freq]) => freq > 1 && val > 1n && val !== 32n && val !== 224n)\n .sort((a, b) => stackCnt.get(b[0])! - stackCnt.get(a[0])!)\n .filter(([val, _]) => {\n return typeof val === 'number' ? BigInt(val) : val <= MAX_160_BIT;\n })\n .slice(0, 13)\n .forEach(([val, _]) => {\n pushN(val);\n });\n pushN(1n);\n // Second pass: emit ops and track mem/stack\n for (const step of plan) {\n if (step.t === 'num') pushN(step.v);\n else if (step.t === 'bytes') pushB(step.b);\n else if (step.t === 'op') op(step.o);\n }\n\n // CALL stack layout (top to bottom): gas, address, value, argsOffset, argsSize, retOffset, retSize\n //\n // Opcodes breakdown:\n // - 0x5f5f: PUSH0 PUSH0 (retSize=0, retOffset=0)\n // - pushN(originalBuf.length): argsSize = actual data length\n // - pushN(padding): argsOffset (skip leading alignment bytes)\n // - 0x34: CALLVALUE (value)\n // - 0x5f35: PUSH0 CALLDATALOAD (address from calldata[0])\n // - 0x5a: GAS (remaining gas)\n // - 0xf1: CALL\n //\n // RETURNDATACOPY(destOffset=0, offset=0, length=RETURNDATASIZE):\n // - 0x3d5f5f3e: RETURNDATASIZE PUSH0 PUSH0 RETURNDATACOPY\n //\n // RETURN(offset=0, size=RETURNDATASIZE):\n // - 0x3d5ff3: RETURNDATASIZE PUSH0 RETURN\n\n op(0x5f); // PUSH0 (retSize)\n op(0x5f); // PUSH0 (retOffset)\n pushN(originalBuf.length); // argsSize = actual data length\n pushN(padding); // argsOffset = padding\n\n const out: number[] = [];\n for (let i = 0; i < ops.length; ++i) {\n out.push(ops[i]);\n if (ops[i] >= 0x60 && ops[i] <= 0x7f && data[i]) out.push(...data[i]!);\n }\n\n // - CALLVALUE, load target address from calldata[0], GAS, CALL\n // - RETURNDATACOPY(0, 0, RETURNDATASIZE)\n // - RETURN(0, RETURNDATASIZE)\n return '0x' + _uint8ArrayToHex(new Uint8Array(out)) + '345f355af13d5f5f3e3d5ff3';\n};\n\nconst MIN_SIZE_FOR_COMPRESSION = 1150;\nconst DECOMPRESSOR_ADDRESS = '0x00000000000000000000000000000000000000e0';\n\nconst _jit = 'jit';\nconst _flz = 'flz';\nconst _cd = 'cd';\n\n/**\n * Compresses eth_call payload using JIT, FastLZ (FLZ), or calldata RLE (CD) compression.\n * Auto-selects best algorithm if not specified. Only compresses if >800 bytes and beneficial.\n * @param payload - eth_call RPC payload\n * @param alg - 'jit' | 'flz' | 'cd' | undefined (auto)\n * @returns (un)compressed eth_call payload\n * @pure\n */\n//! @__PURE__\nexport const compress_call = function (payload: any, alg?: string): any {\n const rpcMethod = payload.params?.[0]?.method || payload.method;\n if (rpcMethod && rpcMethod !== 'eth_call') return payload;\n\n // Extract data and target address from params[0] if available, otherwise top-level\n const txObj = payload.params?.[0] || payload;\n const blockParam = payload.params?.[1] || 'latest';\n const existingStateOverride = payload.params?.[2] || {};\n\n // If there are any existing state overrides for the decompressor address, do not compress\n const hex = _normHex(txObj.data || '0x');\n const originalSize = (txObj.data || '0x').length;\n if (originalSize < MIN_SIZE_FOR_COMPRESSION || (existingStateOverride[DECOMPRESSOR_ADDRESS])) return payload;\n\n const targetAddress = txObj.to || '';\n const data = '0x' + hex;\n\n const autoSelect = !alg && originalSize < 1150;\n const flz = alg === _flz || autoSelect ? LibZip.flzCompress(data) : null;\n const cd = alg === _cd || autoSelect ? LibZip.cdCompress(data) : null;\n let selectedMethod = alg;\n if (!selectedMethod) {\n selectedMethod =\n originalSize >= 1150 && (originalSize < 3000 || originalSize >= 8000)\n ? _jit\n : originalSize >= 3000 && originalSize < 8000\n ? flz!.length < cd!.length\n ? _flz\n : _cd\n : _cd;\n }\n\n let bytecode: string;\n let calldata: string;\n\n if (selectedMethod === _jit) {\n bytecode = _jitDecompressor(data);\n calldata = '0x' + _normHex(targetAddress).padStart(64, '0');\n } else {\n const isFlz = selectedMethod === _flz;\n calldata = isFlz ? flz! : cd!;\n bytecode = isFlz ? flzFwdBytecode(targetAddress) : rleFwdBytecode(targetAddress);\n }\n\n const compressedSize = bytecode.length + calldata.length;\n if (compressedSize >= originalSize) return payload;\n\n return {\n ...payload,\n params: [\n {\n ...txObj,\n to: DECOMPRESSOR_ADDRESS,\n data: calldata,\n },\n blockParam,\n {\n ...existingStateOverride,\n [DECOMPRESSOR_ADDRESS]: { code: bytecode },\n },\n ],\n };\n};\n", "const _sup_enc = new Map<string, string[] | -1>();\nconst _enc = ['deflate-raw', 'deflate', 'gzip'];\nlet supported: string | -1 | null = typeof CompressionStream === 'undefined' ? -1 : null;\n\nexport type PayloadTransform = (payload: unknown) => unknown;\n\n/**\n * Fetch-compatible function that applies HTTP compression (gzip/deflate) to requests.\n * Optionally transforms request payloads before sending.\n *\n * @param input - The resource URL, Request object, or URL string\n * @param init - Optional request initialization options\n * @param transformPayload - Optional function to transform the request payload\n * @returns A Promise that resolves to the Response\n */\n//! @__PURE__\nexport async function compressModule(\n input: string | URL | Request,\n init?: RequestInit,\n): Promise<Response>;\n\n//! @__PURE__\nexport async function compressModule(\n input: string | URL | Request,\n init: RequestInit | undefined,\n transformPayload?: PayloadTransform,\n): Promise<Response>;\n\n//! @__PURE__\nexport async function compressModule(\n input: string | URL | Request,\n init?: RequestInit,\n transformPayload?: PayloadTransform,\n): Promise<Response> {\n const url =\n typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;\n\n const cached = _sup_enc.get(url);\n supported = supported === -1 ? -1 : cached === -1 ? -1 : (cached?.[0] ?? null);\n\n // Only apply the optional payload transform\n // when native HTTP compression is not available for this URL.\n if (transformPayload && init?.body && typeof init.body === 'string') {\n if (supported === -1 || supported === null) {\n try {\n const parsed = JSON.parse(init.body as string);\n const next = transformPayload(parsed);\n if (next !== undefined) {\n init = {\n ...init,\n body: JSON.stringify(next),\n };\n }\n } catch {\n // Non-JSON bodies are left untouched.\n }\n }\n }\n\n if (supported && supported !== -1 && init?.body) {\n const compressed = await new Response(\n new Blob([init.body as string])\n .stream()\n .pipeThrough(new CompressionStream(supported as CompressionFormat)),\n ).blob();\n init = {\n ...init,\n body: compressed,\n headers: { ...(init && init.headers), 'Content-Encoding': supported },\n };\n }\n const response = await fetch(url, init);\n\n if (supported === null) {\n const encodings = response.headers\n .get('Accept-Encoding')\n ?.split(',')\n .filter((e) => _enc.includes(e));\n _sup_enc.set(url, encodings?.length ? encodings : -1);\n }\n\n return response;\n}\n\n/**\n * Combines HTTP compression with EVM JIT compression.\n * Just pass this as `fetchFn` to viem's http transport.\n *\n * @param input - The resource URL or Request object\n * @param init - Optional request initialization options\n * @returns A Promise that resolves to the Response\n *\n * @example\n * ```ts\n * const client = createPublicClient({\n * transport: http(rpcUrl, { fetchFn: compressModuleWithJIT })\n * })\n * ```\n *\n * If the target RPC endpoint and runtime support native HTTP compression,\n * this helper prefers that path and will not apply JIT calldata compression;\n * the JIT-based transform is used as a legacy/fallback path when HTTP\n * content-encoding is unavailable.\n * @pure\n */\n//! @__PURE__\nexport const compressModuleWithJIT = (\n input: RequestInfo | URL,\n init?: RequestInit,\n): Promise<Response> => {\n return import('./jit-compressor').then(({ compress_call }) =>\n compressModule(input, init, compress_call),\n );\n};\n"],
|
|
5
|
+
"mappings": "0cAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,mBAAAE,GAAA,mBAAAC,GAAA,gBAAAC,GAAA,mBAAAC,KAAA,IAAAC,EAEMC,GAEAC,EAEAC,GAUAC,GAeOP,GAUAE,GASAD,GAIPO,GAsTAC,GACAC,EAEAC,GACAC,EACAC,EAWOd,GA5Xbe,GAAAC,GAAA,KAAAZ,EAAuB,kBAEjBC,IAAe,IAAM,MAAQ,GAE7BC,EAAYW,GAAwBA,EAAI,QAAQ,MAAO,EAAE,EAAE,YAAY,EAEvEV,GAAoBU,GAA4B,CACpD,IAAMC,EAAaZ,EAASW,CAAG,EACzBE,EAAMD,EAAW,OACjBE,EAAQ,IAAI,WAAWD,EAAM,CAAC,EACpC,QAASE,EAAI,EAAGA,EAAIF,EAAKE,GAAK,EAC5BD,EAAMC,EAAI,CAAC,EAAI,OAAO,SAASH,EAAW,MAAMG,EAAGA,EAAI,CAAC,EAAG,EAAE,EAE/D,OAAOD,CACT,EAEMZ,GAAoBY,GAA8B,CACtD,IAAIH,EAAM,GACV,QAASI,EAAI,EAAGA,EAAID,EAAM,OAAQC,IAChCJ,GAAOG,EAAMC,CAAC,EAAE,SAAS,EAAE,EAAE,SAAS,EAAG,GAAG,EAE9C,OAA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IN,GAAQA,EAAK,QAAU,mBAAoBF,CAAU,CACtE,CACF,CACA,IAAMS,EAAW,MAAM,MAAML,EAAKF,CAAI,EAEtC,GAAIF,IAAc,KAAM,CACtB,IAAMU,EAAYD,EAAS,QACxB,IAAI,iBAAiB,GACpB,MAAM,GAAG,EACV,OAAQE,GAAMZ,GAAK,SAASY,CAAC,CAAC,EACjCb,GAAS,IAAIM,EAAKM,GAAW,OAASA,EAAY,EAAE,CACtD,CAEA,OAAOD,CACT,CAwBO,IAAMb,GAAwB,CACnCK,EACAC,IAEO,sCAA2B,KAAK,CAAC,CAAE,cAAAU,CAAc,IACtDjB,GAAeM,EAAOC,EAAMU,CAAa,CAC3C",
|
|
6
|
+
"names": ["jit_compressor_exports", "__export", "compress_call", "flzFwdBytecode", "jitBytecode", "rleFwdBytecode", "import_solady", "MAX_160_BIT", "_normHex", "_hexToUint8Array", "_uint8ArrayToHex", "_jitDecompressor", "MIN_SIZE_FOR_COMPRESSION", "DECOMPRESSOR_ADDRESS", "_jit", "_flz", "_cd", "init_jit_compressor", "__esmMin", "hex", "normalized", "len", "bytes", "i", "address", "calldata", "originalBuf", "padding", "buf", "n", "ops", "data", "stack", "trackedMemSize", "mem", "getStackIdx", "val", "idx", "opFreq", "dataFreq", "stackFreq", "wordCache", "wordCacheCost", "roundUp32", "x", "pushCounter", "stackCnt", "pop2", "MASK32", "ctr", "m", "k", "delta", "inc", "dec", "pushOp", "op", "pushD", "d", "pushS", "v", "freq", "trackMem", "offset", "size", "addOp", "imm", "shift", "a", "b", "last", "value", "_", "isInStack", "w", "opcode", "pushN", "pushB", "cntWords", "wordHex", "estShlCost", "seg", "cost", "first", "s", "e", "plan", "emitPushN", "emitPushB", "emitOp", "o", "base", "word", "literal", "literalCost", "literalVal", "baseBytes", "reuseCost", "byte8s", "suffix0s", "step", "out", "payload", "alg", "rpcMethod", "txObj", "blockParam", "existingStateOverride", "originalSize", "targetAddress", "autoSelect", "flz", "cd", "selectedMethod", "bytecode", "isFlz", "index_exports", "__export", "compressModule", "compressModuleWithJIT", "__toCommonJS", "_sup_enc", "_enc", "supported", "input", "init", "transformPayload", "url", "cached", "parsed", "next", "compressed", "response", "encodings", "e", "compress_call"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
var we=Object.create;var L=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var Me=Object.getOwnPropertyNames;var Re=Object.getPrototypeOf,Ie=Object.prototype.hasOwnProperty;var Ce=(t,n)=>()=>(t&&(n=t(t=0)),n);var re=(t,n)=>{for(var s in n)L(t,s,{get:n[s],enumerable:!0})},oe=(t,n,s,a)=>{if(n&&typeof n=="object"||typeof n=="function")for(let f of Me(n))!Ie.call(t,f)&&f!==s&&L(t,f,{get:()=>n[f],enumerable:!(a=Se(n,f))||a.enumerable});return t};var _e=(t,n,s)=>(s=t!=null?we(Re(t)):{},oe(n||!t||!t.__esModule?L(s,"default",{value:t,enumerable:!0}):s,t)),Ae=t=>oe(L({},"__esModule",{value:!0}),t);var ue={};re(ue,{compress_call:()=>Oe,flzFwdBytecode:()=>le,jitBytecode:()=>Pe,rleFwdBytecode:()=>ae});var X,ze,C,Be,ie,le,ae,Pe,fe,Ue,Z,ce,$,V,Oe,be=Ce(()=>{X=require("solady"),ze=(1n<<128n)-1n,C=t=>t.replace(/^0x/,"").toLowerCase(),Be=t=>{let n=C(t),s=n.length,a=new Uint8Array(s/2);for(let f=0;f<s;f+=2)a[f/2]=Number.parseInt(n.slice(f,f+2),16);return a},ie=t=>{let n="";for(let s=0;s<t.length;s++)n+=t[s].toString(16).padStart(2,"0");return n};le=t=>`0x365f73${C(t)}815b838110602f575f80848134865af1503d5f803e3d5ff35b803590815f1a8060051c908115609857600190600783149285831a6007018118840218600201948383011a90601f1660081b0101808603906020811860208211021890815f5b80830151818a015201858110609257505050600201019201916018565b82906075565b6001929350829150019101925f5b82811060b3575001916018565b85851060c1575b60010160a6565b936001818192355f1a878501530194905060ba56`;ae=t=>`0x5f5f5b368110602d575f8083813473${C(t)}5af1503d5f803e3d5ff35b600180820192909160031981019035185f1a8015604c57815301906002565b505f19815282820192607f9060031981019035185f1a818111156072575b160101906002565b838101368437606a56`;Pe=function(t){return fe("0x"+C(t))},fe=function(t){let n=C(t),s=Be(n),a=28,f=new Uint8Array(a+s.length);f.set(s,a);let h=f.length,c=[],u=[],b=[],x=0,M=new Map,U=e=>{let r=b.lastIndexOf(e);return r===-1?-1:b.length-1-r},O=new Map,_=new Map,m=new Map,y=new Map,k=new Map,q=e=>e+31&-32,Q=0,j=new Map,A=()=>[b.pop(),b.pop()],H=(1n<<256n)-1n,J=(e,r,o)=>e.set(r,(e.get(r)||0)+o),Y=(e,r)=>J(e,r,1),v=(e,r)=>J(e,r,-1),T=e=>{c.push(e),Y(O,e)},D=e=>{u.push(e||null),Y(_,e||null)},w=(e,r=1)=>{b.push(e),J(m,e,r),++Q,j.set(e,Q)},ee=(e,r)=>{x=q(e+r)},z=(e,r)=>{if(e===54)w(32n,0);else if(e===89)w(BigInt(x),0);else if(e===27){let[o,l]=A();c[c.length-1]==144&&(c.pop(),u.pop(),[o,l]=[l,o]),w(l<<BigInt(o)&H)}else if(e===23){let[o,l]=A();c[c.length-1]==144&&(c.pop(),u.pop()),w((o|l)&H)}else if(e>=96&&e<=127||e===95){let o=0n;for(let p of r||[])o=o<<8n|BigInt(p);if(o==224n){w(o),T(48),D(null);return}let l=U(o);if(l!==-1&&e!=95){let p=m.get(o)==0;if(l==0&&p){v(m,o);return}if(l==1&&p){T(144);let[E,F]=A();b.push(F),b.push(E),D(null),v(m,o);return}w(o,-1),T(128+l),D(null);return}w(o)}else if(e===81){let o=Number(b.pop());w(M.has(o)?M.get(o):0n)}else if(e===82){let[o,l]=A(),p=Number(o);M.set(p,l&H),ee(p,32)}else if(e===83){let[o,l]=A();ee(Number(o),1)}else e===243&&A();T(e),D(r||null)},de=e=>b.includes(e)||e==224||e==32n,N=e=>z(e),R=e=>{if(e>0&&e===x)return z(89);if(e==32n)return z(54);if(!e)return z(95,void 0);let r=BigInt(e),o=[];for(;r;)o.unshift(Number(r&0xffn)),r>>=8n;return z(95+o.length,o)},te=e=>z(95+e.length,Array.from(e)),he=(e,r)=>(e.match(new RegExp(r,"g"))||[]).length,xe=e=>{let r=0,o=!0;for(let{s:l,e:p}of e)r+=1+p-l+1,31-p>0&&(r+=3),o||(r+=1),o=!1;return r},K=[],B=e=>(K.push({t:"num",v:e}),R(e)),W=e=>(K.push({t:"bytes",b:e}),te(e)),P=e=>(K.push({t:"op",o:e}),N(e));R(1n);for(let e=0;e<h;e+=32){let r=new Uint8Array(32);r.set(f.slice(e,Math.min(e+32,h)),0);let o=[];for(let i=0;i<32;){for(;i<32&&r[i]===0;)++i;if(i>=32)break;let S=i;for(;i<32&&r[i]!==0;)++i;o.push({s:S,e:i-1})}if(!o.length)continue;let l=r.slice(o[0].s),p=1+l.length,E=0n;for(let i of l)E=E<<8n|BigInt(i);let F=Math.ceil(Math.log2(e+1)/8),I=ie(r);if(p>8){if(y.has(I)){if(p>k.get(I)+F){B(y.get(I)),P(81),B(e),P(82);continue}}else if(k.get(I)!=-1){let i=F+3,S=he(n,I);k.set(I,S*32>S*i?i:-1),y.set(I,e)}}let ye=o.every(({s:i,e:S})=>i===S);if(de(l))W(l);else if(ye){for(let{s:i}of o)B(r[i]),B(e+i),P(83);continue}else if(p<=xe(o))W(l);else{let i=!0;for(let{s:S,e:ne}of o){let se=31-ne;W(r.slice(S,ne+1)),se>0&&(B(se*8),P(27)),i||P(23),i=!1}}B(e),P(82)}c=[],u=[],b=[],x=0,M=new Map,Array.from(m.entries()).filter(([e,r])=>r>1&&e>1n&&e!==32n&&e!==224n).sort((e,r)=>j.get(r[0])-j.get(e[0])).filter(([e,r])=>typeof e=="number"?BigInt(e):e<=ze).slice(0,13).forEach(([e,r])=>{R(e)}),R(1n);for(let e of K)e.t==="num"?R(e.v):e.t==="bytes"?te(e.b):e.t==="op"&&N(e.o);N(95),N(95),R(s.length),R(a);let G=[];for(let e=0;e<c.length;++e)G.push(c[e]),c[e]>=96&&c[e]<=127&&u[e]&&G.push(...u[e]);return"0x"+ie(new Uint8Array(G))+"345f355af13d5f5f3e3d5ff3"},Ue=1150,Z="0x00000000000000000000000000000000000000e0",ce="jit",$="flz",V="cd";Oe=function(t,n){let s=t.params?.[0]?.method||t.method;if(s&&s!=="eth_call")return t;let a=t.params?.[0]||t,f=t.params?.[1]||"latest",h=t.params?.[2]||{},c=C(a.data||"0x"),u=(a.data||"0x").length;if(u<Ue||h[Z])return t;let b=a.to||"",x="0x"+c,M=!n&&u<1150,U=n===$||M?X.LibZip.flzCompress(x):null,O=n===V||M?X.LibZip.cdCompress(x):null,_=n;_||(_=u>=1150&&(u<3e3||u>=8e3)?ce:u>=3e3&&u<8e3&&U.length<O.length?$:V);let m,y;if(_===ce)m=fe(x),y="0x"+C(b).padStart(64,"0");else{let q=_===$;y=q?U:O,m=q?le(b):ae(b)}return m.length+y.length>=u?t:{...t,params:[{...a,to:Z,data:y},f,{...h,[Z]:{code:m}}]}}});var Te={};re(Te,{compressModule:()=>me,compressModuleWithJIT:()=>qe});module.exports=Ae(Te);var d=_e(require("node:zlib"),1);var pe=new Map,ke=["deflate-raw","deflate","gzip"],g=typeof CompressionStream>"u"?-1:null;async function me(t,n,s){let a=typeof t=="string"?t:t instanceof URL?t.toString():t.url,f=pe.get(a);if(g=g===-1||f===-1?-1:f?.[0]??null,s&&n?.body&&typeof n.body=="string"&&(g===-1||g===null))try{let c=JSON.parse(n.body),u=s(c);u!==void 0&&(n={...n,body:JSON.stringify(u)})}catch{}if(g&&g!==-1&&n?.body){let c=await new Response(new Blob([n.body]).stream().pipeThrough(new CompressionStream(g))).blob();n={...n,body:c,headers:{...n&&n.headers,"Content-Encoding":g}}}let h=await fetch(a,n);if(g===null){let c=h.headers.get("Accept-Encoding")?.split(",").filter(u=>ke.includes(u));pe.set(a,c?.length?c:-1)}return h}var qe=(t,n)=>Promise.resolve().then(()=>(be(),ue)).then(({compress_call:s})=>me(t,n,s));var ge=(t,n)=>Object.assign(t,{writable:new WritableStream({write(s){return n.write(s),Promise.resolve()},close(){return n.end(),Promise.resolve()}}),readable:new ReadableStream({type:"bytes",start(s){n.on("data",a=>s.enqueue(a)),n.once("end",()=>s.close())}})});globalThis.CompressionStream||(globalThis.CompressionStream=class{constructor(n){let s;n==="deflate"?s=d.default.createDeflate():n==="gzip"?s=d.default.createGzip():n==="br"?s=d.default.createBrotliCompress():s=d.default.createDeflateRaw(),ge(this,s)}});globalThis.DecompressionStream||(globalThis.DecompressionStream=class{constructor(n){let s;n==="deflate"?s=d.default.createInflate():n==="gzip"?s=d.default.createGunzip():n==="br"?s=d.default.createBrotliDecompress():s=d.default.createInflateRaw(),ge(this,s)}});0&&(module.exports={compressModule,compressModuleWithJIT});
|
|
2
|
+
//! @__PURE__
|
|
3
|
+
//# sourceMappingURL=index.node.cjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/jit-compressor.ts", "../../src/index.node.ts", "../../src/index.ts"],
|
|
4
|
+
"sourcesContent": ["import { LibZip } from 'solady';\n\nconst MAX_160_BIT = (1n << 128n) - 1n;\n\nconst _normHex = (hex: string): string => hex.replace(/^0x/, '').toLowerCase();\n\nconst _hexToUint8Array = (hex: string): Uint8Array => {\n const normalized = _normHex(hex);\n const len = normalized.length;\n const bytes = new Uint8Array(len / 2);\n for (let i = 0; i < len; i += 2) {\n bytes[i / 2] = Number.parseInt(normalized.slice(i, i + 2), 16);\n }\n return bytes;\n};\n\nconst _uint8ArrayToHex = (bytes: Uint8Array): string => {\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += bytes[i].toString(16).padStart(2, '0');\n }\n return hex;\n};\n\n/**\n * Generates FastLZ (LZ77) decompressor bytecode. The generated code decompresses incoming calldata and forwards it to the target address.\n * @param address - Target contract address\n * @see {@link https://github.com/Vectorized/solady/blob/main/src/utils/LibZip.sol}\n * @pure\n */\n//! @__PURE__\nexport const flzFwdBytecode = (address: string): string =>\n `0x365f73${_normHex(address)}815b838110602f575f80848134865af1503d5f803e3d5ff35b803590815f1a8060051c908115609857600190600783149285831a6007018118840218600201948383011a90601f1660081b0101808603906020811860208211021890815f5b80830151818a015201858110609257505050600201019201916018565b82906075565b6001929350829150019101925f5b82811060b3575001916018565b85851060c1575b60010160a6565b936001818192355f1a878501530194905060ba56`;\n\n/**\n * Generates RLE (run-length encoded) decompressor bytecode. The generated code decompresses incoming calldata and forwards it to the target address.\n * @param address - Target contract address\n * @see {@link https://github.com/Vectorized/solady/blob/main/src/utils/LibZip.sol}\n * @pure\n */\n//! @__PURE__\nexport const rleFwdBytecode = (address: string): string =>\n `0x5f5f5b368110602d575f8083813473${_normHex(address)}5af1503d5f803e3d5ff35b600180820192909160031981019035185f1a8015604c57815301906002565b505f19815282820192607f9060031981019035185f1a818111156072575b160101906002565b838101368437606a56`;\n\n/**\n * JIT Compiles decompressor bytecode\n * @param calldata - Calldata to compress\n * @pure\n */\n//! @__PURE__\nexport const jitBytecode = function (calldata: string): string {\n return _jitDecompressor('0x' + _normHex(calldata));\n};\n\nconst _jitDecompressor = function (calldata: string): string {\n const hex = _normHex(calldata);\n const originalBuf = _hexToUint8Array(hex);\n\n // Right\u2011align the 4\u2011byte selector in the first 32\u2011byte slot (offset 28),\n // so that everything after the selector is reconstructed on mostly\n // word\u2011aligned boundaries. This keeps the ABI words (and therefore most\n // calldata reconstruction) 32\u2011byte aligned in memory.\n // That way we avoid encoding offsets for writes (most of the time),\n const padding = 28;\n const buf = new Uint8Array(padding + originalBuf.length);\n buf.set(originalBuf, padding);\n\n const n = buf.length;\n\n let ops: number[] = [];\n let data: (number[] | null)[] = [];\n let stack: bigint[] = [];\n let trackedMemSize = 0;\n let mem = new Map<number, bigint>();\n const getStackIdx = (val: bigint): number => {\n const idx = stack.lastIndexOf(val);\n return idx === -1 ? -1 : stack.length - 1 - idx;\n };\n\n const opFreq = new Map<number, number>();\n const dataFreq = new Map<number[] | null, number>();\n const stackFreq = new Map<bigint, number>();\n const wordCache = new Map<string, number>();\n const wordCacheCost = new Map<string, number>();\n const roundUp32 = (x: number) => (x + 31) & ~31;\n\n let pushCounter = 0;\n const stackCnt = new Map<bigint, number>();\n\n const pop2 = (): [bigint, bigint] => [stack.pop()!, stack.pop()!];\n const MASK32 = (1n << 256n) - 1n;\n\n const ctr = <K>(m: Map<K, number>, k: K, delta: number) => m.set(k, (m.get(k) || 0) + delta);\n const inc = <K>(m: Map<K, number>, k: K) => ctr(m, k, 1);\n const dec = <K>(m: Map<K, number>, k: K) => ctr(m, k, -1);\n const pushOp = (op: number) => {\n ops.push(op);\n inc(opFreq, op);\n };\n const pushD = (d: number[] | null) => {\n data.push(d || null);\n inc(dataFreq, d || null);\n };\n const pushS = (v: bigint, freq: number = 1) => {\n stack.push(v);\n ctr(stackFreq, v, freq);\n ++pushCounter;\n stackCnt.set(v, pushCounter);\n };\n\n const trackMem = (offset: number, size: number) => {\n trackedMemSize = roundUp32(offset + size);\n };\n\n const addOp = (op: number, imm?: number[]) => {\n if (op === 0x36) {\n pushS(32n, 0);\n } else if (op === 0x59) {\n pushS(BigInt(trackedMemSize), 0);\n } else if (op === 0x1b) {\n let [shift, val] = pop2();\n if (ops[ops.length - 1] == 144) {\n ops.pop();\n data.pop();\n [shift, val] = [val, shift];\n }\n pushS((val << BigInt(shift)) & MASK32);\n } else if (op === 0x17) {\n // OR\n const [a, b] = pop2();\n if (ops[ops.length - 1] == 144) {\n ops.pop();\n data.pop();\n }\n pushS((a | b) & MASK32);\n } else if ((op >= 0x60 && op <= 0x7f) || op === 0x5f) {\n // PUSH\n let v = 0n;\n for (const b of imm || []) v = (v << 8n) | BigInt(b);\n if (v == 224n) {\n // Special\u2011case the literal 0xe0 (224):\n // the decompressor is always deployed at 0x...00e0, so the final\n // byte of ADDRESS is exactly 0xe0. Since we must send our own\n // address with the eth_call anyway, we can synthesize this value\n // with a single opcode instead of encoding a literal, effectively\n // giving us one more hot constant slot on the stack.\n pushS(v);\n pushOp(0x30); // ADDRESS\n pushD(null);\n return;\n }\n const idx = getStackIdx(v);\n if (idx !== -1 && op != 0x5f) {\n const last = stackFreq.get(v) == 0;\n if (idx == 0 && last) {\n dec(stackFreq, v);\n return;\n }\n if (idx == 1 && last) {\n pushOp(144);\n const [a, b] = pop2();\n stack.push(b);\n stack.push(a);\n pushD(null);\n dec(stackFreq, v);\n return;\n }\n pushS(v, -1);\n pushOp(128 + idx);\n pushD(null);\n return;\n }\n pushS(v);\n } else if (op === 0x51) {\n // MLOAD\n const k = Number(stack.pop()!);\n pushS(mem.has(k) ? mem.get(k)! : 0n);\n } else if (op === 0x52) {\n // MSTORE\n const [offset, value] = pop2();\n const k = Number(offset);\n mem.set(k, value & MASK32);\n trackMem(k, 32);\n } else if (op === 0x53) {\n // MSTORE8\n const [offset, _] = pop2();\n trackMem(Number(offset), 1);\n } else if (op === 0xf3) {\n // RETURN\n pop2();\n }\n pushOp(op);\n pushD(imm || null);\n };\n const isInStack = (w) => stack.includes(w) || w == 0xe0 || w == 32n;\n const op = (opcode: number) => addOp(opcode);\n const pushN = (value: number | bigint) => {\n if (value > 0 && value === trackedMemSize) return addOp(0x59);\n if (value == 32n) return addOp(0x36);\n if (!value) return addOp(0x5f, undefined); // PUSH0\n let v = BigInt(value);\n let bytes: number[] = [];\n while (v) {\n bytes.unshift(Number(v & 0xffn));\n v >>= 8n;\n }\n return addOp(0x5f + bytes.length, bytes);\n };\n const pushB = (buf: Uint8Array) => addOp(0x5f + buf.length, Array.from(buf));\n const cntWords = (hex: string, wordHex: string) =>\n (hex.match(new RegExp(wordHex, 'g')) || []).length;\n\n // Rough cost model\n const estShlCost = (seg: Array<{ s: number; e: number }>) => {\n let cost = 0;\n let first = true;\n for (const { s, e } of seg) {\n cost += 1 + e - s + 1; // PUSH segLen bytes\n if (31 - e > 0) cost += 1 /* PUSH1 */ + 1 /* shift byte */ + 1 /* SHL */;\n if (!first) cost += 1; // OR\n first = false;\n }\n return cost;\n };\n\n type PlanStep =\n | { t: 'num'; v: number | bigint }\n | { t: 'bytes'; b: Uint8Array }\n | { t: 'op'; o: number };\n\n const plan: PlanStep[] = [];\n const emitPushN = (v: number | bigint) => (plan.push({ t: 'num', v }), pushN(v));\n const emitPushB = (b: Uint8Array) => (plan.push({ t: 'bytes', b }), pushB(b));\n const emitOp = (o: number) => (plan.push({ t: 'op', o }), op(o));\n pushN(1n);\n // First pass: decide how to build each 32-byte word without emitting bytecode\n for (let base = 0; base < n; base += 32) {\n const word = new Uint8Array(32);\n word.set(buf.slice(base, Math.min(base + 32, n)), 0);\n\n const seg: Array<{ s: number; e: number }> = [];\n for (let i = 0; i < 32; ) {\n while (i < 32 && word[i] === 0) ++i;\n if (i >= 32) break;\n const s = i;\n while (i < 32 && word[i] !== 0) ++i;\n seg.push({ s, e: i - 1 });\n }\n\n if (!seg.length) continue;\n\n // Decide whether to build this word via SHL/OR or as a single literal word\n const literal = word.slice(seg[0].s);\n const literalCost = 1 + literal.length;\n let literalVal = 0n;\n for (const b of literal) literalVal = (literalVal << 8n) | BigInt(b);\n const baseBytes = Math.ceil(Math.log2(base + 1) / 8);\n const wordHex = _uint8ArrayToHex(word);\n if (literalCost > 8) {\n if (wordCache.has(wordHex)) {\n if (literalCost > wordCacheCost.get(wordHex)! + baseBytes) {\n emitPushN(wordCache.get(wordHex)!);\n emitOp(0x51);\n emitPushN(base);\n emitOp(0x52); // MSTORE\n continue;\n }\n } else if (wordCacheCost.get(wordHex) != -1) {\n const reuseCost = baseBytes + 3;\n const freq = cntWords(hex, wordHex);\n wordCacheCost.set(wordHex, freq * 32 > freq * reuseCost ? reuseCost : -1);\n wordCache.set(wordHex, base);\n }\n }\n\n // Convert literal bytes to bigint for stack comparison\n\n const byte8s = seg.every(({ s, e }) => s === e);\n if (isInStack(literal)) {\n emitPushB(literal);\n } else if (byte8s) {\n for (const { s } of seg) {\n emitPushN(word[s]);\n emitPushN(base + s);\n emitOp(0x53); // MSTORE8\n }\n continue;\n } else if (literalCost <= estShlCost(seg)) {\n emitPushB(literal);\n } else {\n let first = true;\n for (const { s, e } of seg) {\n const suffix0s = 31 - e;\n emitPushB(word.slice(s, e + 1));\n if (suffix0s > 0) {\n emitPushN(suffix0s * 8);\n emitOp(0x1b); // SHL\n }\n if (!first) emitOp(0x17); // OR\n first = false;\n }\n }\n emitPushN(base);\n emitOp(0x52); // MSTORE\n }\n\n ops = [];\n data = [];\n stack = [];\n trackedMemSize = 0;\n mem = new Map();\n // Pre 2nd pass. Push most frequent literals into stack.\n Array.from(stackFreq.entries())\n .filter(([val, freq]) => freq > 1 && val > 1n && val !== 32n && val !== 224n)\n .sort((a, b) => stackCnt.get(b[0])! - stackCnt.get(a[0])!)\n .filter(([val, _]) => {\n return typeof val === 'number' ? BigInt(val) : val <= MAX_160_BIT;\n })\n .slice(0, 13)\n .forEach(([val, _]) => {\n pushN(val);\n });\n pushN(1n);\n // Second pass: emit ops and track mem/stack\n for (const step of plan) {\n if (step.t === 'num') pushN(step.v);\n else if (step.t === 'bytes') pushB(step.b);\n else if (step.t === 'op') op(step.o);\n }\n\n // CALL stack layout (top to bottom): gas, address, value, argsOffset, argsSize, retOffset, retSize\n //\n // Opcodes breakdown:\n // - 0x5f5f: PUSH0 PUSH0 (retSize=0, retOffset=0)\n // - pushN(originalBuf.length): argsSize = actual data length\n // - pushN(padding): argsOffset (skip leading alignment bytes)\n // - 0x34: CALLVALUE (value)\n // - 0x5f35: PUSH0 CALLDATALOAD (address from calldata[0])\n // - 0x5a: GAS (remaining gas)\n // - 0xf1: CALL\n //\n // RETURNDATACOPY(destOffset=0, offset=0, length=RETURNDATASIZE):\n // - 0x3d5f5f3e: RETURNDATASIZE PUSH0 PUSH0 RETURNDATACOPY\n //\n // RETURN(offset=0, size=RETURNDATASIZE):\n // - 0x3d5ff3: RETURNDATASIZE PUSH0 RETURN\n\n op(0x5f); // PUSH0 (retSize)\n op(0x5f); // PUSH0 (retOffset)\n pushN(originalBuf.length); // argsSize = actual data length\n pushN(padding); // argsOffset = padding\n\n const out: number[] = [];\n for (let i = 0; i < ops.length; ++i) {\n out.push(ops[i]);\n if (ops[i] >= 0x60 && ops[i] <= 0x7f && data[i]) out.push(...data[i]!);\n }\n\n // - CALLVALUE, load target address from calldata[0], GAS, CALL\n // - RETURNDATACOPY(0, 0, RETURNDATASIZE)\n // - RETURN(0, RETURNDATASIZE)\n return '0x' + _uint8ArrayToHex(new Uint8Array(out)) + '345f355af13d5f5f3e3d5ff3';\n};\n\nconst MIN_SIZE_FOR_COMPRESSION = 1150;\nconst DECOMPRESSOR_ADDRESS = '0x00000000000000000000000000000000000000e0';\n\nconst _jit = 'jit';\nconst _flz = 'flz';\nconst _cd = 'cd';\n\n/**\n * Compresses eth_call payload using JIT, FastLZ (FLZ), or calldata RLE (CD) compression.\n * Auto-selects best algorithm if not specified. Only compresses if >800 bytes and beneficial.\n * @param payload - eth_call RPC payload\n * @param alg - 'jit' | 'flz' | 'cd' | undefined (auto)\n * @returns (un)compressed eth_call payload\n * @pure\n */\n//! @__PURE__\nexport const compress_call = function (payload: any, alg?: string): any {\n const rpcMethod = payload.params?.[0]?.method || payload.method;\n if (rpcMethod && rpcMethod !== 'eth_call') return payload;\n\n // Extract data and target address from params[0] if available, otherwise top-level\n const txObj = payload.params?.[0] || payload;\n const blockParam = payload.params?.[1] || 'latest';\n const existingStateOverride = payload.params?.[2] || {};\n\n // If there are any existing state overrides for the decompressor address, do not compress\n const hex = _normHex(txObj.data || '0x');\n const originalSize = (txObj.data || '0x').length;\n if (originalSize < MIN_SIZE_FOR_COMPRESSION || (existingStateOverride[DECOMPRESSOR_ADDRESS])) return payload;\n\n const targetAddress = txObj.to || '';\n const data = '0x' + hex;\n\n const autoSelect = !alg && originalSize < 1150;\n const flz = alg === _flz || autoSelect ? LibZip.flzCompress(data) : null;\n const cd = alg === _cd || autoSelect ? LibZip.cdCompress(data) : null;\n let selectedMethod = alg;\n if (!selectedMethod) {\n selectedMethod =\n originalSize >= 1150 && (originalSize < 3000 || originalSize >= 8000)\n ? _jit\n : originalSize >= 3000 && originalSize < 8000\n ? flz!.length < cd!.length\n ? _flz\n : _cd\n : _cd;\n }\n\n let bytecode: string;\n let calldata: string;\n\n if (selectedMethod === _jit) {\n bytecode = _jitDecompressor(data);\n calldata = '0x' + _normHex(targetAddress).padStart(64, '0');\n } else {\n const isFlz = selectedMethod === _flz;\n calldata = isFlz ? flz! : cd!;\n bytecode = isFlz ? flzFwdBytecode(targetAddress) : rleFwdBytecode(targetAddress);\n }\n\n const compressedSize = bytecode.length + calldata.length;\n if (compressedSize >= originalSize) return payload;\n\n return {\n ...payload,\n params: [\n {\n ...txObj,\n to: DECOMPRESSOR_ADDRESS,\n data: calldata,\n },\n blockParam,\n {\n ...existingStateOverride,\n [DECOMPRESSOR_ADDRESS]: { code: bytecode },\n },\n ],\n };\n};\n", "import zlib from 'node:zlib';\n\n// Polyfill for CompressionStream/DecompressionStream in Node.js\nconst make = (ctx: any, handle: any) =>\n Object.assign(ctx, {\n writable: new WritableStream({\n write(chunk) {\n handle.write(chunk);\n return Promise.resolve();\n },\n close() {\n handle.end();\n return Promise.resolve();\n },\n }),\n readable: new ReadableStream({\n type: 'bytes',\n start(ctrl) {\n handle.on('data', (chunk: any) => ctrl.enqueue(chunk));\n handle.once('end', () => ctrl.close());\n },\n }),\n });\n\nif (!globalThis.CompressionStream) {\n globalThis.CompressionStream = class CompressionStream {\n constructor(format: string) {\n let handle;\n if (format === 'deflate') {\n handle = zlib.createDeflate();\n } else if (format === 'gzip') {\n handle = zlib.createGzip();\n } else if (format === 'br') {\n handle = zlib.createBrotliCompress();\n } else {\n handle = zlib.createDeflateRaw();\n }\n make(this, handle);\n }\n } as any;\n}\n\nif (!globalThis.DecompressionStream) {\n globalThis.DecompressionStream = class DecompressionStream {\n constructor(format: string) {\n let handle;\n if (format === 'deflate') {\n handle = zlib.createInflate();\n } else if (format === 'gzip') {\n handle = zlib.createGunzip();\n } else if (format === 'br') {\n handle = zlib.createBrotliDecompress();\n } else {\n handle = zlib.createInflateRaw();\n }\n make(this, handle);\n }\n } as any;\n}\n\nexport * from './index';\n", "const _sup_enc = new Map<string, string[] | -1>();\nconst _enc = ['deflate-raw', 'deflate', 'gzip'];\nlet supported: string | -1 | null = typeof CompressionStream === 'undefined' ? -1 : null;\n\nexport type PayloadTransform = (payload: unknown) => unknown;\n\n/**\n * Fetch-compatible function that applies HTTP compression (gzip/deflate) to requests.\n * Optionally transforms request payloads before sending.\n *\n * @param input - The resource URL, Request object, or URL string\n * @param init - Optional request initialization options\n * @param transformPayload - Optional function to transform the request payload\n * @returns A Promise that resolves to the Response\n */\n//! @__PURE__\nexport async function compressModule(\n input: string | URL | Request,\n init?: RequestInit,\n): Promise<Response>;\n\n//! @__PURE__\nexport async function compressModule(\n input: string | URL | Request,\n init: RequestInit | undefined,\n transformPayload?: PayloadTransform,\n): Promise<Response>;\n\n//! @__PURE__\nexport async function compressModule(\n input: string | URL | Request,\n init?: RequestInit,\n transformPayload?: PayloadTransform,\n): Promise<Response> {\n const url =\n typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;\n\n const cached = _sup_enc.get(url);\n supported = supported === -1 ? -1 : cached === -1 ? -1 : (cached?.[0] ?? null);\n\n // Only apply the optional payload transform\n // when native HTTP compression is not available for this URL.\n if (transformPayload && init?.body && typeof init.body === 'string') {\n if (supported === -1 || supported === null) {\n try {\n const parsed = JSON.parse(init.body as string);\n const next = transformPayload(parsed);\n if (next !== undefined) {\n init = {\n ...init,\n body: JSON.stringify(next),\n };\n }\n } catch {\n // Non-JSON bodies are left untouched.\n }\n }\n }\n\n if (supported && supported !== -1 && init?.body) {\n const compressed = await new Response(\n new Blob([init.body as string])\n .stream()\n .pipeThrough(new CompressionStream(supported as CompressionFormat)),\n ).blob();\n init = {\n ...init,\n body: compressed,\n headers: { ...(init && init.headers), 'Content-Encoding': supported },\n };\n }\n const response = await fetch(url, init);\n\n if (supported === null) {\n const encodings = response.headers\n .get('Accept-Encoding')\n ?.split(',')\n .filter((e) => _enc.includes(e));\n _sup_enc.set(url, encodings?.length ? encodings : -1);\n }\n\n return response;\n}\n\n/**\n * Combines HTTP compression with EVM JIT compression.\n * Just pass this as `fetchFn` to viem's http transport.\n *\n * @param input - The resource URL or Request object\n * @param init - Optional request initialization options\n * @returns A Promise that resolves to the Response\n *\n * @example\n * ```ts\n * const client = createPublicClient({\n * transport: http(rpcUrl, { fetchFn: compressModuleWithJIT })\n * })\n * ```\n *\n * If the target RPC endpoint and runtime support native HTTP compression,\n * this helper prefers that path and will not apply JIT calldata compression;\n * the JIT-based transform is used as a legacy/fallback path when HTTP\n * content-encoding is unavailable.\n * @pure\n */\n//! @__PURE__\nexport const compressModuleWithJIT = (\n input: RequestInfo | URL,\n init?: RequestInit,\n): Promise<Response> => {\n return import('./jit-compressor').then(({ compress_call }) =>\n compressModule(input, init, compress_call),\n );\n};\n"],
|
|
5
|
+
"mappings": "imBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,mBAAAE,GAAA,mBAAAC,GAAA,gBAAAC,GAAA,mBAAAC,KAAA,IAAAC,EAEMC,GAEAC,EAEAC,GAUAC,GAeOP,GAUAE,GASAD,GAIPO,GAsTAC,GACAC,EAEAC,GACAC,EACAC,EAWOd,GA5Xbe,GAAAC,GAAA,KAAAZ,EAAuB,kBAEjBC,IAAe,IAAM,MAAQ,GAE7BC,EAAYW,GAAwBA,EAAI,QAAQ,MAAO,EAAE,EAAE,YAAY,EAEvEV,GAAoBU,GAA4B,CACpD,IAAMC,EAAaZ,EAASW,CAAG,EACzBE,EAAMD,EAAW,OACjBE,EAAQ,IAAI,WAAWD,EAAM,CAAC,EACpC,QAASE,EAAI,EAAGA,EAAIF,EAAKE,GAAK,EAC5BD,EAAMC,EAAI,CAAC,EAAI,OAAO,SAASH,EAAW,MAAMG,EAAGA,EAAI,CAAC,EAAG,EAAE,EAE/D,OAAOD,CACT,EAEMZ,GAAoBY,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AEnCJ,EAAS,EAAAI,QAAK,iBAAiB,EAEjCN,GAAK,KAAME,CAAM,CACnB,CACF,GAGG,WAAW,sBACd,WAAW,oBAAsB,KAA0B,CACzD,YAAYG,EAAgB,CAC1B,IAAIH,EACAG,IAAW,UACbH,EAAS,EAAAI,QAAK,cAAc,EACnBD,IAAW,OACpBH,EAAS,EAAAI,QAAK,aAAa,EAClBD,IAAW,KACpBH,EAAS,EAAAI,QAAK,uBAAuB,EAErCJ,EAAS,EAAAI,QAAK,iBAAiB,EAEjCN,GAAK,KAAME,CAAM,CACnB,CACF",
|
|
6
|
+
"names": ["jit_compressor_exports", "__export", "compress_call", "flzFwdBytecode", "jitBytecode", "rleFwdBytecode", "import_solady", "MAX_160_BIT", "_normHex", "_hexToUint8Array", "_uint8ArrayToHex", "_jitDecompressor", "MIN_SIZE_FOR_COMPRESSION", "DECOMPRESSOR_ADDRESS", "_jit", "_flz", "_cd", "init_jit_compressor", "__esmMin", "hex", "normalized", "len", "bytes", "i", "address", "calldata", "originalBuf", "padding", "buf", "n", "ops", "data", "stack", "trackedMemSize", "mem", "getStackIdx", "val", "idx", "opFreq", "dataFreq", "stackFreq", "wordCache", "wordCacheCost", "roundUp32", "x", "pushCounter", "stackCnt", "pop2", "MASK32", "ctr", "m", "k", "delta", "inc", "dec", "pushOp", "op", "pushD", "d", "pushS", "v", "freq", "trackMem", "offset", "size", "addOp", "imm", "shift", "a", "b", "last", "value", "_", "isInStack", "w", "opcode", "pushN", "pushB", "cntWords", "wordHex", "estShlCost", "seg", "cost", "first", "s", "e", "plan", "emitPushN", "emitPushB", "emitOp", "o", "base", "word", "literal", "literalCost", "literalVal", "baseBytes", "reuseCost", "byte8s", "suffix0s", "step", "out", "payload", "alg", "rpcMethod", "txObj", "blockParam", "existingStateOverride", "originalSize", "targetAddress", "autoSelect", "flz", "cd", "selectedMethod", "bytecode", "isFlz", "index_node_exports", "__export", "compressModule", "compressModuleWithJIT", "__toCommonJS", "import_node_zlib", "_sup_enc", "_enc", "supported", "compressModule", "input", "init", "transformPayload", "url", "cached", "parsed", "next", "compressed", "response", "encodings", "e", "compressModuleWithJIT", "compress_call", "make", "ctx", "handle", "chunk", "ctrl", "format", "zlib"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
var Z=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var bt=Object.getOwnPropertyNames;var gt=Object.prototype.hasOwnProperty;var mt=(s,r)=>{for(var c in r)Z(s,c,{get:r[c],enumerable:!0})},ht=(s,r,c,u)=>{if(r&&typeof r=="object"||typeof r=="function")for(let f of bt(r))!gt.call(s,f)&&f!==c&&Z(s,f,{get:()=>r[f],enumerable:!(u=at(r,f))||u.enumerable});return s};var pt=s=>ht(Z({},"__esModule",{value:!0}),s);var yt={};mt(yt,{compress_call:()=>wt,flzFwdBytecode:()=>ot,jitBytecode:()=>Mt,rleFwdBytecode:()=>it});module.exports=pt(yt);var X=require("solady");const xt=(1n<<128n)-1n,y=s=>s.replace(/^0x/,"").toLowerCase(),dt=s=>{const r=y(s),c=r.length,u=new Uint8Array(c/2);for(let f=0;f<c;f+=2)u[f/2]=Number.parseInt(r.slice(f,f+2),16);return u},et=s=>{let r="";for(let c=0;c<s.length;c++)r+=s[c].toString(16).padStart(2,"0");return r};//! @__PURE__
|
|
2
|
+
const ot=s=>`0x365f73${y(s)}815b838110602f575f80848134865af1503d5f803e3d5ff35b803590815f1a8060051c908115609857600190600783149285831a6007018118840218600201948383011a90601f1660081b0101808603906020811860208211021890815f5b80830151818a015201858110609257505050600201019201916018565b82906075565b6001929350829150019101925f5b82811060b3575001916018565b85851060c1575b60010160a6565b936001818192355f1a878501530194905060ba56`;//! @__PURE__
|
|
3
|
+
const it=s=>`0x5f5f5b368110602d575f8083813473${y(s)}5af1503d5f803e3d5ff35b600180820192909160031981019035185f1a8015604c57815301906002565b505f19815282820192607f9060031981019035185f1a818111156072575b160101906002565b838101368437606a56`;//! @__PURE__
|
|
4
|
+
const Mt=function(s){return st("0x"+y(s))},st=function(s){const r=y(s),c=dt(r),u=28,f=new Uint8Array(u+c.length);f.set(c,u);const z=f.length;let a=[],l=[],b=[],h=0,M=new Map;const O=t=>{const n=b.lastIndexOf(t);return n===-1?-1:b.length-1-n},U=new Map,A=new Map,m=new Map,p=new Map,k=new Map,K=t=>t+31&-32;let G=0;const D=new Map,_=()=>[b.pop(),b.pop()],q=(1n<<256n)-1n,H=(t,n,e)=>t.set(n,(t.get(n)||0)+e),J=(t,n)=>H(t,n,1),Q=(t,n)=>H(t,n,-1),N=t=>{a.push(t),J(U,t)},E=t=>{l.push(t||null),J(A,t||null)},x=(t,n=1)=>{b.push(t),H(m,t,n),++G,D.set(t,G)},Y=(t,n)=>{h=K(t+n)},B=(t,n)=>{if(t===54)x(32n,0);else if(t===89)x(BigInt(h),0);else if(t===27){let[e,i]=_();a[a.length-1]==144&&(a.pop(),l.pop(),[e,i]=[i,e]),x(i<<BigInt(e)&q)}else if(t===23){const[e,i]=_();a[a.length-1]==144&&(a.pop(),l.pop()),x((e|i)&q)}else if(t>=96&&t<=127||t===95){let e=0n;for(const g of n||[])e=e<<8n|BigInt(g);if(e==224n){x(e),N(48),E(null);return}const i=O(e);if(i!==-1&&t!=95){const g=m.get(e)==0;if(i==0&&g){Q(m,e);return}if(i==1&&g){N(144);const[R,j]=_();b.push(j),b.push(R),E(null),Q(m,e);return}x(e,-1),N(128+i),E(null);return}x(e)}else if(t===81){const e=Number(b.pop());x(M.has(e)?M.get(e):0n)}else if(t===82){const[e,i]=_(),g=Number(e);M.set(g,i&q),Y(g,32)}else if(t===83){const[e,i]=_();Y(Number(e),1)}else t===243&&_();N(t),E(n||null)},ct=t=>b.includes(t)||t==224||t==32n,F=t=>B(t),S=t=>{if(t>0&&t===h)return B(89);if(t==32n)return B(54);if(!t)return B(95,void 0);let n=BigInt(t),e=[];for(;n;)e.unshift(Number(n&0xffn)),n>>=8n;return B(95+e.length,e)},v=t=>B(95+t.length,Array.from(t)),ft=(t,n)=>(t.match(new RegExp(n,"g"))||[]).length,lt=t=>{let n=0,e=!0;for(const{s:i,e:g}of t)n+=1+g-i+1,31-g>0&&(n+=3),e||(n+=1),e=!1;return n},P=[],I=t=>(P.push({t:"num",v:t}),S(t)),T=t=>(P.push({t:"bytes",b:t}),v(t)),C=t=>(P.push({t:"op",o:t}),F(t));S(1n);for(let t=0;t<z;t+=32){const n=new Uint8Array(32);n.set(f.slice(t,Math.min(t+32,z)),0);const e=[];for(let o=0;o<32;){for(;o<32&&n[o]===0;)++o;if(o>=32)break;const d=o;for(;o<32&&n[o]!==0;)++o;e.push({s:d,e:o-1})}if(!e.length)continue;const i=n.slice(e[0].s),g=1+i.length;let R=0n;for(const o of i)R=R<<8n|BigInt(o);const j=Math.ceil(Math.log2(t+1)/8),w=et(n);if(g>8){if(p.has(w)){if(g>k.get(w)+j){I(p.get(w)),C(81),I(t),C(82);continue}}else if(k.get(w)!=-1){const o=j+3,d=ft(r,w);k.set(w,d*32>d*o?o:-1),p.set(w,t)}}const ut=e.every(({s:o,e:d})=>o===d);if(ct(i))T(i);else if(ut){for(const{s:o}of e)I(n[o]),I(t+o),C(83);continue}else if(g<=lt(e))T(i);else{let o=!0;for(const{s:d,e:tt}of e){const nt=31-tt;T(n.slice(d,tt+1)),nt>0&&(I(nt*8),C(27)),o||C(23),o=!1}}I(t),C(82)}a=[],l=[],b=[],h=0,M=new Map,Array.from(m.entries()).filter(([t,n])=>n>1&&t>1n&&t!==32n&&t!==224n).sort((t,n)=>D.get(n[0])-D.get(t[0])).filter(([t,n])=>typeof t=="number"?BigInt(t):t<=xt).slice(0,13).forEach(([t,n])=>{S(t)}),S(1n);for(const t of P)t.t==="num"?S(t.v):t.t==="bytes"?v(t.b):t.t==="op"&&F(t.o);F(95),F(95),S(c.length),S(u);const L=[];for(let t=0;t<a.length;++t)L.push(a[t]),a[t]>=96&&a[t]<=127&&l[t]&&L.push(...l[t]);return"0x"+et(new Uint8Array(L))+"345f355af13d5f5f3e3d5ff3"},St=1150,$="0x00000000000000000000000000000000000000e0",rt="jit",V="flz",W="cd";//! @__PURE__
|
|
5
|
+
const wt=function(s,r){const c=s.params?.[0]?.method||s.method;if(c&&c!=="eth_call")return s;const u=s.params?.[0]||s,f=s.params?.[1]||"latest",z=s.params?.[2]||{},a=y(u.data||"0x"),l=(u.data||"0x").length;if(l<St||z[$])return s;const b=u.to||"",h="0x"+a,M=!r&&l<1150,O=r===V||M?X.LibZip.flzCompress(h):null,U=r===W||M?X.LibZip.cdCompress(h):null;let A=r;A||(A=l>=1150&&(l<3e3||l>=8e3)?rt:l>=3e3&&l<8e3&&O.length<U.length?V:W);let m,p;if(A===rt)m=st(h),p="0x"+y(b).padStart(64,"0");else{const K=A===V;p=K?O:U,m=K?ot(b):it(b)}return m.length+p.length>=l?s:{...s,params:[{...u,to:$,data:p},f,{...z,[$]:{code:m}}]}};
|
|
6
|
+
//# sourceMappingURL=jit-compressor.cjs.map
|