viem 0.0.1-alpha.2 → 0.0.1-alpha.4

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.
@@ -1,160 +1,23 @@
1
- var __defProp = Object.defineProperty;
2
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
- var __publicField = (obj, key, value) => {
4
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
- return value;
6
- };
7
-
8
- // package.json
9
- var package_default = {
10
- name: "viem",
11
- description: "TypeScript (& JavaScript) Interface for Ethereum",
12
- version: "0.0.1-alpha.2",
13
- scripts: {
14
- anvil: "source .env && anvil --fork-url $ANVIL_FORK_URL --fork-block-number $VITE_ANVIL_BLOCK_NUMBER --block-time $VITE_ANVIL_BLOCK_TIME",
15
- bench: "vitest bench --no-threads",
16
- "bench:ci": "CI=true vitest bench --no-threads",
17
- build: "tsup",
18
- changeset: "changeset",
19
- "changeset:release": "pnpm build && changeset publish",
20
- "changeset:version": "changeset version && pnpm install --lockfile-only",
21
- dev: "DEV=true tsup",
22
- "dev:docs": "pnpm -r --filter site dev",
23
- format: "rome format src/ test/ --write",
24
- lint: "rome check .",
25
- "lint:fix": "pnpm lint --apply-suggested",
26
- playground: "pnpm --filter playground-dev dev",
27
- "playground:benchmark": "pnpm --filter playground-benchmark dev",
28
- postinstall: "pnpm dev",
29
- preinstall: "npx only-allow pnpm",
30
- prepare: "npx simple-git-hooks",
31
- test: "vitest dev --coverage --no-threads",
32
- "test:ci": "CI=true vitest --coverage --no-threads",
33
- "test:ui": "vitest dev --ui --no-threads",
34
- typecheck: "tsc --noEmit"
35
- },
36
- files: [
37
- "/actions",
38
- "/chains",
39
- "/dist",
40
- "/clients",
41
- "/types",
42
- "/utils",
43
- "/window"
44
- ],
45
- exports: {
46
- ".": {
47
- types: "./dist/index.d.ts",
48
- default: "./dist/index.js"
49
- },
50
- "./actions": {
51
- types: "./dist/actions/index.d.ts",
52
- default: "./dist/actions/index.js"
53
- },
54
- "./chains": {
55
- types: "./dist/chains.d.ts",
56
- default: "./dist/chains.js"
57
- },
58
- "./clients": {
59
- types: "./dist/clients/index.d.ts",
60
- default: "./dist/clients/index.js"
61
- },
62
- "./utils": {
63
- types: "./dist/utils/index.d.ts",
64
- default: "./dist/utils/index.js"
65
- },
66
- "./window": {
67
- types: "./dist/window.d.ts",
68
- default: "./dist/window.js"
69
- },
70
- "./package.json": "./package.json"
71
- },
72
- type: "module",
73
- main: "dist/index.js",
74
- types: "dist/index.d.ts",
75
- sideEffects: false,
76
- dependencies: {
77
- "@noble/hashes": "^1.1.2",
78
- "@wagmi/chains": "^0.1.0",
79
- abitype: "^0.2.5"
80
- },
81
- devDependencies: {
82
- "@actions/core": "^1.10.0",
83
- "@actions/github": "^5.1.1",
84
- "@changesets/changelog-github": "^0.4.5",
85
- "@changesets/cli": "^2.23.2",
86
- "@testing-library/jest-dom": "^5.16.5",
87
- "@types/dedent": "^0.7.0",
88
- "@types/fs-extra": "^9.0.13",
89
- "@types/node": "^17.0.45",
90
- "@vitest/coverage-c8": "^0.24.3",
91
- "@vitest/ui": "^0.19.1",
92
- bundlewatch: "^0.3.3",
93
- dedent: "^0.7.0",
94
- esbuild: "^0.16.12",
95
- "esbuild-register": "^3.4.2",
96
- "essential-eth": "^0.6.2",
97
- ethers: "^5.7.2",
98
- execa: "^6.1.0",
99
- "fs-extra": "^10.1.0",
100
- jsdom: "^20.0.0",
101
- rome: "^11.0.0",
102
- "simple-git-hooks": "^2.8.1",
103
- tsup: "^6.5.0",
104
- typescript: "^4.9.3",
105
- vite: "^3.0.4",
106
- vitest: "^0.25.2",
107
- web3: "^1.8.1"
108
- },
109
- license: "MIT",
110
- repository: "wagmi-dev/viem",
111
- authors: [
112
- "awkweb.eth",
113
- "jxom.eth"
114
- ],
115
- keywords: [
116
- "eth",
117
- "ethereum",
118
- "dapps",
119
- "wallet",
120
- "web3"
121
- ],
122
- "simple-git-hooks": {
123
- "pre-commit": "pnpm format & pnpm lint:fix"
124
- },
125
- pnpm: {
126
- patchedDependencies: {
127
- "vitepress@1.0.0-alpha.34": "patches/vitepress@1.0.0-alpha.34.patch"
128
- }
129
- }
130
- };
131
-
132
- // src/utils/BaseError.ts
133
- var version = process.env.TEST ? "1.0.2" : package_default.version;
134
- var BaseError = class extends Error {
135
- constructor(humanMessage, args = {}) {
136
- const details = args.cause instanceof BaseError ? args.cause.details : args.cause?.message ? args.cause.message : args.details;
137
- const docsPath = args.cause instanceof BaseError ? args.cause.docsPath || args.docsPath : args.docsPath;
138
- const message = [
139
- humanMessage,
140
- ...docsPath ? ["", `Docs: https://viem.sh${docsPath}`] : [],
141
- "",
142
- ...details ? [`Details: ${details}`] : [],
143
- `Version: viem@${version}`,
144
- ...args.cause && !(args.cause instanceof BaseError) && Object.keys(args.cause).length > 0 ? [`Internal Error: ${JSON.stringify(args.cause)}`] : []
145
- ].join("\n");
146
- super(message);
147
- __publicField(this, "humanMessage");
148
- __publicField(this, "details");
149
- __publicField(this, "docsPath");
150
- __publicField(this, "name", "ViemError");
151
- if (args.cause)
152
- this.cause = args.cause;
153
- this.details = details;
154
- this.docsPath = docsPath;
155
- this.humanMessage = humanMessage;
156
- }
157
- };
1
+ import {
2
+ AbiDecodingDataSizeInvalidError,
3
+ AbiEncodingArrayLengthMismatchError,
4
+ AbiEncodingLengthMismatchError,
5
+ AbiFunctionNotFoundError,
6
+ AbiFunctionOutputsNotFoundError,
7
+ AbiFunctionSignatureNotFoundError,
8
+ DataLengthTooLongError,
9
+ DataLengthTooShortError,
10
+ InvalidAbiDecodingTypeError,
11
+ InvalidAbiEncodingTypeError,
12
+ InvalidAddressError,
13
+ InvalidArrayError,
14
+ InvalidBytesBooleanError,
15
+ InvalidDefinitionTypeError,
16
+ InvalidHexBooleanError,
17
+ InvalidHexValueError,
18
+ OffsetOutOfBoundsError,
19
+ SizeExceedsPaddingSizeError
20
+ } from "./chunk-COHLCIQM.js";
158
21
 
159
22
  // src/utils/data/concat.ts
160
23
  function concat(values) {
@@ -233,18 +96,6 @@ function padBytes(bytes, { dir, size: size2 = 32 } = {}) {
233
96
  }
234
97
  return paddedBytes;
235
98
  }
236
- var SizeExceedsPaddingSizeError = class extends BaseError {
237
- constructor({
238
- size: size2,
239
- targetSize,
240
- type
241
- }) {
242
- super(
243
- `${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size2}) exceeds padding size (${targetSize}).`
244
- );
245
- __publicField(this, "name", "SizeExceedsPaddingSizeError");
246
- }
247
- };
248
99
 
249
100
  // src/utils/data/trim.ts
250
101
  function trim(hexOrBytes, { dir = "left" } = {}) {
@@ -457,14 +308,6 @@ function hexToString(hex) {
457
308
  const bytes = hexToBytes(hex);
458
309
  return new TextDecoder().decode(bytes);
459
310
  }
460
- var InvalidHexBooleanError = class extends BaseError {
461
- constructor(hex) {
462
- super(
463
- `Hex value "${hex}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`
464
- );
465
- __publicField(this, "name", "InvalidHexBooleanError");
466
- }
467
- };
468
311
 
469
312
  // src/utils/encoding/decodeBytes.ts
470
313
  function decodeBytes(bytes, to) {
@@ -494,14 +337,6 @@ function bytesToNumber(bytes) {
494
337
  function bytesToString(bytes) {
495
338
  return new TextDecoder().decode(bytes);
496
339
  }
497
- var InvalidBytesBooleanError = class extends BaseError {
498
- constructor(bytes) {
499
- super(
500
- `Bytes value "${bytes}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`
501
- );
502
- __publicField(this, "name", "InvalidBytesBooleanError");
503
- }
504
- };
505
340
 
506
341
  // src/utils/encoding/decodeRlp.ts
507
342
  function decodeRlp(value, to) {
@@ -583,38 +418,6 @@ function rlpToBytes(bytes, offset = 0) {
583
418
  }
584
419
  return [result, consumed];
585
420
  }
586
- var DataLengthTooLongError = class extends BaseError {
587
- constructor({ consumed, length }) {
588
- super(
589
- `Consumed bytes (${consumed}) is shorter than data length (${length - 1}).`
590
- );
591
- __publicField(this, "name", "DataLengthTooLongError");
592
- }
593
- };
594
- var DataLengthTooShortError = class extends BaseError {
595
- constructor({ length, dataLength }) {
596
- super(
597
- `Data length (${dataLength - 1}) is shorter than prefix length (${length - 1}).`
598
- );
599
- __publicField(this, "name", "DataLengthTooShortError");
600
- }
601
- };
602
- var InvalidHexValueError = class extends BaseError {
603
- constructor(value) {
604
- super(
605
- `Hex value "${value}" is an odd length (${value.length}). It must be an even length.`
606
- );
607
- __publicField(this, "name", "InvalidHexValueError");
608
- }
609
- };
610
- var OffsetOutOfBoundsError = class extends BaseError {
611
- constructor({ nextOffset, offset }) {
612
- super(
613
- `Next offset (${nextOffset}) is greater than previous offset + consumed bytes (${offset})`
614
- );
615
- __publicField(this, "name", "OffsetOutOfBoundsError");
616
- }
617
- };
618
421
 
619
422
  // src/utils/solidity.ts
620
423
  var paramsRegex = /((function|event)\s)?(.*)(\((.*)\))/;
@@ -688,12 +491,6 @@ function getAddress(address) {
688
491
  throw new InvalidAddressError({ address });
689
492
  return checksumAddress(address);
690
493
  }
691
- var InvalidAddressError = class extends BaseError {
692
- constructor({ address }) {
693
- super(`Address "${address}" is invalid.`);
694
- __publicField(this, "name", "InvalidAddressError");
695
- }
696
- };
697
494
 
698
495
  // src/utils/address/getContractAddress.ts
699
496
  function getContractAddress(opts) {
@@ -825,6 +622,9 @@ function encodeParams(preparedParams) {
825
622
  }
826
623
  return concat([...staticParams, ...dynamicParams]);
827
624
  }
625
+ function encodeAddress(value) {
626
+ return { dynamic: false, encoded: padHex(value.toLowerCase()) };
627
+ }
828
628
  function encodeArray(value, {
829
629
  length,
830
630
  param
@@ -863,27 +663,6 @@ function encodeArray(value, {
863
663
  encoded: concat(preparedParams.map(({ encoded }) => encoded))
864
664
  };
865
665
  }
866
- function encodeTuple(value, { param }) {
867
- let dynamic = false;
868
- let preparedParams = [];
869
- for (let i = 0; i < param.components.length; i++) {
870
- const param_ = param.components[i];
871
- const index = Array.isArray(value) ? i : param_.name;
872
- const preparedParam = prepareParam({
873
- param: param_,
874
- value: value[index]
875
- });
876
- preparedParams.push(preparedParam);
877
- dynamic = preparedParam.dynamic;
878
- }
879
- return {
880
- dynamic,
881
- encoded: dynamic ? encodeParams(preparedParams) : concat(preparedParams.map(({ encoded }) => encoded))
882
- };
883
- }
884
- function encodeAddress(value) {
885
- return { dynamic: false, encoded: padHex(value.toLowerCase()) };
886
- }
887
666
  function encodeBytes2(value, { param }) {
888
667
  const [_, size_] = param.type.split("bytes");
889
668
  if (!size_)
@@ -917,59 +696,28 @@ function encodeString(value) {
917
696
  ])
918
697
  };
919
698
  }
699
+ function encodeTuple(value, { param }) {
700
+ let dynamic = false;
701
+ let preparedParams = [];
702
+ for (let i = 0; i < param.components.length; i++) {
703
+ const param_ = param.components[i];
704
+ const index = Array.isArray(value) ? i : param_.name;
705
+ const preparedParam = prepareParam({
706
+ param: param_,
707
+ value: value[index]
708
+ });
709
+ preparedParams.push(preparedParam);
710
+ dynamic = preparedParam.dynamic;
711
+ }
712
+ return {
713
+ dynamic,
714
+ encoded: dynamic ? encodeParams(preparedParams) : concat(preparedParams.map(({ encoded }) => encoded))
715
+ };
716
+ }
920
717
  function getArrayComponents(type) {
921
718
  const matches = type.match(/^(.*)\[(\d+)?\]$/);
922
719
  return matches ? [matches[2] ? Number(matches[2]) : null, matches[1]] : void 0;
923
720
  }
924
- var AbiEncodingArrayLengthMismatchError = class extends BaseError {
925
- constructor({
926
- expectedLength,
927
- givenLength,
928
- type
929
- }) {
930
- super(
931
- [
932
- `ABI encoding array length mismatch for type ${type}.`,
933
- `Expected length: ${expectedLength}`,
934
- `Given length: ${givenLength}`
935
- ].join("\n")
936
- );
937
- __publicField(this, "name", "AbiEncodingArrayLengthMismatchError");
938
- }
939
- };
940
- var AbiEncodingLengthMismatchError = class extends BaseError {
941
- constructor({
942
- expectedLength,
943
- givenLength
944
- }) {
945
- super(
946
- [
947
- "ABI encoding params/values length mismatch.",
948
- `Expected length (params): ${expectedLength}`,
949
- `Given length (values): ${givenLength}`
950
- ].join("\n")
951
- );
952
- __publicField(this, "name", "AbiEncodingLengthMismatchError");
953
- }
954
- };
955
- var InvalidAbiEncodingTypeError = class extends BaseError {
956
- constructor(type) {
957
- super(
958
- [
959
- `Type "${type}" is not a valid encoding type.`,
960
- "Please provide a valid ABI type."
961
- ].join("\n"),
962
- { docsPath: "/docs/contract/encodeAbi#params" }
963
- );
964
- __publicField(this, "name", "InvalidAbiEncodingType");
965
- }
966
- };
967
- var InvalidArrayError = class extends BaseError {
968
- constructor(value) {
969
- super([`Value "${value}" is not a valid array.`].join("\n"));
970
- __publicField(this, "name", "InvalidArrayError");
971
- }
972
- };
973
721
 
974
722
  // src/utils/abi/decodeAbi.ts
975
723
  function decodeAbi({
@@ -1032,6 +780,9 @@ function decodeParam({
1032
780
  }
1033
781
  throw new InvalidAbiDecodingTypeError(param.type);
1034
782
  }
783
+ function decodeAddress(value) {
784
+ return { consumed: 32, value: checksumAddress(trim(value)) };
785
+ }
1035
786
  function decodeArray(data, {
1036
787
  param,
1037
788
  length,
@@ -1083,9 +834,6 @@ function decodeArray(data, {
1083
834
  }
1084
835
  return { value, consumed };
1085
836
  }
1086
- function decodeAddress(value) {
1087
- return { consumed: 32, value: checksumAddress(trim(value)) };
1088
- }
1089
837
  function decodeBool(value) {
1090
838
  return { consumed: 32, value: hexToBool(value) };
1091
839
  }
@@ -1161,29 +909,6 @@ function hasDynamicChild(param) {
1161
909
  return true;
1162
910
  return false;
1163
911
  }
1164
- var AbiDecodingDataSizeInvalidError = class extends BaseError {
1165
- constructor(size2) {
1166
- super(
1167
- [
1168
- `Data size of ${size2} bytes is invalid.`,
1169
- "Size must be in increments of 32 bytes (size % 32 === 0)."
1170
- ].join("\n")
1171
- );
1172
- __publicField(this, "name", "AbiDecodingDataSizeInvalidError");
1173
- }
1174
- };
1175
- var InvalidAbiDecodingTypeError = class extends BaseError {
1176
- constructor(type) {
1177
- super(
1178
- [
1179
- `Type "${type}" is not a valid decoding type.`,
1180
- "Please provide a valid ABI type."
1181
- ].join("\n"),
1182
- { docsPath: "/docs/contract/decodeAbi#params" }
1183
- );
1184
- __publicField(this, "name", "InvalidAbiDecodingType");
1185
- }
1186
- };
1187
912
 
1188
913
  // src/utils/abi/getDefinition.ts
1189
914
  function getDefinition(description) {
@@ -1204,22 +929,38 @@ function getParam(param) {
1204
929
  }
1205
930
  return param.type;
1206
931
  }
1207
- var InvalidDefinitionTypeError = class extends BaseError {
1208
- constructor(type) {
1209
- super(
1210
- [
1211
- `"${type}" is not a valid definition type.`,
1212
- 'Valid types: "function", "event", "error"'
1213
- ].join("\n"),
1214
- {
1215
- docsPath: "/docs/contract/getDefinition"
1216
- }
1217
- );
1218
- }
1219
- };
1220
932
 
1221
- // src/utils/abi/encodeFunctionParams.ts
1222
- function encodeFunctionParams({
933
+ // src/utils/abi/decodeFunctionData.ts
934
+ function decodeFunctionData({ abi, data }) {
935
+ const signature = slice(data, 0, 4);
936
+ const description = abi.find(
937
+ (x) => signature === getFunctionSignature(getDefinition(x))
938
+ );
939
+ if (!description)
940
+ throw new AbiFunctionSignatureNotFoundError(signature);
941
+ return {
942
+ functionName: description.name,
943
+ args: "inputs" in description && description.inputs && description.inputs.length > 0 ? decodeAbi({ data: slice(data, 4), params: description.inputs }) : void 0
944
+ };
945
+ }
946
+
947
+ // src/utils/abi/decodeFunctionResult.ts
948
+ function decodeFunctionResult({
949
+ abi,
950
+ functionName,
951
+ data
952
+ }) {
953
+ const description = abi.find((x) => "name" in x && x.name === functionName);
954
+ if (!description)
955
+ throw new AbiFunctionNotFoundError(functionName);
956
+ if (!("outputs" in description))
957
+ throw new AbiFunctionOutputsNotFoundError(functionName);
958
+ const values = decodeAbi({ data, params: description.outputs });
959
+ return values.length > 1 ? values : values.length === 1 ? values[0] : void 0;
960
+ }
961
+
962
+ // src/utils/abi/encodeFunctionData.ts
963
+ function encodeFunctionData({
1223
964
  abi,
1224
965
  args,
1225
966
  functionName
@@ -1235,182 +976,6 @@ function encodeFunctionParams({
1235
976
  }) : void 0;
1236
977
  return concatHex([signature, data ?? "0x"]);
1237
978
  }
1238
- var AbiFunctionNotFoundError = class extends BaseError {
1239
- constructor(functionName) {
1240
- super(
1241
- [
1242
- `Function "${functionName}" not found on ABI.`,
1243
- "Make sure you are using the correct ABI and that the function exists on it."
1244
- ].join("\n"),
1245
- {
1246
- docsPath: "/docs/contract/encodeFunctionParams"
1247
- }
1248
- );
1249
- }
1250
- };
1251
-
1252
- // src/utils/buildRequest.ts
1253
- function buildRequest(request) {
1254
- return async (args) => {
1255
- try {
1256
- return await request(args);
1257
- } catch (err_) {
1258
- let err = err_;
1259
- if (err.code === -32700)
1260
- throw new ParseRpcError(err);
1261
- if (err.code === -32600)
1262
- throw new InvalidRequestRpcError(err);
1263
- if (err.code === -32601)
1264
- throw new MethodNotFoundRpcError(err);
1265
- if (err.code === -32602)
1266
- throw new InvalidParamsRpcError(err);
1267
- if (err.code === -32603)
1268
- throw new InternalRpcError(err);
1269
- if (err.code === -32e3)
1270
- throw new InvalidInputRpcError(err);
1271
- if (err.code === -32001)
1272
- throw new ResourceNotFoundRpcError(err);
1273
- if (err.code === -32002)
1274
- throw new ResourceUnavailableRpcError(err);
1275
- if (err.code === -32003)
1276
- throw new TransactionRejectedRpcError(err);
1277
- if (err.code === -32004)
1278
- throw new MethodNotSupportedRpcError(err);
1279
- if (err.code === -32005)
1280
- throw new LimitExceededRpcError(err);
1281
- if (err.code === -32006)
1282
- throw new JsonRpcVersionUnsupportedError(err);
1283
- if (err_ instanceof BaseError)
1284
- throw err_;
1285
- throw new UnknownRpcError(err);
1286
- }
1287
- };
1288
- }
1289
- var RequestError = class extends BaseError {
1290
- constructor(err, { docsPath, humanMessage }) {
1291
- super(humanMessage, {
1292
- cause: err,
1293
- docsPath
1294
- });
1295
- this.name = err.name;
1296
- }
1297
- };
1298
- var RpcRequestError = class extends RequestError {
1299
- constructor(err, { docsPath, humanMessage }) {
1300
- super(err, { docsPath, humanMessage });
1301
- __publicField(this, "code");
1302
- this.code = err.code;
1303
- this.name = err.name;
1304
- }
1305
- };
1306
- var ParseRpcError = class extends RpcRequestError {
1307
- constructor(err) {
1308
- super(err, {
1309
- humanMessage: "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."
1310
- });
1311
- __publicField(this, "name", "ParseRpcError");
1312
- __publicField(this, "code", -32700);
1313
- }
1314
- };
1315
- var InvalidRequestRpcError = class extends RpcRequestError {
1316
- constructor(err) {
1317
- super(err, { humanMessage: "JSON is not a valid request object." });
1318
- __publicField(this, "name", "InvalidRequestRpcError");
1319
- __publicField(this, "code", -32600);
1320
- }
1321
- };
1322
- var MethodNotFoundRpcError = class extends RpcRequestError {
1323
- constructor(err) {
1324
- super(err, {
1325
- humanMessage: "The method does not exist / is not available."
1326
- });
1327
- __publicField(this, "name", "MethodNotFoundRpcError");
1328
- __publicField(this, "code", -32601);
1329
- }
1330
- };
1331
- var InvalidParamsRpcError = class extends RpcRequestError {
1332
- constructor(err) {
1333
- super(err, {
1334
- humanMessage: [
1335
- "Invalid parameters were provided to the RPC method.",
1336
- "Double check you have provided the correct parameters."
1337
- ].join("\n")
1338
- });
1339
- __publicField(this, "name", "InvalidParamsRpcError");
1340
- __publicField(this, "code", -32602);
1341
- }
1342
- };
1343
- var InternalRpcError = class extends RpcRequestError {
1344
- constructor(err) {
1345
- super(err, { humanMessage: "An internal error was received." });
1346
- __publicField(this, "name", "InternalRpcError");
1347
- __publicField(this, "code", -32603);
1348
- }
1349
- };
1350
- var InvalidInputRpcError = class extends RpcRequestError {
1351
- constructor(err) {
1352
- super(err, {
1353
- humanMessage: [
1354
- "Missing or invalid parameters.",
1355
- "Double check you have provided the correct parameters."
1356
- ].join("\n")
1357
- });
1358
- __publicField(this, "name", "InvalidInputRpcError");
1359
- __publicField(this, "code", -32e3);
1360
- }
1361
- };
1362
- var ResourceNotFoundRpcError = class extends RpcRequestError {
1363
- constructor(err) {
1364
- super(err, { humanMessage: "Requested resource not found." });
1365
- __publicField(this, "name", "ResourceNotFoundRpcError");
1366
- __publicField(this, "code", -32001);
1367
- }
1368
- };
1369
- var ResourceUnavailableRpcError = class extends RpcRequestError {
1370
- constructor(err) {
1371
- super(err, { humanMessage: "Requested resource not available." });
1372
- __publicField(this, "name", "ResourceUnavailableRpcError");
1373
- __publicField(this, "code", -32002);
1374
- }
1375
- };
1376
- var TransactionRejectedRpcError = class extends RpcRequestError {
1377
- constructor(err) {
1378
- super(err, { humanMessage: "Transaction creation failed." });
1379
- __publicField(this, "name", "TransactionRejectedRpcError");
1380
- __publicField(this, "code", -32003);
1381
- }
1382
- };
1383
- var MethodNotSupportedRpcError = class extends RpcRequestError {
1384
- constructor(err) {
1385
- super(err, { humanMessage: "Method is not implemented." });
1386
- __publicField(this, "name", "MethodNotSupportedRpcError");
1387
- __publicField(this, "code", -32004);
1388
- }
1389
- };
1390
- var LimitExceededRpcError = class extends RpcRequestError {
1391
- constructor(err) {
1392
- super(err, { humanMessage: "Request exceeds defined limit." });
1393
- __publicField(this, "name", "LimitExceededRpcError");
1394
- __publicField(this, "code", -32005);
1395
- }
1396
- };
1397
- var JsonRpcVersionUnsupportedError = class extends RpcRequestError {
1398
- constructor(err) {
1399
- super(err, {
1400
- humanMessage: "Version of JSON-RPC protocol is not supported."
1401
- });
1402
- __publicField(this, "name", "JsonRpcVersionUnsupportedError");
1403
- __publicField(this, "code", -32006);
1404
- }
1405
- };
1406
- var UnknownRpcError = class extends RequestError {
1407
- constructor(err) {
1408
- super(err, {
1409
- humanMessage: "An unknown RPC error occurred."
1410
- });
1411
- __publicField(this, "name", "UnknownRpcError");
1412
- }
1413
- };
1414
979
 
1415
980
  // src/constants.ts
1416
981
  var etherUnits = {
@@ -1538,364 +1103,6 @@ function formatTransactionRequest(transactionRequest) {
1538
1103
  };
1539
1104
  }
1540
1105
 
1541
- // src/utils/promise/withCache.ts
1542
- var promiseCache = /* @__PURE__ */ new Map();
1543
- var responseCache = /* @__PURE__ */ new Map();
1544
- function getCache(cacheKey) {
1545
- const buildCache = (cacheKey2, cache) => ({
1546
- clear: () => cache.delete(cacheKey2),
1547
- get: () => cache.get(cacheKey2),
1548
- set: (data) => cache.set(cacheKey2, data)
1549
- });
1550
- const promise = buildCache(cacheKey, promiseCache);
1551
- const response = buildCache(
1552
- cacheKey,
1553
- responseCache
1554
- );
1555
- return {
1556
- clear: () => {
1557
- promise.clear();
1558
- response.clear();
1559
- },
1560
- promise,
1561
- response
1562
- };
1563
- }
1564
- async function withCache(fn, { cacheKey, maxAge = Infinity }) {
1565
- const cache = getCache(cacheKey);
1566
- const response = cache.response.get();
1567
- if (response && maxAge > 0) {
1568
- const age = new Date().getTime() - response.created.getTime();
1569
- if (age < maxAge)
1570
- return response.data;
1571
- }
1572
- let promise = cache.promise.get();
1573
- if (!promise) {
1574
- promise = fn();
1575
- cache.promise.set(promise);
1576
- }
1577
- const data = await promise;
1578
- cache.promise.clear();
1579
- cache.response.set({ created: new Date(), data });
1580
- return data;
1581
- }
1582
-
1583
- // src/utils/wait.ts
1584
- async function wait(time) {
1585
- return new Promise((res) => setTimeout(res, time));
1586
- }
1587
-
1588
- // src/utils/promise/withRetry.ts
1589
- function withRetry(fn, {
1590
- delay: delay_ = 100,
1591
- retryCount = 2,
1592
- shouldRetryOnResponse = () => false,
1593
- shouldRetryOnError = () => false
1594
- } = {}) {
1595
- return new Promise((resolve, reject) => {
1596
- const attemptRetry = async ({ count = 0 } = {}) => {
1597
- const retry = async ({ data } = {}) => {
1598
- const delay = typeof delay_ === "function" ? delay_({ count, data }) : delay_;
1599
- if (delay)
1600
- await wait(delay);
1601
- attemptRetry({ count: count + 1 });
1602
- };
1603
- try {
1604
- const data = await fn();
1605
- if (count < retryCount && await shouldRetryOnResponse({ count, data }))
1606
- return retry({ data });
1607
- resolve(data);
1608
- } catch (err) {
1609
- if (count < retryCount && await shouldRetryOnError({ count, error: err }))
1610
- return retry();
1611
- reject(err);
1612
- }
1613
- };
1614
- attemptRetry();
1615
- });
1616
- }
1617
-
1618
- // src/utils/promise/withTimeout.ts
1619
- function withTimeout(fn, {
1620
- errorInstance,
1621
- timeout,
1622
- signal
1623
- }) {
1624
- return new Promise((resolve, reject) => {
1625
- ;
1626
- (async () => {
1627
- let timeoutId;
1628
- try {
1629
- const controller = new AbortController();
1630
- if (timeout > 0) {
1631
- timeoutId = setTimeout(() => {
1632
- if (signal) {
1633
- controller.abort();
1634
- } else {
1635
- reject(errorInstance);
1636
- }
1637
- }, timeout);
1638
- }
1639
- resolve(await fn({ signal: controller?.signal }));
1640
- } catch (err) {
1641
- if (err.name === "AbortError")
1642
- reject(errorInstance);
1643
- reject(err);
1644
- } finally {
1645
- clearTimeout(timeoutId);
1646
- }
1647
- })();
1648
- });
1649
- }
1650
-
1651
- // src/utils/rpc.ts
1652
- var id = 0;
1653
- async function http(url, {
1654
- body,
1655
- retryDelay = 100,
1656
- retryCount = 2,
1657
- timeout = 0
1658
- }) {
1659
- const response = await withRetry(
1660
- () => withTimeout(
1661
- async ({ signal }) => {
1662
- const response2 = await fetch(url, {
1663
- headers: {
1664
- "Content-Type": "application/json"
1665
- },
1666
- method: "POST",
1667
- body: JSON.stringify({ jsonrpc: "2.0", id: id++, ...body }),
1668
- signal: timeout > 0 ? signal : void 0
1669
- });
1670
- return response2;
1671
- },
1672
- {
1673
- errorInstance: new TimeoutError({ body, url }),
1674
- timeout,
1675
- signal: true
1676
- }
1677
- ),
1678
- {
1679
- delay: ({ count, data: data2 }) => {
1680
- const retryAfter = data2?.headers.get("Retry-After");
1681
- if (retryAfter?.match(/\d/))
1682
- return parseInt(retryAfter) * 1e3;
1683
- return ~~((Math.random() + 0.5) * (1 << count)) * retryDelay;
1684
- },
1685
- retryCount,
1686
- shouldRetryOnResponse: async ({ data: data2 }) => {
1687
- if (data2.status >= 500)
1688
- return true;
1689
- if ([408, 413, 429].includes(data2.status))
1690
- return true;
1691
- return false;
1692
- }
1693
- }
1694
- );
1695
- let data;
1696
- if (response.headers.get("Content-Type")?.startsWith("application/json")) {
1697
- data = await response.json();
1698
- } else {
1699
- data = await response.text();
1700
- }
1701
- if (!response.ok) {
1702
- throw new HttpRequestError({
1703
- body,
1704
- details: JSON.stringify(data.error) || response.statusText,
1705
- status: response.status,
1706
- url
1707
- });
1708
- }
1709
- if (data.error) {
1710
- throw new RpcError({ body, error: data.error, url });
1711
- }
1712
- return data;
1713
- }
1714
- var sockets = /* @__PURE__ */ new Map();
1715
- async function getSocket(url_) {
1716
- const url = new URL(url_);
1717
- const urlKey = url.toString();
1718
- let socket = sockets.get(urlKey);
1719
- if (socket)
1720
- return socket;
1721
- const webSocket2 = new WebSocket(url);
1722
- const requests = /* @__PURE__ */ new Map();
1723
- const subscriptions = /* @__PURE__ */ new Map();
1724
- const onMessage = ({ data }) => {
1725
- const message = JSON.parse(data);
1726
- const isSubscription = message.method === "eth_subscription";
1727
- const id2 = isSubscription ? message.params.subscription : message.id;
1728
- const cache = isSubscription ? subscriptions : requests;
1729
- const callback = cache.get(id2);
1730
- if (callback)
1731
- callback({ data });
1732
- if (!isSubscription)
1733
- cache.delete(id2);
1734
- };
1735
- const onClose = () => {
1736
- sockets.delete(urlKey);
1737
- webSocket2.removeEventListener("close", onClose);
1738
- webSocket2.removeEventListener("message", onMessage);
1739
- };
1740
- webSocket2.addEventListener("close", onClose);
1741
- webSocket2.addEventListener("message", onMessage);
1742
- if (webSocket2.readyState === WebSocket.CONNECTING) {
1743
- await new Promise((resolve, reject) => {
1744
- if (!webSocket2)
1745
- return;
1746
- webSocket2.onopen = resolve;
1747
- webSocket2.onerror = reject;
1748
- });
1749
- }
1750
- socket = Object.assign(webSocket2, {
1751
- requests,
1752
- subscriptions
1753
- });
1754
- sockets.set(urlKey, socket);
1755
- return socket;
1756
- }
1757
- function webSocket(socket, {
1758
- body,
1759
- onData,
1760
- onError
1761
- }) {
1762
- if (socket.readyState === socket.CLOSED || socket.readyState === socket.CLOSING)
1763
- throw new WebSocketRequestError({
1764
- body,
1765
- url: socket.url,
1766
- details: "Socket is closed."
1767
- });
1768
- const id_ = id++;
1769
- const callback = ({ data }) => {
1770
- const message = JSON.parse(data);
1771
- if (typeof message.id === "number" && id_ !== message.id)
1772
- return;
1773
- if (message.error) {
1774
- onError?.(new RpcError({ body, error: message.error, url: socket.url }));
1775
- } else {
1776
- onData?.(message);
1777
- }
1778
- if (body.method === "eth_subscribe" && typeof message.result === "string") {
1779
- socket.subscriptions.set(message.result, callback);
1780
- }
1781
- if (body.method === "eth_unsubscribe") {
1782
- socket.subscriptions.delete(body.params?.[0]);
1783
- }
1784
- };
1785
- socket.requests.set(id_, callback);
1786
- socket.send(JSON.stringify({ jsonrpc: "2.0", ...body, id: id_ }));
1787
- return socket;
1788
- }
1789
- async function webSocketAsync(socket, {
1790
- body,
1791
- timeout = 0
1792
- }) {
1793
- return withTimeout(
1794
- () => new Promise(
1795
- (onData, onError) => rpc.webSocket(socket, {
1796
- body,
1797
- onData,
1798
- onError
1799
- })
1800
- ),
1801
- {
1802
- errorInstance: new TimeoutError({ body, url: socket.url }),
1803
- timeout
1804
- }
1805
- );
1806
- }
1807
- var rpc = {
1808
- http,
1809
- webSocket,
1810
- webSocketAsync
1811
- };
1812
- var HttpRequestError = class extends BaseError {
1813
- constructor({
1814
- body,
1815
- details,
1816
- status,
1817
- url
1818
- }) {
1819
- super(
1820
- [
1821
- "HTTP request failed.",
1822
- "",
1823
- `Status: ${status}`,
1824
- `URL: ${url}`,
1825
- `Request body: ${JSON.stringify(body)}`
1826
- ].join("\n"),
1827
- {
1828
- details
1829
- }
1830
- );
1831
- __publicField(this, "name", "HttpRequestError");
1832
- __publicField(this, "status");
1833
- this.status = status;
1834
- }
1835
- };
1836
- var WebSocketRequestError = class extends BaseError {
1837
- constructor({
1838
- body,
1839
- details,
1840
- url
1841
- }) {
1842
- super(
1843
- [
1844
- "WebSocket request failed.",
1845
- "",
1846
- `URL: ${url}`,
1847
- `Request body: ${JSON.stringify(body)}`
1848
- ].join("\n"),
1849
- {
1850
- details
1851
- }
1852
- );
1853
- __publicField(this, "name", "WebSocketRequestError");
1854
- }
1855
- };
1856
- var RpcError = class extends BaseError {
1857
- constructor({
1858
- body,
1859
- error,
1860
- url
1861
- }) {
1862
- super(
1863
- [
1864
- "RPC Request failed.",
1865
- "",
1866
- `URL: ${url}`,
1867
- `Request body: ${JSON.stringify(body)}`
1868
- ].join("\n"),
1869
- {
1870
- cause: error,
1871
- details: error.message
1872
- }
1873
- );
1874
- __publicField(this, "code");
1875
- __publicField(this, "name", "RpcError");
1876
- this.code = error.code;
1877
- }
1878
- };
1879
- var TimeoutError = class extends BaseError {
1880
- constructor({
1881
- body,
1882
- url
1883
- }) {
1884
- super(
1885
- [
1886
- "The request took too long to respond.",
1887
- "",
1888
- `URL: ${url}`,
1889
- `Request body: ${JSON.stringify(body)}`
1890
- ].join("\n"),
1891
- {
1892
- details: "The request timed out."
1893
- }
1894
- );
1895
- __publicField(this, "name", "TimeoutError");
1896
- }
1897
- };
1898
-
1899
1106
  // src/utils/unit/formatUnit.ts
1900
1107
  function formatUnit(value, decimals) {
1901
1108
  let display = value.toString();
@@ -1954,8 +1161,6 @@ function parseGwei(ether, unit = "wei") {
1954
1161
  }
1955
1162
 
1956
1163
  export {
1957
- __publicField,
1958
- BaseError,
1959
1164
  isBytes,
1960
1165
  isHex,
1961
1166
  pad,
@@ -2003,21 +1208,9 @@ export {
2003
1208
  isAddressEqual,
2004
1209
  encodeAbi,
2005
1210
  decodeAbi,
2006
- encodeFunctionParams,
2007
- buildRequest,
2008
- RpcRequestError,
2009
- ParseRpcError,
2010
- InvalidRequestRpcError,
2011
- MethodNotFoundRpcError,
2012
- InvalidParamsRpcError,
2013
- InternalRpcError,
2014
- InvalidInputRpcError,
2015
- ResourceNotFoundRpcError,
2016
- ResourceUnavailableRpcError,
2017
- TransactionRejectedRpcError,
2018
- MethodNotSupportedRpcError,
2019
- LimitExceededRpcError,
2020
- JsonRpcVersionUnsupportedError,
1211
+ decodeFunctionData,
1212
+ decodeFunctionResult,
1213
+ encodeFunctionData,
2021
1214
  etherUnits,
2022
1215
  gweiUnits,
2023
1216
  weiUnits,
@@ -2029,14 +1222,6 @@ export {
2029
1222
  formatLog,
2030
1223
  formatTransactionReceipt,
2031
1224
  formatTransactionRequest,
2032
- getCache,
2033
- withCache,
2034
- wait,
2035
- getSocket,
2036
- rpc,
2037
- HttpRequestError,
2038
- RpcError,
2039
- TimeoutError,
2040
1225
  formatUnit,
2041
1226
  formatEther,
2042
1227
  formatGwei,