@avalabs/evm-module 0.0.16 → 0.0.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/.turbo/turbo-build.log +10 -10
  2. package/.turbo/turbo-lint.log +1 -1
  3. package/.turbo/turbo-test.log +70 -24
  4. package/CHANGELOG.md +15 -0
  5. package/dist/index.cjs +23 -20
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.cts +9 -1
  8. package/dist/index.d.ts +9 -1
  9. package/dist/index.js +20 -19
  10. package/dist/index.js.map +1 -1
  11. package/package.json +4 -3
  12. package/src/constants.ts +1 -0
  13. package/src/handlers/eth-send-transaction/eth-send-transaction.test.ts +232 -1
  14. package/src/handlers/eth-send-transaction/eth-send-transaction.ts +24 -5
  15. package/src/handlers/eth-sign/eth-sign.test.ts +176 -35
  16. package/src/handlers/eth-sign/eth-sign.ts +29 -8
  17. package/src/handlers/get-balances/evm-balance-service/get-erc20-balances.test.ts +2 -2
  18. package/src/handlers/get-balances/evm-balance-service/get-erc20-balances.ts +4 -6
  19. package/src/handlers/get-balances/get-balances.test.ts +0 -5
  20. package/src/handlers/get-balances/get-balances.ts +14 -3
  21. package/src/handlers/get-balances/glacier-balance-service/get-erc20-balances.test.ts +0 -1
  22. package/src/handlers/get-balances/glacier-balance-service/get-erc20-balances.ts +10 -7
  23. package/src/handlers/get-tokens/get-tokens.test.ts +6 -6
  24. package/src/module.ts +2 -0
  25. package/src/types.ts +9 -0
  26. package/src/utils/parse-erc20-transaction-type.ts +35 -0
  27. package/src/utils/process-transaction-simulation.test.ts +105 -0
  28. package/src/utils/process-transaction-simulation.ts +293 -0
  29. package/src/utils/scan-transaction.ts +63 -0
  30. package/src/handlers/eth-sign/schemas/parse-request-params.ts +0 -90
@@ -0,0 +1,293 @@
1
+ import Blockaid from '@blockaid/client';
2
+ import type { TransactionParams } from '../types';
3
+ import {
4
+ type NetworkContractToken,
5
+ type NetworkToken,
6
+ TokenType,
7
+ AlertType,
8
+ type Alert,
9
+ type BalanceChange,
10
+ type TokenApproval,
11
+ type TokenDiff,
12
+ type TokenDiffItem,
13
+ type TokenApprovals,
14
+ type RpcRequest,
15
+ RpcMethod,
16
+ } from '@avalabs/vm-module-types';
17
+ import { balanceToDisplayValue, numberToBN } from '@avalabs/utils-sdk';
18
+ import { isHexString } from 'ethers';
19
+ import { scanJsonRpc, scanTransaction } from './scan-transaction';
20
+
21
+ export const processTransactionSimulation = async ({
22
+ request,
23
+ dAppUrl,
24
+ params,
25
+ chainId,
26
+ proxyApiUrl,
27
+ }: {
28
+ request: RpcRequest;
29
+ dAppUrl?: string;
30
+ params: TransactionParams;
31
+ chainId: number;
32
+ proxyApiUrl: string;
33
+ }) => {
34
+ let alert: Alert | undefined;
35
+ let balanceChange: BalanceChange | undefined;
36
+ let tokenApprovals: TokenApprovals | undefined;
37
+
38
+ try {
39
+ const { validation, simulation } = await scanTransaction({
40
+ proxyApiUrl,
41
+ chainId,
42
+ params,
43
+ domain: dAppUrl,
44
+ });
45
+
46
+ if (!validation || validation.result_type === 'Error' || validation.result_type === 'Warning') {
47
+ alert = transactionAlerts[AlertType.WARNING];
48
+ } else if (validation.result_type === 'Malicious') {
49
+ alert = transactionAlerts[AlertType.DANGER];
50
+ }
51
+
52
+ if (simulation?.status === 'Success') {
53
+ tokenApprovals = processTokenApprovals(request, simulation.account_summary.exposures);
54
+ balanceChange = processBalanceChange(simulation.account_summary.assets_diffs);
55
+ }
56
+ } catch (error) {
57
+ console.error('processTransactionSimulation error', error);
58
+ alert = transactionAlerts[AlertType.WARNING];
59
+ }
60
+
61
+ return { alert, balanceChange, tokenApprovals };
62
+ };
63
+
64
+ const processTokenApprovals = (
65
+ request: RpcRequest,
66
+ exposures: Blockaid.AddressAssetExposure[],
67
+ ): TokenApprovals | undefined => {
68
+ const approvals: TokenApproval[] = [];
69
+
70
+ for (const exposurePerAsset of exposures) {
71
+ const token = convertAssetToNetworkContractToken(exposurePerAsset.asset);
72
+ if (!token) {
73
+ continue;
74
+ }
75
+
76
+ for (const [spenderAddress, exposurePerSpender] of Object.entries(exposurePerAsset.spenders)) {
77
+ if (exposurePerSpender.exposure.length === 0) {
78
+ approvals.push({
79
+ token,
80
+ spenderAddress,
81
+ logoUri: token.logoUri,
82
+ });
83
+ } else {
84
+ for (const exposure of exposurePerSpender.exposure) {
85
+ if ('raw_value' in exposure) {
86
+ approvals.push({
87
+ token,
88
+ spenderAddress,
89
+ value: exposure.raw_value,
90
+ usdPrice: exposure.usd_price,
91
+ logoUri: token.logoUri,
92
+ });
93
+ } else {
94
+ approvals.push({
95
+ token,
96
+ spenderAddress,
97
+ logoUri: exposure.logo_url,
98
+ usdPrice: exposure.usd_price,
99
+ });
100
+ }
101
+ }
102
+ }
103
+ }
104
+ }
105
+
106
+ if (approvals.length === 0) {
107
+ return undefined;
108
+ }
109
+
110
+ const isEditable =
111
+ approvals.length === 1 &&
112
+ approvals[0]?.token.type === TokenType.ERC20 &&
113
+ request.method === RpcMethod.ETH_SEND_TRANSACTION;
114
+
115
+ return { isEditable, approvals };
116
+ };
117
+
118
+ export const processBalanceChange = (assetDiffs: Blockaid.AssetDiff[]): BalanceChange | undefined => {
119
+ const ins = processAssetDiffs(assetDiffs, 'in');
120
+ const outs = processAssetDiffs(assetDiffs, 'out');
121
+
122
+ if (ins.length === 0 && outs.length === 0) {
123
+ return undefined;
124
+ }
125
+
126
+ return { ins, outs };
127
+ };
128
+
129
+ const processAssetDiffs = (assetDiffs: Blockaid.AssetDiff[], type: 'in' | 'out'): TokenDiff[] => {
130
+ return (
131
+ assetDiffs
132
+ .filter((assetDiff) => assetDiff[type].length > 0)
133
+ // sort asset diffs by length of in/out array
134
+ // this is done to ensure that the token with multiple in/out values are displayed last,
135
+ // to put them in groups with appropriate UI(i.e. accordion), after single in/out tokens
136
+ .sort((a, b) => a[type].length - b[type].length)
137
+ .map((assetDiff) => {
138
+ const asset = assetDiff.asset;
139
+ // convert blockaid asset to network token
140
+ const token: NetworkToken | NetworkContractToken | undefined =
141
+ 'address' in asset ? convertAssetToNetworkContractToken(asset) : convertNativeAssetToToken(asset);
142
+ if (!token) {
143
+ return undefined;
144
+ }
145
+
146
+ const items = assetDiff[type]
147
+ .map((diff) => {
148
+ let displayValue;
149
+ if ('value' in diff && diff.value) {
150
+ if ('decimals' in token) {
151
+ const valueBN = numberToBN(diff.value, token.decimals);
152
+ displayValue = balanceToDisplayValue(valueBN, token.decimals);
153
+ } else if (isHexString(diff.value)) {
154
+ // for some token (like ERC1155) blockaid returns value in hex format
155
+ displayValue = parseInt(diff.value, 16).toString();
156
+ }
157
+ } else if ('type' in token && token.type === TokenType.ERC721) {
158
+ // for ERC721 type token, we just display 1 to indicate that a single NFT will be transferred
159
+ displayValue = '1';
160
+ }
161
+
162
+ return displayValue ? { displayValue, usdPrice: diff.usd_price } : undefined;
163
+ })
164
+ .filter((x): x is TokenDiffItem => x !== undefined);
165
+
166
+ return { token, items };
167
+ })
168
+ .filter((x): x is TokenDiff => x !== undefined)
169
+ );
170
+ };
171
+
172
+ const convertAssetToNetworkContractToken = (
173
+ asset:
174
+ | Blockaid.Erc20TokenDetails
175
+ | Blockaid.Erc1155TokenDetails
176
+ | Blockaid.Erc721TokenDetails
177
+ | Blockaid.NonercTokenDetails,
178
+ ): NetworkContractToken | undefined => {
179
+ let token: NetworkContractToken | undefined;
180
+ if (asset.type === 'ERC20') {
181
+ token = {
182
+ type: TokenType.ERC20,
183
+ address: asset.address,
184
+ decimals: asset.decimals,
185
+ name: asset.name ?? asset.symbol ?? '',
186
+ symbol: asset.symbol ?? '',
187
+ logoUri: asset.logo_url,
188
+ };
189
+ } else if (asset.type === 'ERC1155') {
190
+ token = {
191
+ type: TokenType.ERC1155,
192
+ address: asset.address,
193
+ logoUri: asset.logo_url,
194
+ name: asset.name,
195
+ symbol: asset.symbol,
196
+ };
197
+ } else if (asset.type === 'ERC721') {
198
+ token = {
199
+ type: TokenType.ERC721,
200
+ address: asset.address,
201
+ logoUri: asset.logo_url,
202
+ name: asset.name,
203
+ symbol: asset.symbol,
204
+ };
205
+ } else if (asset.type === 'NONERC') {
206
+ token = {
207
+ type: TokenType.NONERC,
208
+ address: asset.address,
209
+ logoUri: asset.logo_url,
210
+ name: asset.name,
211
+ symbol: asset.symbol,
212
+ };
213
+ }
214
+
215
+ return token;
216
+ };
217
+
218
+ const convertNativeAssetToToken = (asset: Blockaid.NativeAssetDetails): NetworkToken => {
219
+ return {
220
+ name: asset.name ?? '',
221
+ symbol: asset.symbol ?? '',
222
+ decimals: asset.decimals,
223
+ description: '',
224
+ logoUri: asset.logo_url,
225
+ };
226
+ };
227
+
228
+ export const processJsonRpcSimulation = async ({
229
+ request,
230
+ dAppUrl,
231
+ accountAddress,
232
+ chainId,
233
+ data,
234
+ proxyApiUrl,
235
+ }: {
236
+ request: RpcRequest;
237
+ dAppUrl?: string;
238
+ accountAddress: string;
239
+ data: { method: string; params: unknown };
240
+ chainId: number;
241
+ proxyApiUrl: string;
242
+ }) => {
243
+ let alert: Alert | undefined;
244
+ let balanceChange: BalanceChange | undefined;
245
+ let tokenApprovals: TokenApprovals | undefined;
246
+
247
+ try {
248
+ const { validation, simulation } = await scanJsonRpc({
249
+ proxyApiUrl,
250
+ chainId,
251
+ accountAddress,
252
+ data: data as Blockaid.Evm.JsonRpcScanParams.Data,
253
+ domain: dAppUrl,
254
+ });
255
+
256
+ if (!validation || validation.result_type === 'Error' || validation.result_type === 'Warning') {
257
+ alert = transactionAlerts[AlertType.WARNING];
258
+ } else if (validation.result_type === 'Malicious') {
259
+ alert = transactionAlerts[AlertType.DANGER];
260
+ }
261
+
262
+ if (simulation?.status === 'Success') {
263
+ tokenApprovals = processTokenApprovals(request, simulation.account_summary.exposures);
264
+ balanceChange = processBalanceChange(simulation.account_summary.assets_diffs);
265
+ }
266
+ } catch (error) {
267
+ console.error('processJsonRpcSimulation error', error);
268
+ alert = transactionAlerts[AlertType.WARNING];
269
+ }
270
+
271
+ return { alert, balanceChange, tokenApprovals };
272
+ };
273
+
274
+ const transactionAlerts = {
275
+ [AlertType.WARNING]: {
276
+ type: AlertType.WARNING,
277
+ details: {
278
+ title: 'Suspicious Transaction',
279
+ description: 'Use caution, this transaction may be malicious.',
280
+ },
281
+ },
282
+ [AlertType.DANGER]: {
283
+ type: AlertType.DANGER,
284
+ details: {
285
+ title: 'Scam Transaction',
286
+ description: 'This transaction is malicious, do not proceed.',
287
+ actionTitles: {
288
+ reject: 'Reject Transaction',
289
+ proceed: 'Proceed Anyway',
290
+ },
291
+ },
292
+ },
293
+ };
@@ -0,0 +1,63 @@
1
+ import Blockaid from '@blockaid/client';
2
+ import type { TransactionParams } from '../types';
3
+
4
+ const DUMMY_API_KEY = 'DUMMY_API_KEY'; // since we're using our own proxy and api key is handled there, we can use a dummy key here
5
+
6
+ export const scanTransaction = async ({
7
+ proxyApiUrl,
8
+ chainId,
9
+ params,
10
+ domain,
11
+ }: {
12
+ proxyApiUrl: string;
13
+ chainId: number;
14
+ params: TransactionParams;
15
+ domain?: string;
16
+ }): Promise<Blockaid.TransactionScanResponse> => {
17
+ const blockaid = new Blockaid({
18
+ baseURL: proxyApiUrl + '/proxy/blockaid/',
19
+ apiKey: DUMMY_API_KEY,
20
+ });
21
+
22
+ return blockaid.evm.transaction.scan({
23
+ account_address: params.from,
24
+ chain: chainId.toString(),
25
+ options: ['validation', 'simulation'],
26
+ data: {
27
+ from: params.from,
28
+ to: params.to,
29
+ data: params.data,
30
+ value: params.value,
31
+ gas: params.gas,
32
+ gas_price: params.gasPrice,
33
+ },
34
+ metadata: (domain && domain.length > 0 ? { domain } : { non_dapp: true }) as Blockaid.Evm.Metadata,
35
+ });
36
+ };
37
+
38
+ export const scanJsonRpc = async ({
39
+ proxyApiUrl,
40
+ chainId,
41
+ accountAddress,
42
+ data,
43
+ domain,
44
+ }: {
45
+ proxyApiUrl: string;
46
+ chainId: number;
47
+ accountAddress: string;
48
+ data: Blockaid.Evm.JsonRpcScanParams.Data;
49
+ domain?: string;
50
+ }): Promise<Blockaid.TransactionScanResponse> => {
51
+ const blockaid = new Blockaid({
52
+ baseURL: proxyApiUrl + '/proxy/blockaid/',
53
+ apiKey: DUMMY_API_KEY,
54
+ });
55
+
56
+ return blockaid.evm.jsonRpc.scan({
57
+ chain: chainId.toString(),
58
+ options: ['validation', 'simulation'],
59
+ account_address: accountAddress,
60
+ data,
61
+ metadata: (domain && domain.length > 0 ? { domain } : { non_dapp: true }) as Blockaid.Evm.Metadata,
62
+ });
63
+ };
@@ -1,90 +0,0 @@
1
- import { z } from 'zod';
2
- import { ethSignSchema } from './eth-sign';
3
- import {
4
- combinedTypedDataSchema,
5
- ethSignTypedDataSchema,
6
- ethSignTypedDataV1Schema,
7
- ethSignTypedDataV3Schema,
8
- ethSignTypedDataV4Schema,
9
- typedDataSchema,
10
- } from './eth-sign-typed-data';
11
- import { personalSignSchema } from './personal-sign';
12
- import { RpcMethod } from '@avalabs/vm-module-types';
13
-
14
- const paramsSchema = z
15
- .discriminatedUnion('method', [
16
- personalSignSchema,
17
- ethSignSchema,
18
- ethSignTypedDataSchema,
19
- ethSignTypedDataV1Schema,
20
- ethSignTypedDataV3Schema,
21
- ethSignTypedDataV4Schema,
22
- ])
23
- .transform((value, ctx) => {
24
- const { method, params } = value;
25
-
26
- switch (method) {
27
- case RpcMethod.PERSONAL_SIGN:
28
- return {
29
- data: params[0],
30
- address: params[1],
31
- };
32
- case RpcMethod.ETH_SIGN:
33
- return {
34
- data: params[1],
35
- address: params[0],
36
- };
37
- case RpcMethod.SIGN_TYPED_DATA:
38
- case RpcMethod.SIGN_TYPED_DATA_V1: {
39
- const address = params[0];
40
- const data = params[1];
41
-
42
- if (typeof data !== 'string') return { data, address };
43
-
44
- try {
45
- const parsed = JSON.parse(data);
46
- const result = combinedTypedDataSchema.parse(parsed);
47
-
48
- return {
49
- data: result,
50
- address,
51
- };
52
- } catch (e) {
53
- ctx.addIssue({
54
- code: z.ZodIssueCode.custom,
55
- message: 'param is not a valid json',
56
- });
57
-
58
- return z.NEVER;
59
- }
60
- }
61
- case RpcMethod.SIGN_TYPED_DATA_V3:
62
- case RpcMethod.SIGN_TYPED_DATA_V4: {
63
- const address = params[0];
64
- const data = params[1];
65
-
66
- if (typeof data !== 'string') return { data, address };
67
-
68
- try {
69
- const parsed = JSON.parse(data);
70
- const result = typedDataSchema.parse(parsed);
71
-
72
- return {
73
- data: result,
74
- address,
75
- };
76
- } catch (e) {
77
- ctx.addIssue({
78
- code: z.ZodIssueCode.custom,
79
- message: 'param is not a valid json',
80
- });
81
-
82
- return z.NEVER;
83
- }
84
- }
85
- }
86
- });
87
-
88
- export function parseRequestParams(params: { method: RpcMethod; params: unknown }) {
89
- return paramsSchema.safeParse(params);
90
- }