Skip to content

Commit c1247c9

Browse files
committed
Update contractService.ts
1 parent 3b9e644 commit c1247c9

File tree

1 file changed

+84
-3
lines changed

1 file changed

+84
-3
lines changed

apps/box/src/contracts/contractService.ts

Lines changed: 84 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -222,9 +222,90 @@ export class ContractService {
222222
}
223223

224224
async switchChain(newChain: SupportedChain): Promise<void> {
225-
this.chain = newChain;
226-
if (this.provider) {
227-
await this.initialize(this.provider.provider);
225+
console.log(`ContractService: switchChain called - switching from ${this.chain} to ${newChain}`);
226+
227+
if (!this.provider) {
228+
console.error('ContractService: switchChain called but no provider available');
229+
throw new Error('No provider available for chain switching');
230+
}
231+
232+
const chainConfig = getChainConfigByName(newChain);
233+
console.log(`ContractService: Target chain config:`, chainConfig);
234+
235+
try {
236+
// Get current network to check if switch is needed
237+
const currentNetwork = await this.provider.getNetwork();
238+
const expectedChainId = parseInt(chainConfig.chainId, 16);
239+
240+
console.log(`ContractService: Current chainId: ${currentNetwork.chainId}, Target chainId: ${expectedChainId}`);
241+
242+
if (currentNetwork.chainId === expectedChainId) {
243+
console.log(`ContractService: Already on target chain ${newChain}, updating internal state only`);
244+
this.chain = newChain;
245+
await this.initialize(this.provider.provider, { allowNetworkSwitch: false });
246+
return;
247+
}
248+
249+
// Request MetaMask to switch to the target chain
250+
console.log(`ContractService: Requesting MetaMask to switch to ${chainConfig.name} (${chainConfig.chainId})`);
251+
252+
const web3Provider = this.provider.provider;
253+
await web3Provider.request({
254+
method: 'wallet_switchEthereumChain',
255+
params: [{ chainId: chainConfig.chainId }],
256+
});
257+
258+
console.log(`ContractService: Chain switch request sent to MetaMask`);
259+
260+
// Wait for the switch to complete and verify
261+
let verificationAttempts = 0;
262+
const maxVerificationAttempts = 5;
263+
let chainSwitchSuccessful = false;
264+
265+
while (verificationAttempts < maxVerificationAttempts && !chainSwitchSuccessful) {
266+
verificationAttempts++;
267+
console.log(`ContractService: Chain switch verification attempt ${verificationAttempts}/${maxVerificationAttempts}`);
268+
269+
// Wait progressively longer between attempts
270+
const waitTime = 2000 + (verificationAttempts * 1000);
271+
await new Promise(resolve => setTimeout(resolve, waitTime));
272+
273+
try {
274+
const newNetwork = await this.provider.getNetwork();
275+
console.log(`ContractService: Verification attempt ${verificationAttempts} - current chainId: ${newNetwork.chainId}, expected: ${expectedChainId}`);
276+
277+
if (newNetwork.chainId === expectedChainId) {
278+
console.log(`ContractService: Chain switch verified successfully on attempt ${verificationAttempts}`);
279+
chainSwitchSuccessful = true;
280+
break;
281+
}
282+
} catch (verificationError) {
283+
console.warn(`ContractService: Network verification attempt ${verificationAttempts} failed:`, verificationError);
284+
}
285+
}
286+
287+
if (!chainSwitchSuccessful) {
288+
console.error(`ContractService: Chain switch verification failed after ${maxVerificationAttempts} attempts`);
289+
throw new Error(`Chain switch was not completed. Please manually switch to ${chainConfig.name} in MetaMask.`);
290+
}
291+
292+
// Update internal state and reinitialize with the new chain
293+
this.chain = newChain;
294+
await this.initialize(this.provider.provider, { allowNetworkSwitch: false });
295+
296+
console.log(`ContractService: Successfully switched to ${newChain} and reinitialized`);
297+
298+
} catch (error: any) {
299+
console.error(`ContractService: switchChain failed:`, error);
300+
301+
// Handle user rejection gracefully
302+
if (error.code === 4001) {
303+
console.log(`ContractService: User rejected chain switch request`);
304+
throw new Error(`Chain switch cancelled by user`);
305+
}
306+
307+
// Re-throw other errors
308+
throw error;
228309
}
229310
}
230311

0 commit comments

Comments
 (0)