Skip to content

Commit

Permalink
Merge pull request #9035 from hicommonwealth/malik.8811.cleanup-Chain…
Browse files Browse the repository at this point in the history
…Info-type

Update `app.chain.meta` and related types to `ExtendedCommunity` trpc response type + Removed `ChainInfo` type
  • Loading branch information
mzparacha authored Sep 10, 2024
2 parents efae4fa + 60e9c6f commit eb26db5
Show file tree
Hide file tree
Showing 137 changed files with 616 additions and 807 deletions.
24 changes: 8 additions & 16 deletions packages/commonwealth/client/scripts/controllers/app/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ import { z } from 'zod';
import Account from '../../models/Account';
import AddressInfo from '../../models/AddressInfo';
import type BlockInfo from '../../models/BlockInfo';
import ChainInfo from '../../models/ChainInfo';

function storeActiveAccount(account: Account) {
const user = userStore.getState();
Expand Down Expand Up @@ -278,17 +277,14 @@ export async function createUserWithAddress(
chain || '',
true,
);
const chainInfo = ChainInfo.fromTRPCResponse(
communityInfo as z.infer<typeof ExtendedCommunity>,
);

const account = new Account({
addressId: id,
address,
community: {
id: chainInfo.id,
base: chainInfo.base,
ss58Prefix: chainInfo.ss58Prefix,
id: communityInfo?.id || '',
base: communityInfo?.base,
ss58Prefix: communityInfo?.ss58_prefix || 0,
},
validationToken: response.data.result.verification_token,
walletId,
Expand Down Expand Up @@ -414,9 +410,7 @@ export async function handleSocialLoginCallback({
chain || '',
true,
);
desiredChain = ChainInfo.fromTRPCResponse(
communityInfo as z.infer<typeof ExtendedCommunity>,
);
desiredChain = communityInfo as z.infer<typeof ExtendedCommunity>;
}
const isCosmos = desiredChain?.base === ChainBase.CosmosSDK;
const magic = await constructMagic(isCosmos, desiredChain?.id);
Expand Down Expand Up @@ -458,7 +452,7 @@ export async function handleSocialLoginCallback({
// Sign a session
if (isCosmos && desiredChain) {
const signer = { signMessage: magic.cosmos.sign };
const prefix = app.chain?.meta?.bech32Prefix || 'cosmos';
const prefix = app.chain?.meta?.bech32_prefix || 'cosmos';
const canvasChainId = chainBaseToCanvasChainId(
ChainBase.CosmosSDK,
prefix,
Expand Down Expand Up @@ -488,7 +482,7 @@ export async function handleSocialLoginCallback({

const sessionSigner = new SIWESigner({
signer,
chainId: app.chain?.meta?.node?.ethChainId || 1,
chainId: app.chain?.meta?.ChainNode?.eth_chain_id || 1,
});
let sessionObject = await sessionSigner.getSession(CANVAS_TOPIC);
if (!sessionObject) {
Expand Down Expand Up @@ -539,12 +533,10 @@ export async function handleSocialLoginCallback({
chain || '',
true,
);
chainInfo = ChainInfo.fromTRPCResponse(
communityInfo as z.infer<typeof ExtendedCommunity>,
);
chainInfo = communityInfo as z.infer<typeof ExtendedCommunity>;
}

chainInfo && (await updateActiveAddresses(chainInfo.id));
chainInfo && (await updateActiveAddresses(chainInfo.id || ''));
}

const { Profiles: profiles, email: ssoEmail } = response.data.result;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ class CoinbaseWebWalletController implements IWebWallet<string> {
public getChainId() {
// We need app.chain? because the app might not be on a page with a chain (e.g homepage),
// and node? because the chain might not have a node provided
return app.chain?.meta?.node?.ethChainId?.toString() || '1';
return app.chain?.meta?.ChainNode?.eth_chain_id?.toString() || '1';
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
Expand Down Expand Up @@ -132,9 +132,10 @@ class CoinbaseWebWalletController implements IWebWallet<string> {
} catch (switchError) {
// This error code indicates that the chain has not been added to coinbase.
if (switchError.code === 4902) {
const wsRpcUrl = new URL(app.chain?.meta?.node?.url);
const wsRpcUrl = new URL(app.chain?.meta?.ChainNode?.url || '');
const rpcUrl =
app.chain?.meta?.node?.altWalletUrl || `https://${wsRpcUrl.host}`;
app.chain?.meta?.ChainNode?.alt_wallet_url ||
`https://${wsRpcUrl.host}`;

const chains = await axios.get('https://chainid.network/chains.json');
const baseChain = chains.data.find((c) => c.chainId === chainId);
Expand Down Expand Up @@ -173,7 +174,7 @@ class CoinbaseWebWalletController implements IWebWallet<string> {
} catch (error) {
let errorMsg = `Failed to enable coinbase: ${error.message}`;
if (error.code === 4902) {
errorMsg = `Failed to enable coinbase: Please add chain ID ${app?.chain?.meta?.node?.ethChainId}`;
errorMsg = `Failed to enable coinbase: Please add chain ID ${app?.chain?.meta?.ChainNode?.eth_chain_id || 0}`;
}
console.error(errorMsg);
this._enabling = false;
Expand Down Expand Up @@ -215,7 +216,7 @@ class CoinbaseWebWalletController implements IWebWallet<string> {
const url =
rpcUrl.length > 0
? rpcUrl[0]
: app?.chain?.meta?.node?.altWalletUrl;
: app?.chain?.meta?.ChainNode?.alt_wallet_url || '';
await this._web3.givenProvider.request({
method: 'wallet_addEthereumChain',
params: [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ class CosmosEvmWebWalletController implements IWebWallet<string> {

public getSessionSigner() {
return new CosmosSignerCW({
bech32Prefix: app.chain?.meta.bech32Prefix || 'inj',
bech32Prefix: app.chain?.meta.bech32_prefix || 'inj',
signer: {
type: 'ethereum',
signEthereum: (
Expand Down Expand Up @@ -125,7 +125,7 @@ class CosmosEvmWebWalletController implements IWebWallet<string> {
} else {
for (const acc of this._ethAccounts) {
this._accounts.push(
encodeEthAddress(app.chain?.meta.bech32Prefix || 'inj', acc),
encodeEthAddress(app.chain?.meta.bech32_prefix || 'inj', acc),
);
}
}
Expand Down Expand Up @@ -154,7 +154,7 @@ class CosmosEvmWebWalletController implements IWebWallet<string> {
'accountsChanged',
async (accounts: string[]) => {
const encodedAccounts = accounts.map((a) =>
encodeEthAddress(app.chain?.meta.bech32Prefix || 'inj', a),
encodeEthAddress(app.chain?.meta.bech32_prefix || 'inj', a),
);
const updatedAddress = userStore
.getState()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ class EVMKeplrWebWalletController implements IWebWallet<AccountData> {

public getSessionSigner() {
return new CosmosSignerCW({
bech32Prefix: app.chain.meta.bech32Prefix,
bech32Prefix: `${app.chain.meta.bech32_prefix || 0}`,
signer: {
type: 'ethereum',
signEthereum: async (
Expand Down Expand Up @@ -135,14 +135,14 @@ class EVMKeplrWebWalletController implements IWebWallet<AccountData> {
`Failed to enable chain: ${err.message}. Trying experimentalSuggestChain...`,
);

const bech32Prefix = app.chain.meta.bech32Prefix?.toLowerCase();
const bech32Prefix = app.chain.meta.bech32_prefix?.toLowerCase();
const info: ChainInfo = {
chainId: this._chainId,
chainName: app.chain.meta.name,
rpc: url,
// Note that altWalletUrl on Cosmos chains should be the REST endpoint -- if not available, we
// use the RPC url as hack, which will break some querying functionality but not signing.
rest: app?.chain?.meta?.node?.altWalletUrl || url,
rest: app?.chain?.meta?.ChainNode?.alt_wallet_url || url,
bip44: {
coinType: 60,
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
import app from 'state';
import { SERVER_URL } from 'state/api/config';
import IWebWallet from '../../../models/IWebWallet';
import { getChainDecimals } from './utils';

declare global {
interface Window {
Expand Down Expand Up @@ -90,7 +91,7 @@ class KeplrLikeWebWalletController implements IWebWallet<AccountData> {

public getSessionSigner() {
return new CosmosSignerCW({
bech32Prefix: app.chain?.meta?.bech32Prefix || 'osmo',
bech32Prefix: app.chain?.meta?.bech32_prefix || 'osmo',
signer: {
type: 'amino',
signAmino: window.wallet.signAmino,
Expand Down Expand Up @@ -124,21 +125,23 @@ class KeplrLikeWebWalletController implements IWebWallet<AccountData> {
this._chainId = chainId;
client.disconnect();

const decimals = getChainDecimals(app.chain.id || '', app.chain.base);

try {
await window.wallet.enable(this._chainId);
} catch (err) {
console.log(
`Failed to enable chain: ${err.message}. Trying experimentalSuggestChain...`,
);

const bech32Prefix = app.chain?.meta?.bech32Prefix?.toLowerCase();
const bech32Prefix = app.chain?.meta?.bech32_prefix?.toLowerCase();
const info: ChainInfo = {
chainId: this._chainId,
chainName: app.chain?.meta?.name,
rpc: url,
// Note that altWalletUrl on Cosmos chains should be the REST endpoint -- if not available, we
// use the RPC url as hack, which will break some querying functionality but not signing.
rest: app.chain?.meta?.node?.altWalletUrl || url,
rest: app.chain?.meta?.ChainNode?.alt_wallet_url || url,
bip44: {
coinType: 118,
},
Expand All @@ -154,27 +157,27 @@ class KeplrLikeWebWalletController implements IWebWallet<AccountData> {
{
coinDenom: app.chain?.meta?.default_symbol,
coinMinimalDenom: `u${app.chain?.meta?.default_symbol?.toLowerCase()}`,
coinDecimals: app.chain?.meta?.decimals || 6,
coinDecimals: decimals || 6,
},
],
feeCurrencies: [
{
coinDenom: app.chain?.meta?.default_symbol,
coinMinimalDenom: `u${app.chain?.meta?.default_symbol?.toLowerCase()}`,
coinDecimals: app.chain?.meta?.decimals || 6,
coinDecimals: decimals || 6,
gasPriceStep: { low: 0, average: 0.025, high: 0.03 },
},
],
stakeCurrency: {
coinDenom: app.chain?.meta?.default_symbol,
coinMinimalDenom: `u${app.chain?.meta?.default_symbol?.toLowerCase()}`,
coinDecimals: app.chain?.meta?.decimals || 6,
coinDecimals: decimals || 6,
},
features: [],
};
await window.wallet.experimentalSuggestChain(info);
await window.wallet.enable(this._chainId);
this._chain = app.chain.id;
this._chain = app.chain.id || '';
}
console.log(`Enabled web wallet for ${this._chainId}`);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class LeapWebWalletController extends KeplrLikeWebWalletController {

public getSessionSigner() {
return new CosmosSignerCW({
bech32Prefix: app.chain?.meta.bech32Prefix || 'osmo',
bech32Prefix: app.chain?.meta.bech32_prefix || 'osmo',
signer: {
type: 'arbitrary',
signArbitrary: (msg) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ class MetamaskWebWalletController implements IWebWallet<string> {
public getChainId() {
// We need app.chain? because the app might not be on a page with a chain (e.g homepage),
// and node? because the chain might not have a node provided
return app.chain?.meta?.node?.ethChainId?.toString() || '1';
return (app.chain?.meta?.ChainNode?.eth_chain_id || 0)?.toString() || '1';
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
Expand Down Expand Up @@ -142,9 +142,9 @@ class MetamaskWebWalletController implements IWebWallet<string> {
} catch (switchError) {
// This error code indicates that the chain has not been added to MetaMask.
if (switchError.code === 4902) {
const wsRpcUrl = app.chain?.meta?.node?.url ?? '';
const wsRpcUrl = app.chain?.meta?.ChainNode?.url ?? '';
const rpcUrl =
(app.chain?.meta?.node?.altWalletUrl ?? wsRpcUrl)
(app.chain?.meta?.ChainNode?.alt_wallet_url ?? wsRpcUrl)
? new URL(wsRpcUrl).host
: '';

Expand Down Expand Up @@ -194,7 +194,7 @@ class MetamaskWebWalletController implements IWebWallet<string> {
} catch (error) {
let errorMsg = `Failed to enable Metamask: ${error.message}`;
if (error.code === 4902) {
errorMsg = `Failed to enable Metamask: Please add chain ID ${app?.chain?.meta?.node?.ethChainId}`;
errorMsg = `Failed to enable Metamask: Please add chain ID ${app?.chain?.meta?.ChainNode?.eth_chain_id || 0}`;
}
console.error(errorMsg);
this._enabling = false;
Expand Down Expand Up @@ -237,7 +237,7 @@ class MetamaskWebWalletController implements IWebWallet<string> {
const url =
rpcUrl.length > 0
? rpcUrl[0].replace(/(https:\/\/)+/, 'https://')
: app?.chain?.meta?.node?.altWalletUrl;
: app?.chain?.meta?.ChainNode?.alt_wallet_url || '';
await this._web3.givenProvider.request({
method: 'wallet_addEthereumChain',
params: [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ class TerraStationWebWalletController implements IWebWallet<string> {

public getSessionSigner() {
return new CosmosSignerCW({
bech32Prefix: app.chain?.meta.bech32Prefix,
bech32Prefix: `${app.chain?.meta.bech32_prefix || 0}`,
signer: {
type: 'bytes',
signBytes: (message) => window.station.signBytes(toBase64(message)),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ class TerraWalletConnectWebWalletController

public getSessionSigner() {
return new CosmosSignerCW({
bech32Prefix: app.chain?.meta.bech32Prefix,
bech32Prefix: `${app.chain?.meta.bech32_prefix || 0}`,
signer: {
type: 'bytes',
getAddress: () => this._accounts[0].address,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BalanceType } from '@hicommonwealth/shared';
import { BalanceType, ChainBase } from '@hicommonwealth/shared';
import { fetchCachedNodes } from 'state/api/nodes';

export const getCosmosChains = (isEvm?: boolean): string[] => {
Expand All @@ -15,3 +15,16 @@ export const getCosmosChains = (isEvm?: boolean): string[] => {
?.map((node) => node.cosmosChainId || '') ?? []
);
};

export const getChainDecimals = (
chainId: string,
chainBase: ChainBase,
): number => {
let decimals = chainBase === ChainBase.CosmosSDK ? 6 : 18;

if (getCosmosChains(true)?.some((c) => c === chainId)) {
decimals = 18;
}

return decimals;
};
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,13 @@ import { userStore } from 'state/ui/user';
import { hexToNumber } from 'web3-utils';
import { z } from 'zod';
import BlockInfo from '../../../models/BlockInfo';
import ChainInfo from '../../../models/ChainInfo';
import IWebWallet from '../../../models/IWebWallet';

class WalletConnectWebWalletController implements IWebWallet<string> {
private _enabled: boolean;
private _enabling = false;
private _accounts: string[];
private _chainInfo: ChainInfo;
private _chainInfo: z.infer<typeof ExtendedCommunity>;
private _provider;
private _web3: Web3;

Expand Down Expand Up @@ -50,7 +49,7 @@ class WalletConnectWebWalletController implements IWebWallet<string> {
public getChainId() {
// We need app.chain? because the app might not be on a page with a chain (e.g homepage),
// and node? because the chain might not have a node provided
return this._chainInfo?.node?.ethChainId?.toString() || '1';
return this._chainInfo?.ChainNode?.eth_chain_id?.toString() || '1';
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
Expand Down Expand Up @@ -108,14 +107,10 @@ class WalletConnectWebWalletController implements IWebWallet<string> {
true,
);

const chainInfo = ChainInfo.fromTRPCResponse(
communityInfo as z.infer<typeof ExtendedCommunity>,
);

this._chainInfo = chainInfo;
this._chainInfo = communityInfo as z.infer<typeof ExtendedCommunity>;
}

const chainId = this._chainInfo?.node?.ethChainId || 1;
const chainId = this._chainInfo?.ChainNode?.eth_chain_id || 1;
const EthereumProvider = (await import('@walletconnect/ethereum-provider'))
.default;
this._provider = await EthereumProvider.init({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ export default class WebWalletController {

public availableWallets(chain?: ChainBase): IWebWallet<any>[] {
// handle case like injective, where we require a specific wallet
const specificChain = app.chain?.meta?.id;
if (app.chain?.meta?.id) {
const specificChain = app.chain?.meta?.id || '';
if (specificChain) {
const specificWallets = this._wallets.filter(
(w) => !!w.specificChains?.includes(specificChain),
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,14 @@ export default class CosmosAccount extends Account {
Accounts: CosmosAccounts,
address: string,
) {
super({ community: app.chain.meta, address });
super({
community: {
id: app.chain.meta.id || '',
base: app.chain.meta.base,
ss58Prefix: app.chain.meta.ss58_prefix || 0,
},
address,
});
if (!app.isModuleReady) {
// defer chain initialization
app.chainModuleReady.once('ready', () => {
Expand Down
Loading

0 comments on commit eb26db5

Please sign in to comment.