Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import type { Logger } from '@metamask/snap-networks-utils';
import type { FungibleAssetMetadata } from '@metamask/snaps-sdk';
import { array, assert } from '@metamask/superstruct';
import type { Infer } from '@metamask/superstruct';
import { CaipAssetTypeStruct, parseCaipAssetType } from '@metamask/utils';
import { CaipAssetTypeStruct } from '@metamask/utils';
import { parseTronCaipAssetType } from '../../utils/caip';

import { Network, SNAP_OWNED_ASSETS } from '../../constants';
import type { TokenCaipAssetType } from '../../services/assets/types';
Expand Down Expand Up @@ -96,8 +97,8 @@ export class TokenApiClient {
if (SNAP_OWNED_ASSETS.includes(assetType)) {
return false;
}
const { chainId } = parseCaipAssetType(assetType);
return TokenApiClient.supportedNetworks.includes(chainId as Network);
const { chainId } = parseTronCaipAssetType(assetType);
return TokenApiClient.supportedNetworks.includes(chainId);
});

if (supportedAssetTypes.length !== assetTypes.length) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { buildUrl } from '@metamask/snap-networks-utils';
import { assert } from '@metamask/superstruct';

import type { Network } from '../../constants';
import { Network } from '../../constants';
import type { ConfigProvider } from '../../services/config';
import { hexToString } from '../../utils/hex';
import {
Expand Down Expand Up @@ -43,14 +43,14 @@ export class TronHttpClient {
const { baseUrls } = configProvider.config.tronHttpApi;

// Initialize clients for all networks
Object.entries(baseUrls).forEach(([network, baseUrl]) => {
Object.values(Network).forEach((network) => {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Origin': '*',
};

this.#clients.set(network as Network, { baseUrl, headers });
this.#clients.set(network, { baseUrl: baseUrls[network], headers });
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type {
} from '@metamask/snap-networks-utils';
import { assert } from '@metamask/superstruct';

import type { Network } from '../../constants';
import { Network } from '../../constants';
import type { ConfigProvider } from '../../services/config';
import type { TronHttpClient } from '../tron-http/TronHttpClient';
import type { ChainParameter } from '../tron-http/types';
Expand Down Expand Up @@ -80,14 +80,14 @@ export class TrongridApiClient {
const { baseUrls } = configProvider.config.trongridApi;

// Initialize clients for all networks
Object.entries(baseUrls).forEach(([network, baseUrl]) => {
Object.values(Network).forEach((network) => {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Origin': '*',
};

this.#clients.set(network as Network, { baseUrl, headers });
this.#clients.set(network, { baseUrl: baseUrls[network], headers });
});

this.#tronHttpClient = tronHttpClient;
Expand Down
14 changes: 14 additions & 0 deletions packages/tron-wallet-snap/src/constants/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { InvalidParamsError } from '@metamask/snaps-sdk';
import { BigNumber } from 'bignumber.js';

export const ZERO = BigNumber(0);
Expand Down Expand Up @@ -66,6 +67,19 @@ export const Network = {

export type Network = (typeof Network)[keyof typeof Network];

const NETWORK_SCOPES: readonly string[] = Object.values(Network);

export const isSupportedNetwork = (scope: string): scope is Network =>
NETWORK_SCOPES.includes(scope);

export const assertSupportedNetwork = (scope: string): Network => {
if (!isSupportedNetwork(scope)) {
throw new InvalidParamsError(`Unsupported network: "${scope}"`) as Error;
}

return scope;
};

export const KnownCaip19Id = {
TrxMainnet: `${Network.Mainnet}/slip44:195`,
TrxNile: `${Network.Nile}/slip44:195`,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import type { ExtendedKeyringAccount } from '@metamask/snap-networks-utils';

import type { Network } from '../constants';

export type TronKeyringAccount = Omit<ExtendedKeyringAccount, 'scopes'> & {
scopes: Network[];
};
17 changes: 8 additions & 9 deletions packages/tron-wallet-snap/src/handlers/cronjob/cronjob.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ import type { ConfirmSignTransactionContext } from '../../ui/confirmation/views/
import { ConfirmTransactionRequest } from '../../ui/confirmation/views/ConfirmTransactionRequest/ConfirmTransactionRequest';
import { CONFIRM_TRANSACTION_INTERFACE_NAME } from '../../ui/confirmation/views/ConfirmTransactionRequest/types';
import type { ConfirmTransactionRequestContext } from '../../ui/confirmation/views/ConfirmTransactionRequest/types';
import { TrackTransactionParamsStruct } from '../../validation/structs';
import { validateRequest } from '../../validation/validators';

export const CronjobMethod = {
ContinuouslySynchronizeSelectedAccounts:
Expand Down Expand Up @@ -142,15 +144,7 @@ export class CronHandler {
await this.refreshSignTransaction();
break;
case BackgroundEventMethod.TrackTransaction:
await this.trackTransaction(
params as {
txId: string;
scope: Network;
accountIds: string[];
attempt: number;
transactionType?: TransactionType;
},
);
await this.handleTrackTransaction(request);
break;
default:
throw new Error(`Unknown cronjob method: ${method}`);
Expand Down Expand Up @@ -654,6 +648,11 @@ export class CronHandler {
}
}

async handleTrackTransaction(request: JsonRpcRequest): Promise<void> {
validateRequest(request.params, TrackTransactionParamsStruct);
await this.trackTransaction(request.params);
}

/**
* Background job to track a transaction's confirmation status.
* Continues polling until confirmed, then syncs accounts and emits finalized event.
Expand Down
19 changes: 10 additions & 9 deletions packages/tron-wallet-snap/src/handlers/keyring/keyring.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,7 @@ import {
asStrictKeyringAccount,
validateOrigin,
} from '@metamask/snap-networks-utils';
import type {
ExtendedKeyringAccount,
Logger,
} from '@metamask/snap-networks-utils';
import type { Logger } from '@metamask/snap-networks-utils';
import {
InvalidParamsError,
SnapError,
Expand All @@ -39,7 +36,7 @@ import { sortBy } from 'lodash';

import type { SnapClient } from '../../clients/snap/SnapClient';
import { ESSENTIAL_ASSETS } from '../../constants';
import type { Network } from '../../constants';
import type { TronKeyringAccount } from '../../entities/tronKeyringAccount';
import { originPermissions } from '../../permissions';
import type { AccountsService } from '../../services/accounts/AccountsService';
import type { AssetsService } from '../../services/assets/AssetsService';
Expand All @@ -56,6 +53,7 @@ import {
ListAccountAssetsStruct,
ListAccountTransactionsStruct,
PrivateKeyHexStruct,
ResolveAccountAddressStruct,
SignTransactionRequestStruct,
TronKeyringRequestStruct,
} from '../../validation/structs';
Expand Down Expand Up @@ -111,7 +109,7 @@ export class KeyringHandler implements KeyringSnapRpc {
return result ?? null;
}

async #listAccounts(): Promise<ExtendedKeyringAccount[]> {
async #listAccounts(): Promise<TronKeyringAccount[]> {
try {
const keyringAccounts = await this.#accountsService.getAll();

Expand All @@ -133,7 +131,7 @@ export class KeyringHandler implements KeyringSnapRpc {

async #getAccount(
accountId: string,
): Promise<ExtendedKeyringAccount | undefined> {
): Promise<TronKeyringAccount | undefined> {
try {
const account =
(await this.#accountsService.findById(accountId)) ?? undefined;
Expand All @@ -158,7 +156,7 @@ export class KeyringHandler implements KeyringSnapRpc {
}
}

async #getAccountOrThrow(accountId: string): Promise<ExtendedKeyringAccount> {
async #getAccountOrThrow(accountId: string): Promise<TronKeyringAccount> {
const account = await this.#getAccount(accountId);

if (!account) {
Expand Down Expand Up @@ -321,6 +319,9 @@ export class KeyringHandler implements KeyringSnapRpc {
scope: CaipChainId,
request: JsonRpcRequest,
): Promise<ResolvedAccountAddress> {
const params = { scope };
validateRequest(params, ResolveAccountAddressStruct);

this.#logger.info('Resolving account address', { scope, request });

// Get all keyring accounts
Expand All @@ -329,7 +330,7 @@ export class KeyringHandler implements KeyringSnapRpc {
// Resolve the address using the wallet service
const caip10Address = await this.#walletService.resolveAccountAddress(
keyringAccounts,
scope as Network,
params.scope,
request,
);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import type { EntropySourceId } from '@metamask/keyring-api';
import type {
ExtendedKeyringAccount,
IStateManager,
} from '@metamask/snap-networks-utils';
import type { IStateManager } from '@metamask/snap-networks-utils';

import type { TronKeyringAccount } from '../../entities/tronKeyringAccount';
import type { UnencryptedStateValue } from '../state/stateTypes';

/**
Expand All @@ -17,7 +15,7 @@ type AccountCreationRange = {
to: number;
};

type KeyringAccountsState = Record<string, ExtendedKeyringAccount>;
type KeyringAccountsState = Record<string, TronKeyringAccount>;

/**
* Result of merging accounts into `keyringAccounts`.
Expand All @@ -27,8 +25,8 @@ type KeyringAccountsState = Record<string, ExtendedKeyringAccount>;
* conflict losers are omitted (their winners are present in `merged`).
*/
export type KeyringAccountsMergeResult = {
merged: Record<string, ExtendedKeyringAccount>;
added: Record<string, ExtendedKeyringAccount>;
merged: Record<string, TronKeyringAccount>;
added: Record<string, TronKeyringAccount>;
};

/**
Expand All @@ -37,7 +35,7 @@ export type KeyringAccountsMergeResult = {
* @param account - The account to key.
* @returns A stable conflict key for the account.
*/
function getAccountIndexKey(account: ExtendedKeyringAccount): string {
function getAccountIndexKey(account: TronKeyringAccount): string {
return `${account.entropySource}:${account.index}`;
}

Expand All @@ -51,7 +49,7 @@ function getAccountIndexKey(account: ExtendedKeyringAccount): string {
function findAccountByIndexKey(
accounts: KeyringAccountsState,
indexKey: string,
): ExtendedKeyringAccount | undefined {
): TronKeyringAccount | undefined {
return Object.values(accounts).find(
(account) => getAccountIndexKey(account) === indexKey,
);
Expand Down Expand Up @@ -104,7 +102,7 @@ export class AccountsRepository {
*
* @returns All accounts from the state.
*/
async getAll(): Promise<ExtendedKeyringAccount[]> {
async getAll(): Promise<TronKeyringAccount[]> {
const accounts = await this.#state.getKey<
UnencryptedStateValue['keyringAccounts']
>(this.#storageKey);
Expand All @@ -122,7 +120,7 @@ export class AccountsRepository {
async findByEntropySourceAndRange(
entropySource: EntropySourceId,
range: AccountCreationRange,
): Promise<ExtendedKeyringAccount[]> {
): Promise<TronKeyringAccount[]> {
const accounts = await this.getAll();

return accounts
Expand All @@ -135,7 +133,7 @@ export class AccountsRepository {
.sort((first, second) => first.index - second.index);
}

async findById(id: string): Promise<ExtendedKeyringAccount | null> {
async findById(id: string): Promise<TronKeyringAccount | null> {
const accounts = await this.getAll();
return accounts.find((account) => account.id === id) ?? null;
}
Expand All @@ -147,13 +145,13 @@ export class AccountsRepository {
* @returns The matching accounts. Result ordering follows stored account
* ordering, not input ordering.
*/
async findByIds(ids: string[]): Promise<ExtendedKeyringAccount[]> {
async findByIds(ids: string[]): Promise<TronKeyringAccount[]> {
const accounts = await this.getAll();
const normalizedIds = new Set<string>();

ids.forEach((id) => normalizedIds.add(id.toLowerCase()));

const matchedAccounts: ExtendedKeyringAccount[] = [];
const matchedAccounts: TronKeyringAccount[] = [];
accounts.forEach((account) => {
if (normalizedIds.has(account.id.toLowerCase())) {
matchedAccounts.push(account);
Expand All @@ -163,15 +161,13 @@ export class AccountsRepository {
return matchedAccounts;
}

async findByAddress(address: string): Promise<ExtendedKeyringAccount | null> {
async findByAddress(address: string): Promise<TronKeyringAccount | null> {
const accounts = await this.getAll();

return accounts.find((account) => account.address === address) ?? null;
}

async create(
account: ExtendedKeyringAccount,
): Promise<ExtendedKeyringAccount> {
async create(account: TronKeyringAccount): Promise<TronKeyringAccount> {
let persistedAccount = account;

await this.#state.setKeyWith<KeyringAccountsState>(
Expand Down Expand Up @@ -204,7 +200,7 @@ export class AccountsRepository {
* without re-reading state.
*/
async mergeKeyringAccounts(
newAccounts: Record<string, ExtendedKeyringAccount>,
newAccounts: Record<string, TronKeyringAccount>,
): Promise<KeyringAccountsMergeResult> {
let result: KeyringAccountsMergeResult = { merged: {}, added: {} };

Expand Down
Loading
Loading