eth-prototype 1.0.1__py3-none-any.whl → 1.1.0__py3-none-any.whl

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: eth-prototype
3
- Version: 1.0.1
3
+ Version: 1.1.0
4
4
  Summary: Prototype Ethereum Smart Contracts in Python
5
5
  Home-page: https://github.com/gnarvaja/eth-prototype
6
6
  Author: Guillermo M. Narvaja
@@ -18,24 +18,20 @@ Requires-Dist: m9g
18
18
  Requires-Dist: environs
19
19
  Requires-Dist: requests
20
20
  Requires-Dist: hexbytes
21
- Requires-Dist: importlib-metadata ; python_version < "3.8"
21
+ Requires-Dist: importlib-metadata; python_version < "3.8"
22
22
  Provides-Extra: defender
23
- Requires-Dist: boto3 ; extra == 'defender'
23
+ Requires-Dist: boto3; extra == "defender"
24
24
  Provides-Extra: gmpy2
25
- Requires-Dist: gmpy2 ; extra == 'gmpy2'
25
+ Requires-Dist: gmpy2; extra == "gmpy2"
26
26
  Provides-Extra: testing
27
- Requires-Dist: setuptools ; extra == 'testing'
28
- Requires-Dist: pytest ; extra == 'testing'
29
- Requires-Dist: gmpy2 ; extra == 'testing'
30
- Requires-Dist: pytest-cov ; extra == 'testing'
31
- Provides-Extra: testing-w3
32
- Requires-Dist: web3[tester] >=6 ; extra == 'testing-w3'
33
- Requires-Dist: setuptools ; extra == 'testing-w3'
34
- Requires-Dist: pytest ; extra == 'testing-w3'
35
- Requires-Dist: pytest-cov ; extra == 'testing-w3'
36
- Requires-Dist: boto3 ; extra == 'testing-w3'
27
+ Requires-Dist: setuptools; extra == "testing"
28
+ Requires-Dist: pytest; extra == "testing"
29
+ Requires-Dist: gmpy2; extra == "testing"
30
+ Requires-Dist: pytest-cov; extra == "testing"
31
+ Requires-Dist: web3[tester]==6.*; extra == "testing"
32
+ Requires-Dist: boto3; extra == "testing"
37
33
  Provides-Extra: web3
38
- Requires-Dist: web3 >=6 ; extra == 'web3'
34
+ Requires-Dist: web3==6.*; extra == "web3"
39
35
 
40
36
  # eth-prototype
41
37
 
@@ -0,0 +1,14 @@
1
+ ethproto/__init__.py,sha256=YWkAFysBp4tZjLWWB2FFmp5yG23pUYhQvgQW9b3soXs,579
2
+ ethproto/aa_bundler.py,sha256=34yXgQw_vV81Wmf9cFxcLTxLUb1jzCrBE7XOw5RIjtI,8652
3
+ ethproto/build_artifacts.py,sha256=xwCd5hJUHP82IA-y3sSfX6fV15kjCGtV19RxNRcoor0,5441
4
+ ethproto/contracts.py,sha256=rNVbCK1hURy7lWKhzSdXgVWo3wx9O_Ghk-6PfgOsRNk,18662
5
+ ethproto/defender_relay.py,sha256=05A8TfRZwiBhCpo924Pf9CjfKSir2Wvgg1p_asFxJbw,1777
6
+ ethproto/w3wrappers.py,sha256=UbSuaB5_TYF4kiGNwIzvPPE7f0A6soZ7gc5jd180mVM,21065
7
+ ethproto/wadray.py,sha256=JBsu5KcyU9k70bDK03T2IY6qPVFO30WbYPhwrAHdXao,8262
8
+ ethproto/wrappers.py,sha256=9qDwRDOXw3wquzvGfIsub-VPWm98GBWP7dHLFOUPWzg,17307
9
+ eth_prototype-1.1.0.dist-info/AUTHORS.rst,sha256=Ui-05yYXtDZxna6o1yNcfdm8Jt68UIDQ01osiLxlYlU,95
10
+ eth_prototype-1.1.0.dist-info/LICENSE.txt,sha256=U_Q6_nDYDwZPIuhttHi37hXZ2qU2-HlV2geo9hzHXFw,1087
11
+ eth_prototype-1.1.0.dist-info/METADATA,sha256=uOJw45vu6Xwc3uzJ1IfWV0RW1i2ST_ZHJ775Uwbi7zk,2482
12
+ eth_prototype-1.1.0.dist-info/WHEEL,sha256=UvcQYKBHoFqaQd6LKyqHw9fxEolWLQnlzP0h_LgJAfI,91
13
+ eth_prototype-1.1.0.dist-info/top_level.txt,sha256=Dl0X7m6N1hxeo4JpGpSNqWC2gtsN0731g-DL1J0mpjc,9
14
+ eth_prototype-1.1.0.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: bdist_wheel (0.43.0)
2
+ Generator: setuptools (74.0.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
ethproto/aa_bundler.py ADDED
@@ -0,0 +1,234 @@
1
+ import random
2
+ from warnings import warn
3
+ from enum import Enum
4
+ import requests
5
+ from environs import Env
6
+ from eth_abi import encode
7
+ from eth_account import Account
8
+ from eth_account.messages import encode_defunct
9
+ from hexbytes import HexBytes
10
+ from web3 import Web3
11
+ from .contracts import RevertError
12
+
13
+
14
+ env = Env()
15
+
16
+ AA_BUNDLER_SENDER = env.str("AA_BUNDLER_SENDER", None)
17
+ AA_BUNDLER_ENTRYPOINT = env.str("AA_BUNDLER_ENTRYPOINT", "0x0000000071727De22E5E9d8BAf0edAc6f37da032")
18
+ AA_BUNDLER_EXECUTOR_PK = env.str("AA_BUNDLER_EXECUTOR_PK", None)
19
+ AA_BUNDLER_PROVIDER = env.str("AA_BUNDLER_PROVIDER", "alchemy")
20
+
21
+ NonceMode = Enum(
22
+ "NonceMode",
23
+ [
24
+ "RANDOM_KEY", # first time initializes a random key and increments nonce locally with calling the blockchain
25
+ "FIXED_KEY_LOCAL_NONCE", # uses a fixed key, keeps nonce locally and fetches the nonce when receiving
26
+ # 'AA25 invalid account nonce'
27
+ "FIXED_KEY_FETCH_ALWAYS", # uses a fixed key, always fetches unless received as parameter
28
+ ],
29
+ )
30
+
31
+ AA_BUNDLER_NONCE_MODE = env.enum("AA_BUNDLER_NONCE_MODE", default="FIXED_KEY_LOCAL_NONCE", type=NonceMode)
32
+ AA_BUNDLER_NONCE_KEY = env.int("AA_BUNDLER_NONCE_KEY", 0)
33
+ AA_BUNDLER_MAX_GETNONCE_RETRIES = env.int("AA_BUNDLER_MAX_GETNONCE_RETRIES", 3)
34
+
35
+
36
+ GET_NONCE_ABI = [
37
+ {
38
+ "inputs": [
39
+ {"internalType": "address", "name": "sender", "type": "address"},
40
+ {"internalType": "uint192", "name": "key", "type": "uint192"},
41
+ ],
42
+ "name": "getNonce",
43
+ "outputs": [{"internalType": "uint256", "name": "nonce", "type": "uint256"}],
44
+ "stateMutability": "view",
45
+ "type": "function",
46
+ }
47
+ ]
48
+
49
+ NONCE_CACHE = {}
50
+ RANDOM_NONCE_KEY = None
51
+
52
+
53
+ def pack_two(a, b):
54
+ a = HexBytes(a).hex()[2:]
55
+ b = HexBytes(b).hex()[2:]
56
+ return "0x" + a.zfill(32) + b.zfill(32)
57
+
58
+
59
+ def _to_uint(x):
60
+ if isinstance(x, str):
61
+ return int(x, 16)
62
+ elif isinstance(x, int):
63
+ return x
64
+ raise RuntimeError(f"Invalid int value {x}")
65
+
66
+
67
+ def pack_user_operation(user_operation):
68
+ # https://github.com/eth-infinitism/account-abstraction/blob/develop/contracts/interfaces/PackedUserOperation.sol
69
+ return {
70
+ "sender": user_operation["sender"],
71
+ "nonce": _to_uint(user_operation["nonce"]),
72
+ "initCode": "0x",
73
+ "callData": user_operation["callData"],
74
+ "accountGasLimits": pack_two(user_operation["verificationGasLimit"], user_operation["callGasLimit"]),
75
+ "preVerificationGas": _to_uint(user_operation["preVerificationGas"]),
76
+ "gasFees": pack_two(user_operation["maxPriorityFeePerGas"], user_operation["maxFeePerGas"]),
77
+ "paymasterAndData": "0x",
78
+ "signature": "0x",
79
+ }
80
+
81
+
82
+ def hash_packed_user_operation_only(packed_user_op):
83
+ # https://github.com/eth-infinitism/account-abstraction/blob/develop/contracts/core/UserOperationLib.sol#L54
84
+ hash_init_code = Web3.solidity_keccak(["bytes"], [packed_user_op["initCode"]])
85
+ hash_call_data = Web3.solidity_keccak(["bytes"], [packed_user_op["callData"]])
86
+ hash_paymaster_and_data = Web3.solidity_keccak(["bytes"], [packed_user_op["paymasterAndData"]])
87
+ return Web3.keccak(
88
+ hexstr=encode(
89
+ ["address", "uint256", "bytes32", "bytes32", "bytes32", "uint256", "bytes32", "bytes32"],
90
+ [
91
+ packed_user_op["sender"],
92
+ packed_user_op["nonce"],
93
+ hash_init_code,
94
+ hash_call_data,
95
+ HexBytes(packed_user_op["accountGasLimits"]),
96
+ packed_user_op["preVerificationGas"],
97
+ HexBytes(packed_user_op["gasFees"]),
98
+ hash_paymaster_and_data,
99
+ ],
100
+ ).hex()
101
+ ).hex()
102
+
103
+
104
+ def hash_packed_user_operation(packed_user_op, chain_id, entry_point):
105
+ return Web3.keccak(
106
+ hexstr=encode(
107
+ ["bytes32", "address", "uint256"],
108
+ [HexBytes(hash_packed_user_operation_only(packed_user_op)), entry_point, chain_id],
109
+ ).hex()
110
+ ).hex()
111
+
112
+
113
+ def sign_user_operation(private_key, user_operation, chain_id, entry_point):
114
+ packed_user_op = pack_user_operation(user_operation)
115
+ hash = hash_packed_user_operation(packed_user_op, chain_id, entry_point)
116
+ signature = Account.sign_message(encode_defunct(hexstr=hash), private_key)
117
+ return signature.signature.hex()
118
+
119
+
120
+ def make_nonce(nonce_key, nonce):
121
+ nonce_key = _to_uint(nonce_key)
122
+ nonce = _to_uint(nonce)
123
+ return (nonce_key << 64) | nonce
124
+
125
+
126
+ def fetch_nonce(w3, account, entry_point, nonce_key):
127
+ ep = w3.eth.contract(abi=GET_NONCE_ABI, address=entry_point)
128
+ return ep.functions.getNonce(account, nonce_key).call()
129
+
130
+
131
+ def get_random_nonce_key():
132
+ global RANDOM_NONCE_KEY
133
+ if RANDOM_NONCE_KEY is None:
134
+ RANDOM_NONCE_KEY = random.randint(1, 2**192 - 1)
135
+ return RANDOM_NONCE_KEY
136
+
137
+
138
+ def get_nonce_and_key(w3, tx, nonce_mode, entry_point=AA_BUNDLER_ENTRYPOINT, fetch=False):
139
+ nonce_key = tx.get("nonceKey", None)
140
+ nonce = tx.get("nonce", None)
141
+
142
+ if nonce_key is None:
143
+ if nonce_mode == NonceMode.RANDOM_KEY:
144
+ nonce_key = get_random_nonce_key()
145
+ else:
146
+ nonce_key = AA_BUNDLER_NONCE_KEY
147
+
148
+ if nonce is None:
149
+ if fetch or nonce_mode == NonceMode.FIXED_KEY_FETCH_ALWAYS:
150
+ nonce = fetch_nonce(w3, tx.get("from", AA_BUNDLER_SENDER), entry_point, nonce_key)
151
+ elif nonce_key not in NONCE_CACHE:
152
+ nonce = 0
153
+ else:
154
+ nonce = NONCE_CACHE[nonce_key]
155
+ return nonce_key, nonce
156
+
157
+
158
+ def handle_response_error(resp, w3, tx, retry_nonce):
159
+ if "AA25" in resp["error"]["message"] and AA_BUNDLER_MAX_GETNONCE_RETRIES > 0:
160
+ # Retry fetching the nonce
161
+ if retry_nonce == AA_BUNDLER_MAX_GETNONCE_RETRIES:
162
+ raise RevertError(resp["error"]["message"])
163
+ warn(f'{resp["error"]["message"]} error, I will retry fetching the nonce')
164
+ return send_transaction(w3, tx, retry_nonce=(retry_nonce or 0) + 1)
165
+ else:
166
+ raise RevertError(resp["error"]["message"])
167
+
168
+
169
+ def get_base_fee(w3):
170
+ blk = w3.eth.get_block("latest")
171
+ return blk["baseFeePerGas"]
172
+
173
+
174
+ def send_transaction(w3, tx, retry_nonce=None):
175
+ nonce_key, nonce = get_nonce_and_key(
176
+ w3, tx, AA_BUNDLER_NONCE_MODE, entry_point=AA_BUNDLER_ENTRYPOINT, fetch=retry_nonce is not None
177
+ )
178
+ # "0xb61d27f6" = bytes4 hash of execute(address,uint256,bytes)
179
+ call_data = (
180
+ "0xb61d27f6"
181
+ + encode(["address", "uint256", "bytes"], [tx["to"], tx["value"], HexBytes(tx["data"])]).hex()
182
+ )
183
+ dummy_signature = (
184
+ "0xfffffffffffffffffffffffffffffff0000000000000000000000000000000007"
185
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1c"
186
+ )
187
+ user_operation = {
188
+ "sender": tx.get("from", AA_BUNDLER_SENDER),
189
+ "nonce": hex(make_nonce(nonce_key, nonce)),
190
+ "callData": call_data,
191
+ "signature": dummy_signature,
192
+ }
193
+
194
+ if AA_BUNDLER_PROVIDER == "alchemy":
195
+ resp = w3.provider.make_request(
196
+ "eth_estimateUserOperationGas", [user_operation, AA_BUNDLER_ENTRYPOINT]
197
+ )
198
+ if "error" in resp:
199
+ return handle_response_error(resp, w3, tx, retry_nonce)
200
+
201
+ user_operation.update(resp["result"])
202
+
203
+ resp = w3.provider.make_request("rundler_maxPriorityFeePerGas", [])
204
+ if "error" in resp:
205
+ raise RevertError(resp["error"]["message"])
206
+ max_priority_fee_per_gas = resp["result"]
207
+ user_operation["maxPriorityFeePerGas"] = max_priority_fee_per_gas
208
+ user_operation["maxFeePerGas"] = hex(_to_uint(max_priority_fee_per_gas) + _to_uint(get_base_fee(w3)))
209
+ elif AA_BUNDLER_PROVIDER == "gelato":
210
+ user_operation.update(
211
+ {
212
+ "preVerificationGas": "0x00",
213
+ "callGasLimit": "0x00",
214
+ "verificationGasLimit": "0x00",
215
+ "maxFeePerGas": "0x00",
216
+ "maxPriorityFeePerGas": "0x00",
217
+ }
218
+ )
219
+ user_operation["signature"] = sign_user_operation(
220
+ AA_BUNDLER_EXECUTOR_PK, user_operation, tx["chainId"], AA_BUNDLER_ENTRYPOINT
221
+ )
222
+ # Remove paymaster related fields
223
+ user_operation.pop("paymaster", None)
224
+ user_operation.pop("paymasterData", None)
225
+ user_operation.pop("paymasterVerificationGasLimit", None)
226
+ user_operation.pop("paymasterPostOpGasLimit", None)
227
+
228
+ resp = w3.provider.make_request("eth_sendUserOperation", [user_operation, AA_BUNDLER_ENTRYPOINT])
229
+ if "error" in resp:
230
+ return handle_response_error(resp, w3, tx, retry_nonce)
231
+
232
+ # Store nonce in the cache, so next time uses a new nonce
233
+ NONCE_CACHE[nonce_key] = nonce + 1
234
+ return resp["result"]
@@ -1,6 +1,5 @@
1
1
  """Helper classes to use hardhat build artifacts from python"""
2
2
 
3
-
4
3
  import json
5
4
  import os
6
5
  import os.path
@@ -26,17 +25,15 @@ class Artifact:
26
25
  self.abi = kwargs["abi"]
27
26
  self.bytecode = kwargs["bytecode"]
28
27
  self.deployed_bytecode = kwargs["deployedBytecode"]
29
- self.link_references = kwargs["linkReferences"]
30
- self.deployed_link_references = kwargs["deployedLinkReferences"]
28
+ self.link_references = kwargs.get("linkReferences", {})
29
+ self.deployed_link_references = kwargs.get("deployedLinkReferences", {})
31
30
 
32
31
  def link(self, libraries: dict) -> "Artifact":
33
32
  """Returns a new artifact with the external libraries linked
34
33
 
35
34
  Libraries is a dictionary of the form {library_name: address}
36
35
  """
37
- bytecode = self._replace_link_references(
38
- self.bytecode, self.link_references, libraries
39
- )
36
+ bytecode = self._replace_link_references(self.bytecode, self.link_references, libraries)
40
37
  deployed_bytecode = self._replace_link_references(
41
38
  self.deployed_bytecode, self.deployed_link_references, libraries
42
39
  )
@@ -55,9 +52,7 @@ class Artifact:
55
52
  for lib in libs.keys():
56
53
  yield lib, source
57
54
 
58
- def _replace_link_references(
59
- self, bytecode: str, link_references: dict, libraries: dict
60
- ) -> str:
55
+ def _replace_link_references(self, bytecode: str, link_references: dict, libraries: dict) -> str:
61
56
  # remove 0x prefix if present
62
57
  bytecode = bytecode[2:] if bytecode.startswith("0x") else bytecode
63
58
 
@@ -115,17 +110,13 @@ class ArtifactLibrary:
115
110
 
116
111
  if contract not in self._fullpath_cache:
117
112
  for path in self.lookup_paths:
118
- build_artifact_path = (
119
- path / contract / contract.with_suffix(".json").name
120
- )
113
+ build_artifact_path = path / contract / contract.with_suffix(".json").name
121
114
  if build_artifact_path.exists():
122
115
  with open(build_artifact_path) as f:
123
116
  self._fullpath_cache[contract] = Artifact(**json.load(f))
124
117
 
125
118
  if contract not in self._fullpath_cache:
126
- raise FileNotFoundError(
127
- f"Could not find artifact for {contract} on {self.lookup_paths}"
128
- )
119
+ raise FileNotFoundError(f"Could not find artifact for {contract} on {self.lookup_paths}")
129
120
 
130
121
  return self._fullpath_cache[contract]
131
122
 
@@ -145,8 +136,6 @@ class ArtifactLibrary:
145
136
  self._name_cache[contract_name] = Artifact(**json.load(f))
146
137
 
147
138
  if contract_name not in self._name_cache:
148
- raise FileNotFoundError(
149
- f"Could not find artifact for {contract_name} on {self.lookup_paths}"
150
- )
139
+ raise FileNotFoundError(f"Could not find artifact for {contract_name} on {self.lookup_paths}")
151
140
 
152
141
  return self._name_cache[contract_name]
ethproto/w3wrappers.py CHANGED
@@ -108,9 +108,19 @@ def transact(provider, function, tx_kwargs):
108
108
  elif W3_TRANSACT_MODE == "defender-async":
109
109
  from .defender_relay import send_transaction
110
110
 
111
- tx_kwargs = {**provider.tx_kwargs, **tx_kwargs}
111
+ tx_kwargs |= provider.tx_kwargs
112
112
  tx = function.build_transaction(tx_kwargs)
113
113
  return send_transaction(tx)
114
+ elif W3_TRANSACT_MODE == "aa-bundler-async":
115
+ from .aa_bundler import send_transaction
116
+
117
+ tx_kwargs |= provider.tx_kwargs
118
+ # To avoid fetching gas and gasPrice in a standard way, when it's not relevant for user ops
119
+ tx_kwargs.update(dict(gas=0, gasPrice=0))
120
+ tx = function.build_transaction(tx_kwargs)
121
+ return send_transaction(provider.w3, tx)
122
+ else:
123
+ raise RuntimeError(f"Unknown W3_TRANSACT_MODE {W3_TRANSACT_MODE}")
114
124
 
115
125
  return provider.w3.eth.wait_for_transaction_receipt(tx_hash)
116
126
 
@@ -1,13 +0,0 @@
1
- ethproto/__init__.py,sha256=YWkAFysBp4tZjLWWB2FFmp5yG23pUYhQvgQW9b3soXs,579
2
- ethproto/build_artifacts.py,sha256=FzgUO6ierhCVBKHRxTkgrRx4AaAL6G5ql5Yzx_oTTmg,5578
3
- ethproto/contracts.py,sha256=rNVbCK1hURy7lWKhzSdXgVWo3wx9O_Ghk-6PfgOsRNk,18662
4
- ethproto/defender_relay.py,sha256=05A8TfRZwiBhCpo924Pf9CjfKSir2Wvgg1p_asFxJbw,1777
5
- ethproto/w3wrappers.py,sha256=MrRf7GLFgDhKYKiTctjNONZHQNTo6nVzqPzprv0BU2w,20607
6
- ethproto/wadray.py,sha256=JBsu5KcyU9k70bDK03T2IY6qPVFO30WbYPhwrAHdXao,8262
7
- ethproto/wrappers.py,sha256=9qDwRDOXw3wquzvGfIsub-VPWm98GBWP7dHLFOUPWzg,17307
8
- eth_prototype-1.0.1.dist-info/AUTHORS.rst,sha256=Ui-05yYXtDZxna6o1yNcfdm8Jt68UIDQ01osiLxlYlU,95
9
- eth_prototype-1.0.1.dist-info/LICENSE.txt,sha256=U_Q6_nDYDwZPIuhttHi37hXZ2qU2-HlV2geo9hzHXFw,1087
10
- eth_prototype-1.0.1.dist-info/METADATA,sha256=TE-gm2NZKjLg7mgbihmuddG0XwORT7DrAM8UqtLPMtg,2669
11
- eth_prototype-1.0.1.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
12
- eth_prototype-1.0.1.dist-info/top_level.txt,sha256=Dl0X7m6N1hxeo4JpGpSNqWC2gtsN0731g-DL1J0mpjc,9
13
- eth_prototype-1.0.1.dist-info/RECORD,,