iwa 0.0.19__py3-none-any.whl → 0.0.21__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.
Files changed (39) hide show
  1. iwa/core/chain/interface.py +8 -1
  2. iwa/core/chainlist.py +116 -0
  3. iwa/core/constants.py +1 -0
  4. iwa/core/contracts/cache.py +131 -0
  5. iwa/core/contracts/contract.py +7 -0
  6. iwa/core/monitor.py +2 -2
  7. iwa/core/rpc_monitor.py +60 -0
  8. iwa/core/services/safe.py +2 -2
  9. iwa/plugins/gnosis/safe.py +1 -1
  10. iwa/plugins/gnosis/tests/test_safe.py +1 -1
  11. iwa/plugins/olas/contracts/activity_checker.py +63 -25
  12. iwa/plugins/olas/contracts/staking.py +115 -19
  13. iwa/plugins/olas/events.py +141 -0
  14. iwa/plugins/olas/plugin.py +2 -2
  15. iwa/plugins/olas/service_manager/base.py +7 -2
  16. iwa/plugins/olas/service_manager/lifecycle.py +30 -5
  17. iwa/plugins/olas/service_manager/mech.py +9 -0
  18. iwa/plugins/olas/service_manager/staking.py +6 -2
  19. iwa/plugins/olas/tests/test_olas_integration.py +38 -10
  20. iwa/plugins/olas/tests/test_plugin_full.py +3 -5
  21. iwa/plugins/olas/tests/test_service_manager.py +7 -1
  22. iwa/plugins/olas/tests/test_service_manager_errors.py +22 -11
  23. iwa/plugins/olas/tests/test_service_manager_flows.py +24 -8
  24. iwa/plugins/olas/tests/test_service_staking.py +59 -15
  25. iwa/plugins/olas/tests/test_staking_validation.py +8 -14
  26. iwa/tools/test_chainlist.py +38 -0
  27. iwa/tui/rpc.py +1 -1
  28. iwa/tui/screens/wallets.py +2 -2
  29. iwa/tui/tests/test_rpc.py +2 -2
  30. iwa/tui/widgets/base.py +1 -1
  31. iwa/web/routers/olas/staking.py +9 -4
  32. {iwa-0.0.19.dist-info → iwa-0.0.21.dist-info}/METADATA +1 -1
  33. {iwa-0.0.19.dist-info → iwa-0.0.21.dist-info}/RECORD +39 -33
  34. tests/test_monitor.py +3 -3
  35. tests/test_rpc_efficiency.py +103 -0
  36. {iwa-0.0.19.dist-info → iwa-0.0.21.dist-info}/WHEEL +0 -0
  37. {iwa-0.0.19.dist-info → iwa-0.0.21.dist-info}/entry_points.txt +0 -0
  38. {iwa-0.0.19.dist-info → iwa-0.0.21.dist-info}/licenses/LICENSE +0 -0
  39. {iwa-0.0.19.dist-info → iwa-0.0.21.dist-info}/top_level.txt +0 -0
@@ -79,22 +79,9 @@ class StakingContract(ContractInstance):
79
79
  self.chain_name = chain_name
80
80
  self._contract_params_cache: Dict[str, int] = {}
81
81
 
82
- # Get activity checker from the staking contract
83
- activity_checker_address = self.call("activityChecker")
84
- self.activity_checker = ActivityCheckerContract(
85
- activity_checker_address, chain_name=chain_name
86
- )
87
- self.activity_checker_address = activity_checker_address
88
-
89
- # Cache contract parameters
90
- self.available_rewards = self.call("availableRewards")
91
- self.balance = self.call("balance")
92
- self.liveness_period = self.call("livenessPeriod")
93
- self.rewards_per_second = self.call("rewardsPerSecond")
94
- self.max_num_services = self.call("maxNumServices")
95
- self.min_staking_deposit = self.call("minStakingDeposit")
96
- self.min_staking_duration_hours = self.call("minStakingDuration") / 3600
97
- self.staking_token_address = self.call("stakingToken")
82
+ self._activity_checker: Optional[ActivityCheckerContract] = None
83
+ self._activity_checker_address: Optional[EthereumAddress] = None
84
+
98
85
 
99
86
  def get_requirements(self) -> Dict[str, Union[str, int]]:
100
87
  """Get the contract requirements for token and deposits.
@@ -193,10 +180,16 @@ class StakingContract(ContractInstance):
193
180
  remaining_seconds = (epoch_end - datetime.now(timezone.utc)).total_seconds()
194
181
 
195
182
  # Check liveness ratio using activity checker
183
+ # logic: use the latest of (service_start_time, global_checkpoint_time)
184
+ # If service started AFTER global checkpoint, use service_start_time.
185
+ # If service was already running, use global_checkpoint_time.
186
+ global_ts_checkpoint = self.ts_checkpoint()
187
+ effective_ts_start = max(ts_start, global_ts_checkpoint)
188
+
196
189
  liveness_passed = self.is_liveness_ratio_passed(
197
190
  current_nonces=current_nonces,
198
191
  last_nonces=(last_safe_nonce, last_mech_requests),
199
- ts_start=ts_start,
192
+ ts_start=effective_ts_start,
200
193
  )
201
194
 
202
195
  return {
@@ -223,8 +216,36 @@ class StakingContract(ContractInstance):
223
216
  return StakingState(self.call("getStakingState", service_id))
224
217
 
225
218
  def ts_checkpoint(self) -> int:
226
- """Get the timestamp of the last checkpoint."""
227
- return self.call("tsCheckpoint")
219
+ """Get the timestamp of the last checkpoint.
220
+
221
+ Cached until the estimated end of the current epoch (ts_checkpoint + liveness_period).
222
+ """
223
+ now = time.time()
224
+ cache_key = "ts_checkpoint"
225
+
226
+ # Check if we have a valid cached value
227
+ if cache_key in self._contract_params_cache:
228
+ ts = self._contract_params_cache[cache_key]
229
+ # Use liveness period to determine if we should re-check
230
+ if now < ts + self.liveness_period:
231
+ return ts
232
+
233
+ # If past expected epoch end, check at most once per minute
234
+ last_checked = self._contract_params_cache.get(f"{cache_key}_last_checked", 0)
235
+ if now - last_checked < 60:
236
+ return ts
237
+
238
+ # Fetch new value
239
+ ts = self.call("tsCheckpoint")
240
+ self._contract_params_cache[cache_key] = ts
241
+ self._contract_params_cache[f"{cache_key}_last_checked"] = now
242
+ return ts
243
+
244
+ def clear_epoch_cache(self) -> None:
245
+ """Clear cache for epoch-dependent properties."""
246
+ self._contract_params_cache.pop("ts_checkpoint", None)
247
+ self._contract_params_cache.pop("ts_checkpoint_last_checked", None)
248
+ logger.debug(f"Cleared epoch cache for StakingContract {self.address}")
228
249
 
229
250
  def get_required_requests(self, use_liveness_period: bool = True) -> int:
230
251
  """Calculate the required requests for the current epoch.
@@ -246,6 +267,81 @@ class StakingContract(ContractInstance):
246
267
  (time_diff * self.activity_checker.liveness_ratio) / 1e18 + requests_safety_margin
247
268
  )
248
269
 
270
+ @property
271
+ def activity_checker_address_value(self) -> EthereumAddress:
272
+ """Get the activity checker address."""
273
+ if self._activity_checker_address is None:
274
+ self._activity_checker_address = self.call("activityChecker")
275
+ return self._activity_checker_address
276
+
277
+ @property
278
+ def activity_checker_address(self) -> EthereumAddress:
279
+ """Backwards compatibility for activity_checker_address."""
280
+ return self.activity_checker_address_value
281
+
282
+ @property
283
+ def activity_checker(self) -> ActivityCheckerContract:
284
+ """Get the activity checker contract."""
285
+ if self._activity_checker is None:
286
+ self._activity_checker = ActivityCheckerContract(
287
+ self.activity_checker_address_value, chain_name=self.chain_name
288
+ )
289
+ return self._activity_checker
290
+
291
+ @property
292
+ def available_rewards(self) -> int:
293
+ """Get available rewards."""
294
+ if "availableRewards" not in self._contract_params_cache:
295
+ self._contract_params_cache["availableRewards"] = self.call("availableRewards")
296
+ return self._contract_params_cache["availableRewards"]
297
+
298
+ @property
299
+ def balance(self) -> int:
300
+ """Get contract balance."""
301
+ if "balance" not in self._contract_params_cache:
302
+ self._contract_params_cache["balance"] = self.call("balance")
303
+ return self._contract_params_cache["balance"]
304
+
305
+ @property
306
+ def liveness_period(self) -> int:
307
+ """Get liveness period."""
308
+ if "livenessPeriod" not in self._contract_params_cache:
309
+ self._contract_params_cache["livenessPeriod"] = self.call("livenessPeriod")
310
+ return self._contract_params_cache["livenessPeriod"]
311
+
312
+ @property
313
+ def rewards_per_second(self) -> int:
314
+ """Get rewards per second."""
315
+ if "rewardsPerSecond" not in self._contract_params_cache:
316
+ self._contract_params_cache["rewardsPerSecond"] = self.call("rewardsPerSecond")
317
+ return self._contract_params_cache["rewardsPerSecond"]
318
+
319
+ @property
320
+ def max_num_services(self) -> int:
321
+ """Get max number of services."""
322
+ if "maxNumServices" not in self._contract_params_cache:
323
+ self._contract_params_cache["maxNumServices"] = self.call("maxNumServices")
324
+ return self._contract_params_cache["maxNumServices"]
325
+
326
+ @property
327
+ def min_staking_deposit(self) -> int:
328
+ """Get min staking deposit."""
329
+ if "minStakingDeposit" not in self._contract_params_cache:
330
+ self._contract_params_cache["minStakingDeposit"] = self.call("minStakingDeposit")
331
+ return self._contract_params_cache["minStakingDeposit"]
332
+
333
+ @property
334
+ def min_staking_duration_hours(self) -> float:
335
+ """Get min staking duration in hours."""
336
+ return self.min_staking_duration / 3600
337
+
338
+ @property
339
+ def staking_token_address(self) -> EthereumAddress:
340
+ """Get staking token address."""
341
+ if "stakingToken" not in self._contract_params_cache:
342
+ self._contract_params_cache["stakingToken"] = self.call("stakingToken")
343
+ return self._contract_params_cache["stakingToken"]
344
+
249
345
  def is_liveness_ratio_passed(
250
346
  self,
251
347
  current_nonces: tuple,
@@ -0,0 +1,141 @@
1
+ """Event-based cache invalidation for Olas contracts."""
2
+
3
+
4
+ from loguru import logger
5
+
6
+ from iwa.core.contracts.cache import ContractCache
7
+ from iwa.plugins.olas.contracts.staking import StakingContract
8
+
9
+
10
+ class OlasEventInvalidator:
11
+ """Monitors OLAS events and invalidates caches."""
12
+
13
+ def __init__(self, chain_name: str = "gnosis"):
14
+ """Initialize the invalidator."""
15
+ self.chain_name = chain_name
16
+ self.contract_cache = ContractCache()
17
+
18
+ # We need to find active staking contracts to monitor
19
+ # For now, we'll use a dynamic approach or configuration
20
+ # Ideally, this service would know about all deployed staking contracts
21
+ # But efficiently, we might just want to monitor the ones in our cache?
22
+ # A simple approach for this MVP: Monitor contracts currently in the cache
23
+ # OR monitor a known set of staking contracts from constants.
24
+
25
+ # Since EventMonitor requires a list of addresses upfront, let's use the ones
26
+ # defined in constants if available, or just rely on what's active.
27
+ # However, EventMonitor checks transfers, not generic logs for specific events.
28
+ # The base EventMonitor in iwa.core.monitor is too specific (transfers).
29
+ # We should implement a specific loop here or extend EventMonitor.
30
+ # To avoid complex inheritance of a class not designed for extension (EventMonitor),
31
+ # we will implement a focused loop using the same pattern.
32
+
33
+ from iwa.core.chain import ChainInterfaces
34
+ from iwa.plugins.olas.constants import OLAS_TRADER_STAKING_CONTRACTS
35
+
36
+ self.chain_interface = ChainInterfaces().get(chain_name)
37
+ self.web3 = self.chain_interface.web3
38
+
39
+ # Get addresses to monitor
40
+ contracts = OLAS_TRADER_STAKING_CONTRACTS.get(chain_name, {})
41
+ self.staking_addresses = [addr for _, addr in contracts.items()]
42
+
43
+ self.running = False
44
+
45
+ def start(self):
46
+ """Start the event monitoring loop."""
47
+ import threading
48
+
49
+ self.running = True
50
+ thread = threading.Thread(target=self._monitor_loop, daemon=True)
51
+ thread.start()
52
+ logger.info(f"Started OlasEventInvalidator for {len(self.staking_addresses)} contracts")
53
+
54
+ def stop(self):
55
+ """Stop the monitoring loop."""
56
+ self.running = False
57
+
58
+ def _monitor_loop(self):
59
+ """Main monitoring loop."""
60
+ import time
61
+
62
+ try:
63
+ last_block = self.web3.eth.block_number
64
+ except Exception:
65
+ last_block = 0
66
+
67
+ while self.running:
68
+ try:
69
+ current_block = self.web3.eth.block_number
70
+
71
+ if current_block > last_block:
72
+ self._check_events(last_block + 1, current_block)
73
+ last_block = current_block
74
+
75
+ except Exception as e:
76
+ logger.error(f"Error in OlasEventInvalidator: {e}")
77
+
78
+ time.sleep(10) # check every 10 seconds
79
+
80
+ def _check_events(self, from_block: int, to_block: int):
81
+ """Check for relevant events in the block range."""
82
+ # Cap range
83
+ if to_block - from_block > 100:
84
+ from_block = to_block - 100
85
+
86
+ # We care about Checkpoint events on StakingContracts
87
+ # Event signature for Checkpoint: Checkpoint(uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256)
88
+ # Actually easier to use the contract instance to get the topic or event object
89
+
90
+ # Need ABI for this. Let's assume we can get it from a dummy contract instance
91
+ if not self.staking_addresses:
92
+ return
93
+
94
+ # 1. Checkpoint events
95
+ # Topic 0 for Checkpoint event
96
+ # We can construct a filter for all staking addresses
97
+
98
+ try:
99
+ # Ensure contract is cached for later use
100
+ self.contract_cache.get_contract(
101
+ StakingContract, self.staking_addresses[0], self.chain_name
102
+ )
103
+
104
+
105
+ logs = self.web3.eth.get_logs({
106
+ "fromBlock": from_block,
107
+ "toBlock": to_block,
108
+ "address": self.staking_addresses,
109
+ "topics": [self.web3.keccak(text="Checkpoint(uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256)").hex()]
110
+ # Note: signature might vary, safer to use the event object if ABI allows
111
+ })
112
+
113
+ # If we used the contract event object to filter, it handles the topic generation:
114
+ # logs = checkpoint_event_abi.get_logs(fromBlock=from_block, toBlock=to_block)
115
+ # But get_logs on the contract object filters by THAT contract address usually?
116
+ # web3.eth.get_logs is broader.
117
+
118
+ for log in logs:
119
+ addr = log["address"]
120
+ logger.info(f"Checkpoint detected on {addr} at block {log['blockNumber']}")
121
+
122
+ # Invalidate cache for this contract
123
+ # We want to call clear_epoch_cache on the EXISTING cached instance if present
124
+ # ContractCache().get_contract(...) might return it or create new.
125
+ # We need a way to 'get if exists' or assume get_contract is cheap enough.
126
+ # Specifically we want to clear the EPOCH cache, not just destroy the instance
127
+ # (though destroying it works too, it's just less efficient for the next call).
128
+
129
+ # Option A: Just invalidate the instance
130
+ # self.contract_cache.invalidate(StakingContract, addr, self.chain_name)
131
+
132
+ # Option B: Get instance and clear specific cache (safe public access)
133
+ instance = self.contract_cache.get_if_cached(
134
+ StakingContract, addr, self.chain_name
135
+ )
136
+ if instance:
137
+ instance.clear_epoch_cache()
138
+ logger.debug(f"Cleared epoch cache for {addr}")
139
+
140
+ except Exception as e:
141
+ logger.warning(f"Failed to check logs in invalidator: {e}")
@@ -73,12 +73,12 @@ class OlasPlugin(Plugin):
73
73
 
74
74
  try:
75
75
  chain_interface = ChainInterfaces().get(chain_name)
76
- if not chain_interface.chain.rpcs:
76
+ if not chain_interface.current_rpc:
77
77
  return None, None
78
78
  except ValueError:
79
79
  return None, None # Chain not supported/configured
80
80
 
81
- ethereum_client = EthereumClient(chain_interface.chain.rpc)
81
+ ethereum_client = EthereumClient(chain_interface.current_rpc)
82
82
  safe = Safe(safe_address, ethereum_client)
83
83
  owners = safe.retrieve_owners()
84
84
  return owners, True
@@ -5,6 +5,7 @@ from typing import Dict, Optional
5
5
  from loguru import logger
6
6
 
7
7
  from iwa.core.chain import ChainInterfaces
8
+ from iwa.core.contracts.cache import ContractCache
8
9
  from iwa.core.models import Config
9
10
  from iwa.core.wallet import Wallet
10
11
  from iwa.plugins.olas.constants import OLAS_CONTRACTS
@@ -65,8 +66,12 @@ class ServiceManagerBase:
65
66
  if not registry_address or not manager_address:
66
67
  raise ValueError(f"OLAS contracts not found for chain: {chain_name}")
67
68
 
68
- self.registry = ServiceRegistryContract(registry_address, chain_name=chain_name)
69
- self.manager = ServiceManagerContract(manager_address, chain_name=chain_name)
69
+ self.registry = ContractCache().get_contract(
70
+ ServiceRegistryContract, registry_address, chain_name=chain_name
71
+ )
72
+ self.manager = ContractCache().get_contract(
73
+ ServiceManagerContract, manager_address, chain_name=chain_name
74
+ )
70
75
  logger.debug(f"[SM-INIT] ServiceManager initialized. Chain: {chain_name}")
71
76
  logger.debug(f"[SM-INIT] Registry Address: {self.registry.address}")
72
77
  logger.debug(f"[SM-INIT] Manager Address: {self.manager.address}")
@@ -65,6 +65,7 @@ from web3.types import Wei
65
65
 
66
66
  from iwa.core.chain import ChainInterfaces
67
67
  from iwa.core.constants import NATIVE_CURRENCY_ADDRESS, ZERO_ADDRESS
68
+ from iwa.core.contracts.cache import ContractCache
68
69
  from iwa.core.types import EthereumAddress
69
70
  from iwa.core.utils import get_tx_hash
70
71
  from iwa.plugins.olas.constants import (
@@ -485,7 +486,8 @@ class LifecycleManagerMixin:
485
486
  agent_id = agent_ids[0]
486
487
 
487
488
  # Use the ServiceRegistryTokenUtilityContract with official ABI
488
- token_utility = ServiceRegistryTokenUtilityContract(
489
+ token_utility = ContractCache().get_contract(
490
+ ServiceRegistryTokenUtilityContract,
489
491
  address=str(utility_address),
490
492
  chain_name=self.chain_name,
491
493
  )
@@ -759,7 +761,7 @@ class LifecycleManagerMixin:
759
761
  logger.info("[REGISTER] Success - service is now FINISHED_REGISTRATION")
760
762
  return True
761
763
 
762
- def deploy(self) -> Optional[str]: # noqa: C901
764
+ def deploy(self, fund_multisig: bool = False) -> Optional[str]: # noqa: C901
763
765
  """Deploy the service."""
764
766
  logger.info(f"[DEPLOY] Starting deployment for service {self.service.service_id}")
765
767
 
@@ -841,6 +843,25 @@ class LifecycleManagerMixin:
841
843
  except Exception as e:
842
844
  logger.warning(f"[DEPLOY] Failed to register multisig in wallet: {e}")
843
845
 
846
+ # Fund the multisig with 1 xDAI from master if requested (for staking)
847
+ if fund_multisig:
848
+ try:
849
+ funding_amount = Web3.to_wei(1, "ether")
850
+ logger.info(f"[DEPLOY] Funding multisig {multisig_address} with 1 xDAI from master")
851
+ tx_hash = self.wallet.send(
852
+ from_address_or_tag=self.wallet.master_account.address,
853
+ to_address_or_tag=multisig_address,
854
+ token_address_or_name="native",
855
+ amount_wei=funding_amount,
856
+ chain_name=self.chain_name,
857
+ )
858
+ if tx_hash:
859
+ logger.info(f"[DEPLOY] Funded multisig: {tx_hash}")
860
+ else:
861
+ logger.error("[DEPLOY] Failed to fund multisig")
862
+ except Exception as e:
863
+ logger.error(f"[DEPLOY] Failed to fund multisig: {e}")
864
+
844
865
  logger.info("[DEPLOY] Success - service is now DEPLOYED")
845
866
  return multisig_address
846
867
 
@@ -976,7 +997,10 @@ class LifecycleManagerMixin:
976
997
  previous_state = current_state
977
998
  logger.info(f"[SPIN-UP] Step {step}: Processing {current_state.name}...")
978
999
 
979
- if not self._process_spin_up_state(current_state, agent_address, bond_amount_wei):
1000
+ should_fund = staking_contract is not None
1001
+ if not self._process_spin_up_state(
1002
+ current_state, agent_address, bond_amount_wei, fund_multisig=should_fund
1003
+ ):
980
1004
  logger.error(f"[SPIN-UP] Step {step} FAILED at state {current_state.name}")
981
1005
  return False
982
1006
 
@@ -1012,6 +1036,7 @@ class LifecycleManagerMixin:
1012
1036
  current_state: ServiceState,
1013
1037
  agent_address: Optional[str],
1014
1038
  bond_amount_wei: Optional[Wei],
1039
+ fund_multisig: bool = False,
1015
1040
  ) -> bool:
1016
1041
  """Process a single state transition for spin up."""
1017
1042
  if current_state == ServiceState.PRE_REGISTRATION:
@@ -1025,8 +1050,8 @@ class LifecycleManagerMixin:
1025
1050
  ):
1026
1051
  return False
1027
1052
  elif current_state == ServiceState.FINISHED_REGISTRATION:
1028
- logger.info("[SPIN-UP] Action: deploy()")
1029
- if not self.deploy():
1053
+ logger.info(f"[SPIN-UP] Action: deploy(fund_multisig={fund_multisig})")
1054
+ if not self.deploy(fund_multisig=fund_multisig):
1030
1055
  return False
1031
1056
  else:
1032
1057
  logger.error(f"[SPIN-UP] Invalid state: {current_state.name}")
@@ -612,6 +612,15 @@ class MechManagerMixin:
612
612
 
613
613
  if event_found:
614
614
  logger.info(f"Event '{expected_event}' verified successfully")
615
+
616
+ # Log transfer events from receipt
617
+ from iwa.core.services.transaction import TransferLogger
618
+
619
+ transfer_logger = TransferLogger(
620
+ self.wallet.account_service, self.registry.chain_interface
621
+ )
622
+ transfer_logger.log_transfers(receipt)
623
+
615
624
  return tx_hash
616
625
  else:
617
626
  logger.error(f"Event '{expected_event}' NOT found in transaction logs")
@@ -50,6 +50,7 @@ from typing import Optional
50
50
  from loguru import logger
51
51
  from web3 import Web3
52
52
 
53
+ from iwa.core.contracts.cache import ContractCache
53
54
  from iwa.core.types import EthereumAddress
54
55
  from iwa.core.utils import get_tx_hash
55
56
  from iwa.plugins.olas.contracts.staking import StakingContract, StakingState
@@ -96,7 +97,9 @@ class StakingManagerMixin:
96
97
 
97
98
  # Load the staking contract
98
99
  try:
99
- staking = StakingContract(str(staking_address), chain_name=self.chain_name)
100
+ staking = ContractCache().get_contract(
101
+ StakingContract, str(staking_address), chain_name=self.chain_name
102
+ )
100
103
  except Exception as e:
101
104
  logger.error(f"Failed to load staking contract: {e}")
102
105
  return StakingStatus(
@@ -613,7 +616,8 @@ class StakingManagerMixin:
613
616
  # Load staking contract if not provided
614
617
  if not staking_contract:
615
618
  try:
616
- staking_contract = StakingContract(
619
+ staking_contract = ContractCache().get_contract(
620
+ StakingContract,
617
621
  str(self.service.staking_contract_address),
618
622
  chain_name=self.service.chain_name,
619
623
  )
@@ -309,7 +309,10 @@ def test_importer_import_service_config_duplicate(mock_wallet):
309
309
 
310
310
  def test_sm_create_token_utility_missing(mock_wallet):
311
311
  """Cover create() with missing token utility (lines 204-206)."""
312
- with patch("iwa.core.models.Config"):
312
+ with patch("iwa.core.models.Config"), \
313
+ patch("iwa.plugins.olas.service_manager.base.ContractCache") as mock_cache, \
314
+ patch("iwa.plugins.olas.service_manager.staking.ContractCache", mock_cache):
315
+ mock_cache.return_value.get_contract.side_effect = lambda cls, *a, **k: cls(*a, **k)
313
316
  sm = ServiceManager(mock_wallet)
314
317
 
315
318
  with patch.dict("iwa.plugins.olas.service_manager.base.OLAS_CONTRACTS", {"unknown": {}}):
@@ -320,7 +323,10 @@ def test_sm_create_token_utility_missing(mock_wallet):
320
323
 
321
324
  def test_sm_get_staking_status_staked_info_fail(mock_wallet):
322
325
  """Cover get_staking_status with STAKED but get_service_info fails (lines 843-854)."""
323
- with patch("iwa.core.models.Config"):
326
+ with patch("iwa.core.models.Config"), \
327
+ patch("iwa.plugins.olas.service_manager.base.ContractCache") as mock_cache, \
328
+ patch("iwa.plugins.olas.service_manager.staking.ContractCache", mock_cache):
329
+ mock_cache.return_value.get_contract.side_effect = lambda cls, *a, **k: cls(*a, **k)
324
330
  sm = ServiceManager(mock_wallet)
325
331
  sm.service = Service(
326
332
  service_name="t", chain_name="gnosis", service_id=1, staking_contract_address=VALID_ADDR
@@ -341,7 +347,10 @@ def test_sm_get_staking_status_staked_info_fail(mock_wallet):
341
347
 
342
348
  def test_sm_call_checkpoint_prepare_fail(mock_wallet):
343
349
  """Cover call_checkpoint prepare failure (lines 1100-1102)."""
344
- with patch("iwa.core.models.Config"):
350
+ with patch("iwa.core.models.Config"), \
351
+ patch("iwa.plugins.olas.service_manager.base.ContractCache") as mock_cache, \
352
+ patch("iwa.plugins.olas.service_manager.staking.ContractCache", mock_cache):
353
+ mock_cache.return_value.get_contract.side_effect = lambda cls, *a, **k: cls(*a, **k)
345
354
  sm = ServiceManager(mock_wallet)
346
355
  sm.service = Service(
347
356
  service_name="t", chain_name="gnosis", service_id=1, staking_contract_address=VALID_ADDR
@@ -360,7 +369,10 @@ def test_sm_call_checkpoint_prepare_fail(mock_wallet):
360
369
 
361
370
  def test_sm_spin_up_no_service(mock_wallet):
362
371
  """Cover spin_up with no service (lines 1167-1170)."""
363
- with patch("iwa.core.models.Config"):
372
+ with patch("iwa.core.models.Config"), \
373
+ patch("iwa.plugins.olas.service_manager.base.ContractCache") as mock_cache, \
374
+ patch("iwa.plugins.olas.service_manager.staking.ContractCache", mock_cache):
375
+ mock_cache.return_value.get_contract.side_effect = lambda cls, *a, **k: cls(*a, **k)
364
376
  sm = ServiceManager(mock_wallet)
365
377
  sm.service = None
366
378
 
@@ -370,7 +382,10 @@ def test_sm_spin_up_no_service(mock_wallet):
370
382
 
371
383
  def test_sm_spin_up_activation_fail(mock_wallet):
372
384
  """Cover spin_up activation failure (lines 1181-1183)."""
373
- with patch("iwa.core.models.Config"):
385
+ with patch("iwa.core.models.Config"), \
386
+ patch("iwa.plugins.olas.service_manager.base.ContractCache") as mock_cache, \
387
+ patch("iwa.plugins.olas.service_manager.staking.ContractCache", mock_cache):
388
+ mock_cache.return_value.get_contract.side_effect = lambda cls, *a, **k: cls(*a, **k)
374
389
  sm = ServiceManager(mock_wallet)
375
390
  sm.service = Service(service_name="t", chain_name="gnosis", service_id=1)
376
391
 
@@ -387,7 +402,10 @@ def test_sm_spin_up_activation_fail(mock_wallet):
387
402
 
388
403
  def test_sm_wind_down_no_service(mock_wallet):
389
404
  """Cover wind_down with no service (lines 1264-1266)."""
390
- with patch("iwa.core.models.Config"):
405
+ with patch("iwa.core.models.Config"), \
406
+ patch("iwa.plugins.olas.service_manager.base.ContractCache") as mock_cache, \
407
+ patch("iwa.plugins.olas.service_manager.staking.ContractCache", mock_cache):
408
+ mock_cache.return_value.get_contract.side_effect = lambda cls, *a, **k: cls(*a, **k)
391
409
  sm = ServiceManager(mock_wallet)
392
410
  sm.service = None
393
411
 
@@ -397,7 +415,10 @@ def test_sm_wind_down_no_service(mock_wallet):
397
415
 
398
416
  def test_sm_wind_down_nonexistent(mock_wallet):
399
417
  """Cover wind_down with non-existent service (lines 1274-1276)."""
400
- with patch("iwa.core.models.Config"):
418
+ with patch("iwa.core.models.Config"), \
419
+ patch("iwa.plugins.olas.service_manager.base.ContractCache") as mock_cache, \
420
+ patch("iwa.plugins.olas.service_manager.staking.ContractCache", mock_cache):
421
+ mock_cache.return_value.get_contract.side_effect = lambda cls, *a, **k: cls(*a, **k)
401
422
  sm = ServiceManager(mock_wallet)
402
423
  sm.service = Service(service_name="t", chain_name="gnosis", service_id=1)
403
424
 
@@ -411,7 +432,10 @@ def test_sm_wind_down_nonexistent(mock_wallet):
411
432
 
412
433
  def test_sm_mech_request_no_service(mock_wallet):
413
434
  """Cover _send_legacy_mech_request with no service (lines 1502-1504)."""
414
- with patch("iwa.core.models.Config"):
435
+ with patch("iwa.core.models.Config"), \
436
+ patch("iwa.plugins.olas.service_manager.base.ContractCache") as mock_cache, \
437
+ patch("iwa.plugins.olas.service_manager.staking.ContractCache", mock_cache):
438
+ mock_cache.return_value.get_contract.side_effect = lambda cls, *a, **k: cls(*a, **k)
415
439
  sm = ServiceManager(mock_wallet)
416
440
  sm.service = None
417
441
 
@@ -421,7 +445,10 @@ def test_sm_mech_request_no_service(mock_wallet):
421
445
 
422
446
  def test_sm_mech_request_no_address(mock_wallet):
423
447
  """Cover _send_legacy_mech_request missing mech address (lines 1510-1512)."""
424
- with patch("iwa.core.models.Config"):
448
+ with patch("iwa.core.models.Config"), \
449
+ patch("iwa.plugins.olas.service_manager.base.ContractCache") as mock_cache, \
450
+ patch("iwa.plugins.olas.service_manager.staking.ContractCache", mock_cache):
451
+ mock_cache.return_value.get_contract.side_effect = lambda cls, *a, **k: cls(*a, **k)
425
452
  sm = ServiceManager(mock_wallet)
426
453
  sm.service = Service(service_name="t", chain_name="unknown", service_id=1)
427
454
 
@@ -431,7 +458,8 @@ def test_sm_mech_request_no_address(mock_wallet):
431
458
 
432
459
  def test_sm_marketplace_mech_no_service(mock_wallet):
433
460
  """Cover _send_marketplace_mech_request with no service (lines 1549-1551)."""
434
- with patch("iwa.core.models.Config"):
461
+ with patch("iwa.core.models.Config"), \
462
+ patch("iwa.plugins.olas.service_manager.base.ContractCache"):
435
463
  sm = ServiceManager(mock_wallet)
436
464
  sm.service = None
437
465
 
@@ -105,7 +105,7 @@ def test_get_safe_signers_edge_cases(plugin):
105
105
  # 1. No RPC configured
106
106
  with patch("iwa.core.chain.ChainInterfaces") as mock_ci_cls:
107
107
  mock_ci = mock_ci_cls.return_value
108
- mock_ci.get.return_value.chain.rpcs = []
108
+ mock_ci.get.return_value.current_rpc = ""
109
109
  signers, exists = plugin._get_safe_signers("0x1", "gnosis")
110
110
  assert signers is None
111
111
  assert exists is None
@@ -113,8 +113,7 @@ def test_get_safe_signers_edge_cases(plugin):
113
113
  # 2. Safe doesn't exist (raises exception)
114
114
  with patch("iwa.core.chain.ChainInterfaces") as mock_ci_cls:
115
115
  mock_ci = mock_ci_cls.return_value
116
- mock_ci.get.return_value.chain.rpcs = ["http://rpc"]
117
- mock_ci.get.return_value.chain.rpc = "http://rpc"
116
+ mock_ci.get.return_value.current_rpc = "http://rpc"
118
117
  with patch("safe_eth.eth.EthereumClient"), patch("safe_eth.safe.Safe") as mock_safe_cls:
119
118
  mock_safe = mock_safe_cls.return_value
120
119
  mock_safe.retrieve_owners.side_effect = Exception("Generic error")
@@ -126,8 +125,7 @@ def test_get_safe_signers_edge_cases(plugin):
126
125
  # 3. Success path
127
126
  with patch("iwa.core.chain.ChainInterfaces") as mock_ci_cls:
128
127
  mock_ci = mock_ci_cls.return_value
129
- mock_ci.get.return_value.chain.rpcs = ["http://rpc"]
130
- mock_ci.get.return_value.chain.rpc = "http://rpc"
128
+ mock_ci.get.return_value.current_rpc = "http://rpc"
131
129
  with patch("safe_eth.eth.EthereumClient"), patch("safe_eth.safe.Safe") as mock_safe_cls:
132
130
  mock_safe = mock_safe_cls.return_value
133
131
  mock_safe.retrieve_owners.return_value = ["0xAgent"]
@@ -114,11 +114,16 @@ def service_manager(
114
114
  mock_service,
115
115
  ):
116
116
  """ServiceManager fixture with mocked dependencies."""
117
- with patch("iwa.plugins.olas.service_manager.base.Config") as local_mock_config:
117
+ with patch("iwa.plugins.olas.service_manager.base.Config") as local_mock_config, \
118
+ patch("iwa.plugins.olas.service_manager.base.ContractCache") as mock_cache:
118
119
  instance = local_mock_config.return_value
119
120
  instance.plugins = {"olas": mock_olas_config}
120
121
  instance.save_config = MagicMock()
121
122
 
123
+ # Mock ContractCache to return MagicMock contracts
124
+ mock_cache_instance = mock_cache.return_value
125
+ mock_cache_instance.get_contract.return_value = MagicMock()
126
+
122
127
  sm = ServiceManager(mock_wallet)
123
128
  # Ensure service is properly set
124
129
  sm.service = mock_service
@@ -127,6 +132,7 @@ def service_manager(
127
132
  yield sm
128
133
 
129
134
 
135
+
130
136
  def test_init(service_manager):
131
137
  """Test initialization."""
132
138
  assert service_manager.registry is not None