viem 0.0.1-alpha.1 → 0.0.1-alpha.3

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,22 @@
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.1",
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
+ AbiFunctionSignatureNotFoundError,
7
+ DataLengthTooLongError,
8
+ DataLengthTooShortError,
9
+ InvalidAbiDecodingTypeError,
10
+ InvalidAbiEncodingTypeError,
11
+ InvalidAddressError,
12
+ InvalidArrayError,
13
+ InvalidBytesBooleanError,
14
+ InvalidDefinitionTypeError,
15
+ InvalidHexBooleanError,
16
+ InvalidHexValueError,
17
+ OffsetOutOfBoundsError,
18
+ SizeExceedsPaddingSizeError
19
+ } from "./chunk-WZITKXV3.js";
158
20
 
159
21
  // src/utils/data/concat.ts
160
22
  function concat(values) {
@@ -233,18 +95,6 @@ function padBytes(bytes, { dir, size: size2 = 32 } = {}) {
233
95
  }
234
96
  return paddedBytes;
235
97
  }
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
98
 
249
99
  // src/utils/data/trim.ts
250
100
  function trim(hexOrBytes, { dir = "left" } = {}) {
@@ -457,14 +307,6 @@ function hexToString(hex) {
457
307
  const bytes = hexToBytes(hex);
458
308
  return new TextDecoder().decode(bytes);
459
309
  }
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
310
 
469
311
  // src/utils/encoding/decodeBytes.ts
470
312
  function decodeBytes(bytes, to) {
@@ -494,14 +336,6 @@ function bytesToNumber(bytes) {
494
336
  function bytesToString(bytes) {
495
337
  return new TextDecoder().decode(bytes);
496
338
  }
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
339
 
506
340
  // src/utils/encoding/decodeRlp.ts
507
341
  function decodeRlp(value, to) {
@@ -583,38 +417,6 @@ function rlpToBytes(bytes, offset = 0) {
583
417
  }
584
418
  return [result, consumed];
585
419
  }
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
420
 
619
421
  // src/utils/solidity.ts
620
422
  var paramsRegex = /((function|event)\s)?(.*)(\((.*)\))/;
@@ -665,7 +467,7 @@ function hashFunction(def) {
665
467
  var getEventSignature = (event) => hashFunction(event);
666
468
 
667
469
  // src/utils/hash/getFunctionSignature.ts
668
- var getFunctionSignature = (fn) => hashFunction(fn).slice(0, 10);
470
+ var getFunctionSignature = (fn) => slice(hashFunction(fn), 0, 4);
669
471
 
670
472
  // src/utils/address/getAddress.ts
671
473
  var addressRegex = /^(0x)?[a-fA-F0-9]{40}$/;
@@ -688,12 +490,6 @@ function getAddress(address) {
688
490
  throw new InvalidAddressError({ address });
689
491
  return checksumAddress(address);
690
492
  }
691
- var InvalidAddressError = class extends BaseError {
692
- constructor({ address }) {
693
- super(`Address "${address}" is invalid.`);
694
- __publicField(this, "name", "InvalidAddressError");
695
- }
696
- };
697
493
 
698
494
  // src/utils/address/getContractAddress.ts
699
495
  function getContractAddress(opts) {
@@ -754,7 +550,10 @@ function encodeAbi({
754
550
  givenLength: values.length
755
551
  });
756
552
  const preparedParams = prepareParams({ params, values });
757
- return encodeParams(preparedParams);
553
+ const data = encodeParams(preparedParams);
554
+ if (data.length === 0)
555
+ return void 0;
556
+ return data;
758
557
  }
759
558
  function prepareParams({
760
559
  params,
@@ -822,6 +621,9 @@ function encodeParams(preparedParams) {
822
621
  }
823
622
  return concat([...staticParams, ...dynamicParams]);
824
623
  }
624
+ function encodeAddress(value) {
625
+ return { dynamic: false, encoded: padHex(value.toLowerCase()) };
626
+ }
825
627
  function encodeArray(value, {
826
628
  length,
827
629
  param
@@ -860,27 +662,6 @@ function encodeArray(value, {
860
662
  encoded: concat(preparedParams.map(({ encoded }) => encoded))
861
663
  };
862
664
  }
863
- function encodeTuple(value, { param }) {
864
- let dynamic = false;
865
- let preparedParams = [];
866
- for (let i = 0; i < param.components.length; i++) {
867
- const param_ = param.components[i];
868
- const index = Array.isArray(value) ? i : param_.name;
869
- const preparedParam = prepareParam({
870
- param: param_,
871
- value: value[index]
872
- });
873
- preparedParams.push(preparedParam);
874
- dynamic = preparedParam.dynamic;
875
- }
876
- return {
877
- dynamic,
878
- encoded: dynamic ? encodeParams(preparedParams) : concat(preparedParams.map(({ encoded }) => encoded))
879
- };
880
- }
881
- function encodeAddress(value) {
882
- return { dynamic: false, encoded: padHex(value.toLowerCase()) };
883
- }
884
665
  function encodeBytes2(value, { param }) {
885
666
  const [_, size_] = param.type.split("bytes");
886
667
  if (!size_)
@@ -914,59 +695,28 @@ function encodeString(value) {
914
695
  ])
915
696
  };
916
697
  }
698
+ function encodeTuple(value, { param }) {
699
+ let dynamic = false;
700
+ let preparedParams = [];
701
+ for (let i = 0; i < param.components.length; i++) {
702
+ const param_ = param.components[i];
703
+ const index = Array.isArray(value) ? i : param_.name;
704
+ const preparedParam = prepareParam({
705
+ param: param_,
706
+ value: value[index]
707
+ });
708
+ preparedParams.push(preparedParam);
709
+ dynamic = preparedParam.dynamic;
710
+ }
711
+ return {
712
+ dynamic,
713
+ encoded: dynamic ? encodeParams(preparedParams) : concat(preparedParams.map(({ encoded }) => encoded))
714
+ };
715
+ }
917
716
  function getArrayComponents(type) {
918
717
  const matches = type.match(/^(.*)\[(\d+)?\]$/);
919
718
  return matches ? [matches[2] ? Number(matches[2]) : null, matches[1]] : void 0;
920
719
  }
921
- var AbiEncodingArrayLengthMismatchError = class extends BaseError {
922
- constructor({
923
- expectedLength,
924
- givenLength,
925
- type
926
- }) {
927
- super(
928
- [
929
- `ABI encoding array length mismatch for type ${type}.`,
930
- `Expected length: ${expectedLength}`,
931
- `Given length: ${givenLength}`
932
- ].join("\n")
933
- );
934
- __publicField(this, "name", "AbiEncodingArrayLengthMismatchError");
935
- }
936
- };
937
- var AbiEncodingLengthMismatchError = class extends BaseError {
938
- constructor({
939
- expectedLength,
940
- givenLength
941
- }) {
942
- super(
943
- [
944
- "ABI encoding params/values length mismatch.",
945
- `Expected length (params): ${expectedLength}`,
946
- `Given length (values): ${givenLength}`
947
- ].join("\n")
948
- );
949
- __publicField(this, "name", "AbiEncodingLengthMismatchError");
950
- }
951
- };
952
- var InvalidAbiEncodingTypeError = class extends BaseError {
953
- constructor(type) {
954
- super(
955
- [
956
- `Type "${type}" is not a valid encoding type.`,
957
- "Please provide a valid ABI type."
958
- ].join("\n"),
959
- { docsPath: "/docs/contract/encodeAbi#params" }
960
- );
961
- __publicField(this, "name", "InvalidAbiEncodingType");
962
- }
963
- };
964
- var InvalidArrayError = class extends BaseError {
965
- constructor(value) {
966
- super([`Value "${value}" is not a valid array.`].join("\n"));
967
- __publicField(this, "name", "InvalidArrayError");
968
- }
969
- };
970
720
 
971
721
  // src/utils/abi/decodeAbi.ts
972
722
  function decodeAbi({
@@ -1029,6 +779,9 @@ function decodeParam({
1029
779
  }
1030
780
  throw new InvalidAbiDecodingTypeError(param.type);
1031
781
  }
782
+ function decodeAddress(value) {
783
+ return { consumed: 32, value: checksumAddress(trim(value)) };
784
+ }
1032
785
  function decodeArray(data, {
1033
786
  param,
1034
787
  length,
@@ -1080,9 +833,6 @@ function decodeArray(data, {
1080
833
  }
1081
834
  return { value, consumed };
1082
835
  }
1083
- function decodeAddress(value) {
1084
- return { consumed: 32, value: checksumAddress(trim(value)) };
1085
- }
1086
836
  function decodeBool(value) {
1087
837
  return { consumed: 32, value: hexToBool(value) };
1088
838
  }
@@ -1158,192 +908,58 @@ function hasDynamicChild(param) {
1158
908
  return true;
1159
909
  return false;
1160
910
  }
1161
- var AbiDecodingDataSizeInvalidError = class extends BaseError {
1162
- constructor(size2) {
1163
- super(
1164
- [
1165
- `Data size of ${size2} bytes is invalid.`,
1166
- "Size must be in increments of 32 bytes (size % 32 === 0)."
1167
- ].join("\n")
1168
- );
1169
- __publicField(this, "name", "AbiDecodingDataSizeInvalidError");
1170
- }
1171
- };
1172
- var InvalidAbiDecodingTypeError = class extends BaseError {
1173
- constructor(type) {
1174
- super(
1175
- [
1176
- `Type "${type}" is not a valid decoding type.`,
1177
- "Please provide a valid ABI type."
1178
- ].join("\n"),
1179
- { docsPath: "/docs/contract/decodeAbi#params" }
1180
- );
1181
- __publicField(this, "name", "InvalidAbiDecodingType");
911
+
912
+ // src/utils/abi/getDefinition.ts
913
+ function getDefinition(description) {
914
+ if (description.type !== "function" && description.type !== "event" && description.type !== "error")
915
+ throw new InvalidDefinitionTypeError(description.type);
916
+ return `${description.name}(${getParams(description.inputs)})`;
917
+ }
918
+ function getParams(params) {
919
+ if (!params)
920
+ return "";
921
+ return params.map(getParam).join(",");
922
+ }
923
+ function getParam(param) {
924
+ if (param.type.startsWith("tuple")) {
925
+ return `(${getParams(
926
+ param.components
927
+ )})${param.type.slice("tuple".length)}`;
1182
928
  }
1183
- };
929
+ return param.type;
930
+ }
1184
931
 
1185
- // src/utils/buildRequest.ts
1186
- function buildRequest(request) {
1187
- return async (args) => {
1188
- try {
1189
- return await request(args);
1190
- } catch (err_) {
1191
- let err = err_;
1192
- if (err.code === -32700)
1193
- throw new ParseRpcError(err);
1194
- if (err.code === -32600)
1195
- throw new InvalidRequestRpcError(err);
1196
- if (err.code === -32601)
1197
- throw new MethodNotFoundRpcError(err);
1198
- if (err.code === -32602)
1199
- throw new InvalidParamsRpcError(err);
1200
- if (err.code === -32603)
1201
- throw new InternalRpcError(err);
1202
- if (err.code === -32e3)
1203
- throw new InvalidInputRpcError(err);
1204
- if (err.code === -32001)
1205
- throw new ResourceNotFoundRpcError(err);
1206
- if (err.code === -32002)
1207
- throw new ResourceUnavailableRpcError(err);
1208
- if (err.code === -32003)
1209
- throw new TransactionRejectedRpcError(err);
1210
- if (err.code === -32004)
1211
- throw new MethodNotSupportedRpcError(err);
1212
- if (err.code === -32005)
1213
- throw new LimitExceededRpcError(err);
1214
- if (err.code === -32006)
1215
- throw new JsonRpcVersionUnsupportedError(err);
1216
- if (err_ instanceof BaseError)
1217
- throw err_;
1218
- throw new UnknownRpcError(err);
1219
- }
932
+ // src/utils/abi/decodeFunctionData.ts
933
+ function decodeFunctionData({ abi, data }) {
934
+ const signature = slice(data, 0, 4);
935
+ const description = abi.find(
936
+ (x) => signature === getFunctionSignature(getDefinition(x))
937
+ );
938
+ if (!description)
939
+ throw new AbiFunctionSignatureNotFoundError(signature);
940
+ return {
941
+ functionName: description.name,
942
+ args: "inputs" in description && description.inputs && description.inputs.length > 0 ? decodeAbi({ data: slice(data, 4), params: description.inputs }) : void 0
1220
943
  };
1221
944
  }
1222
- var RequestError = class extends BaseError {
1223
- constructor(err, { docsPath, humanMessage }) {
1224
- super(humanMessage, {
1225
- cause: err,
1226
- docsPath
1227
- });
1228
- this.name = err.name;
1229
- }
1230
- };
1231
- var RpcRequestError = class extends RequestError {
1232
- constructor(err, { docsPath, humanMessage }) {
1233
- super(err, { docsPath, humanMessage });
1234
- __publicField(this, "code");
1235
- this.code = err.code;
1236
- this.name = err.name;
1237
- }
1238
- };
1239
- var ParseRpcError = class extends RpcRequestError {
1240
- constructor(err) {
1241
- super(err, {
1242
- humanMessage: "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."
1243
- });
1244
- __publicField(this, "name", "ParseRpcError");
1245
- __publicField(this, "code", -32700);
1246
- }
1247
- };
1248
- var InvalidRequestRpcError = class extends RpcRequestError {
1249
- constructor(err) {
1250
- super(err, { humanMessage: "JSON is not a valid request object." });
1251
- __publicField(this, "name", "InvalidRequestRpcError");
1252
- __publicField(this, "code", -32600);
1253
- }
1254
- };
1255
- var MethodNotFoundRpcError = class extends RpcRequestError {
1256
- constructor(err) {
1257
- super(err, {
1258
- humanMessage: "The method does not exist / is not available."
1259
- });
1260
- __publicField(this, "name", "MethodNotFoundRpcError");
1261
- __publicField(this, "code", -32601);
1262
- }
1263
- };
1264
- var InvalidParamsRpcError = class extends RpcRequestError {
1265
- constructor(err) {
1266
- super(err, {
1267
- humanMessage: [
1268
- "Invalid parameters were provided to the RPC method.",
1269
- "Double check you have provided the correct parameters."
1270
- ].join("\n")
1271
- });
1272
- __publicField(this, "name", "InvalidParamsRpcError");
1273
- __publicField(this, "code", -32602);
1274
- }
1275
- };
1276
- var InternalRpcError = class extends RpcRequestError {
1277
- constructor(err) {
1278
- super(err, { humanMessage: "An internal error was received." });
1279
- __publicField(this, "name", "InternalRpcError");
1280
- __publicField(this, "code", -32603);
1281
- }
1282
- };
1283
- var InvalidInputRpcError = class extends RpcRequestError {
1284
- constructor(err) {
1285
- super(err, {
1286
- humanMessage: [
1287
- "Missing or invalid parameters.",
1288
- "Double check you have provided the correct parameters."
1289
- ].join("\n")
1290
- });
1291
- __publicField(this, "name", "InvalidInputRpcError");
1292
- __publicField(this, "code", -32e3);
1293
- }
1294
- };
1295
- var ResourceNotFoundRpcError = class extends RpcRequestError {
1296
- constructor(err) {
1297
- super(err, { humanMessage: "Requested resource not found." });
1298
- __publicField(this, "name", "ResourceNotFoundRpcError");
1299
- __publicField(this, "code", -32001);
1300
- }
1301
- };
1302
- var ResourceUnavailableRpcError = class extends RpcRequestError {
1303
- constructor(err) {
1304
- super(err, { humanMessage: "Requested resource not available." });
1305
- __publicField(this, "name", "ResourceUnavailableRpcError");
1306
- __publicField(this, "code", -32002);
1307
- }
1308
- };
1309
- var TransactionRejectedRpcError = class extends RpcRequestError {
1310
- constructor(err) {
1311
- super(err, { humanMessage: "Transaction creation failed." });
1312
- __publicField(this, "name", "TransactionRejectedRpcError");
1313
- __publicField(this, "code", -32003);
1314
- }
1315
- };
1316
- var MethodNotSupportedRpcError = class extends RpcRequestError {
1317
- constructor(err) {
1318
- super(err, { humanMessage: "Method is not implemented." });
1319
- __publicField(this, "name", "MethodNotSupportedRpcError");
1320
- __publicField(this, "code", -32004);
1321
- }
1322
- };
1323
- var LimitExceededRpcError = class extends RpcRequestError {
1324
- constructor(err) {
1325
- super(err, { humanMessage: "Request exceeds defined limit." });
1326
- __publicField(this, "name", "LimitExceededRpcError");
1327
- __publicField(this, "code", -32005);
1328
- }
1329
- };
1330
- var JsonRpcVersionUnsupportedError = class extends RpcRequestError {
1331
- constructor(err) {
1332
- super(err, {
1333
- humanMessage: "Version of JSON-RPC protocol is not supported."
1334
- });
1335
- __publicField(this, "name", "JsonRpcVersionUnsupportedError");
1336
- __publicField(this, "code", -32006);
1337
- }
1338
- };
1339
- var UnknownRpcError = class extends RequestError {
1340
- constructor(err) {
1341
- super(err, {
1342
- humanMessage: "An unknown RPC error occurred."
1343
- });
1344
- __publicField(this, "name", "UnknownRpcError");
1345
- }
1346
- };
945
+
946
+ // src/utils/abi/encodeFunctionData.ts
947
+ function encodeFunctionData({
948
+ abi,
949
+ args,
950
+ functionName
951
+ }) {
952
+ const description = abi.find((x) => "name" in x && x.name === functionName);
953
+ if (!description)
954
+ throw new AbiFunctionNotFoundError(functionName);
955
+ const definition = getDefinition(description);
956
+ const signature = getFunctionSignature(definition);
957
+ const data = "inputs" in description && description.inputs ? encodeAbi({
958
+ params: description.inputs,
959
+ values: args ?? []
960
+ }) : void 0;
961
+ return concatHex([signature, data ?? "0x"]);
962
+ }
1347
963
 
1348
964
  // src/constants.ts
1349
965
  var etherUnits = {
@@ -1471,364 +1087,6 @@ function formatTransactionRequest(transactionRequest) {
1471
1087
  };
1472
1088
  }
1473
1089
 
1474
- // src/utils/promise/withCache.ts
1475
- var promiseCache = /* @__PURE__ */ new Map();
1476
- var responseCache = /* @__PURE__ */ new Map();
1477
- function getCache(cacheKey) {
1478
- const buildCache = (cacheKey2, cache) => ({
1479
- clear: () => cache.delete(cacheKey2),
1480
- get: () => cache.get(cacheKey2),
1481
- set: (data) => cache.set(cacheKey2, data)
1482
- });
1483
- const promise = buildCache(cacheKey, promiseCache);
1484
- const response = buildCache(
1485
- cacheKey,
1486
- responseCache
1487
- );
1488
- return {
1489
- clear: () => {
1490
- promise.clear();
1491
- response.clear();
1492
- },
1493
- promise,
1494
- response
1495
- };
1496
- }
1497
- async function withCache(fn, { cacheKey, maxAge = Infinity }) {
1498
- const cache = getCache(cacheKey);
1499
- const response = cache.response.get();
1500
- if (response && maxAge > 0) {
1501
- const age = new Date().getTime() - response.created.getTime();
1502
- if (age < maxAge)
1503
- return response.data;
1504
- }
1505
- let promise = cache.promise.get();
1506
- if (!promise) {
1507
- promise = fn();
1508
- cache.promise.set(promise);
1509
- }
1510
- const data = await promise;
1511
- cache.promise.clear();
1512
- cache.response.set({ created: new Date(), data });
1513
- return data;
1514
- }
1515
-
1516
- // src/utils/wait.ts
1517
- async function wait(time) {
1518
- return new Promise((res) => setTimeout(res, time));
1519
- }
1520
-
1521
- // src/utils/promise/withRetry.ts
1522
- function withRetry(fn, {
1523
- delay: delay_ = 100,
1524
- retryCount = 2,
1525
- shouldRetryOnResponse = () => false,
1526
- shouldRetryOnError = () => false
1527
- } = {}) {
1528
- return new Promise((resolve, reject) => {
1529
- const attemptRetry = async ({ count = 0 } = {}) => {
1530
- const retry = async ({ data } = {}) => {
1531
- const delay = typeof delay_ === "function" ? delay_({ count, data }) : delay_;
1532
- if (delay)
1533
- await wait(delay);
1534
- attemptRetry({ count: count + 1 });
1535
- };
1536
- try {
1537
- const data = await fn();
1538
- if (count < retryCount && await shouldRetryOnResponse({ count, data }))
1539
- return retry({ data });
1540
- resolve(data);
1541
- } catch (err) {
1542
- if (count < retryCount && await shouldRetryOnError({ count, error: err }))
1543
- return retry();
1544
- reject(err);
1545
- }
1546
- };
1547
- attemptRetry();
1548
- });
1549
- }
1550
-
1551
- // src/utils/promise/withTimeout.ts
1552
- function withTimeout(fn, {
1553
- errorInstance,
1554
- timeout,
1555
- signal
1556
- }) {
1557
- return new Promise((resolve, reject) => {
1558
- ;
1559
- (async () => {
1560
- let timeoutId;
1561
- try {
1562
- const controller = new AbortController();
1563
- if (timeout > 0) {
1564
- timeoutId = setTimeout(() => {
1565
- if (signal) {
1566
- controller.abort();
1567
- } else {
1568
- reject(errorInstance);
1569
- }
1570
- }, timeout);
1571
- }
1572
- resolve(await fn({ signal: controller?.signal }));
1573
- } catch (err) {
1574
- if (err.name === "AbortError")
1575
- reject(errorInstance);
1576
- reject(err);
1577
- } finally {
1578
- clearTimeout(timeoutId);
1579
- }
1580
- })();
1581
- });
1582
- }
1583
-
1584
- // src/utils/rpc.ts
1585
- var id = 0;
1586
- async function http(url, {
1587
- body,
1588
- retryDelay = 100,
1589
- retryCount = 2,
1590
- timeout = 0
1591
- }) {
1592
- const response = await withRetry(
1593
- () => withTimeout(
1594
- async ({ signal }) => {
1595
- const response2 = await fetch(url, {
1596
- headers: {
1597
- "Content-Type": "application/json"
1598
- },
1599
- method: "POST",
1600
- body: JSON.stringify({ jsonrpc: "2.0", id: id++, ...body }),
1601
- signal: timeout > 0 ? signal : void 0
1602
- });
1603
- return response2;
1604
- },
1605
- {
1606
- errorInstance: new TimeoutError({ body, url }),
1607
- timeout,
1608
- signal: true
1609
- }
1610
- ),
1611
- {
1612
- delay: ({ count, data: data2 }) => {
1613
- const retryAfter = data2?.headers.get("Retry-After");
1614
- if (retryAfter?.match(/\d/))
1615
- return parseInt(retryAfter) * 1e3;
1616
- return ~~((Math.random() + 0.5) * (1 << count)) * retryDelay;
1617
- },
1618
- retryCount,
1619
- shouldRetryOnResponse: async ({ data: data2 }) => {
1620
- if (data2.status >= 500)
1621
- return true;
1622
- if ([408, 413, 429].includes(data2.status))
1623
- return true;
1624
- return false;
1625
- }
1626
- }
1627
- );
1628
- let data;
1629
- if (response.headers.get("Content-Type")?.startsWith("application/json")) {
1630
- data = await response.json();
1631
- } else {
1632
- data = await response.text();
1633
- }
1634
- if (!response.ok) {
1635
- throw new HttpRequestError({
1636
- body,
1637
- details: JSON.stringify(data.error) || response.statusText,
1638
- status: response.status,
1639
- url
1640
- });
1641
- }
1642
- if (data.error) {
1643
- throw new RpcError({ body, error: data.error, url });
1644
- }
1645
- return data;
1646
- }
1647
- var sockets = /* @__PURE__ */ new Map();
1648
- async function getSocket(url_) {
1649
- const url = new URL(url_);
1650
- const urlKey = url.toString();
1651
- let socket = sockets.get(urlKey);
1652
- if (socket)
1653
- return socket;
1654
- const webSocket2 = new WebSocket(url);
1655
- const requests = /* @__PURE__ */ new Map();
1656
- const subscriptions = /* @__PURE__ */ new Map();
1657
- const onMessage = ({ data }) => {
1658
- const message = JSON.parse(data);
1659
- const isSubscription = message.method === "eth_subscription";
1660
- const id2 = isSubscription ? message.params.subscription : message.id;
1661
- const cache = isSubscription ? subscriptions : requests;
1662
- const callback = cache.get(id2);
1663
- if (callback)
1664
- callback({ data });
1665
- if (!isSubscription)
1666
- cache.delete(id2);
1667
- };
1668
- const onClose = () => {
1669
- sockets.delete(urlKey);
1670
- webSocket2.removeEventListener("close", onClose);
1671
- webSocket2.removeEventListener("message", onMessage);
1672
- };
1673
- webSocket2.addEventListener("close", onClose);
1674
- webSocket2.addEventListener("message", onMessage);
1675
- if (webSocket2.readyState === WebSocket.CONNECTING) {
1676
- await new Promise((resolve, reject) => {
1677
- if (!webSocket2)
1678
- return;
1679
- webSocket2.onopen = resolve;
1680
- webSocket2.onerror = reject;
1681
- });
1682
- }
1683
- socket = Object.assign(webSocket2, {
1684
- requests,
1685
- subscriptions
1686
- });
1687
- sockets.set(urlKey, socket);
1688
- return socket;
1689
- }
1690
- function webSocket(socket, {
1691
- body,
1692
- onData,
1693
- onError
1694
- }) {
1695
- if (socket.readyState === socket.CLOSED || socket.readyState === socket.CLOSING)
1696
- throw new WebSocketRequestError({
1697
- body,
1698
- url: socket.url,
1699
- details: "Socket is closed."
1700
- });
1701
- const id_ = id++;
1702
- const callback = ({ data }) => {
1703
- const message = JSON.parse(data);
1704
- if (typeof message.id === "number" && id_ !== message.id)
1705
- return;
1706
- if (message.error) {
1707
- onError?.(new RpcError({ body, error: message.error, url: socket.url }));
1708
- } else {
1709
- onData?.(message);
1710
- }
1711
- if (body.method === "eth_subscribe" && typeof message.result === "string") {
1712
- socket.subscriptions.set(message.result, callback);
1713
- }
1714
- if (body.method === "eth_unsubscribe") {
1715
- socket.subscriptions.delete(body.params?.[0]);
1716
- }
1717
- };
1718
- socket.requests.set(id_, callback);
1719
- socket.send(JSON.stringify({ jsonrpc: "2.0", ...body, id: id_ }));
1720
- return socket;
1721
- }
1722
- async function webSocketAsync(socket, {
1723
- body,
1724
- timeout = 0
1725
- }) {
1726
- return withTimeout(
1727
- () => new Promise(
1728
- (onData, onError) => rpc.webSocket(socket, {
1729
- body,
1730
- onData,
1731
- onError
1732
- })
1733
- ),
1734
- {
1735
- errorInstance: new TimeoutError({ body, url: socket.url }),
1736
- timeout
1737
- }
1738
- );
1739
- }
1740
- var rpc = {
1741
- http,
1742
- webSocket,
1743
- webSocketAsync
1744
- };
1745
- var HttpRequestError = class extends BaseError {
1746
- constructor({
1747
- body,
1748
- details,
1749
- status,
1750
- url
1751
- }) {
1752
- super(
1753
- [
1754
- "HTTP request failed.",
1755
- "",
1756
- `Status: ${status}`,
1757
- `URL: ${url}`,
1758
- `Request body: ${JSON.stringify(body)}`
1759
- ].join("\n"),
1760
- {
1761
- details
1762
- }
1763
- );
1764
- __publicField(this, "name", "HttpRequestError");
1765
- __publicField(this, "status");
1766
- this.status = status;
1767
- }
1768
- };
1769
- var WebSocketRequestError = class extends BaseError {
1770
- constructor({
1771
- body,
1772
- details,
1773
- url
1774
- }) {
1775
- super(
1776
- [
1777
- "WebSocket request failed.",
1778
- "",
1779
- `URL: ${url}`,
1780
- `Request body: ${JSON.stringify(body)}`
1781
- ].join("\n"),
1782
- {
1783
- details
1784
- }
1785
- );
1786
- __publicField(this, "name", "WebSocketRequestError");
1787
- }
1788
- };
1789
- var RpcError = class extends BaseError {
1790
- constructor({
1791
- body,
1792
- error,
1793
- url
1794
- }) {
1795
- super(
1796
- [
1797
- "RPC Request failed.",
1798
- "",
1799
- `URL: ${url}`,
1800
- `Request body: ${JSON.stringify(body)}`
1801
- ].join("\n"),
1802
- {
1803
- cause: error,
1804
- details: error.message
1805
- }
1806
- );
1807
- __publicField(this, "code");
1808
- __publicField(this, "name", "RpcError");
1809
- this.code = error.code;
1810
- }
1811
- };
1812
- var TimeoutError = class extends BaseError {
1813
- constructor({
1814
- body,
1815
- url
1816
- }) {
1817
- super(
1818
- [
1819
- "The request took too long to respond.",
1820
- "",
1821
- `URL: ${url}`,
1822
- `Request body: ${JSON.stringify(body)}`
1823
- ].join("\n"),
1824
- {
1825
- details: "The request timed out."
1826
- }
1827
- );
1828
- __publicField(this, "name", "TimeoutError");
1829
- }
1830
- };
1831
-
1832
1090
  // src/utils/unit/formatUnit.ts
1833
1091
  function formatUnit(value, decimals) {
1834
1092
  let display = value.toString();
@@ -1887,8 +1145,6 @@ function parseGwei(ether, unit = "wei") {
1887
1145
  }
1888
1146
 
1889
1147
  export {
1890
- __publicField,
1891
- BaseError,
1892
1148
  isBytes,
1893
1149
  isHex,
1894
1150
  pad,
@@ -1936,20 +1192,8 @@ export {
1936
1192
  isAddressEqual,
1937
1193
  encodeAbi,
1938
1194
  decodeAbi,
1939
- buildRequest,
1940
- RpcRequestError,
1941
- ParseRpcError,
1942
- InvalidRequestRpcError,
1943
- MethodNotFoundRpcError,
1944
- InvalidParamsRpcError,
1945
- InternalRpcError,
1946
- InvalidInputRpcError,
1947
- ResourceNotFoundRpcError,
1948
- ResourceUnavailableRpcError,
1949
- TransactionRejectedRpcError,
1950
- MethodNotSupportedRpcError,
1951
- LimitExceededRpcError,
1952
- JsonRpcVersionUnsupportedError,
1195
+ decodeFunctionData,
1196
+ encodeFunctionData,
1953
1197
  etherUnits,
1954
1198
  gweiUnits,
1955
1199
  weiUnits,
@@ -1961,14 +1205,6 @@ export {
1961
1205
  formatLog,
1962
1206
  formatTransactionReceipt,
1963
1207
  formatTransactionRequest,
1964
- getCache,
1965
- withCache,
1966
- wait,
1967
- getSocket,
1968
- rpc,
1969
- HttpRequestError,
1970
- RpcError,
1971
- TimeoutError,
1972
1208
  formatUnit,
1973
1209
  formatEther,
1974
1210
  formatGwei,