├── .npmignore ├── .eslintrc.js ├── src ├── helpers │ ├── types │ │ ├── secret.type.ts │ │ ├── updater.type.ts │ │ ├── snapState.type.ts │ │ ├── snapContent.type.ts │ │ └── proxyRestructure.type.ts │ ├── parser │ │ ├── types │ │ │ └── parser.type.ts │ │ ├── pgw │ │ │ ├── types │ │ │ │ ├── getSnapLatestVersion.type.ts │ │ │ │ ├── postTransactionRiskSummary.type.ts │ │ │ │ ├── postTransactionRisks.type.ts │ │ │ │ ├── getAddressLabel.type.ts │ │ │ │ ├── getTokenInfo.type.ts │ │ │ │ └── postTransactionSimulation.type.ts │ │ │ ├── getSnapLatestVersion.ts │ │ │ ├── index.ts │ │ │ ├── postTransactionRiskSummary.ts │ │ │ ├── postTransactionRisks.ts │ │ │ ├── getAddressLabel.ts │ │ │ ├── postTransactionSimulation.ts │ │ │ └── getTokenInfo.ts │ │ └── parser.ts │ ├── panels │ │ ├── adPanel.ts │ │ ├── projectInsightPanel.ts │ │ ├── riskSummaryPanel.ts │ │ ├── riskPanel.ts │ │ ├── updateAlertPanel.ts │ │ ├── types │ │ │ └── panels.type.ts │ │ └── simulationPanel.ts │ ├── versionCheck.ts │ ├── secret.ts │ ├── snapState.ts │ ├── updater.ts │ ├── proxyRestructure.ts │ ├── simulationContent.ts │ └── snapContent.ts ├── controllers │ ├── __mocks__ │ │ └── logger.mock.ts │ ├── logger.ts │ ├── types │ │ ├── http.type.ts │ │ └── pgw.type.ts │ ├── http.ts │ ├── chainsafer.ts │ └── pgw.ts ├── constants │ ├── wallet.ts │ ├── config.ts │ └── content.ts └── index.ts ├── tsconfig.json ├── .env.production ├── .env.staging ├── .env.test ├── snap.manifest.json ├── README.md ├── LICENSE-MIT ├── .gitignore ├── images └── icon.svg ├── snap.config.js ├── package.json └── LICENSE-APACHE /.npmignore: -------------------------------------------------------------------------------- 1 | # dotenv environment variables file 2 | .env.development 3 | .env.production -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: ['../../.eslintrc.js'], 3 | 4 | ignorePatterns: ['!.eslintrc.js', 'dist/'], 5 | }; 6 | -------------------------------------------------------------------------------- /src/helpers/types/secret.type.ts: -------------------------------------------------------------------------------- 1 | export type TGeneratedUUIDV4 = () => string 2 | export type TGenerateUniqueId = (length?: number) => string 3 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES2017", 4 | "moduleResolution": "node", 5 | }, 6 | "include": [ 7 | "src" 8 | ] 9 | } 10 | -------------------------------------------------------------------------------- /src/helpers/parser/types/parser.type.ts: -------------------------------------------------------------------------------- 1 | export type TParserMapping = ( 2 | responseBody: Record, 3 | key: string, 4 | defaultValue: any, 5 | customParserFunc?: Function 6 | ) => T 7 | -------------------------------------------------------------------------------- /src/helpers/types/updater.type.ts: -------------------------------------------------------------------------------- 1 | export type TNestedKeyUpdater = ( 2 | context: Record, 3 | nestedKey: string, 4 | value: any 5 | ) => void 6 | export type TUpdater = ( 7 | context: Record, 8 | keys: string[], 9 | values: any[] 10 | ) => Record 11 | -------------------------------------------------------------------------------- /src/controllers/__mocks__/logger.mock.ts: -------------------------------------------------------------------------------- 1 | export const mockLog = jest.fn() 2 | export const mockError = jest.fn() 3 | jest.mock('@src/controllers/logger', () => { 4 | return jest.fn().mockImplementation(() => { 5 | return { 6 | log: mockLog, 7 | error: mockError, 8 | } 9 | }) 10 | }) 11 | -------------------------------------------------------------------------------- /src/helpers/types/snapState.type.ts: -------------------------------------------------------------------------------- 1 | import { Json } from '@metamask/snaps-sdk' 2 | 3 | export type TSnapState = { 4 | snapInfo: SnapInfo 5 | } 6 | 7 | export type SnapInfo = { 8 | id: string | undefined 9 | version: string | undefined 10 | } 11 | 12 | export type TGetSnapState = () => Promise> 13 | -------------------------------------------------------------------------------- /src/helpers/panels/adPanel.ts: -------------------------------------------------------------------------------- 1 | import { panel, divider, text } from '@metamask/snaps-sdk' 2 | import { chainSaferAd } from '../../constants/content' 3 | export function convertAdPanel() { 4 | return panel([ 5 | divider(), 6 | text(chainSaferAd.adTitle), 7 | text(chainSaferAd.adContent), 8 | divider(), 9 | ]) 10 | 11 | } -------------------------------------------------------------------------------- /src/helpers/types/snapContent.type.ts: -------------------------------------------------------------------------------- 1 | import { Json, OnTransactionResponse } from '@metamask/snaps-sdk' 2 | import { TSnapState } from './snapState.type' 3 | 4 | export type TTransactionInsightLayout = (args: { 5 | transaction: { 6 | [key: string]: Json 7 | } 8 | chainId: string 9 | transactionOrigin?: string 10 | }) => Promise 11 | -------------------------------------------------------------------------------- /src/helpers/versionCheck.ts: -------------------------------------------------------------------------------- 1 | export const isGreaterVersion = (version: string, compareVersion: string) => { 2 | const versionArray = version.split('.') 3 | const compareVersionArray = compareVersion.split('.') 4 | for (let i = 0; i < versionArray.length; i++) { 5 | if (parseInt(versionArray[i]) > parseInt(compareVersionArray[i])) { 6 | return true 7 | } 8 | } 9 | return false 10 | } 11 | -------------------------------------------------------------------------------- /src/constants/wallet.ts: -------------------------------------------------------------------------------- 1 | export enum ETHEREUM_METHOD { 2 | REQUEST_ACCOUNT = 'eth_requestAccounts', 3 | SEND_TRANSACTION = 'eth_sendTransaction', 4 | SIGN_TYPED_DATA = 'eth_signTypedData', 5 | SIGN = 'eth_sign', 6 | } 7 | 8 | export type TWalletEventMethod = 9 | | ETHEREUM_METHOD.REQUEST_ACCOUNT 10 | | ETHEREUM_METHOD.SEND_TRANSACTION 11 | | ETHEREUM_METHOD.SIGN_TYPED_DATA 12 | | ETHEREUM_METHOD.SIGN 13 | -------------------------------------------------------------------------------- /src/helpers/parser/pgw/types/getSnapLatestVersion.type.ts: -------------------------------------------------------------------------------- 1 | export interface IGetSnapLatestVersionResponseBody { 2 | latest_force_update_version: string 3 | latest_version: string 4 | } 5 | 6 | export interface IGetSnapLatestVersionResponseParsed { 7 | latestForceUpdateVersion: string 8 | latestVersion: string 9 | } 10 | 11 | export type TGetSnapLatestVersion = ( 12 | responseBody: IGetSnapLatestVersionResponseBody 13 | ) => IGetSnapLatestVersionResponseParsed 14 | -------------------------------------------------------------------------------- /.env.production: -------------------------------------------------------------------------------- 1 | ENV='prod' 2 | DAPP_LINK='https://chainsafer.nexone.io/snap/#/' 3 | APP_PLATFORM='snap' 4 | API_PGW_BASE='https://pgw-us1.nexone.io' 5 | API_PGW_BASE_LAYER='/api' 6 | API_PGW_VAESION='v1' 7 | API_PGW_PATH_POST_TRANSACTION_RISKS='crypto/transaction-risks' 8 | API_PGW_PATH_POST_TRANSACTION_RISK_SUMMARY='crypto/transaction-risks/summary' 9 | API_PGW_PATH_POST_TRANSACTION_SIMULATION='crypto/transaction-simulations' 10 | API_PGW_PATH_GET_SNAP_LATEST_VERSION='snap/latest-version' 11 | API_PGW_PATH_GET_TOKEN_INFO='crypto/token-info/{contractAddress}' 12 | API_PGW_PATH_GET_ADDRESS_LABEL='crypto/address-labels/{contractAddress}' -------------------------------------------------------------------------------- /.env.staging: -------------------------------------------------------------------------------- 1 | ENV='stag' 2 | DAPP_LINK='https://chainsafer.stag.nexone.io/snap/#/' 3 | APP_PLATFORM='snap' 4 | API_PGW_BASE='https://pgw-us1.stag.nexone.io' 5 | API_PGW_BASE_LAYER='/api' 6 | API_PGW_VAESION='v1' 7 | API_PGW_PATH_POST_TRANSACTION_RISKS='crypto/transaction-risks' 8 | API_PGW_PATH_POST_TRANSACTION_RISK_SUMMARY='crypto/transaction-risks/summary' 9 | API_PGW_PATH_POST_TRANSACTION_SIMULATION='crypto/transaction-simulations' 10 | API_PGW_PATH_GET_SNAP_LATEST_VERSION='snap/latest-version' 11 | API_PGW_PATH_GET_TOKEN_INFO='crypto/token-info/{contractAddress}' 12 | API_PGW_PATH_GET_ADDRESS_LABEL='crypto/address-labels/{contractAddress}' -------------------------------------------------------------------------------- /src/helpers/secret.ts: -------------------------------------------------------------------------------- 1 | import type { TGeneratedUUIDV4, TGenerateUniqueId } from './types/secret.type' 2 | 3 | import CryptoJS from 'crypto-js' 4 | 5 | export const generatedUUIDV4: TGeneratedUUIDV4 = () => { 6 | const id = generateUniqueId(32) 7 | return `${id.substring(0, 7)}-${id.substring(7, 11)}-${id.substring(11, 15)}-${id.substring( 8 | 15, 9 | 19 10 | )}-${id.substring(19, 23)}-${id.substring(23)}` 11 | } 12 | 13 | export const generateUniqueId: TGenerateUniqueId = (length = 8) => { 14 | const id = CryptoJS.lib.WordArray.random(length / 2).toString() 15 | return id.substring(0, length) 16 | } 17 | -------------------------------------------------------------------------------- /src/helpers/parser/pgw/getSnapLatestVersion.ts: -------------------------------------------------------------------------------- 1 | import type { TGetSnapLatestVersion } from '../../../helpers/parser/pgw/types/getSnapLatestVersion.type' 2 | 3 | import { parserMapping } from '../../../helpers/parser/parser' 4 | 5 | const getSnapLatestVersion: TGetSnapLatestVersion = (responseBody) => { 6 | return { 7 | latestForceUpdateVersion: parserMapping( 8 | responseBody, 9 | 'latest_force_update_version', 10 | '' 11 | ), 12 | latestVersion: parserMapping(responseBody, 'latest_version', ''), 13 | } 14 | } 15 | 16 | export default getSnapLatestVersion 17 | -------------------------------------------------------------------------------- /.env.test: -------------------------------------------------------------------------------- 1 | ENV='test' 2 | DAPP_LINK='https://chainsafer.test.nexone.io/snap/#/' 3 | APP_PLATFORM='snap' 4 | API_PGW_BASE='https://metapgw-us1.test.mgcp.a1q7.net/api' 5 | API_PGW_BASE_LAYER='/api' 6 | API_PGW_VAESION='v1' 7 | API_PGW_PATH_POST_TRANSACTION_RISKS='crypto/transaction-risks' 8 | API_PGW_PATH_POST_TRANSACTION_RISK_SUMMARY='crypto/transaction-risks/summary' 9 | API_PGW_PATH_POST_TRANSACTION_SIMULATION='crypto/transaction-simulations' 10 | API_PGW_PATH_GET_SNAP_LATEST_VERSION='snap/latest-version' 11 | API_PGW_PATH_GET_TOKEN_INFO='crypto/token-info/{contractAddress}' 12 | API_PGW_PATH_GET_ADDRESS_LABEL='crypto/address-labels/{contractAddress}' -------------------------------------------------------------------------------- /src/helpers/parser/pgw/types/postTransactionRiskSummary.type.ts: -------------------------------------------------------------------------------- 1 | export type TSeverityResponse = 'fatal_risk' | 'high_risk' | 'caution' | 'no_risk' | 'unknown' 2 | export type TSeverityParsed = 'fatal_risk' | 'high_risk' | 'caution' | 'no_risk' 3 | 4 | export interface IPostTransactionRiskSummaryResponseBody { 5 | rule_name: string 6 | severity: TSeverityResponse 7 | } 8 | 9 | export interface IPostTransactionRiskSummaryResponseParsed { 10 | ruleName: string 11 | severity: TSeverityParsed 12 | } 13 | 14 | export type TPostTransactionRiskSummary = ( 15 | responseBody: IPostTransactionRiskSummaryResponseBody 16 | ) => IPostTransactionRiskSummaryResponseParsed 17 | -------------------------------------------------------------------------------- /snap.manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0.239", 3 | "description": "TM Chainsafer of MetaMask Snaps.", 4 | "proposedName": "TM ChainSafer", 5 | "source": { 6 | "shasum": "19Ijtz/8XfTw8ovLOUwMdJc3SO7iW3KJW6owaC26Jqo=", 7 | "location": { 8 | "npm": { 9 | "filePath": "dist/bundle.js", 10 | "iconPath": "images/icon.svg", 11 | "packageName": "tm-chainsafer-snap-test", 12 | "registry": "https://registry.npmjs.org/" 13 | } 14 | } 15 | }, 16 | "initialPermissions": { 17 | "endowment:transaction-insight": { 18 | "allowTransactionOrigin": true 19 | }, 20 | "endowment:network-access": {} 21 | }, 22 | "manifestVersion": "0.1" 23 | } 24 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { OnTransactionHandler, OnRpcRequestHandler } from '@metamask/snaps-sdk' 2 | import { transactionInsightLayout } from './helpers/snapContent' 3 | import { TSnapState } from './helpers/types/snapState.type' 4 | import { setSnapState } from './helpers/snapState' 5 | 6 | import Logger from './controllers/logger' 7 | const logger = new Logger('[index]') 8 | 9 | export const onTransaction: OnTransactionHandler = async ({ 10 | transactionOrigin, 11 | chainId, 12 | transaction, 13 | }) => { 14 | logger.log('transactionOrigin:', transactionOrigin) 15 | logger.log('chainId:', chainId) 16 | logger.log('transaction:', transaction) 17 | 18 | return transactionInsightLayout({ transactionOrigin, chainId, transaction }) 19 | } 20 | -------------------------------------------------------------------------------- /src/helpers/parser/parser.ts: -------------------------------------------------------------------------------- 1 | import type { TParserMapping } from '../../helpers/parser/types/parser.type' 2 | import Logger from '../../controllers/logger' 3 | 4 | const logger = new Logger('[helpers.parser.parser]') 5 | 6 | export const parserMapping: TParserMapping = ( 7 | responseBody, 8 | key, 9 | defaultValue, 10 | customParserFunc = undefined 11 | ) => { 12 | const nestedKeys = key.split('.') 13 | let parseTarget = responseBody 14 | 15 | nestedKeys.forEach((nestedKey) => { 16 | parseTarget = parseTarget?.[nestedKey] 17 | }) 18 | 19 | if ((parseTarget === null || parseTarget === undefined) && defaultValue !== undefined) { 20 | logger.error(key, 'not found') 21 | return defaultValue 22 | } 23 | 24 | return customParserFunc?.(parseTarget) || parseTarget 25 | } 26 | -------------------------------------------------------------------------------- /src/helpers/parser/pgw/types/postTransactionRisks.type.ts: -------------------------------------------------------------------------------- 1 | export type TRiskType = 'severe_risk' | 'minor_risk' | 'attention_required' 2 | export interface IPostTransactionRisksResponseBodyItem { 3 | name: string 4 | factor_type: TRiskType 5 | message: string 6 | labels: string[] 7 | } 8 | 9 | export interface IPostTransactionRisksResponseBody { 10 | factors: IPostTransactionRisksResponseBodyItem[] 11 | } 12 | 13 | export interface IPostTransactionRisksParsedItem { 14 | name: string 15 | type: TRiskType 16 | message: string 17 | labels: string[] 18 | } 19 | export interface IPostTransactionRisksResponseParsed { 20 | factors: IPostTransactionRisksParsedItem[] 21 | } 22 | 23 | export type TPostTransactionRisks = ( 24 | responseBody: IPostTransactionRisksResponseBody 25 | ) => IPostTransactionRisksResponseParsed 26 | -------------------------------------------------------------------------------- /src/controllers/logger.ts: -------------------------------------------------------------------------------- 1 | import { ENABLE_CLIENT_CONSOLE } from '../constants/config' 2 | 3 | export default class Logger { 4 | tag: any 5 | enable: boolean 6 | constructor(tag: any) { 7 | this.tag = tag 8 | this.enable = ENABLE_CLIENT_CONSOLE 9 | } 10 | 11 | log = (...params: any[]) => { 12 | this.enable && console.log(this.tag, ...params) 13 | } 14 | 15 | error = (...params: String[]) => { 16 | if (this.enable) { 17 | const fixedWord = 'Oops, Σ( ° △ °|||)' 18 | const style = ` 19 | color: #E71D36; 20 | background: #2E294E; 21 | ` 22 | console.groupCollapsed('%c%s', style, `${this.tag} ${fixedWord}`) 23 | params.forEach((item) => { 24 | console.log(item) 25 | }) 26 | console.groupEnd() 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/helpers/parser/pgw/index.ts: -------------------------------------------------------------------------------- 1 | import postTransactionRisks from '../../../helpers/parser/pgw/postTransactionRisks' 2 | import postTransactionRiskSummary from '../../../helpers/parser/pgw/postTransactionRiskSummary' 3 | import postTransactionSimulation from '../../../helpers/parser/pgw/postTransactionSimulation' 4 | import getSnapLatestVersion from '../../../helpers/parser/pgw/getSnapLatestVersion' 5 | import getTokenInfo from '../../../helpers/parser/pgw/getTokenInfo' 6 | import getAddressLabel from '../../../helpers/parser/pgw/getAddressLabel' 7 | export default { 8 | POST_TRANSACTION_RISKS: postTransactionRisks, 9 | POST_TRANSACTION_RISK_SUMMARY: postTransactionRiskSummary, 10 | POST_TRANSACTION_SIMULATION: postTransactionSimulation, 11 | GET_SNAP_LATEST_VERSION: getSnapLatestVersion, 12 | GET_TOKEN_INFO: getTokenInfo, 13 | GET_ADDRESS_LABEL: getAddressLabel, 14 | } 15 | -------------------------------------------------------------------------------- /src/helpers/parser/pgw/postTransactionRiskSummary.ts: -------------------------------------------------------------------------------- 1 | import type { 2 | TSeverityParsed, 3 | TPostTransactionRiskSummary, 4 | } from '../../../helpers/parser/pgw/types/postTransactionRiskSummary.type' 5 | 6 | import { parserMapping } from '../../../helpers/parser/parser' 7 | 8 | const postTransactionRiskSummary: TPostTransactionRiskSummary = (responseBody) => { 9 | if (responseBody.rule_name === '' && responseBody.severity === 'unknown') { 10 | return { 11 | ruleName: '', 12 | severity: 'no_risk', 13 | } 14 | } 15 | return { 16 | ruleName: parserMapping(responseBody, 'rule_name', '', (name: string) => { 17 | return `rule_${name}` 18 | }), 19 | severity: parserMapping(responseBody, 'severity', 'no_risk'), 20 | } 21 | } 22 | 23 | export default postTransactionRiskSummary 24 | -------------------------------------------------------------------------------- /src/helpers/parser/pgw/types/getAddressLabel.type.ts: -------------------------------------------------------------------------------- 1 | export interface IGetAddressLabelsResponseBody { 2 | address: string 3 | label_infos: IGetAddressLabelsLabelInfosBody[] 4 | notes: IGetAddressLabelsNotesBody[] 5 | } 6 | 7 | export interface IGetAddressLabelsLabelInfosBody { 8 | category: string 9 | risk_level: number 10 | labels: IGetAddressLabelsLabelsBody[] 11 | } 12 | 13 | export interface IGetAddressLabelsLabelsBody { 14 | name: string 15 | source: string 16 | } 17 | export interface IGetAddressLabelsNotesBody { 18 | note: string 19 | source: string 20 | } 21 | 22 | export interface IGetAddressLabelResponseParsed { 23 | address: string 24 | labelInfos: IGetAddressLabelsLabelInfosBody[] 25 | notes: IGetAddressLabelsNotesBody[] 26 | } 27 | export type TGetAddressLabel = ( 28 | responseBody: IGetAddressLabelsResponseBody, 29 | ) => IGetAddressLabelResponseParsed 30 | -------------------------------------------------------------------------------- /src/helpers/types/proxyRestructure.type.ts: -------------------------------------------------------------------------------- 1 | export interface ISendTransactionProxyPayload { 2 | method: 'eth_sendTransaction' 3 | params: Record[] 4 | } 5 | 6 | export interface ISignProxyPayload { 7 | method: 'eth_sign' 8 | params: string[] 9 | } 10 | 11 | export interface ISignTypedDataProxyPayload { 12 | //only metamask will have version postfix 13 | method: 'eth_signTypedData' 14 | params: string[] 15 | } 16 | 17 | export type TProxyObj = 18 | | ISendTransactionProxyPayload 19 | | ISignProxyPayload 20 | | ISignTypedDataProxyPayload 21 | 22 | export type TProxyConvertToPayload = (domain: string, proxyObj?: TProxyObj) => TRestructuredPayload 23 | 24 | export type TRestructuredTxnParams = { 25 | name: string 26 | value: string | Record 27 | } 28 | 29 | export type TRestructuredPayload = { 30 | txn_method: string 31 | url: string 32 | txn_params: TRestructuredTxnParams[] 33 | } 34 | -------------------------------------------------------------------------------- /src/helpers/panels/projectInsightPanel.ts: -------------------------------------------------------------------------------- 1 | import { heading, divider, panel, text } from '@metamask/snaps-sdk' 2 | import { headingText, serviceError } from '../../constants/content' 3 | import { TProjectInsightPanel } from './types/panels.type' 4 | export const covertToProjectInsightPanel: TProjectInsightPanel = (result, error) => { 5 | if (error) { 6 | return panel([]) 7 | } 8 | 9 | if ( 10 | result == null || 11 | Object.keys(result).length == 0 || 12 | (result.BlueCheckMark != null && Object.keys(result).length == 1) 13 | ) { 14 | return panel([]) 15 | } 16 | 17 | const arrayFromObject = Object.keys(result) 18 | 19 | return panel([ 20 | heading(headingText.projectInsightPanel), 21 | divider(), 22 | ...arrayFromObject 23 | .filter((key) => key != 'BlueCheckMark') 24 | .map((key) => { 25 | return text(`${result[key]}`) 26 | }), 27 | ]) 28 | } 29 | -------------------------------------------------------------------------------- /src/helpers/panels/riskSummaryPanel.ts: -------------------------------------------------------------------------------- 1 | import { panel, heading, text, divider } from '@metamask/snaps-sdk' 2 | import { headingText, serviceError, riskIconMapping, apiMapping } from '../../constants/content' 3 | import { TRiskSummaryPanel } from './types/panels.type' 4 | 5 | export const convertToRiskSummaryPanel: TRiskSummaryPanel = (result, error) => { 6 | if (error) { 7 | return panel([ 8 | heading(serviceError.riskApiError), 9 | text(serviceError.riskApiErrorDetail), 10 | text(`${JSON.stringify(error)}`), 11 | divider(), 12 | ]) 13 | } 14 | 15 | if (result == null) { 16 | return panel([]) 17 | } 18 | 19 | return panel([ 20 | heading( 21 | `${riskIconMapping.transaction_risks_summary[result.severity]} ${apiMapping.transaction_risks_summary[result.severity] 22 | }`, 23 | ), 24 | text(`**${apiMapping.transaction_risks_summary[result.ruleName]}**`), 25 | divider(), 26 | ]) 27 | } 28 | -------------------------------------------------------------------------------- /src/helpers/snapState.ts: -------------------------------------------------------------------------------- 1 | import { TGetSnapState, TSnapState } from './types/snapState.type' 2 | import Logger from '../controllers/logger' 3 | const logger = new Logger('[helpers.snapState]') 4 | 5 | export const getSnapState: TGetSnapState = async () => { 6 | const state = await snap.request({ 7 | method: 'snap_manageState', 8 | params: { 9 | operation: 'get', 10 | }, 11 | }) 12 | logger.log('get state:', state) 13 | return state 14 | } 15 | 16 | export const setSnapState = async (newState: TSnapState) => { 17 | logger.log('set state:', newState) 18 | return snap.request({ 19 | method: 'snap_manageState', 20 | params: { 21 | operation: 'update', 22 | newState: newState, 23 | }, 24 | }) 25 | } 26 | 27 | export const clearSnapState = async () => { 28 | logger.log('clearSnapState:') 29 | return snap.request({ 30 | method: 'snap_manageState', 31 | params: { operation: 'clear' }, 32 | }) 33 | } 34 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ChainSafer Snap 2 | 3 | Realtime risk check when use metamask send transaction. 4 | 5 | ## Folder Structure 6 | 7 | ``` 8 | |-- Project 9 | |-- images --- snap logo defined 10 | |-- src 11 | |-- constants --- constants defined 12 | |-- controller --- controller handler, like call api... 13 | |-- types --- controller types struct defined 14 | |-- helpers --- utils 15 | |-- types --- parser tool struct defined 16 | |--parser --- parser tool 17 | |---types --- convert struct method 18 | |---pgw --- pgw api struct defined 19 | |-- index.ts --- metamask event handler defined 20 | ``` 21 | 22 | ## Run 23 | 24 | ``` 25 | > npm install 26 | > npm start 27 | ``` 28 | 29 | ## Manual install 30 | 31 | visit our snap [website](https://chainsafer.nexone.io/snap/#/) for manual install 32 | -------------------------------------------------------------------------------- /src/constants/config.ts: -------------------------------------------------------------------------------- 1 | export const VERSION = process.env.VERSION 2 | export const ENABLE_CLIENT_CONSOLE = process.env.ENV === 'test' 3 | export const DAPP_LINK = process.env.DAPP_LINK 4 | export const APP_PLATFORM = process.env.APP_PLATFORM 5 | export const API = { 6 | PGW: { 7 | base: process.env.API_PGW_BASE, 8 | basicLayer: process.env.API_PGW_BASE_LAYER, 9 | version: process.env.API_PGW_VAESION, 10 | path: { 11 | POST_TRANSACTION_RISKS: process.env.API_PGW_PATH_POST_TRANSACTION_RISKS, 12 | POST_TRANSACTION_RISK_SUMMARY: process.env.API_PGW_PATH_POST_TRANSACTION_RISK_SUMMARY, 13 | POST_TRANSACTION_SIMULATION: process.env.API_PGW_PATH_POST_TRANSACTION_SIMULATION, 14 | GET_SNAP_LATEST_VERSION: process.env.API_PGW_PATH_GET_SNAP_LATEST_VERSION, 15 | GET_TOKEN_INFO: process.env.API_PGW_PATH_GET_TOKEN_INFO, 16 | GET_ADDRESS_LABEL: process.env.API_PGW_PATH_GET_ADDRESS_LABEL, 17 | }, 18 | }, 19 | } 20 | export const supportChainIds = ["1"] 21 | -------------------------------------------------------------------------------- /src/helpers/panels/riskPanel.ts: -------------------------------------------------------------------------------- 1 | import { panel, text, divider, heading } from '@metamask/snaps-sdk' 2 | import { TRiskPanel } from './types/panels.type' 3 | import { apiMapping, headingText, riskIconMapping, serviceError } from '../../constants/content' 4 | 5 | export const convertToRiskPanel: TRiskPanel = (result, error) => { 6 | if (error) { 7 | return panel([ 8 | heading(serviceError.riskApiError), 9 | text(serviceError.riskApiErrorDetail), 10 | text(`${JSON.stringify(error)}`), 11 | divider(), 12 | ]) 13 | } 14 | 15 | if (result == null) { 16 | return panel([]) 17 | } 18 | 19 | return panel([ 20 | text(`${headingText.riskFactor}`), 21 | ...result.factors.map((insight) => 22 | panel([ 23 | text( 24 | `${riskIconMapping.transaction_risk_type[insight.type]} ${apiMapping.transaction_risks[insight.name] 25 | }`, 26 | ), 27 | ]), 28 | ), 29 | divider(), 30 | ]) 31 | } 32 | -------------------------------------------------------------------------------- /src/controllers/types/http.type.ts: -------------------------------------------------------------------------------- 1 | export type IHTTPRequestPayload = { 2 | method: string 3 | headers: Record 4 | body?: string 5 | [key: string]: any 6 | } 7 | 8 | export type IUrlBase = { 9 | path: string 10 | endpoint: string 11 | } 12 | 13 | export type IErrorResponse = { 14 | [key: string]: any 15 | } 16 | 17 | export type IResponseError = { 18 | httpStatusCode: number 19 | errorCode: number 20 | traceId: string 21 | message: string 22 | dateTime: string 23 | } 24 | 25 | export type TMethodFactory = ( 26 | method: string 27 | ) => ( 28 | url: IUrlBase, 29 | request: IHTTPRequestPayload, 30 | onResponseErrorCode?: Function 31 | ) => (isJSONResponse?: boolean) => Promise<[IErrorResponse, T]> 32 | export type TCreateUrlBase = ( 33 | endpoint: string 34 | ) => (pathKey: string, replacer?: Function, version?: string) => IUrlBase 35 | export type TPayload = ( 36 | body: Record, 37 | headers: Record, 38 | additions?: Record 39 | ) => IHTTPRequestPayload 40 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 TrendMicro Software Inc. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /src/helpers/updater.ts: -------------------------------------------------------------------------------- 1 | import type { TNestedKeyUpdater, TUpdater } from '../helpers/types/updater.type' 2 | 3 | import Logger from '../controllers/logger' 4 | 5 | const logger = new Logger('[helper.updater]') 6 | const nestedKeyUpdater: TNestedKeyUpdater = (context, nestedKey, value) => { 7 | let currentNest = context 8 | const keys = nestedKey.split('.') 9 | 10 | keys.forEach((key, index) => { 11 | if (index === keys.length - 1) { 12 | currentNest[key] = value 13 | } else { 14 | // prevention for some default layer is null 15 | if (currentNest[key] === null || currentNest[key] === undefined) { 16 | currentNest[key] = {} 17 | } 18 | currentNest = currentNest[key] 19 | } 20 | }) 21 | } 22 | 23 | export const updater: TUpdater = (context, keys, values) => { 24 | const deRefContext = JSON.parse(JSON.stringify(context)) 25 | if (keys.length === values.length) { 26 | keys.forEach((nestedKey, index) => { 27 | nestedKeyUpdater(deRefContext, nestedKey, values[index]) 28 | }) 29 | } else { 30 | logger.error('unequal length with keys and values') 31 | } 32 | return deRefContext 33 | } 34 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | dist/ 3 | coverage/ 4 | .cache/ 5 | public/ 6 | .vscode/settings.json 7 | package-lock.json 8 | 9 | # Logs 10 | logs 11 | *.log 12 | npm-debug.log* 13 | yarn-debug.log* 14 | yarn-error.log* 15 | lerna-debug.log* 16 | 17 | # Diagnostic reports (https://nodejs.org/api/report.html) 18 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 19 | 20 | # Runtime data 21 | pids 22 | *.pid 23 | *.seed 24 | *.pid.lock 25 | 26 | # Coverage directory used by tools like istanbul 27 | coverage 28 | *.lcov 29 | 30 | # nyc test coverage 31 | .nyc_output 32 | 33 | # node-waf configuration 34 | .lock-wscript 35 | 36 | # Compiled binary addons (https://nodejs.org/api/addons.html) 37 | build/Release 38 | 39 | # Dependency directories 40 | node_modules/ 41 | 42 | # TypeScript cache 43 | *.tsbuildinfo 44 | 45 | # Optional npm cache directory 46 | .npm 47 | 48 | # Optional eslint cache 49 | .eslintcache 50 | 51 | # Microbundle cache 52 | .rpt2_cache/ 53 | .rts2_cache_cjs/ 54 | .rts2_cache_es/ 55 | .rts2_cache_umd/ 56 | 57 | # Optional REPL history 58 | .node_repl_history 59 | 60 | # Output of 'npm pack' 61 | *.tgz 62 | 63 | # Yarn Integrity file 64 | .yarn-integrity 65 | 66 | # dotenv environment variables file 67 | .env 68 | 69 | # Stores VSCode versions used for testing VSCode extensions 70 | .vscode-test 71 | 72 | # yarn v2 73 | .yarn/cache 74 | .yarn/unplugged 75 | .yarn/build-state.yml 76 | .yarn/install-state.gz 77 | .pnp.* 78 | -------------------------------------------------------------------------------- /src/helpers/parser/pgw/types/getTokenInfo.type.ts: -------------------------------------------------------------------------------- 1 | export interface IGetTokenInfoResponseBody { 2 | bitcointalk?: string 3 | blog?: string 4 | blue_checkmark?: boolean 5 | contract_address?: string 6 | description?: string 7 | discord?: string 8 | divisor?: number 9 | email?: string 10 | facebook?: string 11 | github?: string 12 | linkedin?: string 13 | reddit?: string 14 | slack?: string 15 | symbol?: string 16 | telegram?: string 17 | token_name?: string 18 | tokenPriceUSD?: string 19 | total_supply?: string 20 | twitter?: string 21 | website?: string 22 | wechat?: string 23 | whitepaper?: string 24 | } 25 | 26 | export interface IGetTokenInfoResponseParsed { 27 | Bitcointalk?: string 28 | Blog?: string 29 | BlueCheckMark?: boolean 30 | ContractAddress?: string 31 | Description?: string 32 | Discord?: string 33 | Divisor?: number 34 | Email?: string 35 | Facebook?: string 36 | Github?: string 37 | Linkedin?: string 38 | Reddit?: string 39 | Slack?: string 40 | Symbol?: string 41 | Telegram?: string 42 | TokenName?: string 43 | TokenPriceUSD?: string 44 | TotalSupply?: string 45 | Twitter?: string 46 | Website?: string 47 | Wechat?: string 48 | Whitepaper?: string 49 | } 50 | 51 | export type TGetTokenInfo = (responseBody: IGetTokenInfoResponseBody) => IGetTokenInfoResponseParsed 52 | -------------------------------------------------------------------------------- /src/helpers/proxyRestructure.ts: -------------------------------------------------------------------------------- 1 | import { ETHEREUM_METHOD } from '../constants/wallet' 2 | import type { 3 | TProxyConvertToPayload, 4 | TRestructuredPayload, 5 | TRestructuredTxnParams, 6 | } from './types/proxyRestructure.type' 7 | 8 | import Logger from '../controllers/logger' 9 | 10 | const logger = new Logger('[helpers.proxyRestructure]') 11 | export const proxyConvertToPayload: TProxyConvertToPayload = (domain, proxyObj) => { 12 | const txn: TRestructuredTxnParams[] = [] 13 | let method = '' 14 | if (proxyObj?.hasOwnProperty('method')) { 15 | method = proxyObj.method 16 | } 17 | 18 | if (ETHEREUM_METHOD.SEND_TRANSACTION === proxyObj?.method) { 19 | const entries = Object.entries(proxyObj?.params[0] || {}) 20 | entries.map(([key, value]) => { 21 | txn.push({ name: key, value }) 22 | }) 23 | } 24 | 25 | // only metamask will have version postfix 26 | if ( 27 | ETHEREUM_METHOD.SIGN === proxyObj?.method || 28 | proxyObj?.method.includes(ETHEREUM_METHOD.SIGN_TYPED_DATA) 29 | ) { 30 | proxyObj?.params?.forEach((value, key) => { 31 | txn.push({ name: `${key}`, value }) 32 | }) 33 | } 34 | 35 | const restructured: TRestructuredPayload = { 36 | txn_method: method, 37 | url: domain, 38 | txn_params: txn, 39 | } 40 | logger.log('proxyConvertToPayload', restructured) 41 | return restructured 42 | } 43 | -------------------------------------------------------------------------------- /src/helpers/panels/updateAlertPanel.ts: -------------------------------------------------------------------------------- 1 | import { panel, text, divider } from '@metamask/snaps-sdk' 2 | import { headingText, serviceError, updateAlert } from '../../constants/content' 3 | import { TUpdateAlertPanel } from './types/panels.type' 4 | import { isGreaterVersion } from '../versionCheck' 5 | import { VERSION } from '../../constants/config' 6 | 7 | export const convertToUpdateAlertPanel: TUpdateAlertPanel = (result, error) => { 8 | if (error) { 9 | return { 10 | panel: panel([ 11 | text(`${headingText.latestVersion}`), 12 | text(`${serviceError.serviceError}`), 13 | text(`${JSON.stringify(error)}`), 14 | divider(), 15 | ]), 16 | isForceUpdate: false, 17 | } 18 | } 19 | 20 | const isUpdateAvailable = isGreaterVersion(result.latestVersion, VERSION) 21 | const isForceUpdate = isGreaterVersion(result.latestForceUpdateVersion, VERSION) 22 | 23 | if (isUpdateAvailable) { 24 | if (isForceUpdate) { 25 | return { 26 | panel: panel([text(`${updateAlert.forceUpdate}`), divider()]), 27 | isForceUpdate, 28 | } 29 | } else { 30 | return { 31 | panel: panel([text(`${updateAlert.snapUpdate}`), divider()]), 32 | isForceUpdate, 33 | } 34 | } 35 | } else { 36 | return { 37 | panel: panel([]), 38 | isForceUpdate, 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /images/icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /src/helpers/parser/pgw/postTransactionRisks.ts: -------------------------------------------------------------------------------- 1 | import type { 2 | TPostTransactionRisks, 3 | IPostTransactionRisksResponseBodyItem, 4 | IPostTransactionRisksParsedItem, 5 | TRiskType, 6 | IPostTransactionRisksResponseBody, 7 | } from '../../../helpers/parser/pgw/types/postTransactionRisks.type' 8 | import { parserMapping } from '../../../helpers/parser/parser' 9 | 10 | export const postTransactionRisks: TPostTransactionRisks = (responseBody) => { 11 | return { 12 | factors: parserMapping( 13 | responseBody, 14 | 'factors', 15 | [], 16 | (factors: IPostTransactionRisksResponseBodyItem[]) => { 17 | return factors.map((factor) => { 18 | return { 19 | name: parserMapping(factor, 'name', ''), 20 | type: parserMapping(factor, 'factor_type', 'attention_required'), 21 | message: parserMapping(factor, 'message', ''), 22 | labels: checkIfLabelsExists(responseBody, factors), 23 | } 24 | }) as IPostTransactionRisksParsedItem[] 25 | } 26 | ), 27 | } 28 | } 29 | 30 | export const checkIfLabelsExists = ( 31 | responseBody: IPostTransactionRisksResponseBody, 32 | factor: IPostTransactionRisksResponseBodyItem[] 33 | ): string[] => { 34 | if (responseBody.hasOwnProperty('labels')) { 35 | return parserMapping(factor, 'labels', []) 36 | } 37 | return [] 38 | } 39 | 40 | export default postTransactionRisks 41 | -------------------------------------------------------------------------------- /src/helpers/parser/pgw/getAddressLabel.ts: -------------------------------------------------------------------------------- 1 | import type { 2 | TGetAddressLabel, 3 | IGetAddressLabelsLabelInfosBody, 4 | IGetAddressLabelsNotesBody, 5 | IGetAddressLabelsLabelsBody, 6 | } from '../../../helpers/parser/pgw/types/getAddressLabel.type' 7 | import { parserMapping } from '../../../helpers/parser/parser' 8 | const getAddressLabel: TGetAddressLabel = (responseBody) => { 9 | const labelInfos = responseBody.label_infos?.map(convertToLabelInfoParsed) || [] 10 | const notesResult = responseBody.notes?.map(convertToNotesParsed) || [] 11 | return { 12 | address: parserMapping(responseBody, 'address', ''), 13 | labelInfos, 14 | notes: notesResult, 15 | } 16 | } 17 | 18 | function convertToNotesParsed(labels: IGetAddressLabelsNotesBody): IGetAddressLabelsNotesBody { 19 | return { 20 | note: parserMapping(labels, 'note', ''), 21 | source: parserMapping(labels, 'source', ''), 22 | } 23 | } 24 | 25 | function convertToLabelInfoParsed( 26 | labelInfo: IGetAddressLabelsLabelInfosBody, 27 | ): IGetAddressLabelsLabelInfosBody { 28 | let labels = [] 29 | if (labelInfo.labels != null && labelInfo.labels.length > 0) { 30 | labelInfo.labels.forEach(function (label) { 31 | labels.push(convertToLabelParsed(label)) 32 | }) 33 | } 34 | 35 | return { 36 | category: parserMapping(labelInfo, 'category', ''), 37 | risk_level: parserMapping(labelInfo, 'risk_level', ''), 38 | labels: labels, 39 | } 40 | } 41 | 42 | function convertToLabelParsed(labels: IGetAddressLabelsLabelsBody): IGetAddressLabelsLabelsBody { 43 | return { 44 | name: parserMapping(labels, 'name', ''), 45 | source: parserMapping(labels, 'source', ''), 46 | } 47 | } 48 | export default getAddressLabel 49 | -------------------------------------------------------------------------------- /src/helpers/panels/types/panels.type.ts: -------------------------------------------------------------------------------- 1 | import { Copyable, Panel, Text, Heading, Divider, Spinner } from '@metamask/snaps-sdk' 2 | import { IResponseError } from '../../../controllers/types/http.type' 3 | import { IPostTransactionRisksResponseParsed } from '../../parser/pgw/types/postTransactionRisks.type' 4 | import { IGetSnapLatestVersionResponseParsed } from '../../parser/pgw/types/getSnapLatestVersion.type' 5 | import { IPostTransactionRiskSummaryResponseParsed } from '../../parser/pgw/types/postTransactionRiskSummary.type' 6 | import { 7 | IPostTransactionSimulationResponseParsed, 8 | IPostTransactionSimulationTokenChangeParsed, 9 | } from '../../parser/pgw/types/postTransactionSimulation.type' 10 | import { IGetTokenInfoResponseParsed } from '../../parser/pgw/types/getTokenInfo.type' 11 | import { IGetAddressLabelResponseParsed } from '../../parser/pgw/types/getAddressLabel.type' 12 | export type TUpdateAlert = { panel: Panel; isForceUpdate: boolean } 13 | export type TUpdateAlertPanel = ( 14 | result: IGetSnapLatestVersionResponseParsed, 15 | error: IResponseError 16 | ) => TUpdateAlert 17 | 18 | export type TRiskPanel = ( 19 | result: IPostTransactionRisksResponseParsed, 20 | error: IResponseError 21 | ) => Panel 22 | 23 | export type TRiskSummaryPanel = ( 24 | result: IPostTransactionRiskSummaryResponseParsed, 25 | error: IResponseError 26 | ) => Panel 27 | 28 | export type TSimulationPanel = ( 29 | result: IPostTransactionSimulationResponseParsed, 30 | error: IResponseError 31 | ) => Promise 32 | 33 | export type TProjectInsightPanel = ( 34 | result: IGetTokenInfoResponseParsed, 35 | error: IResponseError 36 | ) => Panel 37 | 38 | export type TPaymentDetail = (tokenChanges: IPostTransactionSimulationTokenChangeParsed[]) => Promise 39 | 40 | export type TGetAddressLabel = ( 41 | result: IGetAddressLabelResponseParsed, 42 | error: IResponseError 43 | ) => Panel 44 | -------------------------------------------------------------------------------- /src/controllers/types/pgw.type.ts: -------------------------------------------------------------------------------- 1 | import type { IPostTransactionRisksResponseParsed } from '../../helpers/parser/pgw/types/postTransactionRisks.type' 2 | import type { IPostTransactionRiskSummaryResponseParsed } from '../../helpers/parser/pgw/types/postTransactionRiskSummary.type' 3 | import type { 4 | IPostTransactionSimulationResponseParsed, 5 | IPostTransactionSimulationRequestPayload, 6 | } from '../../helpers/parser/pgw/types/postTransactionSimulation.type' 7 | import type { IGetSnapLatestVersionResponseParsed } from '../../helpers/parser/pgw/types/getSnapLatestVersion.type' 8 | import type { TRestructuredPayload } from '../../helpers/types/proxyRestructure.type' 9 | import type { IResponseError } from '../../controllers/types/http.type' 10 | import type { IGetTokenInfoResponseParsed } from '../../helpers/parser/pgw/types/getTokenInfo.type' 11 | import type { IGetAddressLabelResponseParsed } from '../../helpers/parser/pgw/types/getAddressLabel.type' 12 | export type TOnResponseErrorCode = (response: any, responseBody: any) => IResponseError 13 | export type TPostTransactionRisks = ( 14 | postTransactionRequestBody: TRestructuredPayload, 15 | headerOption?: Record 16 | ) => Promise 17 | export type TPostTransactionRiskSummary = ( 18 | postTransactionRequestBody: TRestructuredPayload, 19 | headerOption?: Record 20 | ) => Promise 21 | export type TPostTransactionSimulation = ( 22 | postTransactionRequestBody: IPostTransactionSimulationRequestPayload, 23 | headerOption?: Record 24 | ) => Promise 25 | 26 | export type TGetSnapLatestVersion = ( 27 | headerOption?: Record 28 | ) => Promise 29 | 30 | export type TGetTokenInfo = ( 31 | contractAddress: string, 32 | headerOption?: Record 33 | ) => Promise 34 | 35 | export type TGetAddressLabel = ( 36 | contractAddress: string, 37 | headerOption?: Record 38 | ) => Promise 39 | -------------------------------------------------------------------------------- /snap.config.js: -------------------------------------------------------------------------------- 1 | const through = require('through2') 2 | const envify = require('envify/custom') 3 | const snapManifest = require('./snap.manifest.json') 4 | const dotenv = require('dotenv') 5 | dotenv.config({ 6 | path: `.env.${process.env.NODE_ENV}`, 7 | }) 8 | process.env.VERSION = snapManifest.version 9 | 10 | module.exports = { 11 | cliOptions: { 12 | src: './src/index.ts', 13 | port: 8080, 14 | }, 15 | bundlerCustomizer: (bundler) => { 16 | bundler 17 | .transform(function () { 18 | let data = '' 19 | return through( 20 | function (buffer, _encoding, callback) { 21 | data += buffer 22 | callback() 23 | }, 24 | function (callback) { 25 | this.push("globalThis.Buffer = require('buffer/').Buffer;") 26 | this.push(data) 27 | callback() 28 | } 29 | ) 30 | }) 31 | .transform( 32 | envify({ 33 | VERSION: process.env.VERSION, 34 | ENV: process.env.ENV, 35 | APP_PLATFORM: process.env.APP_PLATFORM, 36 | API_PGW_BASE: process.env.API_PGW_BASE, 37 | API_PGW_BASE_LAYER: process.env.API_PGW_BASE_LAYER, 38 | API_PGW_VAESION: process.env.API_PGW_VAESION, 39 | API_PGW_PATH_POST_TRANSACTION_RISKS: 40 | process.env.API_PGW_PATH_POST_TRANSACTION_RISKS, 41 | API_PGW_PATH_POST_TRANSACTION_RISK_SUMMARY: 42 | process.env.API_PGW_PATH_POST_TRANSACTION_RISK_SUMMARY, 43 | API_PGW_PATH_POST_TRANSACTION_SIMULATION: 44 | process.env.API_PGW_PATH_POST_TRANSACTION_SIMULATION, 45 | API_PGW_PATH_GET_SNAP_LATEST_VERSION: 46 | process.env.API_PGW_PATH_GET_SNAP_LATEST_VERSION, 47 | API_PGW_PATH_GET_TOKEN_INFO: process.env.API_PGW_PATH_GET_TOKEN_INFO, 48 | API_PGW_PATH_GET_ADDRESS_LABEL: process.env.API_PGW_PATH_GET_ADDRESS_LABEL, 49 | }) 50 | ) 51 | }, 52 | } 53 | -------------------------------------------------------------------------------- /src/helpers/simulationContent.ts: -------------------------------------------------------------------------------- 1 | import { Panel, heading, panel, text } from '@metamask/snaps-sdk' 2 | import { TPaymentDetail } from './panels/types/panels.type' 3 | import { 4 | simulationBalanceChange, 5 | tokenSymbolAndValue, 6 | tokenNameWithBlueMark, 7 | tokenNameWithoutBlueMark, 8 | headingText, 9 | } from '../constants/content' 10 | import Logger from '../controllers/logger' 11 | import { getTokenInfo } from '../controllers/chainsafer' 12 | import { IPostTransactionSimulationTokenChangeParsed } from './parser/pgw/types/postTransactionSimulation.type' 13 | const logger = new Logger('[helper.panels.paymentDetailPanel]') 14 | 15 | export const covertPaymentDetail: TPaymentDetail = async (tokenChanges) => { 16 | const filterPayDetails = tokenChanges.filter((tokenChange) => tokenChange.direction == 'out') 17 | const filterGetDetails = tokenChanges.filter((tokenChange) => tokenChange.direction == 'in') 18 | const payDetails = await getPaymentDetails(filterPayDetails) 19 | const getDetails = await getPaymentDetails(filterGetDetails) 20 | let paymentDetailPanel = [] 21 | paymentDetailPanel.push(heading(headingText.paymentDetailPanel)) 22 | paymentDetailPanel.push(text(simulationBalanceChange.paymentDetailPanelPay)) 23 | paymentDetailPanel.push(panel(payDetails)) 24 | paymentDetailPanel.push(text(simulationBalanceChange.paymentDetailPanelGet)) 25 | paymentDetailPanel.push(panel(getDetails)) 26 | return paymentDetailPanel 27 | } 28 | 29 | function caculateRawAmonut(rawAmount: string, decimals: number): string { 30 | if (rawAmount != null && rawAmount != '') { 31 | const amount = Number(rawAmount) / Math.pow(10, decimals) 32 | return amount.toString() 33 | } 34 | return '' 35 | } 36 | 37 | function covertTokenNameWithReputation(tokenName: string, isBlueMark: boolean): string { 38 | if (tokenName && tokenName != '') { 39 | if (isBlueMark) { 40 | return tokenNameWithBlueMark(tokenName) 41 | } else { 42 | return tokenNameWithoutBlueMark(tokenName) 43 | } 44 | } 45 | return '' 46 | } 47 | 48 | async function getPaymentDetails( 49 | tokenChanges: IPostTransactionSimulationTokenChangeParsed[] 50 | ): Promise { 51 | const detail = [] 52 | 53 | for (const token of tokenChanges) { 54 | detail.push( 55 | text( 56 | tokenSymbolAndValue( 57 | token.type.toUpperCase(), 58 | token.symbol.toUpperCase(), 59 | caculateRawAmonut(token.rawAmount, token.decimals), 60 | Number.isNaN(token.dollarValue) ? 0 : Number(token.dollarValue.toFixed(2)) 61 | ) 62 | ) 63 | ) 64 | 65 | if (token.direction === 'in') { 66 | const [result, error] = await getTokenInfo(token.contractAddress) 67 | if (result && result.BlueCheckMark) { 68 | detail.push(text(covertTokenNameWithReputation(token.name, result.BlueCheckMark))) 69 | } 70 | } 71 | } 72 | 73 | return detail 74 | } 75 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tm-chainsafer-snap-test", 3 | "version": "1.0.239", 4 | "description": "TM Chainsafer of MetaMask Snaps.", 5 | "keywords": [ 6 | "Snap", 7 | "TM-Chainsafer" 8 | ], 9 | "license": "(MIT-0 OR Apache-2.0)", 10 | "author": "John Chang", 11 | "main": "src/index.ts", 12 | "files": [ 13 | "dist/", 14 | "images/", 15 | "snap.manifest.json", 16 | "LICENSE-APACHE", 17 | "LICENSE-MIT" 18 | ], 19 | "scripts": { 20 | "build": "json -I -f package.json -e 'this.name=\"tm-chainsafer-snap\"' && NODE_ENV=production mm-snap build", 21 | "build:clean": "yarn clean && yarn build", 22 | "build:stag": "json -I -f package.json -e 'this.name=\"tm-chainsafer-snap-stag\"' && NODE_ENV=staging mm-snap build", 23 | "build:test": "json -I -f package.json -e 'this.name=\"tm-chainsafer-snap-test\"' && NODE_ENV=test mm-snap build", 24 | "clean": "rimraf dist", 25 | "deploy": "npm publish", 26 | "lint": "yarn lint:eslint && yarn lint:misc --check", 27 | "lint:eslint": "eslint . --cache --ext js,ts", 28 | "lint:fix": "yarn lint:eslint --fix && yarn lint:misc --write", 29 | "lint:misc": "prettier '**/*.json' '**/*.md' '!CHANGELOG.md' --ignore-path .gitignore", 30 | "serve": "mm-snap serve", 31 | "start": "NODE_ENV=development mm-snap watch", 32 | "update-snap-version": "json -I -f snap.manifest.json -e ", 33 | "update:version": "npm version --no-git-tag-version --allow-same-version" 34 | }, 35 | "dependencies": { 36 | "@ethersproject/units": "^5.7.0", 37 | "@metamask/snaps-cli": "^4.0.0", 38 | "@metamask/snaps-sdk": "^1.3.1", 39 | "auto-version-js": "^0.3.10", 40 | "browserify": "^17.0.0", 41 | "buffer": "^6.0.3", 42 | "crypto-js": "^4.1.1", 43 | "dotenv": "^16.3.1", 44 | "envify": "^4.1.0", 45 | "jest": "^29.5.0", 46 | "json": "^11.0.0", 47 | "ts-jest": "^29.0.5" 48 | }, 49 | "devDependencies": { 50 | "@lavamoat/allow-scripts": "^2.0.3", 51 | "@metamask/auto-changelog": "^2.6.0", 52 | "@metamask/eslint-config": "^10.0.0", 53 | "@metamask/eslint-config-jest": "^10.0.0", 54 | "@metamask/eslint-config-nodejs": "^10.0.0", 55 | "@metamask/eslint-config-typescript": "^10.0.0", 56 | "@typescript-eslint/eslint-plugin": "^5.33.0", 57 | "@typescript-eslint/parser": "^5.33.0", 58 | "eslint": "^8.21.0", 59 | "eslint-config-prettier": "^8.1.0", 60 | "eslint-plugin-import": "^2.26.0", 61 | "eslint-plugin-jest": "^26.8.2", 62 | "eslint-plugin-jsdoc": "^39.2.9", 63 | "eslint-plugin-node": "^11.1.0", 64 | "eslint-plugin-prettier": "^4.2.1", 65 | "prettier": "^2.2.1", 66 | "prettier-plugin-packagejson": "^2.2.11", 67 | "rimraf": "^3.0.2", 68 | "through2": "^4.0.2", 69 | "typescript": "^4.7.4" 70 | }, 71 | "engines": { 72 | "node": ">=16.0.0" 73 | }, 74 | "publishConfig": { 75 | "access": "public", 76 | "registry": "https://registry.npmjs.org/" 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/controllers/http.ts: -------------------------------------------------------------------------------- 1 | import { API } from '../constants/config' 2 | import type { TMethodFactory, TCreateUrlBase, TPayload } from '../controllers/types/http.type' 3 | import Logger from '../controllers/logger' 4 | 5 | const logger = new Logger('[controllers.http]') 6 | 7 | export const methodFactory: TMethodFactory = (method) => { 8 | return (url, request, onResponseErrorCode) => { 9 | return async (isJSONResponse = true) => { 10 | const urlObj = new URL(url.path, url.endpoint) 11 | request.method = method 12 | // or it will throw exception 13 | if (method === 'GET' || method === 'HEAD') { 14 | delete request.body 15 | } 16 | 17 | let response = null 18 | let responseBody = null 19 | let error = null 20 | 21 | try { 22 | response = await fetch(urlObj.href, request) 23 | logger.log(url.path, 'response', response) 24 | if (isJSONResponse) { 25 | responseBody = await response.json() 26 | logger.log(url.path, 'responseBody', responseBody) 27 | } 28 | 29 | if (response.status !== 200) { 30 | error = onResponseErrorCode?.(response, responseBody) 31 | } 32 | 33 | return [error, !error ? (isJSONResponse ? responseBody : response) : null] 34 | } catch (innerError) { 35 | logger.error(url.path, innerError) 36 | const responseError = { 37 | apiName: url.path, 38 | innerError: innerError as Error, 39 | } 40 | return [responseError, null] 41 | } 42 | } 43 | } 44 | } 45 | 46 | export const createUrlBase: TCreateUrlBase = (endpoint) => { 47 | const targetService = API[endpoint as keyof typeof API] 48 | 49 | if (!targetService) { 50 | logger.error('no any matched api end point') 51 | throw new Error('no any matched api end point') 52 | } 53 | 54 | return (pathKey, replacer = undefined, version = targetService.version) => { 55 | const path = targetService.path[pathKey as keyof typeof targetService.path] 56 | let combinedPath = '' 57 | 58 | if (!path) { 59 | logger.error('no any matched api path key') 60 | throw new Error('no any matched api path key') 61 | } 62 | 63 | if (targetService.basicLayer !== '') { 64 | combinedPath += `${targetService.basicLayer}` 65 | } 66 | 67 | if (version !== '') { 68 | combinedPath += `/${version}` 69 | } 70 | combinedPath += `/${path}` 71 | 72 | if (replacer) { 73 | combinedPath = replacer(combinedPath) 74 | } 75 | 76 | return { 77 | path: combinedPath, 78 | endpoint: targetService.base, 79 | } 80 | } 81 | } 82 | 83 | export const payload: TPayload = (body, headers, additions = {}) => { 84 | return { 85 | method: '', 86 | headers, 87 | body: JSON.stringify(body), 88 | ...additions, 89 | } 90 | } 91 | 92 | export const get = methodFactory('GET') 93 | export const post = methodFactory('POST') 94 | export const put = methodFactory('PUT') 95 | export const patch = methodFactory('PATCH') 96 | -------------------------------------------------------------------------------- /src/helpers/snapContent.ts: -------------------------------------------------------------------------------- 1 | import { 2 | postTransactionRisk, 3 | postTransactionSimulation, 4 | postTransactionRiskSummary, 5 | getSnapLatestVersion, 6 | getTokenInfoBySimulationResult, 7 | } from '../controllers/chainsafer' 8 | import { panel, divider, text } from '@metamask/snaps-sdk' 9 | import { serviceError } from '../constants/content' 10 | import { TTransactionInsightLayout } from './types/snapContent.type' 11 | import { TUpdateAlert } from './panels/types/panels.type' 12 | import { convertToUpdateAlertPanel } from './panels/updateAlertPanel' 13 | import { convertToRiskPanel } from './panels/riskPanel' 14 | import { convertToRiskSummaryPanel } from './panels/riskSummaryPanel' 15 | import { convertToSimulationPanel } from './panels/simulationPanel' 16 | import { covertToProjectInsightPanel } from './panels/projectInsightPanel' 17 | import { convertAdPanel } from './panels/adPanel' 18 | import { supportChainIds } from '../constants/config' 19 | 20 | export const transactionInsightLayout: TTransactionInsightLayout = async ({ 21 | transactionOrigin, 22 | chainId, 23 | transaction, 24 | }) => { 25 | if (transaction) { 26 | const [latestVersionResult, latestVersionError] = await getSnapLatestVersion() 27 | 28 | const updateAlert: TUpdateAlert = convertToUpdateAlertPanel( 29 | latestVersionResult, 30 | latestVersionError 31 | ) 32 | 33 | if (updateAlert.isForceUpdate) { 34 | // snap need force update early return 35 | return { 36 | content: updateAlert.panel, 37 | } 38 | } 39 | 40 | const adDisplayPanel = convertAdPanel() 41 | 42 | const [[riskSummaryResult, riskSummaryError], [riskResult, riskError]] = await Promise.all([ 43 | postTransactionRiskSummary(transactionOrigin, transaction), 44 | postTransactionRisk(transactionOrigin, transaction), 45 | ]) 46 | let simulationPanel = panel([]) 47 | let projectInsightPanel = panel([]) 48 | const networkId = 49 | chainId.length > 0 && chainId.split(':').length == 2 ? chainId.split(':')[1] : '' 50 | 51 | if (supportChainIds.includes(networkId)) { 52 | const [simulationResult, simulationError] = await postTransactionSimulation( 53 | chainId, 54 | transaction 55 | ) 56 | const [tokenInfoResult, tokenInfoError] = await getTokenInfoBySimulationResult( 57 | simulationResult 58 | ) 59 | simulationPanel = await convertToSimulationPanel( 60 | simulationResult, 61 | simulationError 62 | ) 63 | projectInsightPanel = covertToProjectInsightPanel(tokenInfoResult, tokenInfoError) 64 | } else { 65 | simulationPanel = panel([divider(), text(serviceError.unsupportedChainId), divider()]) 66 | } 67 | 68 | let riskPanel = convertToRiskPanel(riskResult, riskError) 69 | let riskSummaryPanel = convertToRiskSummaryPanel(riskSummaryResult, riskSummaryError) 70 | 71 | let displayPanel = panel([]) 72 | 73 | if (riskSummaryResult.severity == 'caution') { 74 | displayPanel = panel([ 75 | adDisplayPanel, 76 | updateAlert.panel, 77 | simulationPanel, 78 | riskSummaryPanel, 79 | riskPanel, 80 | projectInsightPanel, 81 | ]) 82 | } else { 83 | displayPanel = panel([ 84 | adDisplayPanel, 85 | updateAlert.panel, 86 | riskSummaryPanel, 87 | riskPanel, 88 | simulationPanel, 89 | projectInsightPanel, 90 | ]) 91 | } 92 | 93 | return { 94 | content: displayPanel, 95 | } 96 | } 97 | 98 | return { content: panel([text(`${serviceError.serviceError}`)]) } 99 | } -------------------------------------------------------------------------------- /src/helpers/parser/pgw/types/postTransactionSimulation.type.ts: -------------------------------------------------------------------------------- 1 | export interface IPostTransactionSimulationRequestPayload { 2 | network_id: string 3 | from: string 4 | to: string 5 | call_data: string 6 | value?: number 7 | gas: number 8 | } 9 | 10 | export interface IPostTransactionSimulationResult { 11 | from_address_balance_diff: string 12 | from_address_balance_original: string 13 | signature_function: string 14 | to_address_balance_diff: string 15 | to_address_balance_original: string 16 | transfer_token_address: string 17 | } 18 | 19 | export interface IPostTransactionSimulationResponseBody { 20 | evm_err_address: string 21 | evm_err_message: string 22 | has_simulation_result: boolean 23 | txn_method_name: string 24 | from_address: string 25 | to_address: string 26 | sender_asset_change: IPostTransactionSimulationAssetChangeBody 27 | recipient_asset_changes: IPostTransactionSimulationAssetChangeBody[] 28 | contracts: IPostTransactionSimulationContractBody[] 29 | } 30 | 31 | export interface IPostTransactionSimulationAssetChangeBody { 32 | address: string 33 | balance_diff: IPostTransactionSimulationBalanceDiffBody 34 | is_contract: boolean 35 | token_changes: IPostTransactionSimulationTokenChangeBody[] 36 | } 37 | 38 | export interface IPostTransactionSimulationTokenChangeBody { 39 | direction: string 40 | type: string 41 | contract_address: string 42 | symbol: string 43 | name: string 44 | icon: string 45 | decimals: number 46 | dollar_value: string 47 | description: string 48 | token_id: number 49 | raw_amount: string 50 | } 51 | 52 | export interface IPostTransactionSimulationBalanceDiffBody { 53 | origin: string 54 | after: string 55 | origin_dollar_value: string 56 | after_dollar_value: string 57 | symbol: string 58 | name: string 59 | icon: string 60 | decimals: number 61 | } 62 | 63 | export interface IPostTransactionSimulationContractBody { 64 | address: string 65 | contract_name: string 66 | is_public: boolean 67 | fee: string 68 | fee_dollar_value: string 69 | } 70 | 71 | export interface IPostTransactionSimulationResponseParsed { 72 | evmErrAddress: string 73 | evmErrMessage: string 74 | hasSimulationResult: boolean 75 | txnMethodName: string 76 | fromAddress: string 77 | toAddress: string 78 | senderAssetChange: IPostTransactionSimulationAssetChangeParsed 79 | recipientAssetChanges: IPostTransactionSimulationAssetChangeParsed[] 80 | contracts: IPostTransactionSimulationContractParsed[] 81 | } 82 | 83 | export interface IPostTransactionSimulationAssetChangeParsed { 84 | address: string 85 | balanceDiff: IPostTransactionSimulationBalanceDiffParsed 86 | tokenChanges: IPostTransactionSimulationTokenChangeParsed[] 87 | isContract: boolean 88 | } 89 | 90 | export interface IPostTransactionSimulationTokenChangeParsed { 91 | direction: string 92 | type: string 93 | contractAddress: string 94 | symbol: string 95 | name: string 96 | icon: string 97 | decimals: number 98 | dollarValue: number 99 | description: string 100 | tokenId: number 101 | rawAmount: string 102 | } 103 | 104 | export interface IPostTransactionSimulationBalanceDiffParsed { 105 | origin: number 106 | after: number 107 | originDollarValue: number 108 | afterDollarValue: number 109 | symbol: string 110 | name: string 111 | icon: string 112 | decimals: number 113 | } 114 | 115 | export interface IPostTransactionSimulationContractParsed { 116 | address: string 117 | contractName: string 118 | isPublic: boolean 119 | fee: string 120 | feeDollarValue: string 121 | } 122 | 123 | export type TPostTransactionSimulation = ( 124 | responseBody: IPostTransactionSimulationResponseBody, 125 | ) => IPostTransactionSimulationResponseParsed 126 | -------------------------------------------------------------------------------- /src/helpers/parser/pgw/postTransactionSimulation.ts: -------------------------------------------------------------------------------- 1 | import type { 2 | TPostTransactionSimulation, 3 | IPostTransactionSimulationAssetChangeBody, 4 | IPostTransactionSimulationAssetChangeParsed, 5 | IPostTransactionSimulationContractBody, 6 | IPostTransactionSimulationContractParsed, 7 | } from '../../../helpers/parser/pgw/types/postTransactionSimulation.type' 8 | 9 | import { parserMapping } from '../../../helpers/parser/parser' 10 | 11 | const postTransactionSimulation: TPostTransactionSimulation = (responseBody) => { 12 | let senderAssetChange = null 13 | if (responseBody.sender_asset_change != null) { 14 | senderAssetChange = convertToAssetChangeParsed(responseBody.sender_asset_change) 15 | } 16 | 17 | let recipientAssetChanges = null 18 | if ( 19 | responseBody.recipient_asset_changes != null && 20 | responseBody.recipient_asset_changes.length > 0 21 | ) { 22 | recipientAssetChanges = [] 23 | responseBody.recipient_asset_changes.forEach(function (assetChange) { 24 | recipientAssetChanges.push(convertToAssetChangeParsed(assetChange)) 25 | }) 26 | } 27 | 28 | let contracts = null 29 | if (responseBody.contracts != null && responseBody.contracts.length > 0) { 30 | contracts = [] 31 | responseBody.contracts.forEach(function (contract) { 32 | contracts.push(convertToContractParsed(contract)) 33 | }) 34 | } 35 | 36 | return { 37 | evmErrAddress: parserMapping(responseBody, 'evm_err_address', ''), 38 | evmErrMessage: parserMapping(responseBody, 'evm_err_message', ''), 39 | hasSimulationResult: parserMapping(responseBody, 'has_simulation_result', false), 40 | txnMethodName: parserMapping(responseBody, 'txn_method_name', ''), 41 | fromAddress: parserMapping(responseBody, 'from_address', ''), 42 | toAddress: parserMapping(responseBody, 'to_address', ''), 43 | senderAssetChange: senderAssetChange, 44 | recipientAssetChanges: recipientAssetChanges, 45 | contracts: contracts, 46 | } 47 | } 48 | 49 | function convertToAssetChangeParsed( 50 | assetChange: IPostTransactionSimulationAssetChangeBody, 51 | ): IPostTransactionSimulationAssetChangeParsed { 52 | let balanceDiff = null 53 | if (assetChange.balance_diff != null) { 54 | balanceDiff = { 55 | origin: parseFloat(parserMapping(assetChange.balance_diff, 'origin', '')), 56 | after: parseFloat(parserMapping(assetChange.balance_diff, 'after', '')), 57 | originDollarValue: parseFloat( 58 | parserMapping(assetChange.balance_diff, 'origin_dollar_value', ''), 59 | ), 60 | afterDollarValue: parseFloat( 61 | parserMapping(assetChange.balance_diff, 'after_dollar_value', ''), 62 | ), 63 | symbol: parserMapping(assetChange.balance_diff, 'symbol', ''), 64 | name: parserMapping(assetChange.balance_diff, 'name', ''), 65 | icon: parserMapping(assetChange.balance_diff, 'icon', ''), 66 | decimals: parserMapping(assetChange.balance_diff, 'decimals', 0), 67 | } 68 | } 69 | 70 | let tokenChanges = null 71 | if (assetChange.token_changes != null && assetChange.token_changes.length > 0) { 72 | tokenChanges = [] 73 | assetChange.token_changes.forEach(function (tokenChange) { 74 | tokenChanges.push({ 75 | direction: parserMapping(tokenChange, 'direction', ''), 76 | type: parserMapping(tokenChange, 'type', ''), 77 | contractAddress: parserMapping(tokenChange, 'contract_address', ''), 78 | symbol: parserMapping(tokenChange, 'symbol', ''), 79 | name: parserMapping(tokenChange, 'name', ''), 80 | icon: parserMapping(tokenChange, 'icon', ''), 81 | decimals: parserMapping(tokenChange, 'decimals', 0), 82 | dollarValue: parseFloat(parserMapping(tokenChange, 'dollar_value', '')), 83 | description: parserMapping(tokenChange, 'description', ''), 84 | tokenId: parserMapping(tokenChange, 'token_id', 0), 85 | rawAmount: parserMapping(tokenChange, 'raw_amount', ''), 86 | }) 87 | }) 88 | } 89 | 90 | return { 91 | address: parserMapping(assetChange, 'address', ''), 92 | isContract: parserMapping(assetChange, 'is_contract', ''), 93 | balanceDiff: balanceDiff, 94 | tokenChanges: tokenChanges, 95 | } 96 | } 97 | 98 | function convertToContractParsed( 99 | contract: IPostTransactionSimulationContractBody, 100 | ): IPostTransactionSimulationContractParsed { 101 | return { 102 | address: parserMapping(contract, 'address', ''), 103 | contractName: parserMapping(contract, 'contract_name', ''), 104 | isPublic: parserMapping(contract, 'is_public', false), 105 | fee: parserMapping(contract, 'fee', ''), 106 | feeDollarValue: parserMapping(contract, 'fee_dollar_value', ''), 107 | } 108 | } 109 | 110 | export default postTransactionSimulation 111 | -------------------------------------------------------------------------------- /src/controllers/chainsafer.ts: -------------------------------------------------------------------------------- 1 | import pgw from './pgw' 2 | import Logger from './logger' 3 | import { proxyConvertToPayload } from './../helpers/proxyRestructure' 4 | import { ISendTransactionProxyPayload } from './../helpers/types/proxyRestructure.type' 5 | import { IResponseError } from './../controllers/types/http.type' 6 | import { Json } from '@metamask/snaps-sdk' 7 | import { IPostTransactionRisksResponseParsed } from '../helpers/parser/pgw/types/postTransactionRisks.type' 8 | import { 9 | IPostTransactionSimulationRequestPayload, 10 | IPostTransactionSimulationResponseParsed, 11 | } from '../helpers/parser/pgw/types/postTransactionSimulation.type' 12 | import { IPostTransactionRiskSummaryResponseParsed } from './../helpers/parser/pgw/types/postTransactionRiskSummary.type' 13 | import { IGetSnapLatestVersionResponseParsed } from '../helpers/parser/pgw/types/getSnapLatestVersion.type' 14 | import { IGetTokenInfoResponseParsed } from '../helpers/parser/pgw/types/getTokenInfo.type' 15 | import { IGetAddressLabelResponseParsed } from '../helpers/parser/pgw/types/getAddressLabel.type' 16 | const logger = new Logger('[controllers.chainsafer]') 17 | 18 | export const postTransactionRiskSummary = async ( 19 | original: string, 20 | transaction: Json 21 | ): Promise<[IPostTransactionRiskSummaryResponseParsed, IResponseError]> => { 22 | let result: IPostTransactionRiskSummaryResponseParsed = 23 | {} as IPostTransactionRiskSummaryResponseParsed 24 | let error: IResponseError = null 25 | 26 | const txn = { 27 | method: 'eth_sendTransaction', 28 | url: original, 29 | params: [transaction], 30 | } 31 | 32 | try { 33 | result = await pgw.postTransactionRiskSummary( 34 | proxyConvertToPayload(original, txn as ISendTransactionProxyPayload) 35 | ) 36 | } catch (e) { 37 | logger.error(`${JSON.stringify(e)}`) 38 | error = e 39 | } 40 | 41 | return [result, error] 42 | } 43 | 44 | export const postTransactionRisk = async ( 45 | original: string, 46 | transaction: Json 47 | ): Promise<[IPostTransactionRisksResponseParsed, IResponseError]> => { 48 | let result: IPostTransactionRisksResponseParsed = {} as IPostTransactionRisksResponseParsed 49 | let error: IResponseError = null 50 | 51 | const txn = { 52 | method: 'eth_sendTransaction', 53 | url: original, 54 | params: [transaction], 55 | } 56 | 57 | try { 58 | result = await pgw.postTransactionRisks( 59 | proxyConvertToPayload(original, txn as ISendTransactionProxyPayload) 60 | ) 61 | } catch (e) { 62 | logger.error(`${JSON.stringify(e)}`) 63 | error = e 64 | } 65 | 66 | return [result, error] 67 | } 68 | 69 | export const postTransactionSimulation = async ( 70 | chainId: string, 71 | transaction: Json 72 | ): Promise<[IPostTransactionSimulationResponseParsed, IResponseError]> => { 73 | let result: IPostTransactionSimulationResponseParsed = 74 | {} as IPostTransactionSimulationResponseParsed 75 | let error: IResponseError = null 76 | 77 | let payload = { 78 | network_id: 79 | chainId.length > 0 && chainId.split(':').length == 2 ? chainId.split(':')[1] : '', 80 | from: transaction['from'] || '', 81 | to: transaction['to'] || '', 82 | call_data: transaction['data'] || '', 83 | value: parseInt(transaction['value'], 16) || 0, 84 | gas: parseInt(transaction['gas'], 16) || 0, 85 | } as IPostTransactionSimulationRequestPayload 86 | 87 | try { 88 | result = await pgw.postTransactionSimulation(payload) 89 | } catch (e) { 90 | logger.error(`${JSON.stringify(e)}`) 91 | error = e 92 | } 93 | 94 | return [result, error] 95 | } 96 | 97 | export const getSnapLatestVersion = async (): Promise< 98 | [IGetSnapLatestVersionResponseParsed, IResponseError] 99 | > => { 100 | let result: IGetSnapLatestVersionResponseParsed = {} as IGetSnapLatestVersionResponseParsed 101 | let error: IResponseError = null 102 | 103 | try { 104 | result = await pgw.getSnapLatestVersion() 105 | } catch (e) { 106 | logger.error(`${JSON.stringify(e)}`) 107 | error = e 108 | } 109 | 110 | return [result, error] 111 | } 112 | 113 | export const getTokenInfoBySimulationResult = async ( 114 | simulationResult: IPostTransactionSimulationResponseParsed 115 | ): Promise<[IGetTokenInfoResponseParsed, IResponseError]> => { 116 | if ( 117 | simulationResult && 118 | simulationResult.senderAssetChange != null && 119 | simulationResult.senderAssetChange.tokenChanges != null && 120 | simulationResult.senderAssetChange.tokenChanges.length > 0 121 | ) { 122 | const filterTokenChanges = simulationResult.senderAssetChange.tokenChanges.filter( 123 | (tokenChange) => tokenChange.direction == 'in' 124 | ) 125 | if (filterTokenChanges.length > 0) { 126 | return await getTokenInfo(filterTokenChanges[0].contractAddress) 127 | } else { 128 | return [null, null] 129 | } 130 | } else { 131 | return [null, null] 132 | } 133 | } 134 | 135 | export const getTokenInfo = async ( 136 | contractAddress: string 137 | ): Promise<[IGetTokenInfoResponseParsed, IResponseError]> => { 138 | let result: IGetTokenInfoResponseParsed = {} as IGetTokenInfoResponseParsed 139 | let error: IResponseError = null 140 | 141 | try { 142 | result = await pgw.getTokenInfo(contractAddress) 143 | } catch (e) { 144 | logger.error(`${JSON.stringify(e)}`) 145 | error = e 146 | } 147 | 148 | return [result, error] 149 | } 150 | export const getAddressLabel = async ( 151 | contractAddress: string 152 | ): Promise<[IGetAddressLabelResponseParsed, IResponseError]> => { 153 | let result: IGetAddressLabelResponseParsed = {} as IGetAddressLabelResponseParsed 154 | let error: IResponseError = null 155 | try { 156 | result = await pgw.getAddressLabel(contractAddress) 157 | } catch (e) { 158 | logger.error(`${JSON.stringify(e)}`) 159 | error = e 160 | } 161 | 162 | return [result, error] 163 | } 164 | -------------------------------------------------------------------------------- /src/helpers/panels/simulationPanel.ts: -------------------------------------------------------------------------------- 1 | import { panel, heading, text, divider } from '@metamask/snaps-sdk' 2 | import { TSimulationPanel } from './types/panels.type' 3 | import { 4 | headingText, 5 | simulationBalanceChange, 6 | evmErrorAddress, 7 | evmErrMessage, 8 | serviceError, 9 | balanceWithUsd, 10 | balanceWithoutUsd, 11 | transactionMethodIs, 12 | countRecipient, 13 | recipientLableInfo, 14 | recipientListWarningContractTitle, 15 | } from '../../constants/content' 16 | import { covertPaymentDetail } from '../simulationContent' 17 | import { TGetAddressLabel } from './types/panels.type' 18 | import { getAddressLabel } from '../../controllers/chainsafer' 19 | export const convertToSimulationPanel: TSimulationPanel = async (result, error) => { 20 | if (error) { 21 | return panel([ 22 | heading(headingText.transactionSimulation), 23 | divider(), 24 | text(serviceError.simulationError), 25 | text(`${JSON.stringify(error)}`), 26 | divider(), 27 | ]) 28 | } 29 | 30 | if (result == null) { 31 | return panel([]) 32 | } 33 | 34 | if (result.evmErrAddress != '' || result.evmErrMessage != '') { 35 | return panel([ 36 | heading(headingText.transactionSimulation), 37 | divider(), 38 | text(serviceError.simulationError), 39 | text(evmErrorAddress(result.evmErrAddress)), 40 | text(evmErrMessage(result.evmErrMessage)), 41 | divider(), 42 | ]) 43 | } 44 | 45 | if (result.senderAssetChange == null && result.contracts == null) { 46 | return panel([]) 47 | } 48 | 49 | let transactionMethod = [] 50 | let paymentDetail = [] 51 | let balanceChange = [] 52 | let recipients = [] 53 | 54 | //transaction method 55 | if (result.txnMethodName != null && result.txnMethodName != '') { 56 | transactionMethod = [text(transactionMethodIs(result.txnMethodName)), divider()] 57 | } 58 | // payment detail 59 | if ( 60 | result.senderAssetChange != null && 61 | result.senderAssetChange.tokenChanges != null && 62 | result.senderAssetChange.tokenChanges.length > 0 63 | ) { 64 | paymentDetail = await covertPaymentDetail(result.senderAssetChange.tokenChanges) 65 | } 66 | 67 | // balance diff 68 | if (result.senderAssetChange != null && result.senderAssetChange.balanceDiff != null) { 69 | const originWei = result.senderAssetChange.balanceDiff.origin 70 | const originUSD = result.senderAssetChange.balanceDiff.originDollarValue 71 | const afterWei = result.senderAssetChange.balanceDiff.after 72 | const afterUSD = result.senderAssetChange.balanceDiff.afterDollarValue 73 | const diffWei = Math.abs(afterWei - originWei) 74 | const diffUSD = Math.abs(afterUSD - originUSD) 75 | 76 | balanceChange = [ 77 | heading(headingText.balanceChanges), 78 | text(simulationBalanceChange.balanceChangeBefore), 79 | text(convertWeiToEthWithUSD(originWei, originUSD)), 80 | text(simulationBalanceChange.balanceChangeAfter), 81 | text(convertWeiToEthWithUSD(afterWei, afterUSD)), 82 | text(`**${simulationBalanceChange.separators}**`), 83 | text(`**${simulationBalanceChange.balanceDiff}**`), 84 | text(`**${convertWeiToEthWithUSD(diffWei, diffUSD)}**`), 85 | ] 86 | } 87 | 88 | // recipients 89 | if (result && result.recipientAssetChanges != null && result.recipientAssetChanges.length > 0) { 90 | let recipientAddressPanels = [] 91 | let recipientDescription = countRecipient(result.recipientAssetChanges.length) 92 | let warningAddressCount = 0 93 | 94 | for (let i = 0; i < result.recipientAssetChanges.length; i++) { 95 | // get recipient address is CA or EOA first 96 | let addressType = converToRecipientAddressType( 97 | result.recipientAssetChanges[i].isContract, 98 | ) 99 | const [addressLabelsResult, addressLabelsError] = await getAddressLabel( 100 | result.recipientAssetChanges[i].address, 101 | ) 102 | let addressLabelsPanel = convertToAddressLabelsPanel( 103 | addressLabelsResult, 104 | addressLabelsError, 105 | ) 106 | //if get address label panel is not null, return result 107 | if (addressLabelsPanel.children.length != 0) { 108 | warningAddressCount++ 109 | recipientAddressPanels.push( 110 | text(addressType), 111 | text(result.recipientAssetChanges[i].address), 112 | ) 113 | } 114 | recipientAddressPanels.push(addressLabelsPanel) 115 | } 116 | 117 | if (warningAddressCount > 0) { 118 | recipientDescription += recipientListWarningContractTitle(warningAddressCount) 119 | } 120 | 121 | recipients.push( 122 | heading(headingText.recipientsPanel), 123 | text(recipientDescription), 124 | ...recipientAddressPanels, 125 | ) 126 | } 127 | 128 | return panel([ 129 | ...transactionMethod, 130 | ...paymentDetail, 131 | ...balanceChange, 132 | ...recipients, 133 | divider(), 134 | ]) 135 | } 136 | 137 | function convertWeiToEthWithUSD(wei: number, usd: number): string { 138 | if (Number.isNaN(wei)) { 139 | return balanceWithUsd(0, 0) 140 | } else { 141 | const eth = wei / 1e18 142 | if (Number.isNaN(usd)) { 143 | return balanceWithoutUsd(eth) 144 | } else { 145 | return balanceWithUsd(eth, Number(usd.toFixed(2))) 146 | } 147 | } 148 | } 149 | 150 | function converToRecipientAddressType(isContract: boolean): string { 151 | if (isContract) { 152 | return `• {CA}` 153 | } 154 | return `• {EOA}` 155 | } 156 | 157 | export const convertToAddressLabelsPanel: TGetAddressLabel = (result, error) => { 158 | if (result == null || error) { 159 | return panel([]) 160 | } 161 | 162 | let addressLabelsPanel = [] 163 | if (result != null && result.labelInfos != null && result.labelInfos.length > 0) { 164 | for (let i = 0; i < result.labelInfos.length; i++) { 165 | let riskLevel = result.labelInfos[i].risk_level 166 | // riskLevel condition 167 | if (riskLevel >= 3) { 168 | if (result.labelInfos[i].labels != null && result.labelInfos[i].labels.length > 0) { 169 | for (let j = 0; j < result.labelInfos[i].labels.length; j++) { 170 | let labelName = result.labelInfos[i].labels[j].name 171 | let source = result.labelInfos[i].labels[j].source 172 | addressLabelsPanel.push(text(recipientLableInfo(labelName, source))) 173 | } 174 | } 175 | } 176 | } 177 | } 178 | 179 | return panel(addressLabelsPanel) 180 | } 181 | -------------------------------------------------------------------------------- /src/helpers/parser/pgw/getTokenInfo.ts: -------------------------------------------------------------------------------- 1 | import type { TGetTokenInfo } from '../../../helpers/parser/pgw/types/getTokenInfo.type' 2 | 3 | import { parserMapping } from '../../../helpers/parser/parser' 4 | import { resProjectInsightWebsite, resProjectInsightBlog, resProjectInsightTwitter, resProjectInsightDiscord } from '../../../constants/content' 5 | 6 | const getTokenInfo: TGetTokenInfo = (responseBody) => { 7 | let tokenInfo = {} 8 | if ( 9 | responseBody.hasOwnProperty('website') && 10 | responseBody.website !== null && 11 | responseBody.website !== '' 12 | ) { 13 | tokenInfo = { 14 | ...tokenInfo, 15 | Website: resProjectInsightWebsite(parserMapping(responseBody, 'website', '')), 16 | } 17 | } 18 | if ( 19 | responseBody.hasOwnProperty('blog') && 20 | responseBody.blog !== null && 21 | responseBody.blog !== '' 22 | ) { 23 | tokenInfo = { 24 | ...tokenInfo, 25 | Blog: resProjectInsightBlog( 26 | parserMapping(responseBody, 'blog', '') 27 | ), 28 | } 29 | } 30 | if ( 31 | responseBody.hasOwnProperty('twitter') && 32 | responseBody.twitter !== null && 33 | responseBody.twitter !== '' 34 | ) { 35 | tokenInfo = { 36 | ...tokenInfo, 37 | Twitter: resProjectInsightTwitter(parserMapping(responseBody, 'twitter', '')), 38 | } 39 | } 40 | if ( 41 | responseBody.hasOwnProperty('discord') && 42 | responseBody.discord !== null && 43 | responseBody.discord !== '' 44 | ) { 45 | tokenInfo = { 46 | ...tokenInfo, 47 | Discord: resProjectInsightDiscord(parserMapping(responseBody, 'discord', '')), 48 | } 49 | } 50 | if (responseBody.hasOwnProperty('blue_checkmark') && responseBody.blue_checkmark !== null) { 51 | tokenInfo = { 52 | ...tokenInfo, 53 | BlueCheckMark: parserMapping(responseBody, 'blue_checkmark', ''), 54 | } 55 | } 56 | // if ( 57 | // responseBody.hasOwnProperty('bitcointalk') && 58 | // responseBody.bitcointalk !== null && 59 | // responseBody.bitcointalk !== '' 60 | // ) { 61 | // tokenInfo = { 62 | // ...tokenInfo, 63 | // Bitcointalk: parserMapping(responseBody, 'bitcointalk', ''), 64 | // } 65 | // } 66 | // if ( 67 | // responseBody.hasOwnProperty('contract_address') && 68 | // responseBody.contract_address !== null && 69 | // responseBody.contract_address !== '' 70 | // ) { 71 | // tokenInfo = { 72 | // ...tokenInfo, 73 | // ContractAddress: parserMapping(responseBody, 'contract_address', ''), 74 | // } 75 | // } 76 | // if ( 77 | // responseBody.hasOwnProperty('description') && 78 | // responseBody.description !== null && 79 | // responseBody.description !== '' 80 | // ) { 81 | // tokenInfo = { 82 | // ...tokenInfo, 83 | // Description: parserMapping(responseBody, 'description', ''), 84 | // } 85 | // } 86 | // if (responseBody.hasOwnProperty('divisor') && responseBody.divisor !== null) { 87 | // tokenInfo = { 88 | // ...tokenInfo, 89 | // Divisor: parserMapping(responseBody, 'divisor', 0), 90 | // } 91 | // } 92 | // if ( 93 | // responseBody.hasOwnProperty('email') && 94 | // responseBody.email !== null && 95 | // responseBody.email !== '' 96 | // ) { 97 | // tokenInfo = { 98 | // ...tokenInfo, 99 | // Email: parserMapping(responseBody, 'email', ''), 100 | // } 101 | // } 102 | // if ( 103 | // responseBody.hasOwnProperty('facebook') && 104 | // responseBody.facebook !== null && 105 | // responseBody.facebook !== '' 106 | // ) { 107 | // tokenInfo = { 108 | // ...tokenInfo, 109 | // Facebook: parserMapping(responseBody, 'facebook', ''), 110 | // } 111 | // } 112 | // if ( 113 | // responseBody.hasOwnProperty('github') && 114 | // responseBody.github !== null && 115 | // responseBody.github !== '' 116 | // ) { 117 | // tokenInfo = { 118 | // ...tokenInfo, 119 | // Github: parserMapping(responseBody, 'github', ''), 120 | // } 121 | // } 122 | // if ( 123 | // responseBody.hasOwnProperty('linkedin') && 124 | // responseBody.linkedin !== null && 125 | // responseBody.linkedin !== '' 126 | // ) { 127 | // tokenInfo = { 128 | // ...tokenInfo, 129 | // Linkedin: parserMapping(responseBody, 'linkedin', ''), 130 | // } 131 | // } 132 | // if ( 133 | // responseBody.hasOwnProperty('reddit') && 134 | // responseBody.reddit !== null && 135 | // responseBody.reddit !== '' 136 | // ) { 137 | // tokenInfo = { 138 | // ...tokenInfo, 139 | // Reddit: parserMapping(responseBody, 'reddit', ''), 140 | // } 141 | // } 142 | // if ( 143 | // responseBody.hasOwnProperty('slack') && 144 | // responseBody.slack !== null && 145 | // responseBody.slack !== '' 146 | // ) { 147 | // tokenInfo = { 148 | // ...tokenInfo, 149 | // Slack: parserMapping(responseBody, 'slack', ''), 150 | // } 151 | // } 152 | // if ( 153 | // responseBody.hasOwnProperty('symbol') && 154 | // responseBody.symbol !== null && 155 | // responseBody.symbol !== '' 156 | // ) { 157 | // tokenInfo = { 158 | // ...tokenInfo, 159 | // Symbol: parserMapping(responseBody, 'symbol', ''), 160 | // } 161 | // } 162 | // if ( 163 | // responseBody.hasOwnProperty('telegram') && 164 | // responseBody.telegram !== null && 165 | // responseBody.telegram !== '' 166 | // ) { 167 | // tokenInfo = { 168 | // ...tokenInfo, 169 | // Telegram: parserMapping(responseBody, 'telegram', ''), 170 | // } 171 | // } 172 | // if ( 173 | // responseBody.hasOwnProperty('token_name') && 174 | // responseBody.token_name !== null && 175 | // responseBody.token_name !== '' 176 | // ) { 177 | // tokenInfo = { 178 | // ...tokenInfo, 179 | // TokenName: parserMapping(responseBody, 'token_name', ''), 180 | // } 181 | // } 182 | // if ( 183 | // responseBody.hasOwnProperty('tokenPriceUSD') && 184 | // responseBody.tokenPriceUSD !== null && 185 | // responseBody.tokenPriceUSD !== '' 186 | // ) { 187 | // tokenInfo = { 188 | // ...tokenInfo, 189 | // TokenPriceUSD: parserMapping(responseBody, 'tokenPriceUSD', ''), 190 | // } 191 | // } 192 | // if ( 193 | // responseBody.hasOwnProperty('total_supply') && 194 | // responseBody.total_supply !== null && 195 | // responseBody.total_supply !== '' 196 | // ) { 197 | // tokenInfo = { 198 | // ...tokenInfo, 199 | // TotalSupply: parserMapping(responseBody, 'total_supply', ''), 200 | // } 201 | // } 202 | 203 | // if ( 204 | // responseBody.hasOwnProperty('wechat') && 205 | // responseBody.wechat !== null && 206 | // responseBody.wechat !== '' 207 | // ) { 208 | // tokenInfo = { 209 | // ...tokenInfo, 210 | // Wechat: parserMapping(responseBody, 'wechat', ''), 211 | // } 212 | // } 213 | // if ( 214 | // responseBody.hasOwnProperty('whitepaper') && 215 | // responseBody.whitepaper !== null && 216 | // responseBody.whitepaper !== '' 217 | // ) { 218 | // tokenInfo = { 219 | // ...tokenInfo, 220 | // Whitepaper: parserMapping(responseBody, 'whitepaper', ''), 221 | // } 222 | // } 223 | 224 | return tokenInfo 225 | } 226 | 227 | export default getTokenInfo 228 | -------------------------------------------------------------------------------- /src/controllers/pgw.ts: -------------------------------------------------------------------------------- 1 | import type { IPostTransactionRisksResponseBody } from '../helpers/parser/pgw/types/postTransactionRisks.type' 2 | import type { IPostTransactionRiskSummaryResponseBody } from '../helpers/parser/pgw/types/postTransactionRiskSummary.type' 3 | import type { IPostTransactionSimulationResponseBody } from '../helpers/parser/pgw/types/postTransactionSimulation.type' 4 | import type { IGetSnapLatestVersionResponseBody } from '../helpers/parser/pgw/types/getSnapLatestVersion.type' 5 | import type { IGetTokenInfoResponseBody } from '../helpers/parser/pgw/types/getTokenInfo.type' 6 | import type { IGetAddressLabelsResponseBody } from '../helpers/parser/pgw/types/getAddressLabel.type' 7 | import type { 8 | TGetSnapLatestVersion, 9 | TOnResponseErrorCode, 10 | TPostTransactionRisks, 11 | TPostTransactionRiskSummary, 12 | TPostTransactionSimulation, 13 | TGetTokenInfo, 14 | TGetAddressLabel, 15 | } from '../controllers/types/pgw.type' 16 | 17 | import { generatedUUIDV4 } from '../helpers/secret' 18 | import Logger from '../controllers/logger' 19 | import { createUrlBase, get, payload, post } from '../controllers/http' 20 | 21 | import pgwParser from '../helpers/parser/pgw' 22 | import { APP_PLATFORM } from '../constants/config' 23 | 24 | const logger = new Logger('[controllers.pgw]') 25 | const pgwBase = createUrlBase('PGW') 26 | 27 | export const onResponseErrorCode: TOnResponseErrorCode = (response, responseBody) => { 28 | //able to be extended if any further spec 29 | //there is no any payload sometime when statusCode is 50X 30 | const { status } = response 31 | const error = { 32 | httpStatusCode: status, 33 | traceId: responseBody?.trace_id, 34 | errorCode: responseBody?.err_code, 35 | message: responseBody?.message, 36 | dateTime: responseBody?.datetime, 37 | } 38 | 39 | return error 40 | } 41 | 42 | const header = (addition = {}) => { 43 | return { 44 | 'Content-Type': 'application/json;charset=utf-8', 45 | 'X-Trace-ID': generatedUUIDV4(), //frontend generated guid per request, need regenerate when retry 46 | 'X-App-Platform': APP_PLATFORM, 47 | ...addition, 48 | } 49 | } 50 | 51 | const postTransactionRisks: TPostTransactionRisks = async ( 52 | postTransactionRequestBody, 53 | headerOption = {}, 54 | ) => { 55 | const keyPath = 'POST_TRANSACTION_RISKS' 56 | const url = pgwBase(keyPath) 57 | const body = postTransactionRequestBody 58 | const headers = header(headerOption) 59 | 60 | logger.log('postTransactionRisks', 'head', headers) 61 | logger.log('postTransactionRisks', 'body', body) 62 | 63 | const request = await post(url, payload(body, headers), onResponseErrorCode) 64 | const [error, response] = await request() 65 | 66 | logger.log('postTransactionRisks', 'error', error) 67 | logger.log('postTransactionRisks', 'response', response) 68 | 69 | if (error) { 70 | throw error 71 | } 72 | 73 | const responseParsed = pgwParser[keyPath](response) 74 | logger.log('postTransactionRisks', 'responseParsed', responseParsed) 75 | 76 | return responseParsed 77 | } 78 | 79 | const postTransactionRiskSummary: TPostTransactionRiskSummary = async ( 80 | postTransactionRequestBody, 81 | headerOption = {}, 82 | ) => { 83 | const keyPath = 'POST_TRANSACTION_RISK_SUMMARY' 84 | const url = pgwBase(keyPath) 85 | const body = postTransactionRequestBody 86 | const headers = await header(headerOption) 87 | 88 | logger.log('postTransactionRiskSummary', 'head', headers) 89 | logger.log('postTransactionRiskSummary', 'body', body) 90 | 91 | const request = await post(url, payload(body, headers), onResponseErrorCode) 92 | const [error, response] = await request() 93 | 94 | logger.log('postTransactionRiskSummary', 'error', error) 95 | logger.log('postTransactionRiskSummary', 'response', response) 96 | 97 | if (error) { 98 | throw error 99 | } 100 | 101 | const responseParsed = pgwParser[keyPath](response) 102 | logger.log('postTransactionRiskSummary', 'responseParsed', responseParsed) 103 | 104 | return responseParsed 105 | } 106 | 107 | const postTransactionSimulation: TPostTransactionSimulation = async ( 108 | postTransactionRequestBody, 109 | headerOption = {}, 110 | ) => { 111 | const keyPath = 'POST_TRANSACTION_SIMULATION' 112 | const url = pgwBase(keyPath) 113 | const body = postTransactionRequestBody 114 | const headers = await header(headerOption) 115 | 116 | logger.log('postTransactionSimulation', 'head', headers) 117 | logger.log('postTransactionSimulation', 'body', body) 118 | 119 | const request = await post(url, payload(body, headers), onResponseErrorCode) 120 | const [error, response] = await request() 121 | 122 | logger.log('postTransactionSimulation', 'error', error) 123 | logger.log('postTransactionSimulation', 'response', response) 124 | 125 | if (error) { 126 | throw error 127 | } 128 | 129 | const responseParsed = pgwParser[keyPath](response) 130 | logger.log('postTransactionSimulation', 'responseParsed', responseParsed) 131 | return responseParsed 132 | } 133 | 134 | const getSnapLatestVersion: TGetSnapLatestVersion = async (headerOption = {}) => { 135 | const keyPath = 'GET_SNAP_LATEST_VERSION' 136 | const url = pgwBase(keyPath) 137 | const body = {} 138 | const headers = header(headerOption) 139 | 140 | logger.log('getSnapLatestVersion', 'head', headers) 141 | logger.log('getSnapLatestVersion', 'body', body) 142 | 143 | const request = await get(url, payload(body, headers), onResponseErrorCode) 144 | const [error, response] = await request() 145 | 146 | logger.log('getSnapLatestVersion', 'error', error) 147 | logger.log('getSnapLatestVersion', 'response', response) 148 | 149 | if (error) { 150 | throw error 151 | } 152 | 153 | const responseParsed = pgwParser[keyPath](response) 154 | logger.log('getSnapLatestVersion', 'responseParsed', responseParsed) 155 | 156 | return responseParsed 157 | } 158 | 159 | const getTokenInfo: TGetTokenInfo = async (contractAddress, headerOption = {}) => { 160 | const keyPath = 'GET_TOKEN_INFO' 161 | const url = pgwBase(keyPath, (path: string) => 162 | path.replace('{contractAddress}', contractAddress), 163 | ) 164 | const body = {} 165 | const headers = header(headerOption) 166 | 167 | logger.log('getTokenInfo', 'head', headers) 168 | logger.log('getTokenInfo', 'body', body) 169 | 170 | const request = await get(url, payload(body, headers), onResponseErrorCode) 171 | const [error, response] = await request() 172 | 173 | logger.log('getTokenInfo', 'error', error) 174 | logger.log('getTokenInfo', 'response', response) 175 | 176 | if (error) { 177 | throw error 178 | } 179 | 180 | const responseParsed = pgwParser[keyPath](response) 181 | logger.log('getTokenInfo', 'responseParsed', responseParsed) 182 | 183 | return responseParsed 184 | } 185 | 186 | const getAddressLabel: TGetAddressLabel = async (contractAddress, headerOption = {}) => { 187 | const keyPath = 'GET_ADDRESS_LABEL' 188 | const url = pgwBase(keyPath, (path: string) => 189 | path.replace('{contractAddress}', contractAddress), 190 | ) 191 | const body = {} 192 | const headers = header(headerOption) 193 | 194 | logger.log('getAddressLabel', 'head', headers) 195 | logger.log('getAddressLabel', 'body', body) 196 | 197 | const request = await get(url, payload(body, headers), onResponseErrorCode) 198 | const [error, response] = await request() 199 | 200 | logger.log('getAddressLabel', 'error', error) 201 | logger.log('getAddressLabel', 'response', response) 202 | 203 | if (error) { 204 | throw error 205 | } 206 | 207 | const responseParsed = pgwParser[keyPath](response) 208 | logger.log('getAddressLabel', 'responseParsed', responseParsed) 209 | 210 | return responseParsed 211 | } 212 | 213 | export default { 214 | postTransactionRisks, 215 | postTransactionRiskSummary, 216 | postTransactionSimulation, 217 | getSnapLatestVersion, 218 | getTokenInfo, 219 | getAddressLabel, 220 | } 221 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | Copyright 2023 TrendMicro Software Inc. -------------------------------------------------------------------------------- /src/constants/content.ts: -------------------------------------------------------------------------------- 1 | import { DAPP_LINK } from "./config" 2 | 3 | export const riskIconMapping = { 4 | transaction_risks_summary: { 5 | fatal_risk: '❌', 6 | high_risk: '🔶', 7 | caution: '🟨', 8 | }, 9 | transaction_risk_type: { 10 | severe_risk: '🔴', 11 | minor_risk: '🟠', 12 | attention_required: '🟡', 13 | }, 14 | } 15 | export const updateAlert = { 16 | forceUpdate: 17 | `[❕ ALERT] Current version is not available anymore! Please visit 🌐“${DAPP_LINK}” to update.`, 18 | snapUpdate: 19 | `[❕ ALERT] There is an update of ChainSafer Snap, for better protection, please visit 🌐“${DAPP_LINK}” to update.`, 20 | } 21 | 22 | export function collectionSummary(collectionTokenName: string, reputation: string) { 23 | return `Collection:${collectionTokenName} (Reputation ${reputation} )` 24 | } 25 | export const serviceError = { 26 | serviceError: 'Trend Micro ChainSafer is not available now, please try again later.', 27 | simulationError: '[Simulation] Service not available now.', 28 | riskApiError: '🚧 [Risk detection] No service', 29 | riskApiErrorDetail: 'Risk detection service not available now, please try again later.', 30 | unsupportedChainId: '[Simulation] Only Support Ethereum Mainnet currently.', 31 | } 32 | 33 | export function countRecipient(recipientNumber: number) { 34 | return `This transaction goes thru ${recipientNumber} contracts/ recipients` 35 | } 36 | 37 | export function recipientLableInfo(name: string, source: string) { 38 | return `🚨Label: ${name}_${source}` 39 | } 40 | 41 | export function recipientListWarningContractTitle(contract: number) { 42 | return `, ${contract} of them might exist security concern:` 43 | } 44 | 45 | export function evmErrorAddress(evmErrorAddress: string) { 46 | return `address: ${evmErrorAddress}` 47 | } 48 | 49 | export function evmErrMessage(evmErrMessage: string) { 50 | return `error: ${evmErrMessage}` 51 | } 52 | 53 | export function transactionMethodIs(method: string) { 54 | return `Transaction Method: ${method}` 55 | } 56 | 57 | export const chainSaferAd = { 58 | adTitle: '[ 📣 NEWS] Want a comprehensive protection? 🛡️ ', 59 | adContent: 'Check the SecuX x Trend Micro ChainSafer special hardware wallet 💪🏼', 60 | } 61 | 62 | export const headingText = { 63 | latestVersion: 'Latest Version', 64 | riskSummary: 'Risk Summary Check', 65 | riskFactor: '**- Risky factors -**', 66 | transactionSimulation: 'Transaction Simulation', 67 | pay: 'Pay ➞', 68 | balanceChanges: 'Balance Changes', 69 | paymentDetailPanel: 'Payment Detail', 70 | projectInsightPanel: 'Project Insight', 71 | recipientsPanel: 'Recipients', 72 | } 73 | 74 | export function tokenNameWithBlueMark(tokenName: string) { 75 | return `${tokenName} (Reputation 🆗)` 76 | } 77 | 78 | export function tokenNameWithoutBlueMark(tokenName: string) { 79 | return `${tokenName} (Reputation ❔️)` 80 | } 81 | 82 | export function tokenSymbolAndValue( 83 | tokenType: string, 84 | tokenSymbol: string, 85 | rawAmount: string, 86 | usd: number, 87 | ) { 88 | return `{${tokenType}} ${rawAmount} ${tokenSymbol} (≈$ ${usd})` 89 | } 90 | 91 | export function balanceWithUsd(eth: number, usd: number) { 92 | return `${eth} ETH (≈$ ${usd})` 93 | } 94 | 95 | export function resProjectInsightWebsite(website: string) { 96 | return `Website 🌐 [${website}]` 97 | } 98 | 99 | export function resProjectInsightBlog(blog: string) { 100 | return `Blog 🌐 [${blog}]` 101 | } 102 | 103 | export function resProjectInsightTwitter(twitter: string) { 104 | return `Twitter👉🏻 [${twitter}]` 105 | } 106 | 107 | export function resProjectInsightDiscord(discord: string) { 108 | return `Discord👉🏻 [${discord}]` 109 | } 110 | 111 | export function balanceWithoutUsd(eth: number) { 112 | return `${eth} ETH` 113 | } 114 | 115 | export const simulationBalanceChange = { 116 | balanceChangeBefore: 'Before ➞', 117 | balanceChangeAfter: '➞ After', 118 | separators: '---', 119 | balanceDiff: '💰Balance Diff.', 120 | paymentDetailPanelGet: '➞ Get', 121 | paymentDetailPanelPay: 'Pay ➞', 122 | } 123 | 124 | export const apiMapping = { 125 | transaction_risks_summary: { 126 | fatal_risk: 'Extreme Risk', 127 | high_risk: 'Medium Risk', 128 | caution: 'Low Risk', 129 | no_risk: 'No Detected Risk', 130 | rule_address_erc20_transfer: 'ERC-20 token transfer to known malicious account', 131 | rule_address_erc20_approve: 'ERC-20 token approval for known malicious contract', 132 | rule_address_erc721_set_approval_for_all: 133 | 'NFT global approval for known malicious contract', 134 | rule_address_eip712_transfer: 135 | 'Signing may pre-approve transfers to known malicious account', 136 | rule_address_withdraw_ape_coin: 'Ape transfer to known malicious contract', 137 | rule_address_increase_approval: 'Token approval for known malicious contract', 138 | rule_address_increase_allowance: 'Token allowance for known malicious contract', 139 | rule_address_eth_sign: 'High-risk signing method (eth_sign)', 140 | rule_address_eth_signature: 'Malicious address detected', 141 | rule_address_eth_transfer_payable_contract: 'Transfer to known malicious contract', 142 | rule_address_eth_transfer_contract: 'Transfer to known malicious contract', 143 | rule_address_eth_transfer_eoa: 'Token transfer to known malicious account', 144 | rule_url_scam_wrs_dangerous: 'Known malicious website', 145 | rule_address_blocklist: 'Known malicious account', 146 | rule_url_scam_dna: 'AI-flagged suspicious website', 147 | rule_domain_short_available_time_with_erc20_transfer: 148 | 'Short duration domain & ERC-20 token transfer', 149 | rule_domain_short_available_time_with_eip712_transfer: 150 | 'Short duration domain & signing may pre-approve transfers', 151 | rule_domain_short_available_time_with_erc20_approve: 152 | 'Short duration domain & ERC-20 token approval for contract', 153 | rule_domain_short_available_time_with_erc721_setapprovalforall: 154 | 'Short duration domain & NFT global approval', 155 | rule_domain_short_available_time_with_payable_contract: 156 | 'Short duration domain & ERC-20 token transfer to contract', 157 | rule_domain_short_available_time_with_contract: 158 | 'Short duration domain & transaction request', 159 | rule_domain_short_available_time_with_eoa: 160 | 'Short duration domain & ERC-20 token transfer to account', 161 | rule_ssl_domain_mismatch_with_erc20_transfer: 162 | 'Domain-SSL mismatch & ERC-20 transfer to account', 163 | rule_ssl_domain_mismatch_with_eip712_transfer: 164 | 'Domain-SSL mismatch & signing may pre-approve transfers', 165 | rule_ssl_domain_mismatch_with_erc20_approve: 166 | 'Domain-SSL mismatch & ERC-20 approval for contract', 167 | rule_ssl_domain_mismatch_with_erc721_setapprovalforall: 168 | 'Domain-SSL mismatch & NFT global approval', 169 | rule_ssl_domain_mismatch_with_payable_contract: 170 | 'Domain-SSL mismatch & token transfer to contract', 171 | rule_ssl_domain_mismatch_with_contract: 'Domain-SSL mismatch & transaction request', 172 | rule_ssl_domain_mismatch_with_eoa: 'Domain-SSL mismatch & token transfer to account', 173 | rule_url_ssl_domain_mismatch: 'Domain-SSL mismatch', 174 | rule_domain_short_available_time_with_withdrawapecoin: 175 | 'Short duration domain & withdraw ape coin', 176 | rule_ssl_domain_mismatch_with_withdrawapecoin: 'Domain-SSL mismatch & withdraw ape', 177 | rule_domain_short_available_time_with_increaseapproval: 178 | 'Short duration domain & increase approval', 179 | rule_ssl_domain_mismatch_with_increaseapproval: 'Domain-SSL mismatch & increase approval', 180 | rule_domain_short_available_time_with_increaseallowance: 181 | 'Short duration domain & increase allowance', 182 | rule_ssl_domain_mismatch_with_increaseallowance: 'Domain-SSL mismatch & increase allowance', 183 | rule_ssl_short_available_time_with_erc20_transfer: 184 | 'SSL certificate expires soon & ERC-20 transfer to account', 185 | rule_ssl_short_available_time_with_eip712_transfer: 186 | 'SSL expires soon & signing may pre-approve transfers', 187 | rule_ssl_short_available_time_with_erc20_approve: 188 | 'SSL certificate expires soon & ERC-20 approval for contract', 189 | rule_ssl_short_available_time_with_erc721_setapprovalforall: 190 | 'SSL certificate expires soon & NFT global approval', 191 | rule_ssl_short_available_time_with_payable_contract: 192 | 'SSL certificate expires soon & token transfer to contract', 193 | rule_ssl_short_available_time_with_contract: 194 | 'SSL certificate expires soon & transaction request', 195 | rule_ssl_short_available_time_with_eoa: 196 | 'SSL certificate expires soon & Token Transfer to Account', 197 | rule_domain_short_create_time_with_erc20_transfer: 198 | 'Recently created domain & token transfer to contract', 199 | rule_domain_short_create_time_with_eip712_transfer: 200 | 'Recently created domain & signing may pre-approve transfers', 201 | rule_domain_short_create_time_with_erc20_approve: 202 | 'Recently created domain & ERC-20 token approval for contract', 203 | rule_domain_short_create_time_with_erc721_setapprovalforall: 204 | 'Recently created domain & NFT global approval', 205 | rule_domain_short_create_time_with_payable_contract: 206 | 'Recently created domain & token transfer to contract', 207 | rule_domain_short_create_time_with_contract: 208 | 'Recently created domain & transaction request', 209 | rule_domain_short_create_time_with_eoa: 210 | 'Recently created domain & token transfer to account', 211 | rule_ssl_short_create_time_with_erc20_transfer: 212 | 'Recent SSL certificate & ERC-20 token transfer to account', 213 | rule_ssl_short_create_time_with_eip712_transfer: 214 | 'Recent SSL certificate & signing may pre-approve transfers', 215 | rule_ssl_short_create_time_with_erc20_approve: 216 | 'Recent SSL certificate & ERC-20 token approval for contract', 217 | rule_ssl_short_create_time_with_erc721_setapprovalforall: 218 | 'Recent SSL certificate & NFT global approval request', 219 | rule_ssl_short_create_time_with_payable_contract: 220 | 'Recent SSL certificate & token transfer to contract', 221 | rule_ssl_short_create_time_with_contract: 'Recent SSL certificate & transaction request', 222 | rule_ssl_short_create_time_with_eoa: 'Recent SSL certificate & account transaction', 223 | rule_address_erc20_transfer_caution: 'ERC-20 token transfer to account', 224 | rule_address_erc20_approve_caution: 'ERC-20 token approval', 225 | rule_address_erc721_set_approval_for_all_caution: 'NFT global approval', 226 | rule_address_eip712_transfer_caution: 'Signing may pre-approve transfers', 227 | rule_address_eth_transfer_payable_contract_caution: 'Token transfer to contract', 228 | rule_address_eth_transfer_contract_caution: 229 | 'Contract may have the ability to transfer assets', 230 | rule_address_eth_transfer_eoa_caution: 'Token transfer to account', 231 | rule_domain_short_available_time: 'Short duration domain', 232 | rule_ssl_short_available_time: 'SSL certificate expires soon', 233 | rule_address_contract_not_public: 'Unverifiable private contract', 234 | rule_address_eth_signature_caution: 'Unrecognized transaction type', 235 | rule_domain_short_create_time: 'Recently created domain', 236 | rule_ssl_short_create_time: 'Recent SSL certificate', 237 | rule_ssl_short_available_time_with_withdrawapecoin: 238 | 'SSL certificate expires soon & withdraw ape', 239 | rule_domain_short_create_time_with_withdrawapecoin: 240 | 'Recently created domain & withdraw ape', 241 | rule_ssl_short_create_time_with_withdrawapecoin: 'Recent SSL certificate & withdraw ape', 242 | rule_address_withdraw_ape_coin_caution: 'withdraw ape coin', 243 | rule_ssl_short_available_time_with_increaseapproval: 244 | 'SSL certificate expires soon & increase approval', 245 | rule_domain_short_create_time_with_increaseapproval: 246 | 'Recently created domain & increase approval', 247 | rule_ssl_short_create_time_with_increaseapproval: 248 | 'Recent SSL certificate & increase approval', 249 | rule_address_increase_approval_caution: 'increase approval', 250 | rule_ssl_short_available_time_with_increaseallowance: 251 | 'SSL certificate expires soon & increase allowance', 252 | rule_domain_short_create_time_with_increaseallowance: 253 | 'Recently created domain & increase allowance', 254 | rule_ssl_short_create_time_with_increaseallowance: 255 | 'Recent SSL certificate & increase allowance', 256 | rule_address_increase_allowance_caution: 'increase allowance', 257 | }, 258 | transaction_risks: { 259 | factor_url_blocklist: 'Known malicious website', 260 | factor_url_ai_scam: 'AI-flagged suspicious website', 261 | factor_address_blocklist: 'Known malicious account', 262 | factor_eth_sign: 'High-risk signature type', 263 | factor_contract_not_public: 'Unverifiable private contract', 264 | factor_uncategorized_signature: 'Unrecognized transaction type', 265 | factor_erc20_transfer: 'ERC-20 token transfer', 266 | factor_erc20_approve: 'ERC-20 token approval', 267 | factor_eip712_transfer: 'Signature Request', 268 | factor_erc721_setapprovalforall: 'NFT global approval', 269 | factor_ssl_short_create: 'Recent SSL certificate', 270 | factor_ssl_short_available: 'SSL certificate expires soon', 271 | factor_domain_short_create: 'Recent website domain', 272 | factor_domain_short_available: 'Short-term domain validity', 273 | factor_p2p_transfer: 'Transfer to account', 274 | factor_contract_transfer: 'Transfer to contract', 275 | factor_ssl_domain_mismatch: 'SSL certificate-domain mismatch', 276 | factor_payable_contract_transfer: 'Contract may have the ability to transfer assets', 277 | factor_withdraw_ape_coin: 'Withdraw Ape Coin', 278 | factor_increase_approval: 'Increase Approval', 279 | factor_increase_allowance: 'Increase Allowance', 280 | }, 281 | } 282 | --------------------------------------------------------------------------------