Skip to content

Commit

Permalink
Flow emulator progress
Browse files Browse the repository at this point in the history
Closes #287
  • Loading branch information
tombeckenham committed Dec 23, 2024
1 parent 6be4f8d commit a1a3940
Show file tree
Hide file tree
Showing 25 changed files with 294 additions and 101 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,5 @@ dist.7z
/playwright/.cache/
dependency-usage.md
extension-dependencies.md
emulator-account.pkey
flow.json
3 changes: 3 additions & 0 deletions _raw/_locales/en/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,9 @@
"Testnet": {
"message": "Testnet"
},
"Emulator": {
"message": "Emulator"
},
"Crescendo": {
"message": "Crescendo"
},
Expand Down
3 changes: 3 additions & 0 deletions _raw/_locales/ja/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,9 @@
"Testnet": {
"message": "Testnet"
},
"Emulator": {
"message": "Emulator"
},
"Crescendo": {
"message": "Crescendo"
},
Expand Down
3 changes: 3 additions & 0 deletions _raw/_locales/ru/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,9 @@
"Testnet": {
"message": "Testnet"
},
"Emulator": {
"message": "Emulator"
},
"Crescendo": {
"message": "Crescendo"
},
Expand Down
3 changes: 3 additions & 0 deletions _raw/_locales/zh_CN/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,9 @@
"Testnet": {
"message": "测试网"
},
"Emulator": {
"message": "沙盒网"
},
"Crescendo": {
"message": "沙盒网"
},
Expand Down
122 changes: 27 additions & 95 deletions src/background/controller/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,19 @@ import {
import i18n from 'background/service/i18n';
import { type DisplayedKeryring, KEYRING_CLASS } from 'background/service/keyring';
import type { CacheState } from 'background/service/pageStateCache';
import { getScripts } from 'background/utils';
import {
getScripts,
checkEmulatorStatus,
checkEmulatorAccount,
createEmulatorAccount,
} from 'background/utils';
import emoji from 'background/utils/emoji.json';
import fetchConfig from 'background/utils/remoteConfig';
import { notification, storage } from 'background/webapi';
import { openIndexPage } from 'background/webapi/tab';
import { INTERNAL_REQUEST_ORIGIN, EVENTS, KEYRING_TYPE } from 'consts';

import { fclTestnetConfig, fclMainnetConfig } from '../fclConfig';
import { fclTestnetConfig, fclMainnetConfig, fclEmulatorConfig } from '../fclConfig';
import placeholder from '../images/placeholder.png';
import { type CoinItem } from '../service/coinList';
import DisplayKeyring from '../service/keyring/display';
Expand Down Expand Up @@ -3306,12 +3311,24 @@ export class WalletController extends BaseController {
}

switchNetwork = async (network: string) => {
if (network === 'emulator') {
const isEmulatorRunning = await checkEmulatorStatus();
console.log('isEmulatorRunning ', isEmulatorRunning);
if (!isEmulatorRunning) {
throw new Error(
'Flow emulator is not running. Please start it with `flow emulator start` and try again.'
);
}
}

await userWalletService.setNetwork(network);
eventBus.emit('switchNetwork', network);
if (network === 'testnet') {
await fclTestnetConfig();
} else if (network === 'mainnet') {
await fclMainnetConfig();
} else if (network === 'emulator') {
await fclEmulatorConfig();
}
this.refreshAll();

Expand Down Expand Up @@ -3406,6 +3423,9 @@ export class WalletController extends BaseController {
case 'crescendo':
baseURL = 'https://flow-view-source.vercel.app/crescendo';
break;
case 'emulator':
baseURL = 'http://localhost:8888/flow/events'; // Flow emulator explorer endpoint
break;
}
}

Expand Down Expand Up @@ -3461,98 +3481,7 @@ export class WalletController extends BaseController {
title = chrome.i18n.getMessage('Transaction__Sealed'),
body = '',
icon = chrome.runtime.getURL('./images/icon-64.png')
) => {
if (!txId || !txId.match(/^0?x?[0-9a-fA-F]{64}/)) {
return;
}
const address = (await this.getCurrentAddress()) || '0x';
const network = await this.getNetwork();

try {
chrome.storage.session.set({
transactionPending: { txId, network, date: new Date() },
});
eventBus.emit('transactionPending');
chrome.runtime.sendMessage({
msg: 'transactionPending',
network: network,
});
transactionService.setPending(txId, address, network, icon, title);

// Listen to the transaction until it's sealed.
// This will throw an error if there is an error with the transaction
await fcl.tx(txId).onceSealed();

// Track the transaction result
mixpanelTrack.track('transaction_result', {
tx_id: txId,
is_successful: true,
});

try {
// Send a notification to the user only on success
if (sendNotification) {
const baseURL = this.getFlowscanUrl();
notification.create(`${baseURL}/transaction/${txId}`, title, body, icon);
}
} catch (err: unknown) {
// We don't want to throw an error if the notification fails
console.error('listenTransaction notification error ', err);
}
} catch (err: unknown) {
// An error has occurred while listening to the transaction
let errorMessage = 'unknown error';
let errorCode: number | undefined = undefined;

if (err instanceof TransactionError) {
errorCode = err.code;
errorMessage = err.message;
} else {
if (err instanceof Error) {
errorMessage = err.message;
} else if (typeof err === 'string') {
errorMessage = err;
}
// From fcl-core transaction-error.ts
const ERROR_CODE_REGEX = /\[Error Code: (\d+)\]/;
const match = errorMessage.match(ERROR_CODE_REGEX);
errorCode = match ? parseInt(match[1], 10) : undefined;
}

console.warn({
msg: 'transactionError',
errorMessage,
errorCode,
});

// Track the transaction error
mixpanelTrack.track('transaction_result', {
tx_id: txId,
is_successful: false,
error_message: errorMessage,
});

// Tell the UI that there was an error
chrome.runtime.sendMessage({
msg: 'transactionError',
errorMessage,
errorCode,
});
} finally {
// Remove the pending transaction from the UI
await chrome.storage.session.remove('transactionPending');
transactionService.removePending(txId, address, network);

// Refresh the transaction list
this.refreshTransaction(address, 15, 0);

// Tell the UI that the transaction is done
eventBus.emit('transactionDone');
chrome.runtime.sendMessage({
msg: 'transactionDone',
});
}
};
) => {};

getNFTListCahce = async (): Promise<NFTData> => {
const network = await this.getNetwork();
Expand Down Expand Up @@ -3728,6 +3657,7 @@ export class WalletController extends BaseController {
};

getCadenceScripts = async () => {
console.log('getCadenceScripts');
try {
const cadenceScrpts = await storage.get('cadenceScripts');
const now = new Date();
Expand All @@ -3739,16 +3669,18 @@ export class WalletController extends BaseController {
now.getTime() <= cadenceScrpts['expiry'] &&
cadenceScrpts.network === network
) {
console.log('returning cached scripts', cadenceScrpts['data']);
return cadenceScrpts['data'];
}

// const { cadence, networks } = data;
// const cadencev1 = (await openapiService.cadenceScripts(network)) ?? {};

const cadenceScriptsV2 = (await openapiService.cadenceScriptsV2()) ?? {};
console.log('cadenceScriptsV2', cadenceScriptsV2);
// const { scripts, version } = cadenceScriptsV2;
// const cadenceVersion = cadenceScriptsV2.version;
const cadence = cadenceScriptsV2.scripts[network];
const cadence = cadenceScriptsV2.scripts[network === 'emulator' ? 'testnet' : network];

// for (const item of cadence) {
// console.log(cadenceVersion, 'cadenceVersion');
Expand Down
14 changes: 14 additions & 0 deletions src/background/fclConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,3 +134,17 @@ export const fclTestnetConfig = async () => {
}
}
};

// Configure FCL for Emulator
export const fclEmulatorConfig = async () => {
const config = fcl
.config()
.put('accessNode.api', 'http://localhost:8888')
.put('sdk.transport', httpSend)
.put('flow.network', 'emulator')
// Default emulator account with contracts deployed
.put('0xFungibleToken', '0xee82856bf20e2aa6')
.put('0xFlowToken', '0x0ae53cb6e3f42a79')
.put('0xNonFungibleToken', '0xf8d6e0586b0a20c7')
.put('0xMetadataViews', '0xf8d6e0586b0a20c7');
};
5 changes: 4 additions & 1 deletion src/background/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { EVENTS } from 'consts';

import { providerController, walletController } from './controller';
import { preAuthzServiceDefinition } from './controller/serviceDefinition';
import { fclTestnetConfig, fclMainnetConfig } from './fclConfig';
import { fclTestnetConfig, fclMainnetConfig, fclEmulatorConfig } from './fclConfig';
import {
permissionService,
preferenceService,
Expand Down Expand Up @@ -99,6 +99,9 @@ async function fclSetup() {
case 'testnet':
await fclTestnetConfig();
break;
case 'emulator':
await fclEmulatorConfig();
break;
}
}

Expand Down
1 change: 1 addition & 0 deletions src/background/service/networkModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ export enum FlowNetwork {
mainnet = 'mainnet',
testnet = 'testnet',
crescendo = 'crescendo',
emulator = 'emulator',
}

export enum Period {
Expand Down
5 changes: 5 additions & 0 deletions src/background/service/openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1441,6 +1441,7 @@ class OpenApiService {
const isProduction = process.env.NODE_ENV === 'production';
let url;

const isEmulator = network === 'emulator';
if (isProduction) {
url = `https://raw.githubusercontent.com/Outblock/token-list-jsons/outblock/jsons/${network}/${chainType}/default.json`;
} else if (
Expand All @@ -1449,6 +1450,10 @@ class OpenApiService {
(network === 'testnet' || network === 'mainnet')
) {
url = `https://raw.githubusercontent.com/Outblock/token-list-jsons/outblock/jsons/${network}/${chainType}/dev.json`;
} else if (isEmulator) {
// TODO: remove this after emulator is ready
const emulatorNetwork = 'testnet';
url = `https://raw.githubusercontent.com/Outblock/token-list-jsons/outblock/jsons/${emulatorNetwork}/${chainType}/emulator.json`;
} else {
url = `https://raw.githubusercontent.com/Outblock/token-list-jsons/outblock/jsons/${network}/${chainType}/default.json`;
}
Expand Down
8 changes: 8 additions & 0 deletions src/background/service/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,13 @@ class Transaction {
mainnet: [],
crescendo: [],
testnet: [],
emulator: [],
},
pendingItem: {
mainnet: [],
crescendo: [],
testnet: [],
emulator: [],
},
},
});
Expand All @@ -59,11 +61,13 @@ class Transaction {
mainnet: [],
crescendo: [],
testnet: [],
emulator: [],
},
pendingItem: {
mainnet: [],
testnet: [],
crescendo: [],
emulator: [],
},
},
});
Expand All @@ -77,11 +81,13 @@ class Transaction {
mainnet: [],
crescendo: [],
testnet: [],
emulator: [],
},
pendingItem: {
mainnet: [],
testnet: [],
crescendo: [],
emulator: [],
},
};
this.session = {
Expand All @@ -91,11 +97,13 @@ class Transaction {
mainnet: [],
testnet: [],
crescendo: [],
emulator: [],
},
pendingItem: {
mainnet: [],
testnet: [],
crescendo: [],
emulator: [],
},
};
};
Expand Down
2 changes: 1 addition & 1 deletion src/background/service/userWallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ class UserWallet {
};

setUserWallets = async (filteredData, network) => {
console.log('filteredData ', filteredData);
console.log('userWalletService - setUserWallets - filteredData ', filteredData, network);
this.store.wallets[network] = filteredData;
let walletIndex = (await storage.get('currentWalletIndex')) || 0;
if (this.store.wallets[network] && this.store.wallets[network].length > 0) {
Expand Down
3 changes: 2 additions & 1 deletion src/background/utils/defaultTokenList.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
"address": {
"mainnet": "0x1654653399040a61",
"testnet": "0x7e60df042a9c0868",
"crescendo": "0x7e60df042a9c0868"
"crescendo": "0x7e60df042a9c0868",
"emulator": "0x0ae53cb6e3f42a79"
},
"contract_name": "FlowToken",
"storage_path": {
Expand Down
Loading

0 comments on commit a1a3940

Please sign in to comment.