viem 0.2.0-canary.20230316T042447 → 0.2.0-jxom-local-accounts.20230321T210352

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 (59) hide show
  1. package/dist/abi.d.ts +3 -3
  2. package/dist/abi.js +2 -2
  3. package/dist/abi.mjs +1 -1
  4. package/dist/{chain-1b53ef88.d.ts → chain-75b0942e.d.ts} +53 -48
  5. package/dist/{chain-ec8c485d.d.ts → chain-f8db473f.d.ts} +1 -1
  6. package/dist/chains.d.ts +3 -3
  7. package/dist/chains.js +63 -63
  8. package/dist/chains.mjs +1 -1
  9. package/dist/{chunk-A5BRAPQQ.js → chunk-FHJTO6BQ.js} +1480 -1162
  10. package/dist/chunk-FHJTO6BQ.js.map +1 -0
  11. package/dist/{chunk-PLALZ2GD.mjs → chunk-IXGTN6B7.mjs} +2 -2
  12. package/dist/chunk-IXGTN6B7.mjs.map +1 -0
  13. package/dist/{chunk-GZ67J32T.js → chunk-K66BKQUH.js} +19 -19
  14. package/dist/{chunk-GZ67J32T.js.map → chunk-K66BKQUH.js.map} +1 -1
  15. package/dist/{chunk-ISLCPEI2.mjs → chunk-PB263D6W.mjs} +1768 -1450
  16. package/dist/chunk-PB263D6W.mjs.map +1 -0
  17. package/dist/contract.d.ts +8 -7
  18. package/dist/contract.js +2 -2
  19. package/dist/contract.mjs +1 -1
  20. package/dist/{createClient-a28317a9.d.ts → createClient-f87255c1.d.ts} +6 -6
  21. package/dist/{createPublicClient-75540130.d.ts → createPublicClient-62c74ebc.d.ts} +160 -206
  22. package/dist/{eip1193-4f4e240c.d.ts → eip1193-ae706fd8.d.ts} +1 -1
  23. package/dist/{encodeFunctionResult-1f324375.d.ts → encodeFunctionResult-4792a6a3.d.ts} +1 -1
  24. package/dist/{encodePacked-d5d5264a.d.ts → encodePacked-3fcdd54b.d.ts} +1 -1
  25. package/dist/ens.d.ts +5 -4
  26. package/dist/ens.js +3 -3
  27. package/dist/ens.mjs +2 -2
  28. package/dist/ethers.d.ts +4 -6
  29. package/dist/ethers.js +5 -5
  30. package/dist/ethers.js.map +1 -1
  31. package/dist/ethers.mjs +5 -5
  32. package/dist/ethers.mjs.map +1 -1
  33. package/dist/{formatAbiItem-15e8817d.d.ts → formatAbiItem-765ebc53.d.ts} +1 -1
  34. package/dist/{getAbiItem-3e809ff9.d.ts → getAbiItem-693e6e1b.d.ts} +1 -1
  35. package/dist/index.d.ts +14 -13
  36. package/dist/index.js +99 -91
  37. package/dist/index.js.map +1 -1
  38. package/dist/index.mjs +13 -5
  39. package/dist/index.mjs.map +1 -1
  40. package/dist/{parseGwei-6fff7cbe.d.ts → parseGwei-7efc43fc.d.ts} +46 -10
  41. package/dist/public.d.ts +5 -4
  42. package/dist/public.js +2 -2
  43. package/dist/public.mjs +1 -1
  44. package/dist/{test-2bd23d7e.d.ts → test-98c0b642.d.ts} +33 -32
  45. package/dist/test.d.ts +10 -10
  46. package/dist/test.js +2 -2
  47. package/dist/test.mjs +1 -1
  48. package/dist/typedData-0514bb3c.d.ts +76 -0
  49. package/dist/utils/index.d.ts +28 -18
  50. package/dist/utils/index.js +8 -2
  51. package/dist/utils/index.mjs +11 -5
  52. package/dist/wallet.d.ts +5 -4
  53. package/dist/wallet.js +2 -2
  54. package/dist/wallet.mjs +1 -1
  55. package/dist/window.d.ts +2 -2
  56. package/package.json +3 -1
  57. package/dist/chunk-A5BRAPQQ.js.map +0 -1
  58. package/dist/chunk-ISLCPEI2.mjs.map +0 -1
  59. package/dist/chunk-PLALZ2GD.mjs.map +0 -1
@@ -20,7 +20,7 @@ import "abitype";
20
20
  var package_default = {
21
21
  name: "viem",
22
22
  description: "TypeScript Interface for Ethereum",
23
- version: "0.1.20",
23
+ version: "0.1.21",
24
24
  scripts: {
25
25
  anvil: "source .env && anvil --fork-url $VITE_ANVIL_FORK_URL --fork-block-number $VITE_ANVIL_BLOCK_NUMBER --block-time $VITE_ANVIL_BLOCK_TIME",
26
26
  bench: "vitest bench --no-threads",
@@ -142,6 +142,8 @@ var package_default = {
142
142
  dependencies: {
143
143
  "@noble/hashes": "^1.1.2",
144
144
  "@noble/secp256k1": "^1.7.1",
145
+ "@scure/bip32": "^1.2.0",
146
+ "@scure/bip39": "^1.1.1",
145
147
  "@wagmi/chains": "~0.2.11",
146
148
  abitype: "~0.7.1",
147
149
  "idna-uts46-hx": "^4.1.2",
@@ -218,7 +220,9 @@ var BaseError = class extends Error {
218
220
  shortMessage || "An error occurred.",
219
221
  "",
220
222
  ...args.metaMessages ? [...args.metaMessages, ""] : [],
221
- ...docsPath6 ? [`Docs: https://viem.sh${docsPath6}.html`] : [],
223
+ ...docsPath6 ? [
224
+ `Docs: https://viem.sh${docsPath6}.html${args.docsSlug ? `#${args.docsSlug}` : ""}`
225
+ ] : [],
222
226
  ...details ? [`Details: ${details}`] : [],
223
227
  `Version: ${getVersion()}`
224
228
  ].join("\n");
@@ -519,6 +523,23 @@ var UnsupportedPackedAbiType = class extends BaseError {
519
523
  }
520
524
  };
521
525
 
526
+ // src/errors/account.ts
527
+ var AccountNotFoundError = class extends BaseError {
528
+ constructor({ docsPath: docsPath6 } = {}) {
529
+ super(
530
+ [
531
+ "Could not find an Account to execute with this Action.",
532
+ "Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the WalletClient."
533
+ ].join("\n"),
534
+ {
535
+ docsPath: docsPath6,
536
+ docsSlug: "account"
537
+ }
538
+ );
539
+ __publicField(this, "name", "AccountNotFoundError");
540
+ }
541
+ };
542
+
522
543
  // src/errors/address.ts
523
544
  var InvalidAddressError = class extends BaseError {
524
545
  constructor({ address }) {
@@ -583,1409 +604,1453 @@ var ChainMismatchError = class extends BaseError {
583
604
  __publicField(this, "name", "ChainMismatchError");
584
605
  }
585
606
  };
586
-
587
- // src/constants/abis.ts
588
- var multicall3Abi = [
589
- {
590
- inputs: [
591
- {
592
- components: [
593
- {
594
- name: "target",
595
- type: "address"
596
- },
597
- {
598
- name: "allowFailure",
599
- type: "bool"
600
- },
601
- {
602
- name: "callData",
603
- type: "bytes"
604
- }
605
- ],
606
- name: "calls",
607
- type: "tuple[]"
608
- }
609
- ],
610
- name: "aggregate3",
611
- outputs: [
612
- {
613
- components: [
614
- {
615
- name: "success",
616
- type: "bool"
617
- },
618
- {
619
- name: "returnData",
620
- type: "bytes"
621
- }
622
- ],
623
- name: "returnData",
624
- type: "tuple[]"
625
- }
626
- ],
627
- stateMutability: "view",
628
- type: "function"
629
- }
630
- ];
631
-
632
- // src/constants/solidity.ts
633
- var panicReasons = {
634
- 1: "An `assert` condition failed.",
635
- 17: "Arithmic operation resulted in underflow or overflow.",
636
- 18: "Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).",
637
- 33: "Attempted to convert to an invalid type.",
638
- 34: "Attempted to access a storage byte array that is incorrectly encoded.",
639
- 49: "Performed `.pop()` on an empty array",
640
- 50: "Array index is out of bounds.",
641
- 65: "Allocated too much memory or created an array which is too large.",
642
- 81: "Attempted to call a zero-initialized variable of internal function type."
643
- };
644
- var solidityError = {
645
- inputs: [
646
- {
647
- name: "message",
648
- type: "string"
649
- }
650
- ],
651
- name: "Error",
652
- type: "error"
653
- };
654
- var solidityPanic = {
655
- inputs: [
656
- {
657
- name: "reason",
658
- type: "uint256"
659
- }
660
- ],
661
- name: "Panic",
662
- type: "error"
663
- };
664
-
665
- // src/constants/unit.ts
666
- var etherUnits = {
667
- gwei: 9,
668
- wei: 18
669
- };
670
- var gweiUnits = {
671
- ether: -9,
672
- wei: 9
673
- };
674
- var weiUnits = {
675
- ether: -18,
676
- gwei: -9
677
- };
678
-
679
- // src/errors/transaction.ts
680
- function prettyPrint(args) {
681
- const entries = Object.entries(args).map(([key, value]) => {
682
- if (value === void 0 || value === false)
683
- return null;
684
- return [key, value];
685
- }).filter(Boolean);
686
- const maxLength = entries.reduce((acc, [key]) => Math.max(acc, key.length), 0);
687
- return entries.map(([key, value]) => ` ${`${key}:`.padEnd(maxLength + 1)} ${value}`).join("\n");
688
- }
689
- var FeeConflictError = class extends BaseError {
607
+ var ChainNotFoundError = class extends BaseError {
690
608
  constructor() {
691
609
  super(
692
610
  [
693
- "Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.",
694
- "Use `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others."
611
+ "No chain was provided to the request.",
612
+ "Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient."
695
613
  ].join("\n")
696
614
  );
697
- __publicField(this, "name", "FeeConflictError");
698
- }
699
- };
700
- var TransactionExecutionError = class extends BaseError {
701
- constructor(cause, {
702
- account,
703
- docsPath: docsPath6,
704
- chain,
705
- data,
706
- gas,
707
- gasPrice,
708
- maxFeePerGas,
709
- maxPriorityFeePerGas,
710
- nonce,
711
- to,
712
- value
713
- }) {
714
- const prettyArgs = prettyPrint({
715
- chain: chain && `${chain?.name} (id: ${chain?.id})`,
716
- from: account.address,
717
- to,
718
- value: typeof value !== "undefined" && `${formatEther(value)} ${chain?.nativeCurrency.symbol || "ETH"}`,
719
- data,
720
- gas,
721
- gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`,
722
- maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`,
723
- maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`,
724
- nonce
725
- });
726
- super(cause.shortMessage, {
727
- cause,
728
- docsPath: docsPath6,
729
- metaMessages: [
730
- ...cause.metaMessages ? [...cause.metaMessages, " "] : [],
731
- "Request Arguments:",
732
- prettyArgs
733
- ].filter(Boolean)
734
- });
735
- __publicField(this, "cause");
736
- __publicField(this, "name", "TransactionExecutionError");
737
- this.cause = cause;
738
- }
739
- };
740
- var TransactionNotFoundError = class extends BaseError {
741
- constructor({
742
- blockHash,
743
- blockNumber,
744
- blockTag,
745
- hash: hash2,
746
- index
747
- }) {
748
- let identifier = "Transaction";
749
- if (blockTag && index !== void 0)
750
- identifier = `Transaction at block time "${blockTag}" at index "${index}"`;
751
- if (blockHash && index !== void 0)
752
- identifier = `Transaction at block hash "${blockHash}" at index "${index}"`;
753
- if (blockNumber && index !== void 0)
754
- identifier = `Transaction at block number "${blockNumber}" at index "${index}"`;
755
- if (hash2)
756
- identifier = `Transaction with hash "${hash2}"`;
757
- super(`${identifier} could not be found.`);
758
- __publicField(this, "name", "TransactionNotFoundError");
615
+ __publicField(this, "name", "ChainNotFoundError");
759
616
  }
760
617
  };
761
- var TransactionReceiptNotFoundError = class extends BaseError {
762
- constructor({ hash: hash2 }) {
763
- super(
764
- `Transaction receipt with hash "${hash2}" could not be found. The Transaction may not be processed on a block yet.`
765
- );
766
- __publicField(this, "name", "TransactionReceiptNotFoundError");
618
+
619
+ // src/accounts/index.ts
620
+ import { HDKey } from "@scure/bip32";
621
+
622
+ // src/accounts/utils/parseAccount.ts
623
+ function parseAccount(account) {
624
+ if (typeof account === "string")
625
+ return { address: account, type: "json-rpc" };
626
+ return account;
627
+ }
628
+
629
+ // src/utils/data/concat.ts
630
+ function concat(values) {
631
+ if (typeof values[0] === "string")
632
+ return concatHex(values);
633
+ return concatBytes(values);
634
+ }
635
+ function concatBytes(values) {
636
+ let length = 0;
637
+ for (const arr of values) {
638
+ length += arr.length;
767
639
  }
768
- };
769
- var WaitForTransactionReceiptTimeoutError = class extends BaseError {
770
- constructor({ hash: hash2 }) {
771
- super(
772
- `Timed out while waiting for transaction with hash "${hash2}" to be confirmed.`
773
- );
774
- __publicField(this, "name", "WaitForTransactionReceiptTimeoutError");
640
+ const result = new Uint8Array(length);
641
+ let offset = 0;
642
+ for (const arr of values) {
643
+ result.set(arr, offset);
644
+ offset += arr.length;
775
645
  }
776
- };
646
+ return result;
647
+ }
648
+ function concatHex(values) {
649
+ return `0x${values.reduce(
650
+ (acc, x) => acc + x.replace("0x", ""),
651
+ ""
652
+ )}`;
653
+ }
777
654
 
778
- // src/errors/contract.ts
779
- var CallExecutionError = class extends BaseError {
780
- constructor(cause, {
781
- account,
782
- docsPath: docsPath6,
783
- chain,
784
- data,
785
- gas,
786
- gasPrice,
787
- maxFeePerGas,
788
- maxPriorityFeePerGas,
789
- nonce,
790
- to,
791
- value
792
- }) {
793
- const prettyArgs = prettyPrint({
794
- from: account?.address,
795
- to,
796
- value: typeof value !== "undefined" && `${formatEther(value)} ${chain?.nativeCurrency.symbol || "ETH"}`,
797
- data,
798
- gas,
799
- gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`,
800
- maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`,
801
- maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`,
802
- nonce
803
- });
804
- super(cause.shortMessage, {
805
- cause,
806
- docsPath: docsPath6,
807
- metaMessages: [
808
- ...cause.metaMessages ? [...cause.metaMessages, " "] : [],
809
- "Raw Call Arguments:",
810
- prettyArgs
811
- ].filter(Boolean)
812
- });
813
- __publicField(this, "cause");
814
- __publicField(this, "name", "CallExecutionError");
815
- this.cause = cause;
816
- }
817
- };
818
- var ContractFunctionExecutionError = class extends BaseError {
819
- constructor(cause, {
820
- abi,
821
- args,
822
- contractAddress,
823
- docsPath: docsPath6,
824
- functionName,
825
- sender
826
- }) {
827
- const abiItem = getAbiItem({ abi, args, name: functionName });
828
- const formattedArgs = abiItem ? formatAbiItemWithArgs({
829
- abiItem,
830
- args,
831
- includeFunctionName: false,
832
- includeName: false
833
- }) : void 0;
834
- const functionWithParams = abiItem ? formatAbiItem(abiItem, { includeName: true }) : void 0;
835
- const prettyArgs = prettyPrint({
836
- address: contractAddress && getContractAddress(contractAddress),
837
- function: functionWithParams,
838
- args: formattedArgs && formattedArgs !== "()" && `${[...Array(functionName?.length ?? 0).keys()].map(() => " ").join("")}${formattedArgs}`,
839
- sender
655
+ // src/utils/data/isBytes.ts
656
+ function isBytes(value) {
657
+ if (!value)
658
+ return false;
659
+ if (typeof value !== "object")
660
+ return false;
661
+ if (!("BYTES_PER_ELEMENT" in value))
662
+ return false;
663
+ return value.BYTES_PER_ELEMENT === 1 && value.constructor.name === "Uint8Array";
664
+ }
665
+
666
+ // src/utils/data/isHex.ts
667
+ function isHex(value) {
668
+ if (!value)
669
+ return false;
670
+ if (typeof value !== "string")
671
+ return false;
672
+ return /^0x[0-9a-fA-F]*$/.test(value);
673
+ }
674
+
675
+ // src/utils/data/pad.ts
676
+ function pad(hexOrBytes, { dir, size: size2 = 32 } = {}) {
677
+ if (typeof hexOrBytes === "string")
678
+ return padHex(hexOrBytes, { dir, size: size2 });
679
+ return padBytes(hexOrBytes, { dir, size: size2 });
680
+ }
681
+ function padHex(hex_, { dir, size: size2 = 32 } = {}) {
682
+ if (size2 === null)
683
+ return hex_;
684
+ let hex = hex_.replace("0x", "");
685
+ if (hex.length > size2 * 2)
686
+ throw new SizeExceedsPaddingSizeError({
687
+ size: Math.ceil(hex.length / 2),
688
+ targetSize: size2,
689
+ type: "hex"
840
690
  });
841
- super(
842
- cause.shortMessage || `An unknown error occurred while executing the contract function "${functionName}".`,
843
- {
844
- cause,
845
- docsPath: docsPath6,
846
- metaMessages: [
847
- ...cause.metaMessages ? [...cause.metaMessages, " "] : [],
848
- "Contract Call:",
849
- prettyArgs
850
- ].filter(Boolean)
851
- }
852
- );
853
- __publicField(this, "abi");
854
- __publicField(this, "args");
855
- __publicField(this, "cause");
856
- __publicField(this, "contractAddress");
857
- __publicField(this, "formattedArgs");
858
- __publicField(this, "functionName");
859
- __publicField(this, "sender");
860
- __publicField(this, "name", "ContractFunctionExecutionError");
861
- this.abi = abi;
862
- this.args = args;
863
- this.cause = cause;
864
- this.contractAddress = contractAddress;
865
- this.functionName = functionName;
866
- this.sender = sender;
691
+ return `0x${hex[dir === "right" ? "padEnd" : "padStart"](
692
+ size2 * 2,
693
+ "0"
694
+ )}`;
695
+ }
696
+ function padBytes(bytes, { dir, size: size2 = 32 } = {}) {
697
+ if (size2 === null)
698
+ return bytes;
699
+ if (bytes.length > size2)
700
+ throw new SizeExceedsPaddingSizeError({
701
+ size: bytes.length,
702
+ targetSize: size2,
703
+ type: "bytes"
704
+ });
705
+ const paddedBytes = new Uint8Array(size2);
706
+ for (let i = 0; i < size2; i++) {
707
+ const padEnd = dir === "right";
708
+ paddedBytes[padEnd ? i : size2 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1];
867
709
  }
868
- };
869
- var ContractFunctionRevertedError = class extends BaseError {
870
- constructor({
871
- abi,
872
- data,
873
- functionName,
874
- message
875
- }) {
876
- let decodedData = void 0;
877
- let metaMessages;
878
- let reason;
879
- if (data && data !== "0x") {
880
- decodedData = decodeErrorResult({ abi, data });
881
- const { abiItem, errorName, args: errorArgs } = decodedData;
882
- if (errorName === "Error") {
883
- reason = errorArgs[0];
884
- } else if (errorName === "Panic") {
885
- const [firstArg] = errorArgs;
886
- reason = panicReasons[firstArg];
887
- } else if (errorArgs) {
888
- const errorWithParams = abiItem ? formatAbiItem(abiItem, { includeName: true }) : void 0;
889
- const formattedArgs = abiItem ? formatAbiItemWithArgs({
890
- abiItem,
891
- args: errorArgs,
892
- includeFunctionName: false,
893
- includeName: false
894
- }) : void 0;
895
- metaMessages = [
896
- errorWithParams ? `Error: ${errorWithParams}` : "",
897
- formattedArgs && formattedArgs !== "()" ? ` ${[...Array(errorName?.length ?? 0).keys()].map(() => " ").join("")}${formattedArgs}` : ""
898
- ];
899
- }
900
- } else if (message)
901
- reason = message;
902
- super(
903
- reason ? [
904
- `The contract function "${functionName}" reverted with the following reason:`,
905
- reason
906
- ].join("\n") : `The contract function "${functionName}" reverted.`,
907
- {
908
- metaMessages
909
- }
710
+ return paddedBytes;
711
+ }
712
+
713
+ // src/utils/data/trim.ts
714
+ function trim(hexOrBytes, { dir = "left" } = {}) {
715
+ let data = typeof hexOrBytes === "string" ? hexOrBytes.replace("0x", "") : hexOrBytes;
716
+ let sliceLength = 0;
717
+ for (let i = 0; i < data.length - 1; i++) {
718
+ if (data[dir === "left" ? i : data.length - i - 1].toString() === "0")
719
+ sliceLength++;
720
+ else
721
+ break;
722
+ }
723
+ data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength);
724
+ if (typeof hexOrBytes === "string") {
725
+ if (data.length === 1 && dir === "right")
726
+ data = `${data}0`;
727
+ return `0x${data}`;
728
+ }
729
+ return data;
730
+ }
731
+
732
+ // src/utils/data/size.ts
733
+ function size(value) {
734
+ if (isHex(value))
735
+ return Math.ceil((value.length - 2) / 2);
736
+ return value.length;
737
+ }
738
+
739
+ // src/utils/data/slice.ts
740
+ function slice(value, start, end) {
741
+ if (isHex(value))
742
+ return sliceHex(value, start, end);
743
+ return sliceBytes(value, start, end);
744
+ }
745
+ function assertStartOffset(value, start) {
746
+ if (typeof start === "number" && start > 0 && start > size(value) - 1)
747
+ throw new Error(
748
+ `Slice starting at offset "${start}" is out-of-bounds (size: ${size(
749
+ value
750
+ )}).`
910
751
  );
911
- __publicField(this, "name", "ContractFunctionRevertedError");
912
- __publicField(this, "data");
913
- __publicField(this, "reason");
914
- this.reason = reason;
915
- this.data = decodedData;
752
+ }
753
+ function sliceBytes(value, start, end) {
754
+ assertStartOffset(value, start);
755
+ return value.slice(start, end);
756
+ }
757
+ function sliceHex(value_, start, end) {
758
+ assertStartOffset(value_, start);
759
+ const value = value_.replace("0x", "").slice((start ?? 0) * 2, (end ?? value_.length) * 2);
760
+ return `0x${value}`;
761
+ }
762
+
763
+ // src/utils/encoding/toHex.ts
764
+ var hexes = Array.from(
765
+ { length: 256 },
766
+ (_v, i) => i.toString(16).padStart(2, "0")
767
+ );
768
+ function boolToHex(value) {
769
+ return `0x${Number(value)}`;
770
+ }
771
+ function bytesToHex(value) {
772
+ let hex = "";
773
+ for (let i = 0; i < value.length; i++) {
774
+ hex += hexes[value[i]];
916
775
  }
917
- };
918
- var ContractFunctionZeroDataError = class extends BaseError {
919
- constructor({ functionName }) {
920
- super(`The contract function "${functionName}" returned no data ("0x").`, {
921
- metaMessages: [
922
- "This could be due to any of the following:",
923
- ` - The contract does not have the function "${functionName}",`,
924
- " - The parameters passed to the contract function may be invalid, or",
925
- " - The address is not a contract."
926
- ]
776
+ return `0x${hex}`;
777
+ }
778
+ function toHex(value) {
779
+ if (typeof value === "number" || typeof value === "bigint")
780
+ return numberToHex(value);
781
+ if (typeof value === "string") {
782
+ return stringToHex(value);
783
+ }
784
+ if (typeof value === "boolean")
785
+ return boolToHex(value);
786
+ return bytesToHex(value);
787
+ }
788
+ function numberToHex(value_, opts = {}) {
789
+ const { signed, size: size2 } = opts;
790
+ let value = BigInt(value_);
791
+ let maxValue;
792
+ if (size2) {
793
+ if (signed)
794
+ maxValue = (1n << BigInt(size2) * 8n - 1n) - 1n;
795
+ else
796
+ maxValue = 2n ** (BigInt(size2) * 8n) - 1n;
797
+ } else if (typeof value_ === "number") {
798
+ maxValue = BigInt(Number.MAX_SAFE_INTEGER);
799
+ }
800
+ const minValue = typeof maxValue === "bigint" && signed ? -maxValue - 1n : 0;
801
+ if (maxValue && value > maxValue || value < minValue) {
802
+ const suffix = typeof value_ === "bigint" ? "n" : "";
803
+ throw new IntegerOutOfRangeError({
804
+ max: maxValue ? `${maxValue}${suffix}` : void 0,
805
+ min: `${minValue}${suffix}`,
806
+ signed,
807
+ size: size2,
808
+ value: `${value_}${suffix}`
927
809
  });
928
- __publicField(this, "name", "ContractFunctionZeroDataError");
929
810
  }
930
- };
931
- var RawContractError = class extends BaseError {
932
- constructor({ data, message }) {
933
- super(message || "");
934
- __publicField(this, "code", 3);
935
- __publicField(this, "name", "RawContractError");
936
- __publicField(this, "data");
937
- this.data = data;
811
+ const hex = `0x${(signed && value < 0 ? (1n << BigInt(size2 * 8)) + BigInt(value) : value).toString(16)}`;
812
+ if (size2)
813
+ return pad(hex, { size: size2 });
814
+ return hex;
815
+ }
816
+ var encoder = new TextEncoder();
817
+ function stringToHex(value_) {
818
+ const value = encoder.encode(value_);
819
+ return toHex(value);
820
+ }
821
+
822
+ // src/utils/encoding/toBytes.ts
823
+ var encoder2 = new TextEncoder();
824
+ function toBytes(value) {
825
+ if (typeof value === "number" || typeof value === "bigint")
826
+ return numberToBytes(value);
827
+ if (typeof value === "boolean")
828
+ return boolToBytes(value);
829
+ if (value.startsWith("0x"))
830
+ return hexToBytes(value);
831
+ return stringToBytes(value);
832
+ }
833
+ function boolToBytes(value) {
834
+ const bytes = new Uint8Array(1);
835
+ bytes[0] = Number(value);
836
+ return bytes;
837
+ }
838
+ function hexToBytes(hex_) {
839
+ let hex = hex_.slice(2);
840
+ if (hex.length % 2)
841
+ hex = `0${hex}`;
842
+ const bytes = new Uint8Array(hex.length / 2);
843
+ for (let index = 0; index < bytes.length; index++) {
844
+ const start = index * 2;
845
+ const hexByte = hex.slice(start, start + 2);
846
+ const byte = Number.parseInt(hexByte, 16);
847
+ if (Number.isNaN(byte) || byte < 0)
848
+ throw new BaseError(`Invalid byte sequence ("${hexByte}" in "${hex}").`);
849
+ bytes[index] = byte;
938
850
  }
939
- };
851
+ return bytes;
852
+ }
853
+ function numberToBytes(value, opts) {
854
+ const hex = numberToHex(value, opts);
855
+ return hexToBytes(hex);
856
+ }
857
+ function stringToBytes(value) {
858
+ return encoder2.encode(value);
859
+ }
940
860
 
941
- // src/errors/data.ts
942
- var SizeExceedsPaddingSizeError = class extends BaseError {
943
- constructor({
944
- size: size2,
945
- targetSize,
946
- type
947
- }) {
948
- super(
949
- `${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size2}) exceeds padding size (${targetSize}).`
950
- );
951
- __publicField(this, "name", "SizeExceedsPaddingSizeError");
861
+ // src/utils/encoding/toRlp.ts
862
+ function toRlp(hexOrBytes, to_) {
863
+ const to = to_ || "hex";
864
+ return format(bytesToRlp(parse(hexOrBytes)), to);
865
+ }
866
+ function parse(hexOrBytes) {
867
+ if (Array.isArray(hexOrBytes))
868
+ return hexOrBytes.map(parse);
869
+ return typeof hexOrBytes === "string" ? toBytes(hexOrBytes) : hexOrBytes;
870
+ }
871
+ function format(bytes, type = "bytes") {
872
+ return type === "hex" ? bytesToHex(bytes) : bytes;
873
+ }
874
+ function bytesToRlp(bytes) {
875
+ if (Array.isArray(bytes)) {
876
+ const encoded = concat(bytes.map(bytesToRlp));
877
+ return new Uint8Array([...encodeLength(encoded.length, 192), ...encoded]);
952
878
  }
953
- };
879
+ if (bytes.length === 1 && bytes[0] < 128)
880
+ return bytes;
881
+ return new Uint8Array([...encodeLength(bytes.length, 128), ...bytes]);
882
+ }
883
+ function encodeLength(length, offset) {
884
+ if (length < 56)
885
+ return [offset + length];
886
+ return [toBytes(length).length + offset + 55, ...toBytes(length)];
887
+ }
888
+
889
+ // src/utils/encoding/fromHex.ts
890
+ function fromHex(hex, to) {
891
+ if (to === "number")
892
+ return hexToNumber(hex);
893
+ if (to === "bigint")
894
+ return hexToBigInt(hex);
895
+ if (to === "string")
896
+ return hexToString(hex);
897
+ if (to === "boolean")
898
+ return hexToBool(hex);
899
+ return hexToBytes(hex);
900
+ }
901
+ function hexToBigInt(hex, opts = {}) {
902
+ const { signed } = opts;
903
+ const value = BigInt(hex);
904
+ if (!signed)
905
+ return value;
906
+ const size2 = (hex.length - 2) / 2;
907
+ const max = (1n << BigInt(size2) * 8n - 1n) - 1n;
908
+ if (value <= max)
909
+ return value;
910
+ return value - BigInt(`0x${"f".padStart(size2 * 2, "f")}`) - 1n;
911
+ }
912
+ function hexToBool(hex) {
913
+ if (trim(hex) === "0x0")
914
+ return false;
915
+ if (trim(hex) === "0x1")
916
+ return true;
917
+ throw new InvalidHexBooleanError(hex);
918
+ }
919
+ function hexToNumber(hex, opts = {}) {
920
+ return Number(hexToBigInt(hex, opts));
921
+ }
922
+ function hexToString(hex) {
923
+ const bytes = hexToBytes(hex);
924
+ return new TextDecoder().decode(bytes);
925
+ }
926
+
927
+ // src/utils/encoding/fromBytes.ts
928
+ function fromBytes(bytes, to) {
929
+ if (to === "number")
930
+ return bytesToNumber(bytes);
931
+ if (to === "bigint")
932
+ return bytesToBigint(bytes);
933
+ if (to === "boolean")
934
+ return bytesToBool(bytes);
935
+ if (to === "string")
936
+ return bytesToString(bytes);
937
+ return bytesToHex(bytes);
938
+ }
939
+ function bytesToBigint(bytes) {
940
+ const hex = bytesToHex(bytes);
941
+ return hexToBigInt(hex);
942
+ }
943
+ function bytesToBool(bytes) {
944
+ if (bytes.length > 1 || bytes[0] > 1)
945
+ throw new InvalidBytesBooleanError(bytes);
946
+ return Boolean(bytes[0]);
947
+ }
948
+ function bytesToNumber(bytes) {
949
+ const hex = bytesToHex(bytes);
950
+ return hexToNumber(hex);
951
+ }
952
+ function bytesToString(bytes) {
953
+ return new TextDecoder().decode(bytes);
954
+ }
954
955
 
955
- // src/errors/encoding.ts
956
- var DataLengthTooLongError = class extends BaseError {
957
- constructor({ consumed, length }) {
958
- super(
959
- `Consumed bytes (${consumed}) is shorter than data length (${length - 1}).`
960
- );
961
- __publicField(this, "name", "DataLengthTooLongError");
962
- }
963
- };
964
- var DataLengthTooShortError = class extends BaseError {
965
- constructor({ length, dataLength }) {
966
- super(
967
- `Data length (${dataLength - 1}) is shorter than prefix length (${length - 1}).`
968
- );
969
- __publicField(this, "name", "DataLengthTooShortError");
970
- }
971
- };
972
- var IntegerOutOfRangeError = class extends BaseError {
973
- constructor({
974
- max,
975
- min,
976
- signed,
977
- size: size2,
978
- value
979
- }) {
980
- super(
981
- `Number "${value}" is not in safe ${size2 ? `${size2 * 8}-bit ${signed ? "signed" : "unsigned"} ` : ""}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`
982
- );
983
- __publicField(this, "name", "IntegerOutOfRangeError");
956
+ // src/utils/encoding/fromRlp.ts
957
+ function fromRlp(value, to) {
958
+ const bytes = parse2(value);
959
+ const [data, consumed] = rlpToBytes(bytes);
960
+ if (consumed < bytes.length)
961
+ throw new DataLengthTooLongError({
962
+ consumed,
963
+ length: bytes.length
964
+ });
965
+ return format2(data, to);
966
+ }
967
+ function parse2(value) {
968
+ if (typeof value === "string") {
969
+ if (value.length > 3 && value.length % 2 !== 0)
970
+ throw new InvalidHexValueError(value);
971
+ return hexToBytes(value);
984
972
  }
985
- };
986
- var InvalidBytesBooleanError = class extends BaseError {
987
- constructor(bytes) {
988
- super(
989
- `Bytes value "${bytes}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`
990
- );
991
- __publicField(this, "name", "InvalidBytesBooleanError");
973
+ return value;
974
+ }
975
+ function format2(bytes, to) {
976
+ if (Array.isArray(bytes))
977
+ return bytes.map((b) => format2(b, to));
978
+ return to === "hex" ? trim(bytesToHex(bytes)) : bytes;
979
+ }
980
+ function rlpToBytes(bytes, offset = 0) {
981
+ if (bytes.length === 0)
982
+ return [new Uint8Array([]), 0];
983
+ const prefix = bytes[offset];
984
+ if (prefix <= 127)
985
+ return [new Uint8Array([bytes[offset]]), 1];
986
+ if (prefix <= 183) {
987
+ const length2 = prefix - 128;
988
+ const offset_ = offset + 1;
989
+ if (offset_ + length2 > bytes.length)
990
+ throw new DataLengthTooShortError({
991
+ length: offset_ + length2,
992
+ dataLength: bytes.length
993
+ });
994
+ return [bytes.slice(offset_, offset_ + length2), 1 + length2];
992
995
  }
993
- };
994
- var InvalidHexBooleanError = class extends BaseError {
995
- constructor(hex) {
996
- super(
997
- `Hex value "${hex}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`
998
- );
999
- __publicField(this, "name", "InvalidHexBooleanError");
996
+ if (prefix <= 191) {
997
+ const lengthOfLength2 = prefix - 183;
998
+ const offset_ = offset + 1;
999
+ const length2 = bytesToNumber(bytes.slice(offset_, offset_ + lengthOfLength2));
1000
+ if (offset_ + lengthOfLength2 + length2 > bytes.length)
1001
+ throw new DataLengthTooShortError({
1002
+ length: lengthOfLength2 + length2,
1003
+ dataLength: bytes.length - lengthOfLength2
1004
+ });
1005
+ return [
1006
+ bytes.slice(offset_ + lengthOfLength2, offset_ + lengthOfLength2 + length2),
1007
+ 1 + lengthOfLength2 + length2
1008
+ ];
1000
1009
  }
1001
- };
1002
- var InvalidHexValueError = class extends BaseError {
1003
- constructor(value) {
1004
- super(
1005
- `Hex value "${value}" is an odd length (${value.length}). It must be an even length.`
1006
- );
1007
- __publicField(this, "name", "InvalidHexValueError");
1010
+ let lengthOfLength = 0;
1011
+ let length = prefix - 192;
1012
+ if (prefix > 247) {
1013
+ lengthOfLength = prefix - 247;
1014
+ length = bytesToNumber(bytes.slice(offset + 1, offset + 1 + lengthOfLength));
1008
1015
  }
1009
- };
1010
- var OffsetOutOfBoundsError = class extends BaseError {
1011
- constructor({ nextOffset, offset }) {
1012
- super(
1013
- `Next offset (${nextOffset}) is greater than previous offset + consumed bytes (${offset})`
1014
- );
1015
- __publicField(this, "name", "OffsetOutOfBoundsError");
1016
+ let nextOffset = offset + 1 + lengthOfLength;
1017
+ if (nextOffset > bytes.length)
1018
+ throw new DataLengthTooShortError({
1019
+ length: nextOffset,
1020
+ dataLength: bytes.length
1021
+ });
1022
+ let consumed = 1 + lengthOfLength + length;
1023
+ let result = [];
1024
+ while (nextOffset < offset + consumed) {
1025
+ const decoded = rlpToBytes(bytes, nextOffset);
1026
+ result.push(decoded[0]);
1027
+ nextOffset += decoded[1];
1028
+ if (nextOffset > offset + consumed)
1029
+ throw new OffsetOutOfBoundsError({
1030
+ nextOffset,
1031
+ offset: offset + consumed
1032
+ });
1016
1033
  }
1017
- };
1034
+ return [result, consumed];
1035
+ }
1018
1036
 
1019
- // src/errors/estimateGas.ts
1020
- var EstimateGasExecutionError = class extends BaseError {
1021
- constructor(cause, {
1022
- account,
1023
- docsPath: docsPath6,
1024
- chain,
1025
- data,
1026
- gas,
1027
- gasPrice,
1028
- maxFeePerGas,
1029
- maxPriorityFeePerGas,
1030
- nonce,
1031
- to,
1032
- value
1033
- }) {
1034
- const prettyArgs = prettyPrint({
1035
- from: account.address,
1036
- to,
1037
- value: typeof value !== "undefined" && `${formatEther(value)} ${chain?.nativeCurrency.symbol || "ETH"}`,
1038
- data,
1039
- gas,
1040
- gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`,
1041
- maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`,
1042
- maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`,
1043
- nonce
1044
- });
1045
- super(cause.shortMessage, {
1046
- cause,
1047
- docsPath: docsPath6,
1048
- metaMessages: [
1049
- ...cause.metaMessages ? [...cause.metaMessages, " "] : [],
1050
- "Estimate Gas Arguments:",
1051
- prettyArgs
1052
- ].filter(Boolean)
1053
- });
1054
- __publicField(this, "cause");
1055
- __publicField(this, "name", "EstimateGasExecutionError");
1056
- this.cause = cause;
1037
+ // src/utils/contract/extractFunctionParts.ts
1038
+ var paramsRegex = /((function|event)\s)?(.*)(\((.*)\))/;
1039
+ function extractFunctionParts(def) {
1040
+ const parts = def.match(paramsRegex);
1041
+ const type = parts?.[2] || void 0;
1042
+ const name = parts?.[3];
1043
+ const params = parts?.[5] || void 0;
1044
+ return { type, name, params };
1045
+ }
1046
+ function extractFunctionName(def) {
1047
+ return extractFunctionParts(def).name;
1048
+ }
1049
+ function extractFunctionParams(def) {
1050
+ const params = extractFunctionParts(def).params;
1051
+ const splitParams = params?.split(",").map((x) => x.trim().split(" "));
1052
+ return splitParams?.map((param) => ({
1053
+ type: param[0],
1054
+ name: param[1] === "indexed" ? param[2] : param[1],
1055
+ ...param[1] === "indexed" ? { indexed: true } : {}
1056
+ }));
1057
+ }
1058
+ function extractFunctionType(def) {
1059
+ return extractFunctionParts(def).type;
1060
+ }
1061
+
1062
+ // src/utils/hash/keccak256.ts
1063
+ import { keccak_256 } from "@noble/hashes/sha3";
1064
+ function keccak256(value, to_) {
1065
+ const to = to_ || "hex";
1066
+ const bytes = keccak_256(isHex(value) ? toBytes(value) : value);
1067
+ if (to === "bytes")
1068
+ return bytes;
1069
+ return toHex(bytes);
1070
+ }
1071
+
1072
+ // src/utils/hash/hashFunction.ts
1073
+ var hash = (value) => keccak256(toBytes(value));
1074
+ function hashFunction(def) {
1075
+ const name = extractFunctionName(def);
1076
+ const params = extractFunctionParams(def);
1077
+ if (!params || params.length === 0)
1078
+ return hash(def.replace(/ /g, ""));
1079
+ return hash(`${name}(${params.map(({ type }) => type).join(",")})`);
1080
+ }
1081
+
1082
+ // src/utils/hash/getEventSelector.ts
1083
+ var getEventSelector = (event) => hashFunction(event);
1084
+
1085
+ // src/utils/hash/getFunctionSelector.ts
1086
+ var getFunctionSelector = (fn) => slice(hashFunction(fn), 0, 4);
1087
+
1088
+ // src/utils/address/isAddress.ts
1089
+ var addressRegex = /^0x[a-fA-F0-9]{40}$/;
1090
+ function isAddress(address) {
1091
+ return addressRegex.test(address);
1092
+ }
1093
+
1094
+ // src/utils/address/getAddress.ts
1095
+ function checksumAddress(address_) {
1096
+ const hexAddress = address_.substring(2).toLowerCase();
1097
+ const hash2 = keccak256(stringToBytes(hexAddress), "bytes");
1098
+ let address = hexAddress.split("");
1099
+ for (let i = 0; i < 40; i += 2) {
1100
+ if (hash2[i >> 1] >> 4 >= 8 && address[i]) {
1101
+ address[i] = address[i].toUpperCase();
1102
+ }
1103
+ if ((hash2[i >> 1] & 15) >= 8 && address[i + 1]) {
1104
+ address[i + 1] = address[i + 1].toUpperCase();
1105
+ }
1057
1106
  }
1058
- };
1107
+ return `0x${address.join("")}`;
1108
+ }
1109
+ function getAddress(address) {
1110
+ if (!isAddress(address))
1111
+ throw new InvalidAddressError({ address });
1112
+ return checksumAddress(address);
1113
+ }
1114
+
1115
+ // src/utils/address/getContractAddress.ts
1116
+ function getContractAddress2(opts) {
1117
+ if (opts.opcode === "CREATE2")
1118
+ return getCreate2Address(opts);
1119
+ return getCreateAddress(opts);
1120
+ }
1121
+ function getCreateAddress(opts) {
1122
+ const from = toBytes(getAddress(opts.from));
1123
+ let nonce = toBytes(opts.nonce);
1124
+ if (nonce[0] === 0)
1125
+ nonce = new Uint8Array([]);
1126
+ return getAddress(
1127
+ `0x${keccak256(toRlp([from, nonce], "bytes")).slice(26)}`
1128
+ );
1129
+ }
1130
+ function getCreate2Address(opts) {
1131
+ const from = toBytes(getAddress(opts.from));
1132
+ const salt = pad(isBytes(opts.salt) ? opts.salt : toBytes(opts.salt), {
1133
+ size: 32
1134
+ });
1135
+ const bytecodeHash = toBytes(
1136
+ keccak256(
1137
+ isBytes(opts.bytecode) ? opts.bytecode : toBytes(opts.bytecode)
1138
+ )
1139
+ );
1140
+ return getAddress(
1141
+ slice(keccak256(concat([toBytes("0xff"), from, salt, bytecodeHash])), 12)
1142
+ );
1143
+ }
1059
1144
 
1060
- // src/errors/log.ts
1061
- var FilterTypeNotSupportedError = class extends BaseError {
1062
- constructor(type) {
1063
- super(`Filter type "${type}" is not supported.`);
1064
- __publicField(this, "name", "FilterTypeNotSupportedError");
1065
- }
1066
- };
1145
+ // src/utils/address/isAddressEqual.ts
1146
+ function isAddressEqual(a, b) {
1147
+ if (!isAddress(a))
1148
+ throw new InvalidAddressError({ address: a });
1149
+ if (!isAddress(b))
1150
+ throw new InvalidAddressError({ address: b });
1151
+ return a.toLowerCase() === b.toLowerCase();
1152
+ }
1067
1153
 
1068
- // src/errors/node.ts
1069
- var ExecutionRevertedError = class extends BaseError {
1070
- constructor({
1071
- cause,
1072
- message
1073
- } = {}) {
1074
- const reason = message?.replace("execution reverted: ", "")?.replace("execution reverted", "");
1075
- super(
1076
- `Execution reverted ${reason ? `with reason: ${reason}` : "for an unknown reason"}.`,
1077
- {
1078
- cause
1079
- }
1080
- );
1081
- __publicField(this, "name", "ExecutionRevertedError");
1154
+ // src/accounts/toAccount.ts
1155
+ function toAccount(source) {
1156
+ if (typeof source === "string") {
1157
+ if (!isAddress(source))
1158
+ throw new InvalidAddressError({ address: source });
1159
+ return {
1160
+ address: source,
1161
+ type: "json-rpc"
1162
+ };
1082
1163
  }
1083
- };
1084
- __publicField(ExecutionRevertedError, "code", 3);
1085
- __publicField(ExecutionRevertedError, "nodeMessage", /execution reverted/);
1086
- var FeeCapTooHighError = class extends BaseError {
1087
- constructor({
1088
- cause,
1089
- maxFeePerGas
1090
- } = {}) {
1091
- super(
1092
- `The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}) cannot be higher than the maximum allowed value (2^256-1).`,
1164
+ if (!isAddress(source.address))
1165
+ throw new InvalidAddressError({ address: source.address });
1166
+ return {
1167
+ address: source.address,
1168
+ signMessage: source.signMessage,
1169
+ signTransaction: source.signTransaction,
1170
+ signTypedData: source.signTypedData,
1171
+ source: "custom",
1172
+ type: "local"
1173
+ };
1174
+ }
1175
+
1176
+ // src/constants/abis.ts
1177
+ var multicall3Abi = [
1178
+ {
1179
+ inputs: [
1093
1180
  {
1094
- cause
1181
+ components: [
1182
+ {
1183
+ name: "target",
1184
+ type: "address"
1185
+ },
1186
+ {
1187
+ name: "allowFailure",
1188
+ type: "bool"
1189
+ },
1190
+ {
1191
+ name: "callData",
1192
+ type: "bytes"
1193
+ }
1194
+ ],
1195
+ name: "calls",
1196
+ type: "tuple[]"
1095
1197
  }
1096
- );
1097
- __publicField(this, "name", "FeeCapTooHigh");
1098
- }
1099
- };
1100
- __publicField(FeeCapTooHighError, "nodeMessage", /max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/);
1101
- var FeeCapTooLowError = class extends BaseError {
1102
- constructor({
1103
- cause,
1104
- maxFeePerGas
1105
- } = {}) {
1106
- super(
1107
- `The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)}` : ""} gwei) cannot be lower than the block base fee.`,
1198
+ ],
1199
+ name: "aggregate3",
1200
+ outputs: [
1108
1201
  {
1109
- cause
1202
+ components: [
1203
+ {
1204
+ name: "success",
1205
+ type: "bool"
1206
+ },
1207
+ {
1208
+ name: "returnData",
1209
+ type: "bytes"
1210
+ }
1211
+ ],
1212
+ name: "returnData",
1213
+ type: "tuple[]"
1110
1214
  }
1111
- );
1112
- __publicField(this, "name", "FeeCapTooLow");
1113
- }
1114
- };
1115
- __publicField(FeeCapTooLowError, "nodeMessage", /max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/);
1116
- var NonceTooHighError = class extends BaseError {
1117
- constructor({ cause, nonce } = {}) {
1118
- super(
1119
- `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is higher than the next one expected.`,
1120
- { cause }
1121
- );
1122
- __publicField(this, "name", "NonceTooHighError");
1123
- }
1124
- };
1125
- __publicField(NonceTooHighError, "nodeMessage", /nonce too high/);
1126
- var NonceTooLowError = class extends BaseError {
1127
- constructor({ cause, nonce } = {}) {
1128
- super(
1129
- [
1130
- `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is lower than the current nonce of the account.`,
1131
- "Try increasing the nonce or find the latest nonce with `getTransactionCount`."
1132
- ].join("\n"),
1133
- { cause }
1134
- );
1135
- __publicField(this, "name", "NonceTooLowError");
1215
+ ],
1216
+ stateMutability: "view",
1217
+ type: "function"
1136
1218
  }
1219
+ ];
1220
+
1221
+ // src/constants/solidity.ts
1222
+ var panicReasons = {
1223
+ 1: "An `assert` condition failed.",
1224
+ 17: "Arithmic operation resulted in underflow or overflow.",
1225
+ 18: "Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).",
1226
+ 33: "Attempted to convert to an invalid type.",
1227
+ 34: "Attempted to access a storage byte array that is incorrectly encoded.",
1228
+ 49: "Performed `.pop()` on an empty array",
1229
+ 50: "Array index is out of bounds.",
1230
+ 65: "Allocated too much memory or created an array which is too large.",
1231
+ 81: "Attempted to call a zero-initialized variable of internal function type."
1137
1232
  };
1138
- __publicField(NonceTooLowError, "nodeMessage", /nonce too low|transaction already imported/);
1139
- var NonceMaxValueError = class extends BaseError {
1140
- constructor({ cause, nonce } = {}) {
1141
- super(
1142
- `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}exceeds the maximum allowed nonce.`,
1143
- { cause }
1144
- );
1145
- __publicField(this, "name", "NonceMaxValueError");
1146
- }
1233
+ var solidityError = {
1234
+ inputs: [
1235
+ {
1236
+ name: "message",
1237
+ type: "string"
1238
+ }
1239
+ ],
1240
+ name: "Error",
1241
+ type: "error"
1147
1242
  };
1148
- __publicField(NonceMaxValueError, "nodeMessage", /nonce has max value/);
1149
- var InsufficientFundsError = class extends BaseError {
1150
- constructor({ cause } = {}) {
1151
- super(
1152
- [
1153
- "The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."
1154
- ].join("\n"),
1155
- {
1156
- cause,
1157
- metaMessages: [
1158
- "This error could arise when the account does not have enough funds to:",
1159
- " - pay for the total gas fee,",
1160
- " - pay for the value to send.",
1161
- " ",
1162
- "The cost of the transaction is calculated as `gas * gas fee + value`, where:",
1163
- " - `gas` is the amount of gas needed for transaction to execute,",
1164
- " - `gas fee` is the gas fee,",
1165
- " - `value` is the amount of ether to send to the recipient."
1166
- ]
1167
- }
1168
- );
1169
- __publicField(this, "name", "InsufficientFundsError");
1170
- }
1243
+ var solidityPanic = {
1244
+ inputs: [
1245
+ {
1246
+ name: "reason",
1247
+ type: "uint256"
1248
+ }
1249
+ ],
1250
+ name: "Panic",
1251
+ type: "error"
1171
1252
  };
1172
- __publicField(InsufficientFundsError, "nodeMessage", /insufficient funds/);
1173
- var IntrinsicGasTooHighError = class extends BaseError {
1174
- constructor({ cause, gas } = {}) {
1175
- super(
1176
- `The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction exceeds the limit allowed for the block.`,
1177
- {
1178
- cause
1179
- }
1180
- );
1181
- __publicField(this, "name", "IntrinsicGasTooHighError");
1182
- }
1253
+
1254
+ // src/constants/unit.ts
1255
+ var etherUnits = {
1256
+ gwei: 9,
1257
+ wei: 18
1183
1258
  };
1184
- __publicField(IntrinsicGasTooHighError, "nodeMessage", /intrinsic gas too high|gas limit reached/);
1185
- var IntrinsicGasTooLowError = class extends BaseError {
1186
- constructor({ cause, gas } = {}) {
1187
- super(
1188
- `The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction is too low.`,
1189
- {
1190
- cause
1191
- }
1192
- );
1193
- __publicField(this, "name", "IntrinsicGasTooLowError");
1194
- }
1259
+ var gweiUnits = {
1260
+ ether: -9,
1261
+ wei: 9
1195
1262
  };
1196
- __publicField(IntrinsicGasTooLowError, "nodeMessage", /intrinsic gas too low/);
1197
- var TransactionTypeNotSupportedError = class extends BaseError {
1198
- constructor({ cause }) {
1199
- super("The transaction type is not supported for this chain.", {
1200
- cause
1201
- });
1202
- __publicField(this, "name", "TransactionTypeNotSupportedError");
1203
- }
1263
+ var weiUnits = {
1264
+ ether: -18,
1265
+ gwei: -9
1204
1266
  };
1205
- __publicField(TransactionTypeNotSupportedError, "nodeMessage", /transaction type not valid/);
1206
- var TipAboveFeeCapError = class extends BaseError {
1207
- constructor({
1208
- cause,
1209
- maxPriorityFeePerGas,
1210
- maxFeePerGas
1211
- } = {}) {
1267
+
1268
+ // src/errors/transaction.ts
1269
+ function prettyPrint(args) {
1270
+ const entries = Object.entries(args).map(([key, value]) => {
1271
+ if (value === void 0 || value === false)
1272
+ return null;
1273
+ return [key, value];
1274
+ }).filter(Boolean);
1275
+ const maxLength = entries.reduce((acc, [key]) => Math.max(acc, key.length), 0);
1276
+ return entries.map(([key, value]) => ` ${`${key}:`.padEnd(maxLength + 1)} ${value}`).join("\n");
1277
+ }
1278
+ var FeeConflictError = class extends BaseError {
1279
+ constructor() {
1212
1280
  super(
1213
1281
  [
1214
- `The provided tip (\`maxPriorityFeePerGas\`${maxPriorityFeePerGas ? ` = ${formatGwei(maxPriorityFeePerGas)} gwei` : ""}) cannot be higher than the fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}).`
1215
- ].join("\n"),
1216
- {
1217
- cause
1218
- }
1282
+ "Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.",
1283
+ "Use `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others."
1284
+ ].join("\n")
1219
1285
  );
1220
- __publicField(this, "name", "TipAboveFeeCapError");
1221
- }
1222
- };
1223
- __publicField(TipAboveFeeCapError, "nodeMessage", /max priority fee per gas higher than max fee per gas|tip higher than fee cap/);
1224
- var UnknownNodeError = class extends BaseError {
1225
- constructor({ cause }) {
1226
- super(`An error occurred while executing: ${cause?.message}`, {
1227
- cause
1228
- });
1229
- __publicField(this, "name", "UnknownNodeError");
1286
+ __publicField(this, "name", "FeeConflictError");
1230
1287
  }
1231
1288
  };
1232
-
1233
- // src/errors/request.ts
1234
- var RequestError = class extends BaseError {
1235
- constructor(err, {
1289
+ var TransactionExecutionError = class extends BaseError {
1290
+ constructor(cause, {
1291
+ account,
1236
1292
  docsPath: docsPath6,
1237
- metaMessages,
1238
- shortMessage
1293
+ chain,
1294
+ data,
1295
+ gas,
1296
+ gasPrice,
1297
+ maxFeePerGas,
1298
+ maxPriorityFeePerGas,
1299
+ nonce,
1300
+ to,
1301
+ value
1239
1302
  }) {
1240
- super(shortMessage, {
1241
- cause: err,
1303
+ const prettyArgs = prettyPrint({
1304
+ chain: chain && `${chain?.name} (id: ${chain?.id})`,
1305
+ from: account?.address,
1306
+ to,
1307
+ value: typeof value !== "undefined" && `${formatEther(value)} ${chain?.nativeCurrency.symbol || "ETH"}`,
1308
+ data,
1309
+ gas,
1310
+ gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`,
1311
+ maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`,
1312
+ maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`,
1313
+ nonce
1314
+ });
1315
+ super(cause.shortMessage, {
1316
+ cause,
1242
1317
  docsPath: docsPath6,
1243
- metaMessages
1318
+ metaMessages: [
1319
+ ...cause.metaMessages ? [...cause.metaMessages, " "] : [],
1320
+ "Request Arguments:",
1321
+ prettyArgs
1322
+ ].filter(Boolean)
1244
1323
  });
1245
- this.name = err.name;
1324
+ __publicField(this, "cause");
1325
+ __publicField(this, "name", "TransactionExecutionError");
1326
+ this.cause = cause;
1246
1327
  }
1247
1328
  };
1248
- var RpcRequestError = class extends RequestError {
1249
- constructor(err, { docsPath: docsPath6, shortMessage }) {
1250
- super(err, { docsPath: docsPath6, metaMessages: err.metaMessages, shortMessage });
1251
- __publicField(this, "code");
1252
- this.code = err.code;
1253
- this.name = err.name;
1329
+ var TransactionNotFoundError = class extends BaseError {
1330
+ constructor({
1331
+ blockHash,
1332
+ blockNumber,
1333
+ blockTag,
1334
+ hash: hash2,
1335
+ index
1336
+ }) {
1337
+ let identifier = "Transaction";
1338
+ if (blockTag && index !== void 0)
1339
+ identifier = `Transaction at block time "${blockTag}" at index "${index}"`;
1340
+ if (blockHash && index !== void 0)
1341
+ identifier = `Transaction at block hash "${blockHash}" at index "${index}"`;
1342
+ if (blockNumber && index !== void 0)
1343
+ identifier = `Transaction at block number "${blockNumber}" at index "${index}"`;
1344
+ if (hash2)
1345
+ identifier = `Transaction with hash "${hash2}"`;
1346
+ super(`${identifier} could not be found.`);
1347
+ __publicField(this, "name", "TransactionNotFoundError");
1254
1348
  }
1255
1349
  };
1256
- var ParseRpcError = class extends RpcRequestError {
1257
- constructor(err) {
1258
- super(err, {
1259
- shortMessage: "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."
1260
- });
1261
- __publicField(this, "name", "ParseRpcError");
1262
- __publicField(this, "code", -32700);
1350
+ var TransactionReceiptNotFoundError = class extends BaseError {
1351
+ constructor({ hash: hash2 }) {
1352
+ super(
1353
+ `Transaction receipt with hash "${hash2}" could not be found. The Transaction may not be processed on a block yet.`
1354
+ );
1355
+ __publicField(this, "name", "TransactionReceiptNotFoundError");
1263
1356
  }
1264
1357
  };
1265
- var InvalidRequestRpcError = class extends RpcRequestError {
1266
- constructor(err) {
1267
- super(err, { shortMessage: "JSON is not a valid request object." });
1268
- __publicField(this, "name", "InvalidRequestRpcError");
1269
- __publicField(this, "code", -32600);
1358
+ var WaitForTransactionReceiptTimeoutError = class extends BaseError {
1359
+ constructor({ hash: hash2 }) {
1360
+ super(
1361
+ `Timed out while waiting for transaction with hash "${hash2}" to be confirmed.`
1362
+ );
1363
+ __publicField(this, "name", "WaitForTransactionReceiptTimeoutError");
1270
1364
  }
1271
1365
  };
1272
- var MethodNotFoundRpcError = class extends RpcRequestError {
1273
- constructor(err) {
1274
- super(err, {
1275
- shortMessage: "The method does not exist / is not available."
1366
+
1367
+ // src/errors/contract.ts
1368
+ var CallExecutionError = class extends BaseError {
1369
+ constructor(cause, {
1370
+ account: account_,
1371
+ docsPath: docsPath6,
1372
+ chain,
1373
+ data,
1374
+ gas,
1375
+ gasPrice,
1376
+ maxFeePerGas,
1377
+ maxPriorityFeePerGas,
1378
+ nonce,
1379
+ to,
1380
+ value
1381
+ }) {
1382
+ const account = account_ ? parseAccount(account_) : void 0;
1383
+ const prettyArgs = prettyPrint({
1384
+ from: account?.address,
1385
+ to,
1386
+ value: typeof value !== "undefined" && `${formatEther(value)} ${chain?.nativeCurrency.symbol || "ETH"}`,
1387
+ data,
1388
+ gas,
1389
+ gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`,
1390
+ maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`,
1391
+ maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`,
1392
+ nonce
1276
1393
  });
1277
- __publicField(this, "name", "MethodNotFoundRpcError");
1278
- __publicField(this, "code", -32601);
1394
+ super(cause.shortMessage, {
1395
+ cause,
1396
+ docsPath: docsPath6,
1397
+ metaMessages: [
1398
+ ...cause.metaMessages ? [...cause.metaMessages, " "] : [],
1399
+ "Raw Call Arguments:",
1400
+ prettyArgs
1401
+ ].filter(Boolean)
1402
+ });
1403
+ __publicField(this, "cause");
1404
+ __publicField(this, "name", "CallExecutionError");
1405
+ this.cause = cause;
1279
1406
  }
1280
1407
  };
1281
- var InvalidParamsRpcError = class extends RpcRequestError {
1282
- constructor(err) {
1283
- super(err, {
1284
- shortMessage: [
1285
- "Invalid parameters were provided to the RPC method.",
1286
- "Double check you have provided the correct parameters."
1287
- ].join("\n")
1408
+ var ContractFunctionExecutionError = class extends BaseError {
1409
+ constructor(cause, {
1410
+ abi,
1411
+ args,
1412
+ contractAddress,
1413
+ docsPath: docsPath6,
1414
+ functionName,
1415
+ sender
1416
+ }) {
1417
+ const abiItem = getAbiItem({ abi, args, name: functionName });
1418
+ const formattedArgs = abiItem ? formatAbiItemWithArgs({
1419
+ abiItem,
1420
+ args,
1421
+ includeFunctionName: false,
1422
+ includeName: false
1423
+ }) : void 0;
1424
+ const functionWithParams = abiItem ? formatAbiItem(abiItem, { includeName: true }) : void 0;
1425
+ const prettyArgs = prettyPrint({
1426
+ address: contractAddress && getContractAddress(contractAddress),
1427
+ function: functionWithParams,
1428
+ args: formattedArgs && formattedArgs !== "()" && `${[...Array(functionName?.length ?? 0).keys()].map(() => " ").join("")}${formattedArgs}`,
1429
+ sender
1288
1430
  });
1289
- __publicField(this, "name", "InvalidParamsRpcError");
1290
- __publicField(this, "code", -32602);
1431
+ super(
1432
+ cause.shortMessage || `An unknown error occurred while executing the contract function "${functionName}".`,
1433
+ {
1434
+ cause,
1435
+ docsPath: docsPath6,
1436
+ metaMessages: [
1437
+ ...cause.metaMessages ? [...cause.metaMessages, " "] : [],
1438
+ "Contract Call:",
1439
+ prettyArgs
1440
+ ].filter(Boolean)
1441
+ }
1442
+ );
1443
+ __publicField(this, "abi");
1444
+ __publicField(this, "args");
1445
+ __publicField(this, "cause");
1446
+ __publicField(this, "contractAddress");
1447
+ __publicField(this, "formattedArgs");
1448
+ __publicField(this, "functionName");
1449
+ __publicField(this, "sender");
1450
+ __publicField(this, "name", "ContractFunctionExecutionError");
1451
+ this.abi = abi;
1452
+ this.args = args;
1453
+ this.cause = cause;
1454
+ this.contractAddress = contractAddress;
1455
+ this.functionName = functionName;
1456
+ this.sender = sender;
1291
1457
  }
1292
1458
  };
1293
- var InternalRpcError = class extends RpcRequestError {
1294
- constructor(err) {
1295
- super(err, { shortMessage: "An internal error was received." });
1296
- __publicField(this, "name", "InternalRpcError");
1297
- __publicField(this, "code", -32603);
1459
+ var ContractFunctionRevertedError = class extends BaseError {
1460
+ constructor({
1461
+ abi,
1462
+ data,
1463
+ functionName,
1464
+ message
1465
+ }) {
1466
+ let decodedData = void 0;
1467
+ let metaMessages;
1468
+ let reason;
1469
+ if (data && data !== "0x") {
1470
+ decodedData = decodeErrorResult({ abi, data });
1471
+ const { abiItem, errorName, args: errorArgs } = decodedData;
1472
+ if (errorName === "Error") {
1473
+ reason = errorArgs[0];
1474
+ } else if (errorName === "Panic") {
1475
+ const [firstArg] = errorArgs;
1476
+ reason = panicReasons[firstArg];
1477
+ } else if (errorArgs) {
1478
+ const errorWithParams = abiItem ? formatAbiItem(abiItem, { includeName: true }) : void 0;
1479
+ const formattedArgs = abiItem ? formatAbiItemWithArgs({
1480
+ abiItem,
1481
+ args: errorArgs,
1482
+ includeFunctionName: false,
1483
+ includeName: false
1484
+ }) : void 0;
1485
+ metaMessages = [
1486
+ errorWithParams ? `Error: ${errorWithParams}` : "",
1487
+ formattedArgs && formattedArgs !== "()" ? ` ${[...Array(errorName?.length ?? 0).keys()].map(() => " ").join("")}${formattedArgs}` : ""
1488
+ ];
1489
+ }
1490
+ } else if (message)
1491
+ reason = message;
1492
+ super(
1493
+ reason ? [
1494
+ `The contract function "${functionName}" reverted with the following reason:`,
1495
+ reason
1496
+ ].join("\n") : `The contract function "${functionName}" reverted.`,
1497
+ {
1498
+ metaMessages
1499
+ }
1500
+ );
1501
+ __publicField(this, "name", "ContractFunctionRevertedError");
1502
+ __publicField(this, "data");
1503
+ __publicField(this, "reason");
1504
+ this.reason = reason;
1505
+ this.data = decodedData;
1298
1506
  }
1299
1507
  };
1300
- var InvalidInputRpcError = class extends RpcRequestError {
1301
- constructor(err) {
1302
- super(err, {
1303
- shortMessage: [
1304
- "Missing or invalid parameters.",
1305
- "Double check you have provided the correct parameters."
1306
- ].join("\n")
1508
+ var ContractFunctionZeroDataError = class extends BaseError {
1509
+ constructor({ functionName }) {
1510
+ super(`The contract function "${functionName}" returned no data ("0x").`, {
1511
+ metaMessages: [
1512
+ "This could be due to any of the following:",
1513
+ ` - The contract does not have the function "${functionName}",`,
1514
+ " - The parameters passed to the contract function may be invalid, or",
1515
+ " - The address is not a contract."
1516
+ ]
1307
1517
  });
1308
- __publicField(this, "name", "InvalidInputRpcError");
1309
- __publicField(this, "code", -32e3);
1518
+ __publicField(this, "name", "ContractFunctionZeroDataError");
1310
1519
  }
1311
1520
  };
1312
- var ResourceNotFoundRpcError = class extends RpcRequestError {
1313
- constructor(err) {
1314
- super(err, { shortMessage: "Requested resource not found." });
1315
- __publicField(this, "name", "ResourceNotFoundRpcError");
1316
- __publicField(this, "code", -32001);
1521
+ var RawContractError = class extends BaseError {
1522
+ constructor({ data, message }) {
1523
+ super(message || "");
1524
+ __publicField(this, "code", 3);
1525
+ __publicField(this, "name", "RawContractError");
1526
+ __publicField(this, "data");
1527
+ this.data = data;
1317
1528
  }
1318
1529
  };
1319
- var ResourceUnavailableRpcError = class extends RpcRequestError {
1320
- constructor(err) {
1321
- super(err, { shortMessage: "Requested resource not available." });
1322
- __publicField(this, "name", "ResourceUnavailableRpcError");
1323
- __publicField(this, "code", -32002);
1530
+
1531
+ // src/errors/data.ts
1532
+ var SizeExceedsPaddingSizeError = class extends BaseError {
1533
+ constructor({
1534
+ size: size2,
1535
+ targetSize,
1536
+ type
1537
+ }) {
1538
+ super(
1539
+ `${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size2}) exceeds padding size (${targetSize}).`
1540
+ );
1541
+ __publicField(this, "name", "SizeExceedsPaddingSizeError");
1324
1542
  }
1325
1543
  };
1326
- var TransactionRejectedRpcError = class extends RpcRequestError {
1327
- constructor(err) {
1328
- super(err, { shortMessage: "Transaction creation failed." });
1329
- __publicField(this, "name", "TransactionRejectedRpcError");
1330
- __publicField(this, "code", -32003);
1544
+
1545
+ // src/errors/encoding.ts
1546
+ var DataLengthTooLongError = class extends BaseError {
1547
+ constructor({ consumed, length }) {
1548
+ super(
1549
+ `Consumed bytes (${consumed}) is shorter than data length (${length - 1}).`
1550
+ );
1551
+ __publicField(this, "name", "DataLengthTooLongError");
1331
1552
  }
1332
1553
  };
1333
- var MethodNotSupportedRpcError = class extends RpcRequestError {
1334
- constructor(err) {
1335
- super(err, { shortMessage: "Method is not implemented." });
1336
- __publicField(this, "name", "MethodNotSupportedRpcError");
1337
- __publicField(this, "code", -32004);
1554
+ var DataLengthTooShortError = class extends BaseError {
1555
+ constructor({ length, dataLength }) {
1556
+ super(
1557
+ `Data length (${dataLength - 1}) is shorter than prefix length (${length - 1}).`
1558
+ );
1559
+ __publicField(this, "name", "DataLengthTooShortError");
1338
1560
  }
1339
1561
  };
1340
- var LimitExceededRpcError = class extends RpcRequestError {
1341
- constructor(err) {
1342
- super(err, { shortMessage: "Request exceeds defined limit." });
1343
- __publicField(this, "name", "LimitExceededRpcError");
1344
- __publicField(this, "code", -32005);
1562
+ var IntegerOutOfRangeError = class extends BaseError {
1563
+ constructor({
1564
+ max,
1565
+ min,
1566
+ signed,
1567
+ size: size2,
1568
+ value
1569
+ }) {
1570
+ super(
1571
+ `Number "${value}" is not in safe ${size2 ? `${size2 * 8}-bit ${signed ? "signed" : "unsigned"} ` : ""}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`
1572
+ );
1573
+ __publicField(this, "name", "IntegerOutOfRangeError");
1345
1574
  }
1346
1575
  };
1347
- var JsonRpcVersionUnsupportedError = class extends RpcRequestError {
1348
- constructor(err) {
1349
- super(err, {
1350
- shortMessage: "Version of JSON-RPC protocol is not supported."
1351
- });
1352
- __publicField(this, "name", "JsonRpcVersionUnsupportedError");
1353
- __publicField(this, "code", -32006);
1576
+ var InvalidBytesBooleanError = class extends BaseError {
1577
+ constructor(bytes) {
1578
+ super(
1579
+ `Bytes value "${bytes}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`
1580
+ );
1581
+ __publicField(this, "name", "InvalidBytesBooleanError");
1354
1582
  }
1355
1583
  };
1356
- var UserRejectedRequestError = class extends RpcRequestError {
1357
- constructor(err) {
1358
- super(err, {
1359
- shortMessage: "User rejected the request."
1360
- });
1361
- __publicField(this, "name", "UserRejectedRequestError");
1362
- __publicField(this, "code", 4001);
1584
+ var InvalidHexBooleanError = class extends BaseError {
1585
+ constructor(hex) {
1586
+ super(
1587
+ `Hex value "${hex}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`
1588
+ );
1589
+ __publicField(this, "name", "InvalidHexBooleanError");
1363
1590
  }
1364
1591
  };
1365
- var SwitchChainError = class extends RpcRequestError {
1366
- constructor(err) {
1367
- super(err, {
1368
- shortMessage: "An error occurred when attempting to switch chain."
1369
- });
1370
- __publicField(this, "name", "SwitchChainError");
1371
- __publicField(this, "code", 4902);
1592
+ var InvalidHexValueError = class extends BaseError {
1593
+ constructor(value) {
1594
+ super(
1595
+ `Hex value "${value}" is an odd length (${value.length}). It must be an even length.`
1596
+ );
1597
+ __publicField(this, "name", "InvalidHexValueError");
1372
1598
  }
1373
1599
  };
1374
- var UnknownRpcError = class extends RequestError {
1375
- constructor(err) {
1376
- super(err, {
1377
- shortMessage: "An unknown RPC error occurred."
1378
- });
1379
- __publicField(this, "name", "UnknownRpcError");
1600
+ var OffsetOutOfBoundsError = class extends BaseError {
1601
+ constructor({ nextOffset, offset }) {
1602
+ super(
1603
+ `Next offset (${nextOffset}) is greater than previous offset + consumed bytes (${offset})`
1604
+ );
1605
+ __publicField(this, "name", "OffsetOutOfBoundsError");
1380
1606
  }
1381
1607
  };
1382
1608
 
1383
- // src/errors/rpc.ts
1384
- var HttpRequestError = class extends BaseError {
1385
- constructor({
1386
- body,
1387
- details,
1388
- headers,
1389
- status,
1390
- url
1609
+ // src/errors/estimateGas.ts
1610
+ var EstimateGasExecutionError = class extends BaseError {
1611
+ constructor(cause, {
1612
+ account,
1613
+ docsPath: docsPath6,
1614
+ chain,
1615
+ data,
1616
+ gas,
1617
+ gasPrice,
1618
+ maxFeePerGas,
1619
+ maxPriorityFeePerGas,
1620
+ nonce,
1621
+ to,
1622
+ value
1391
1623
  }) {
1392
- super("HTTP request failed.", {
1393
- details,
1624
+ const prettyArgs = prettyPrint({
1625
+ from: account?.address,
1626
+ to,
1627
+ value: typeof value !== "undefined" && `${formatEther(value)} ${chain?.nativeCurrency.symbol || "ETH"}`,
1628
+ data,
1629
+ gas,
1630
+ gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`,
1631
+ maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`,
1632
+ maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`,
1633
+ nonce
1634
+ });
1635
+ super(cause.shortMessage, {
1636
+ cause,
1637
+ docsPath: docsPath6,
1394
1638
  metaMessages: [
1395
- status && `Status: ${status}`,
1396
- `URL: ${getUrl(url)}`,
1397
- `Request body: ${stringify(body)}`
1639
+ ...cause.metaMessages ? [...cause.metaMessages, " "] : [],
1640
+ "Estimate Gas Arguments:",
1641
+ prettyArgs
1398
1642
  ].filter(Boolean)
1399
1643
  });
1400
- __publicField(this, "name", "HttpRequestError");
1401
- __publicField(this, "body");
1402
- __publicField(this, "headers");
1403
- __publicField(this, "status");
1404
- __publicField(this, "url");
1405
- this.body = body;
1406
- this.headers = headers;
1407
- this.status = status;
1408
- this.url = url;
1644
+ __publicField(this, "cause");
1645
+ __publicField(this, "name", "EstimateGasExecutionError");
1646
+ this.cause = cause;
1409
1647
  }
1410
1648
  };
1411
- var WebSocketRequestError = class extends BaseError {
1649
+
1650
+ // src/errors/log.ts
1651
+ var FilterTypeNotSupportedError = class extends BaseError {
1652
+ constructor(type) {
1653
+ super(`Filter type "${type}" is not supported.`);
1654
+ __publicField(this, "name", "FilterTypeNotSupportedError");
1655
+ }
1656
+ };
1657
+
1658
+ // src/errors/node.ts
1659
+ var ExecutionRevertedError = class extends BaseError {
1412
1660
  constructor({
1413
- body,
1414
- details,
1415
- url
1416
- }) {
1417
- super("WebSocket request failed.", {
1418
- details,
1419
- metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`]
1420
- });
1421
- __publicField(this, "name", "WebSocketRequestError");
1661
+ cause,
1662
+ message
1663
+ } = {}) {
1664
+ const reason = message?.replace("execution reverted: ", "")?.replace("execution reverted", "");
1665
+ super(
1666
+ `Execution reverted ${reason ? `with reason: ${reason}` : "for an unknown reason"}.`,
1667
+ {
1668
+ cause
1669
+ }
1670
+ );
1671
+ __publicField(this, "name", "ExecutionRevertedError");
1422
1672
  }
1423
1673
  };
1424
- var RpcError = class extends BaseError {
1674
+ __publicField(ExecutionRevertedError, "code", 3);
1675
+ __publicField(ExecutionRevertedError, "nodeMessage", /execution reverted/);
1676
+ var FeeCapTooHighError = class extends BaseError {
1425
1677
  constructor({
1426
- body,
1427
- error,
1428
- url
1429
- }) {
1430
- super("RPC Request failed.", {
1431
- cause: error,
1432
- details: error.message,
1433
- metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`]
1434
- });
1435
- __publicField(this, "code");
1436
- __publicField(this, "name", "RpcError");
1437
- this.code = error.code;
1678
+ cause,
1679
+ maxFeePerGas
1680
+ } = {}) {
1681
+ super(
1682
+ `The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}) cannot be higher than the maximum allowed value (2^256-1).`,
1683
+ {
1684
+ cause
1685
+ }
1686
+ );
1687
+ __publicField(this, "name", "FeeCapTooHigh");
1438
1688
  }
1439
1689
  };
1440
- var TimeoutError = class extends BaseError {
1690
+ __publicField(FeeCapTooHighError, "nodeMessage", /max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/);
1691
+ var FeeCapTooLowError = class extends BaseError {
1441
1692
  constructor({
1442
- body,
1443
- url
1444
- }) {
1445
- super("The request took too long to respond.", {
1446
- details: "The request timed out.",
1447
- metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`]
1448
- });
1449
- __publicField(this, "name", "TimeoutError");
1450
- }
1451
- };
1452
-
1453
- // src/errors/transport.ts
1454
- var UrlRequiredError = class extends BaseError {
1455
- constructor() {
1693
+ cause,
1694
+ maxFeePerGas
1695
+ } = {}) {
1456
1696
  super(
1457
- "No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",
1697
+ `The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)}` : ""} gwei) cannot be lower than the block base fee.`,
1458
1698
  {
1459
- docsPath: "/docs/clients/intro"
1699
+ cause
1460
1700
  }
1461
1701
  );
1702
+ __publicField(this, "name", "FeeCapTooLow");
1462
1703
  }
1463
1704
  };
1464
-
1465
- // src/utils/data/concat.ts
1466
- function concat(values) {
1467
- if (typeof values[0] === "string")
1468
- return concatHex(values);
1469
- return concatBytes(values);
1470
- }
1471
- function concatBytes(values) {
1472
- let length = 0;
1473
- for (const arr of values) {
1474
- length += arr.length;
1475
- }
1476
- const result = new Uint8Array(length);
1477
- let offset = 0;
1478
- for (const arr of values) {
1479
- result.set(arr, offset);
1480
- offset += arr.length;
1705
+ __publicField(FeeCapTooLowError, "nodeMessage", /max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/);
1706
+ var NonceTooHighError = class extends BaseError {
1707
+ constructor({ cause, nonce } = {}) {
1708
+ super(
1709
+ `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is higher than the next one expected.`,
1710
+ { cause }
1711
+ );
1712
+ __publicField(this, "name", "NonceTooHighError");
1481
1713
  }
1482
- return result;
1483
- }
1484
- function concatHex(values) {
1485
- return `0x${values.reduce(
1486
- (acc, x) => acc + x.replace("0x", ""),
1487
- ""
1488
- )}`;
1489
- }
1490
-
1491
- // src/utils/data/isBytes.ts
1492
- function isBytes(value) {
1493
- if (!value)
1494
- return false;
1495
- if (typeof value !== "object")
1496
- return false;
1497
- if (!("BYTES_PER_ELEMENT" in value))
1498
- return false;
1499
- return value.BYTES_PER_ELEMENT === 1 && value.constructor.name === "Uint8Array";
1500
- }
1501
-
1502
- // src/utils/data/isHex.ts
1503
- function isHex(value) {
1504
- if (!value)
1505
- return false;
1506
- if (typeof value !== "string")
1507
- return false;
1508
- return /^0x[0-9a-fA-F]*$/.test(value);
1509
- }
1510
-
1511
- // src/utils/data/pad.ts
1512
- function pad(hexOrBytes, { dir, size: size2 = 32 } = {}) {
1513
- if (typeof hexOrBytes === "string")
1514
- return padHex(hexOrBytes, { dir, size: size2 });
1515
- return padBytes(hexOrBytes, { dir, size: size2 });
1516
- }
1517
- function padHex(hex_, { dir, size: size2 = 32 } = {}) {
1518
- if (size2 === null)
1519
- return hex_;
1520
- let hex = hex_.replace("0x", "");
1521
- if (hex.length > size2 * 2)
1522
- throw new SizeExceedsPaddingSizeError({
1523
- size: Math.ceil(hex.length / 2),
1524
- targetSize: size2,
1525
- type: "hex"
1526
- });
1527
- return `0x${hex[dir === "right" ? "padEnd" : "padStart"](
1528
- size2 * 2,
1529
- "0"
1530
- )}`;
1531
- }
1532
- function padBytes(bytes, { dir, size: size2 = 32 } = {}) {
1533
- if (size2 === null)
1534
- return bytes;
1535
- if (bytes.length > size2)
1536
- throw new SizeExceedsPaddingSizeError({
1537
- size: bytes.length,
1538
- targetSize: size2,
1539
- type: "bytes"
1540
- });
1541
- const paddedBytes = new Uint8Array(size2);
1542
- for (let i = 0; i < size2; i++) {
1543
- const padEnd = dir === "right";
1544
- paddedBytes[padEnd ? i : size2 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1];
1714
+ };
1715
+ __publicField(NonceTooHighError, "nodeMessage", /nonce too high/);
1716
+ var NonceTooLowError = class extends BaseError {
1717
+ constructor({ cause, nonce } = {}) {
1718
+ super(
1719
+ [
1720
+ `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is lower than the current nonce of the account.`,
1721
+ "Try increasing the nonce or find the latest nonce with `getTransactionCount`."
1722
+ ].join("\n"),
1723
+ { cause }
1724
+ );
1725
+ __publicField(this, "name", "NonceTooLowError");
1545
1726
  }
1546
- return paddedBytes;
1547
- }
1548
-
1549
- // src/utils/data/trim.ts
1550
- function trim(hexOrBytes, { dir = "left" } = {}) {
1551
- let data = typeof hexOrBytes === "string" ? hexOrBytes.replace("0x", "") : hexOrBytes;
1552
- let sliceLength = 0;
1553
- for (let i = 0; i < data.length - 1; i++) {
1554
- if (data[dir === "left" ? i : data.length - i - 1].toString() === "0")
1555
- sliceLength++;
1556
- else
1557
- break;
1727
+ };
1728
+ __publicField(NonceTooLowError, "nodeMessage", /nonce too low|transaction already imported/);
1729
+ var NonceMaxValueError = class extends BaseError {
1730
+ constructor({ cause, nonce } = {}) {
1731
+ super(
1732
+ `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}exceeds the maximum allowed nonce.`,
1733
+ { cause }
1734
+ );
1735
+ __publicField(this, "name", "NonceMaxValueError");
1558
1736
  }
1559
- data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength);
1560
- if (typeof hexOrBytes === "string") {
1561
- if (data.length === 1 && dir === "right")
1562
- data = `${data}0`;
1563
- return `0x${data}`;
1737
+ };
1738
+ __publicField(NonceMaxValueError, "nodeMessage", /nonce has max value/);
1739
+ var InsufficientFundsError = class extends BaseError {
1740
+ constructor({ cause } = {}) {
1741
+ super(
1742
+ [
1743
+ "The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."
1744
+ ].join("\n"),
1745
+ {
1746
+ cause,
1747
+ metaMessages: [
1748
+ "This error could arise when the account does not have enough funds to:",
1749
+ " - pay for the total gas fee,",
1750
+ " - pay for the value to send.",
1751
+ " ",
1752
+ "The cost of the transaction is calculated as `gas * gas fee + value`, where:",
1753
+ " - `gas` is the amount of gas needed for transaction to execute,",
1754
+ " - `gas fee` is the gas fee,",
1755
+ " - `value` is the amount of ether to send to the recipient."
1756
+ ]
1757
+ }
1758
+ );
1759
+ __publicField(this, "name", "InsufficientFundsError");
1564
1760
  }
1565
- return data;
1566
- }
1567
-
1568
- // src/utils/data/size.ts
1569
- function size(value) {
1570
- if (isHex(value))
1571
- return Math.ceil((value.length - 2) / 2);
1572
- return value.length;
1573
- }
1574
-
1575
- // src/utils/data/slice.ts
1576
- function slice(value, start, end) {
1577
- if (isHex(value))
1578
- return sliceHex(value, start, end);
1579
- return sliceBytes(value, start, end);
1580
- }
1581
- function assertStartOffset(value, start) {
1582
- if (typeof start === "number" && start > 0 && start > size(value) - 1)
1583
- throw new Error(
1584
- `Slice starting at offset "${start}" is out-of-bounds (size: ${size(
1585
- value
1586
- )}).`
1761
+ };
1762
+ __publicField(InsufficientFundsError, "nodeMessage", /insufficient funds/);
1763
+ var IntrinsicGasTooHighError = class extends BaseError {
1764
+ constructor({ cause, gas } = {}) {
1765
+ super(
1766
+ `The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction exceeds the limit allowed for the block.`,
1767
+ {
1768
+ cause
1769
+ }
1587
1770
  );
1588
- }
1589
- function sliceBytes(value, start, end) {
1590
- assertStartOffset(value, start);
1591
- return value.slice(start, end);
1592
- }
1593
- function sliceHex(value_, start, end) {
1594
- assertStartOffset(value_, start);
1595
- const value = value_.replace("0x", "").slice((start ?? 0) * 2, (end ?? value_.length) * 2);
1596
- return `0x${value}`;
1597
- }
1598
-
1599
- // src/utils/encoding/toHex.ts
1600
- var hexes = Array.from(
1601
- { length: 256 },
1602
- (_v, i) => i.toString(16).padStart(2, "0")
1603
- );
1604
- function boolToHex(value) {
1605
- return `0x${Number(value)}`;
1606
- }
1607
- function bytesToHex(value) {
1608
- let hex = "";
1609
- for (let i = 0; i < value.length; i++) {
1610
- hex += hexes[value[i]];
1771
+ __publicField(this, "name", "IntrinsicGasTooHighError");
1772
+ }
1773
+ };
1774
+ __publicField(IntrinsicGasTooHighError, "nodeMessage", /intrinsic gas too high|gas limit reached/);
1775
+ var IntrinsicGasTooLowError = class extends BaseError {
1776
+ constructor({ cause, gas } = {}) {
1777
+ super(
1778
+ `The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction is too low.`,
1779
+ {
1780
+ cause
1781
+ }
1782
+ );
1783
+ __publicField(this, "name", "IntrinsicGasTooLowError");
1611
1784
  }
1612
- return `0x${hex}`;
1613
- }
1614
- function toHex(value) {
1615
- if (typeof value === "number" || typeof value === "bigint")
1616
- return numberToHex(value);
1617
- if (typeof value === "string") {
1618
- return stringToHex(value);
1785
+ };
1786
+ __publicField(IntrinsicGasTooLowError, "nodeMessage", /intrinsic gas too low/);
1787
+ var TransactionTypeNotSupportedError = class extends BaseError {
1788
+ constructor({ cause }) {
1789
+ super("The transaction type is not supported for this chain.", {
1790
+ cause
1791
+ });
1792
+ __publicField(this, "name", "TransactionTypeNotSupportedError");
1619
1793
  }
1620
- if (typeof value === "boolean")
1621
- return boolToHex(value);
1622
- return bytesToHex(value);
1623
- }
1624
- function numberToHex(value_, opts = {}) {
1625
- const { signed, size: size2 } = opts;
1626
- let value = BigInt(value_);
1627
- let maxValue;
1628
- if (size2) {
1629
- if (signed)
1630
- maxValue = (1n << BigInt(size2) * 8n - 1n) - 1n;
1631
- else
1632
- maxValue = 2n ** (BigInt(size2) * 8n) - 1n;
1633
- } else if (typeof value_ === "number") {
1634
- maxValue = BigInt(Number.MAX_SAFE_INTEGER);
1794
+ };
1795
+ __publicField(TransactionTypeNotSupportedError, "nodeMessage", /transaction type not valid/);
1796
+ var TipAboveFeeCapError = class extends BaseError {
1797
+ constructor({
1798
+ cause,
1799
+ maxPriorityFeePerGas,
1800
+ maxFeePerGas
1801
+ } = {}) {
1802
+ super(
1803
+ [
1804
+ `The provided tip (\`maxPriorityFeePerGas\`${maxPriorityFeePerGas ? ` = ${formatGwei(maxPriorityFeePerGas)} gwei` : ""}) cannot be higher than the fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}).`
1805
+ ].join("\n"),
1806
+ {
1807
+ cause
1808
+ }
1809
+ );
1810
+ __publicField(this, "name", "TipAboveFeeCapError");
1635
1811
  }
1636
- const minValue = typeof maxValue === "bigint" && signed ? -maxValue - 1n : 0;
1637
- if (maxValue && value > maxValue || value < minValue) {
1638
- const suffix = typeof value_ === "bigint" ? "n" : "";
1639
- throw new IntegerOutOfRangeError({
1640
- max: maxValue ? `${maxValue}${suffix}` : void 0,
1641
- min: `${minValue}${suffix}`,
1642
- signed,
1643
- size: size2,
1644
- value: `${value_}${suffix}`
1812
+ };
1813
+ __publicField(TipAboveFeeCapError, "nodeMessage", /max priority fee per gas higher than max fee per gas|tip higher than fee cap/);
1814
+ var UnknownNodeError = class extends BaseError {
1815
+ constructor({ cause }) {
1816
+ super(`An error occurred while executing: ${cause?.message}`, {
1817
+ cause
1645
1818
  });
1819
+ __publicField(this, "name", "UnknownNodeError");
1646
1820
  }
1647
- const hex = `0x${(signed && value < 0 ? (1n << BigInt(size2 * 8)) + BigInt(value) : value).toString(16)}`;
1648
- if (size2)
1649
- return pad(hex, { size: size2 });
1650
- return hex;
1651
- }
1652
- var encoder = new TextEncoder();
1653
- function stringToHex(value_) {
1654
- const value = encoder.encode(value_);
1655
- return toHex(value);
1656
- }
1821
+ };
1657
1822
 
1658
- // src/utils/encoding/toBytes.ts
1659
- var encoder2 = new TextEncoder();
1660
- function toBytes(value) {
1661
- if (typeof value === "number" || typeof value === "bigint")
1662
- return numberToBytes(value);
1663
- if (typeof value === "boolean")
1664
- return boolToBytes(value);
1665
- if (value.startsWith("0x"))
1666
- return hexToBytes(value);
1667
- return stringToBytes(value);
1668
- }
1669
- function boolToBytes(value) {
1670
- const bytes = new Uint8Array(1);
1671
- bytes[0] = Number(value);
1672
- return bytes;
1673
- }
1674
- function hexToBytes(hex_) {
1675
- let hex = hex_.slice(2);
1676
- if (hex.length % 2)
1677
- hex = `0${hex}`;
1678
- const bytes = new Uint8Array(hex.length / 2);
1679
- for (let index = 0; index < bytes.length; index++) {
1680
- const start = index * 2;
1681
- const hexByte = hex.slice(start, start + 2);
1682
- const byte = Number.parseInt(hexByte, 16);
1683
- if (Number.isNaN(byte) || byte < 0)
1684
- throw new BaseError(`Invalid byte sequence ("${hexByte}" in "${hex}").`);
1685
- bytes[index] = byte;
1823
+ // src/errors/request.ts
1824
+ var RequestError = class extends BaseError {
1825
+ constructor(err, {
1826
+ docsPath: docsPath6,
1827
+ metaMessages,
1828
+ shortMessage
1829
+ }) {
1830
+ super(shortMessage, {
1831
+ cause: err,
1832
+ docsPath: docsPath6,
1833
+ metaMessages
1834
+ });
1835
+ this.name = err.name;
1686
1836
  }
1687
- return bytes;
1688
- }
1689
- function numberToBytes(value, opts) {
1690
- const hex = numberToHex(value, opts);
1691
- return hexToBytes(hex);
1692
- }
1693
- function stringToBytes(value) {
1694
- return encoder2.encode(value);
1695
- }
1696
-
1697
- // src/utils/encoding/toRlp.ts
1698
- function toRlp(hexOrBytes, to_) {
1699
- const to = to_ || "hex";
1700
- return format(bytesToRlp(parse(hexOrBytes)), to);
1701
- }
1702
- function parse(hexOrBytes) {
1703
- if (Array.isArray(hexOrBytes))
1704
- return hexOrBytes.map(parse);
1705
- return typeof hexOrBytes === "string" ? toBytes(hexOrBytes) : hexOrBytes;
1706
- }
1707
- function format(bytes, type = "bytes") {
1708
- return type === "hex" ? bytesToHex(bytes) : bytes;
1709
- }
1710
- function bytesToRlp(bytes) {
1711
- if (Array.isArray(bytes)) {
1712
- const encoded = concat(bytes.map(bytesToRlp));
1713
- return new Uint8Array([...encodeLength(encoded.length, 192), ...encoded]);
1837
+ };
1838
+ var RpcRequestError = class extends RequestError {
1839
+ constructor(err, { docsPath: docsPath6, shortMessage }) {
1840
+ super(err, { docsPath: docsPath6, metaMessages: err.metaMessages, shortMessage });
1841
+ __publicField(this, "code");
1842
+ this.code = err.code;
1843
+ this.name = err.name;
1714
1844
  }
1715
- if (bytes.length === 1 && bytes[0] < 128)
1716
- return bytes;
1717
- return new Uint8Array([...encodeLength(bytes.length, 128), ...bytes]);
1718
- }
1719
- function encodeLength(length, offset) {
1720
- if (length < 56)
1721
- return [offset + length];
1722
- return [toBytes(length).length + offset + 55, ...toBytes(length)];
1723
- }
1724
-
1725
- // src/utils/encoding/fromHex.ts
1726
- function fromHex(hex, to) {
1727
- if (to === "number")
1728
- return hexToNumber(hex);
1729
- if (to === "bigint")
1730
- return hexToBigInt(hex);
1731
- if (to === "string")
1732
- return hexToString(hex);
1733
- if (to === "boolean")
1734
- return hexToBool(hex);
1735
- return hexToBytes(hex);
1736
- }
1737
- function hexToBigInt(hex, opts = {}) {
1738
- const { signed } = opts;
1739
- const value = BigInt(hex);
1740
- if (!signed)
1741
- return value;
1742
- const size2 = (hex.length - 2) / 2;
1743
- const max = (1n << BigInt(size2) * 8n - 1n) - 1n;
1744
- if (value <= max)
1745
- return value;
1746
- return value - BigInt(`0x${"f".padStart(size2 * 2, "f")}`) - 1n;
1747
- }
1748
- function hexToBool(hex) {
1749
- if (trim(hex) === "0x0")
1750
- return false;
1751
- if (trim(hex) === "0x1")
1752
- return true;
1753
- throw new InvalidHexBooleanError(hex);
1754
- }
1755
- function hexToNumber(hex, opts = {}) {
1756
- return Number(hexToBigInt(hex, opts));
1757
- }
1758
- function hexToString(hex) {
1759
- const bytes = hexToBytes(hex);
1760
- return new TextDecoder().decode(bytes);
1761
- }
1762
-
1763
- // src/utils/encoding/fromBytes.ts
1764
- function fromBytes(bytes, to) {
1765
- if (to === "number")
1766
- return bytesToNumber(bytes);
1767
- if (to === "bigint")
1768
- return bytesToBigint(bytes);
1769
- if (to === "boolean")
1770
- return bytesToBool(bytes);
1771
- if (to === "string")
1772
- return bytesToString(bytes);
1773
- return bytesToHex(bytes);
1774
- }
1775
- function bytesToBigint(bytes) {
1776
- const hex = bytesToHex(bytes);
1777
- return hexToBigInt(hex);
1778
- }
1779
- function bytesToBool(bytes) {
1780
- if (bytes.length > 1 || bytes[0] > 1)
1781
- throw new InvalidBytesBooleanError(bytes);
1782
- return Boolean(bytes[0]);
1783
- }
1784
- function bytesToNumber(bytes) {
1785
- const hex = bytesToHex(bytes);
1786
- return hexToNumber(hex);
1787
- }
1788
- function bytesToString(bytes) {
1789
- return new TextDecoder().decode(bytes);
1790
- }
1791
-
1792
- // src/utils/encoding/fromRlp.ts
1793
- function fromRlp(value, to) {
1794
- const bytes = parse2(value);
1795
- const [data, consumed] = rlpToBytes(bytes);
1796
- if (consumed < bytes.length)
1797
- throw new DataLengthTooLongError({
1798
- consumed,
1799
- length: bytes.length
1845
+ };
1846
+ var ParseRpcError = class extends RpcRequestError {
1847
+ constructor(err) {
1848
+ super(err, {
1849
+ shortMessage: "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."
1850
+ });
1851
+ __publicField(this, "name", "ParseRpcError");
1852
+ __publicField(this, "code", -32700);
1853
+ }
1854
+ };
1855
+ var InvalidRequestRpcError = class extends RpcRequestError {
1856
+ constructor(err) {
1857
+ super(err, { shortMessage: "JSON is not a valid request object." });
1858
+ __publicField(this, "name", "InvalidRequestRpcError");
1859
+ __publicField(this, "code", -32600);
1860
+ }
1861
+ };
1862
+ var MethodNotFoundRpcError = class extends RpcRequestError {
1863
+ constructor(err) {
1864
+ super(err, {
1865
+ shortMessage: "The method does not exist / is not available."
1800
1866
  });
1801
- return format2(data, to);
1802
- }
1803
- function parse2(value) {
1804
- if (typeof value === "string") {
1805
- if (value.length > 3 && value.length % 2 !== 0)
1806
- throw new InvalidHexValueError(value);
1807
- return hexToBytes(value);
1867
+ __publicField(this, "name", "MethodNotFoundRpcError");
1868
+ __publicField(this, "code", -32601);
1808
1869
  }
1809
- return value;
1810
- }
1811
- function format2(bytes, to) {
1812
- if (Array.isArray(bytes))
1813
- return bytes.map((b) => format2(b, to));
1814
- return to === "hex" ? trim(bytesToHex(bytes)) : bytes;
1815
- }
1816
- function rlpToBytes(bytes, offset = 0) {
1817
- if (bytes.length === 0)
1818
- return [new Uint8Array([]), 0];
1819
- const prefix = bytes[offset];
1820
- if (prefix <= 127)
1821
- return [new Uint8Array([bytes[offset]]), 1];
1822
- if (prefix <= 183) {
1823
- const length2 = prefix - 128;
1824
- const offset_ = offset + 1;
1825
- if (offset_ + length2 > bytes.length)
1826
- throw new DataLengthTooShortError({
1827
- length: offset_ + length2,
1828
- dataLength: bytes.length
1829
- });
1830
- return [bytes.slice(offset_, offset_ + length2), 1 + length2];
1870
+ };
1871
+ var InvalidParamsRpcError = class extends RpcRequestError {
1872
+ constructor(err) {
1873
+ super(err, {
1874
+ shortMessage: [
1875
+ "Invalid parameters were provided to the RPC method.",
1876
+ "Double check you have provided the correct parameters."
1877
+ ].join("\n")
1878
+ });
1879
+ __publicField(this, "name", "InvalidParamsRpcError");
1880
+ __publicField(this, "code", -32602);
1831
1881
  }
1832
- if (prefix <= 191) {
1833
- const lengthOfLength2 = prefix - 183;
1834
- const offset_ = offset + 1;
1835
- const length2 = bytesToNumber(bytes.slice(offset_, offset_ + lengthOfLength2));
1836
- if (offset_ + lengthOfLength2 + length2 > bytes.length)
1837
- throw new DataLengthTooShortError({
1838
- length: lengthOfLength2 + length2,
1839
- dataLength: bytes.length - lengthOfLength2
1840
- });
1841
- return [
1842
- bytes.slice(offset_ + lengthOfLength2, offset_ + lengthOfLength2 + length2),
1843
- 1 + lengthOfLength2 + length2
1844
- ];
1882
+ };
1883
+ var InternalRpcError = class extends RpcRequestError {
1884
+ constructor(err) {
1885
+ super(err, { shortMessage: "An internal error was received." });
1886
+ __publicField(this, "name", "InternalRpcError");
1887
+ __publicField(this, "code", -32603);
1845
1888
  }
1846
- let lengthOfLength = 0;
1847
- let length = prefix - 192;
1848
- if (prefix > 247) {
1849
- lengthOfLength = prefix - 247;
1850
- length = bytesToNumber(bytes.slice(offset + 1, offset + 1 + lengthOfLength));
1889
+ };
1890
+ var InvalidInputRpcError = class extends RpcRequestError {
1891
+ constructor(err) {
1892
+ super(err, {
1893
+ shortMessage: [
1894
+ "Missing or invalid parameters.",
1895
+ "Double check you have provided the correct parameters."
1896
+ ].join("\n")
1897
+ });
1898
+ __publicField(this, "name", "InvalidInputRpcError");
1899
+ __publicField(this, "code", -32e3);
1851
1900
  }
1852
- let nextOffset = offset + 1 + lengthOfLength;
1853
- if (nextOffset > bytes.length)
1854
- throw new DataLengthTooShortError({
1855
- length: nextOffset,
1856
- dataLength: bytes.length
1901
+ };
1902
+ var ResourceNotFoundRpcError = class extends RpcRequestError {
1903
+ constructor(err) {
1904
+ super(err, { shortMessage: "Requested resource not found." });
1905
+ __publicField(this, "name", "ResourceNotFoundRpcError");
1906
+ __publicField(this, "code", -32001);
1907
+ }
1908
+ };
1909
+ var ResourceUnavailableRpcError = class extends RpcRequestError {
1910
+ constructor(err) {
1911
+ super(err, { shortMessage: "Requested resource not available." });
1912
+ __publicField(this, "name", "ResourceUnavailableRpcError");
1913
+ __publicField(this, "code", -32002);
1914
+ }
1915
+ };
1916
+ var TransactionRejectedRpcError = class extends RpcRequestError {
1917
+ constructor(err) {
1918
+ super(err, { shortMessage: "Transaction creation failed." });
1919
+ __publicField(this, "name", "TransactionRejectedRpcError");
1920
+ __publicField(this, "code", -32003);
1921
+ }
1922
+ };
1923
+ var MethodNotSupportedRpcError = class extends RpcRequestError {
1924
+ constructor(err) {
1925
+ super(err, { shortMessage: "Method is not implemented." });
1926
+ __publicField(this, "name", "MethodNotSupportedRpcError");
1927
+ __publicField(this, "code", -32004);
1928
+ }
1929
+ };
1930
+ var LimitExceededRpcError = class extends RpcRequestError {
1931
+ constructor(err) {
1932
+ super(err, { shortMessage: "Request exceeds defined limit." });
1933
+ __publicField(this, "name", "LimitExceededRpcError");
1934
+ __publicField(this, "code", -32005);
1935
+ }
1936
+ };
1937
+ var JsonRpcVersionUnsupportedError = class extends RpcRequestError {
1938
+ constructor(err) {
1939
+ super(err, {
1940
+ shortMessage: "Version of JSON-RPC protocol is not supported."
1857
1941
  });
1858
- let consumed = 1 + lengthOfLength + length;
1859
- let result = [];
1860
- while (nextOffset < offset + consumed) {
1861
- const decoded = rlpToBytes(bytes, nextOffset);
1862
- result.push(decoded[0]);
1863
- nextOffset += decoded[1];
1864
- if (nextOffset > offset + consumed)
1865
- throw new OffsetOutOfBoundsError({
1866
- nextOffset,
1867
- offset: offset + consumed
1868
- });
1942
+ __publicField(this, "name", "JsonRpcVersionUnsupportedError");
1943
+ __publicField(this, "code", -32006);
1869
1944
  }
1870
- return [result, consumed];
1871
- }
1872
-
1873
- // src/utils/contract/extractFunctionParts.ts
1874
- var paramsRegex = /((function|event)\s)?(.*)(\((.*)\))/;
1875
- function extractFunctionParts(def) {
1876
- const parts = def.match(paramsRegex);
1877
- const type = parts?.[2] || void 0;
1878
- const name = parts?.[3];
1879
- const params = parts?.[5] || void 0;
1880
- return { type, name, params };
1881
- }
1882
- function extractFunctionName(def) {
1883
- return extractFunctionParts(def).name;
1884
- }
1885
- function extractFunctionParams(def) {
1886
- const params = extractFunctionParts(def).params;
1887
- const splitParams = params?.split(",").map((x) => x.trim().split(" "));
1888
- return splitParams?.map((param) => ({
1889
- type: param[0],
1890
- name: param[1] === "indexed" ? param[2] : param[1],
1891
- ...param[1] === "indexed" ? { indexed: true } : {}
1892
- }));
1893
- }
1894
- function extractFunctionType(def) {
1895
- return extractFunctionParts(def).type;
1896
- }
1897
-
1898
- // src/utils/hash/keccak256.ts
1899
- import { keccak_256 } from "@noble/hashes/sha3";
1900
- function keccak256(value, to_) {
1901
- const to = to_ || "hex";
1902
- const bytes = keccak_256(isHex(value) ? toBytes(value) : value);
1903
- if (to === "bytes")
1904
- return bytes;
1905
- return toHex(bytes);
1906
- }
1907
-
1908
- // src/utils/hash/hashFunction.ts
1909
- var hash = (value) => keccak256(toBytes(value));
1910
- function hashFunction(def) {
1911
- const name = extractFunctionName(def);
1912
- const params = extractFunctionParams(def);
1913
- if (!params || params.length === 0)
1914
- return hash(def.replace(/ /g, ""));
1915
- return hash(`${name}(${params.map(({ type }) => type).join(",")})`);
1916
- }
1917
-
1918
- // src/utils/hash/getEventSelector.ts
1919
- var getEventSelector = (event) => hashFunction(event);
1920
-
1921
- // src/utils/hash/getFunctionSelector.ts
1922
- var getFunctionSelector = (fn) => slice(hashFunction(fn), 0, 4);
1923
-
1924
- // src/utils/address/isAddress.ts
1925
- var addressRegex = /^0x[a-fA-F0-9]{40}$/;
1926
- function isAddress(address) {
1927
- return addressRegex.test(address);
1928
- }
1945
+ };
1946
+ var UserRejectedRequestError = class extends RpcRequestError {
1947
+ constructor(err) {
1948
+ super(err, {
1949
+ shortMessage: "User rejected the request."
1950
+ });
1951
+ __publicField(this, "name", "UserRejectedRequestError");
1952
+ __publicField(this, "code", 4001);
1953
+ }
1954
+ };
1955
+ var SwitchChainError = class extends RpcRequestError {
1956
+ constructor(err) {
1957
+ super(err, {
1958
+ shortMessage: "An error occurred when attempting to switch chain."
1959
+ });
1960
+ __publicField(this, "name", "SwitchChainError");
1961
+ __publicField(this, "code", 4902);
1962
+ }
1963
+ };
1964
+ var UnknownRpcError = class extends RequestError {
1965
+ constructor(err) {
1966
+ super(err, {
1967
+ shortMessage: "An unknown RPC error occurred."
1968
+ });
1969
+ __publicField(this, "name", "UnknownRpcError");
1970
+ }
1971
+ };
1929
1972
 
1930
- // src/utils/address/getAddress.ts
1931
- function checksumAddress(address_) {
1932
- const hexAddress = address_.substring(2).toLowerCase();
1933
- const hash2 = keccak256(stringToBytes(hexAddress), "bytes");
1934
- let address = hexAddress.split("");
1935
- for (let i = 0; i < 40; i += 2) {
1936
- if (hash2[i >> 1] >> 4 >= 8 && address[i]) {
1937
- address[i] = address[i].toUpperCase();
1938
- }
1939
- if ((hash2[i >> 1] & 15) >= 8 && address[i + 1]) {
1940
- address[i + 1] = address[i + 1].toUpperCase();
1941
- }
1973
+ // src/errors/rpc.ts
1974
+ var HttpRequestError = class extends BaseError {
1975
+ constructor({
1976
+ body,
1977
+ details,
1978
+ headers,
1979
+ status,
1980
+ url
1981
+ }) {
1982
+ super("HTTP request failed.", {
1983
+ details,
1984
+ metaMessages: [
1985
+ status && `Status: ${status}`,
1986
+ `URL: ${getUrl(url)}`,
1987
+ `Request body: ${stringify(body)}`
1988
+ ].filter(Boolean)
1989
+ });
1990
+ __publicField(this, "name", "HttpRequestError");
1991
+ __publicField(this, "body");
1992
+ __publicField(this, "headers");
1993
+ __publicField(this, "status");
1994
+ __publicField(this, "url");
1995
+ this.body = body;
1996
+ this.headers = headers;
1997
+ this.status = status;
1998
+ this.url = url;
1942
1999
  }
1943
- return `0x${address.join("")}`;
1944
- }
1945
- function getAddress(address) {
1946
- if (!isAddress(address))
1947
- throw new InvalidAddressError({ address });
1948
- return checksumAddress(address);
1949
- }
1950
-
1951
- // src/utils/address/getContractAddress.ts
1952
- function getContractAddress2(opts) {
1953
- if (opts.opcode === "CREATE2")
1954
- return getCreate2Address(opts);
1955
- return getCreateAddress(opts);
1956
- }
1957
- function getCreateAddress(opts) {
1958
- const from = toBytes(getAddress(opts.from));
1959
- let nonce = toBytes(opts.nonce);
1960
- if (nonce[0] === 0)
1961
- nonce = new Uint8Array([]);
1962
- return getAddress(
1963
- `0x${keccak256(toRlp([from, nonce], "bytes")).slice(26)}`
1964
- );
1965
- }
1966
- function getCreate2Address(opts) {
1967
- const from = toBytes(getAddress(opts.from));
1968
- const salt = pad(isBytes(opts.salt) ? opts.salt : toBytes(opts.salt), {
1969
- size: 32
1970
- });
1971
- const bytecodeHash = toBytes(
1972
- keccak256(
1973
- isBytes(opts.bytecode) ? opts.bytecode : toBytes(opts.bytecode)
1974
- )
1975
- );
1976
- return getAddress(
1977
- slice(keccak256(concat([toBytes("0xff"), from, salt, bytecodeHash])), 12)
1978
- );
1979
- }
2000
+ };
2001
+ var WebSocketRequestError = class extends BaseError {
2002
+ constructor({
2003
+ body,
2004
+ details,
2005
+ url
2006
+ }) {
2007
+ super("WebSocket request failed.", {
2008
+ details,
2009
+ metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`]
2010
+ });
2011
+ __publicField(this, "name", "WebSocketRequestError");
2012
+ }
2013
+ };
2014
+ var RpcError = class extends BaseError {
2015
+ constructor({
2016
+ body,
2017
+ error,
2018
+ url
2019
+ }) {
2020
+ super("RPC Request failed.", {
2021
+ cause: error,
2022
+ details: error.message,
2023
+ metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`]
2024
+ });
2025
+ __publicField(this, "code");
2026
+ __publicField(this, "name", "RpcError");
2027
+ this.code = error.code;
2028
+ }
2029
+ };
2030
+ var TimeoutError = class extends BaseError {
2031
+ constructor({
2032
+ body,
2033
+ url
2034
+ }) {
2035
+ super("The request took too long to respond.", {
2036
+ details: "The request timed out.",
2037
+ metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`]
2038
+ });
2039
+ __publicField(this, "name", "TimeoutError");
2040
+ }
2041
+ };
1980
2042
 
1981
- // src/utils/address/isAddressEqual.ts
1982
- function isAddressEqual(a, b) {
1983
- if (!isAddress(a))
1984
- throw new InvalidAddressError({ address: a });
1985
- if (!isAddress(b))
1986
- throw new InvalidAddressError({ address: b });
1987
- return a.toLowerCase() === b.toLowerCase();
1988
- }
2043
+ // src/errors/transport.ts
2044
+ var UrlRequiredError = class extends BaseError {
2045
+ constructor() {
2046
+ super(
2047
+ "No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",
2048
+ {
2049
+ docsPath: "/docs/clients/intro"
2050
+ }
2051
+ );
2052
+ }
2053
+ };
1989
2054
 
1990
2055
  // src/utils/abi/encodeAbiParameters.ts
1991
2056
  function encodeAbiParameters(params, values) {
@@ -2828,21 +2893,6 @@ function formatAbiItemWithArgs({
2828
2893
  ).join(", ")})`;
2829
2894
  }
2830
2895
 
2831
- // src/utils/account.ts
2832
- function getAccount(account) {
2833
- if (typeof account === "string") {
2834
- if (!isAddress(account))
2835
- throw new InvalidAddressError({ address: account });
2836
- return { address: account, type: "json-rpc" };
2837
- }
2838
- if (!isAddress(account.address))
2839
- throw new InvalidAddressError({ address: account.address });
2840
- return {
2841
- ...account,
2842
- type: "local"
2843
- };
2844
- }
2845
-
2846
2896
  // src/utils/promise/withCache.ts
2847
2897
  var promiseCache = /* @__PURE__ */ new Map();
2848
2898
  var responseCache = /* @__PURE__ */ new Map();
@@ -3452,59 +3502,268 @@ function webSocket(socket, {
3452
3502
  url: socket.url,
3453
3503
  details: "Socket is closed."
3454
3504
  });
3455
- const id_ = id++;
3456
- const callback = ({ data }) => {
3457
- const message = JSON.parse(data);
3458
- if (typeof message.id === "number" && id_ !== message.id)
3459
- return;
3460
- if (message.error) {
3461
- onError?.(new RpcError({ body, error: message.error, url: socket.url }));
3462
- } else {
3463
- onData?.(message);
3464
- }
3465
- if (body.method === "eth_subscribe" && typeof message.result === "string") {
3466
- socket.subscriptions.set(message.result, callback);
3467
- }
3468
- if (body.method === "eth_unsubscribe") {
3469
- socket.subscriptions.delete(body.params?.[0]);
3470
- }
3471
- };
3472
- socket.requests.set(id_, callback);
3473
- socket.send(JSON.stringify({ jsonrpc: "2.0", ...body, id: id_ }));
3474
- return socket;
3505
+ const id_ = id++;
3506
+ const callback = ({ data }) => {
3507
+ const message = JSON.parse(data);
3508
+ if (typeof message.id === "number" && id_ !== message.id)
3509
+ return;
3510
+ if (message.error) {
3511
+ onError?.(new RpcError({ body, error: message.error, url: socket.url }));
3512
+ } else {
3513
+ onData?.(message);
3514
+ }
3515
+ if (body.method === "eth_subscribe" && typeof message.result === "string") {
3516
+ socket.subscriptions.set(message.result, callback);
3517
+ }
3518
+ if (body.method === "eth_unsubscribe") {
3519
+ socket.subscriptions.delete(body.params?.[0]);
3520
+ }
3521
+ };
3522
+ socket.requests.set(id_, callback);
3523
+ socket.send(JSON.stringify({ jsonrpc: "2.0", ...body, id: id_ }));
3524
+ return socket;
3525
+ }
3526
+ async function webSocketAsync(socket, {
3527
+ body,
3528
+ timeout = 1e4
3529
+ }) {
3530
+ return withTimeout(
3531
+ () => new Promise(
3532
+ (onData, onError) => rpc.webSocket(socket, {
3533
+ body,
3534
+ onData,
3535
+ onError
3536
+ })
3537
+ ),
3538
+ {
3539
+ errorInstance: new TimeoutError({ body, url: socket.url }),
3540
+ timeout
3541
+ }
3542
+ );
3543
+ }
3544
+ var rpc = {
3545
+ http,
3546
+ webSocket,
3547
+ webSocketAsync
3548
+ };
3549
+
3550
+ // src/utils/signature/hashMessage.ts
3551
+ function hashMessage(message, to_) {
3552
+ const messageBytes = toBytes(message);
3553
+ const prefixBytes = toBytes(
3554
+ `Ethereum Signed Message:
3555
+ ${messageBytes.length}`
3556
+ );
3557
+ return keccak256(concat([prefixBytes, messageBytes]), to_);
3558
+ }
3559
+
3560
+ // src/utils/typedData.ts
3561
+ function validateTypedData({
3562
+ domain,
3563
+ message,
3564
+ primaryType,
3565
+ types: types_
3566
+ }) {
3567
+ const types = types_;
3568
+ const validateData = (struct, value_) => {
3569
+ for (const param of struct) {
3570
+ const { name, type: type_ } = param;
3571
+ const type = type_;
3572
+ const value = value_[name];
3573
+ const integerMatch = type.match(integerRegex);
3574
+ if (integerMatch && (typeof value === "number" || typeof value === "bigint")) {
3575
+ const [_type, base, size_] = integerMatch;
3576
+ numberToHex(value, {
3577
+ signed: base === "int",
3578
+ size: parseInt(size_) / 8
3579
+ });
3580
+ }
3581
+ if (type === "address" && typeof value === "string" && !isAddress(value))
3582
+ throw new InvalidAddressError({ address: value });
3583
+ const bytesMatch = type.match(bytesRegex);
3584
+ if (bytesMatch) {
3585
+ const [_type, size_] = bytesMatch;
3586
+ if (size_ && size(value) !== parseInt(size_))
3587
+ throw new BytesSizeMismatchError({
3588
+ expectedSize: parseInt(size_),
3589
+ givenSize: size(value)
3590
+ });
3591
+ }
3592
+ const struct2 = types[type];
3593
+ if (struct2)
3594
+ validateData(struct2, value);
3595
+ }
3596
+ };
3597
+ if (types["EIP712Domain"] && domain)
3598
+ validateData(types["EIP712Domain"], domain);
3599
+ if (primaryType !== "EIP712Domain") {
3600
+ const type = types[primaryType];
3601
+ validateData(type, message);
3602
+ }
3603
+ }
3604
+
3605
+ // src/utils/signature/hashTypedData.ts
3606
+ function hashTypedData({
3607
+ domain: domain_,
3608
+ message,
3609
+ primaryType,
3610
+ types: types_
3611
+ }) {
3612
+ const domain = typeof domain_ === "undefined" ? {} : domain_;
3613
+ const types = {
3614
+ EIP712Domain: [
3615
+ domain?.name && { name: "name", type: "string" },
3616
+ domain?.version && { name: "version", type: "string" },
3617
+ domain?.chainId && { name: "chainId", type: "uint256" },
3618
+ domain?.verifyingContract && {
3619
+ name: "verifyingContract",
3620
+ type: "address"
3621
+ },
3622
+ domain?.salt && { name: "salt", type: "bytes32" }
3623
+ ].filter(Boolean),
3624
+ ...types_
3625
+ };
3626
+ validateTypedData({
3627
+ domain,
3628
+ message,
3629
+ primaryType,
3630
+ types
3631
+ });
3632
+ let parts = ["0x1901"];
3633
+ if (domain)
3634
+ parts.push(
3635
+ hashDomain({
3636
+ domain,
3637
+ types
3638
+ })
3639
+ );
3640
+ if (primaryType !== "EIP712Domain") {
3641
+ parts.push(
3642
+ hashStruct({
3643
+ data: message,
3644
+ primaryType,
3645
+ types
3646
+ })
3647
+ );
3648
+ }
3649
+ return keccak256(concat(parts));
3650
+ }
3651
+ function hashDomain({
3652
+ domain,
3653
+ types
3654
+ }) {
3655
+ return hashStruct({
3656
+ data: domain,
3657
+ primaryType: "EIP712Domain",
3658
+ types
3659
+ });
3660
+ }
3661
+ function hashStruct({
3662
+ data,
3663
+ primaryType,
3664
+ types
3665
+ }) {
3666
+ const encoded = encodeData({
3667
+ data,
3668
+ primaryType,
3669
+ types
3670
+ });
3671
+ return keccak256(encoded);
3672
+ }
3673
+ function encodeData({
3674
+ data,
3675
+ primaryType,
3676
+ types
3677
+ }) {
3678
+ let encodedTypes = [{ type: "bytes32" }];
3679
+ const encodedValues = [hashType({ primaryType, types })];
3680
+ for (const field of types[primaryType]) {
3681
+ const [type, value] = encodeField({
3682
+ types,
3683
+ name: field.name,
3684
+ type: field.type,
3685
+ value: data[field.name]
3686
+ });
3687
+ encodedTypes.push(type);
3688
+ encodedValues.push(value);
3689
+ }
3690
+ return encodeAbiParameters(encodedTypes, encodedValues);
3475
3691
  }
3476
- async function webSocketAsync(socket, {
3477
- body,
3478
- timeout = 1e4
3692
+ function hashType({
3693
+ primaryType,
3694
+ types
3479
3695
  }) {
3480
- return withTimeout(
3481
- () => new Promise(
3482
- (onData, onError) => rpc.webSocket(socket, {
3483
- body,
3484
- onData,
3485
- onError
3486
- })
3487
- ),
3488
- {
3489
- errorInstance: new TimeoutError({ body, url: socket.url }),
3490
- timeout
3491
- }
3492
- );
3696
+ const encodedHashType = toHex(encodeType({ primaryType, types }));
3697
+ return keccak256(encodedHashType);
3493
3698
  }
3494
- var rpc = {
3495
- http,
3496
- webSocket,
3497
- webSocketAsync
3498
- };
3499
-
3500
- // src/utils/signature/hashMessage.ts
3501
- function hashMessage(message, to_) {
3502
- const messageBytes = toBytes(message);
3503
- const prefixBytes = toBytes(
3504
- `Ethereum Signed Message:
3505
- ${messageBytes.length}`
3506
- );
3507
- return keccak256(concat([prefixBytes, messageBytes]), to_);
3699
+ function encodeType({
3700
+ primaryType,
3701
+ types
3702
+ }) {
3703
+ let result = "";
3704
+ const unsortedDeps = findTypeDependencies({ primaryType, types });
3705
+ unsortedDeps.delete(primaryType);
3706
+ const deps = [primaryType, ...Array.from(unsortedDeps).sort()];
3707
+ for (const type of deps) {
3708
+ result += `${type}(${types[type].map(({ name, type: t }) => `${t} ${name}`).join(",")})`;
3709
+ }
3710
+ return result;
3711
+ }
3712
+ function findTypeDependencies({
3713
+ primaryType: primaryType_,
3714
+ types
3715
+ }, results = /* @__PURE__ */ new Set()) {
3716
+ const match = primaryType_.match(/^\w*/u);
3717
+ const primaryType = match?.[0];
3718
+ if (results.has(primaryType) || types[primaryType] === void 0) {
3719
+ return results;
3720
+ }
3721
+ results.add(primaryType);
3722
+ for (const field of types[primaryType]) {
3723
+ findTypeDependencies({ primaryType: field.type, types }, results);
3724
+ }
3725
+ return results;
3726
+ }
3727
+ function encodeField({
3728
+ types,
3729
+ name,
3730
+ type,
3731
+ value
3732
+ }) {
3733
+ if (types[type] !== void 0) {
3734
+ return [
3735
+ { type: "bytes32" },
3736
+ keccak256(encodeData({ data: value, primaryType: type, types }))
3737
+ ];
3738
+ }
3739
+ if (type === "bytes") {
3740
+ const prepend = value.length % 2 ? "0" : "";
3741
+ value = `0x${prepend + value.slice(2)}`;
3742
+ return [{ type: "bytes32" }, keccak256(value)];
3743
+ }
3744
+ if (type === "string")
3745
+ return [{ type: "bytes32" }, keccak256(toHex(value))];
3746
+ if (type.lastIndexOf("]") === type.length - 1) {
3747
+ const parsedType = type.slice(0, type.lastIndexOf("["));
3748
+ const typeValuePairs = value.map(
3749
+ (item) => encodeField({
3750
+ name,
3751
+ type: parsedType,
3752
+ types,
3753
+ value: item
3754
+ })
3755
+ );
3756
+ return [
3757
+ { type: "bytes32" },
3758
+ keccak256(
3759
+ encodeAbiParameters(
3760
+ typeValuePairs.map(([t]) => t),
3761
+ typeValuePairs.map(([, v]) => v)
3762
+ )
3763
+ )
3764
+ ];
3765
+ }
3766
+ return [{ type }, value];
3508
3767
  }
3509
3768
 
3510
3769
  // src/utils/signature/recoverAddress.ts
@@ -3535,6 +3794,25 @@ function recoverMessageAddress({
3535
3794
  return recoverAddress({ hash: hashMessage(message), signature });
3536
3795
  }
3537
3796
 
3797
+ // src/utils/signature/recoverTypedDataAddress.ts
3798
+ function recoverTypedDataAddress({
3799
+ domain,
3800
+ message,
3801
+ primaryType,
3802
+ signature,
3803
+ types
3804
+ }) {
3805
+ return recoverAddress({
3806
+ hash: hashTypedData({
3807
+ domain,
3808
+ message,
3809
+ primaryType,
3810
+ types
3811
+ }),
3812
+ signature
3813
+ });
3814
+ }
3815
+
3538
3816
  // src/utils/signature/verifyMessage.ts
3539
3817
  function verifyMessage({
3540
3818
  address,
@@ -3547,9 +3825,37 @@ function verifyMessage({
3547
3825
  );
3548
3826
  }
3549
3827
 
3828
+ // src/utils/signature/verifyTypedData.ts
3829
+ function verifyTypedData({
3830
+ address,
3831
+ domain,
3832
+ message,
3833
+ primaryType,
3834
+ signature,
3835
+ types
3836
+ }) {
3837
+ return isAddressEqual(
3838
+ getAddress(address),
3839
+ recoverTypedDataAddress({
3840
+ domain,
3841
+ message,
3842
+ primaryType,
3843
+ signature,
3844
+ types
3845
+ })
3846
+ );
3847
+ }
3848
+
3550
3849
  // src/utils/transaction/assertRequest.ts
3551
3850
  function assertRequest(args) {
3552
- const { account, gasPrice, maxFeePerGas, maxPriorityFeePerGas, to } = args;
3851
+ const {
3852
+ account: account_,
3853
+ gasPrice,
3854
+ maxFeePerGas,
3855
+ maxPriorityFeePerGas,
3856
+ to
3857
+ } = args;
3858
+ const account = account_ ? parseAccount(account_) : void 0;
3553
3859
  if (account && !isAddress(account.address))
3554
3860
  throw new InvalidAddressError({ address: account.address });
3555
3861
  if (to && !isAddress(to))
@@ -3565,7 +3871,7 @@ function assertRequest(args) {
3565
3871
  // src/actions/public/call.ts
3566
3872
  async function call(client, args) {
3567
3873
  const {
3568
- account,
3874
+ account: account_,
3569
3875
  blockNumber,
3570
3876
  blockTag = "latest",
3571
3877
  accessList,
@@ -3579,6 +3885,7 @@ async function call(client, args) {
3579
3885
  value,
3580
3886
  ...rest
3581
3887
  } = args;
3888
+ const account = account_ ? parseAccount(account_) : void 0;
3582
3889
  try {
3583
3890
  assertRequest(args);
3584
3891
  const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0;
@@ -3612,6 +3919,7 @@ async function call(client, args) {
3612
3919
  } catch (err) {
3613
3920
  throw getCallError(err, {
3614
3921
  ...args,
3922
+ account,
3615
3923
  chain: client.chain
3616
3924
  });
3617
3925
  }
@@ -3625,6 +3933,7 @@ async function simulateContract(client, {
3625
3933
  functionName,
3626
3934
  ...callRequest
3627
3935
  }) {
3936
+ const account = callRequest.account ? parseAccount(callRequest.account) : void 0;
3628
3937
  const calldata = encodeFunctionData({
3629
3938
  abi,
3630
3939
  args,
@@ -3659,7 +3968,7 @@ async function simulateContract(client, {
3659
3968
  args,
3660
3969
  docsPath: "/docs/contract/simulateContract",
3661
3970
  functionName,
3662
- sender: callRequest.account?.address
3971
+ sender: account?.address
3663
3972
  });
3664
3973
  }
3665
3974
  }
@@ -3751,9 +4060,13 @@ async function createContractEventFilter(client, {
3751
4060
 
3752
4061
  // src/actions/public/estimateGas.ts
3753
4062
  async function estimateGas(client, args) {
4063
+ if (!args.account)
4064
+ throw new AccountNotFoundError({
4065
+ docsPath: "/docs/actions/public/estimateGas"
4066
+ });
4067
+ const account = parseAccount(args.account);
3754
4068
  try {
3755
4069
  const {
3756
- account,
3757
4070
  accessList,
3758
4071
  blockNumber,
3759
4072
  blockTag = "latest",
@@ -3766,7 +4079,7 @@ async function estimateGas(client, args) {
3766
4079
  to,
3767
4080
  value,
3768
4081
  ...rest
3769
- } = args.account.type === "local" ? await prepareRequest(client, args) : args;
4082
+ } = account.type === "local" ? await prepareRequest(client, args) : args;
3770
4083
  const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0;
3771
4084
  assertRequest(args);
3772
4085
  const formatter = client.chain?.formatters?.transactionRequest;
@@ -3797,6 +4110,7 @@ async function estimateGas(client, args) {
3797
4110
  } catch (err) {
3798
4111
  throw getEstimateGasError(err, {
3799
4112
  ...args,
4113
+ account,
3800
4114
  chain: client.chain
3801
4115
  });
3802
4116
  }
@@ -3810,6 +4124,7 @@ async function estimateContractGas(client, {
3810
4124
  functionName,
3811
4125
  ...request
3812
4126
  }) {
4127
+ const account = parseAccount(request.account);
3813
4128
  const data = encodeFunctionData({
3814
4129
  abi,
3815
4130
  args,
@@ -3829,7 +4144,7 @@ async function estimateContractGas(client, {
3829
4144
  args,
3830
4145
  docsPath: "/docs/contract/simulateContract",
3831
4146
  functionName,
3832
- sender: request.account?.address
4147
+ sender: account?.address
3833
4148
  });
3834
4149
  }
3835
4150
  }
@@ -4980,7 +5295,12 @@ async function addChain(client, { chain }) {
4980
5295
  }
4981
5296
 
4982
5297
  // src/actions/wallet/deployContract.ts
4983
- function deployContract(walletClient, { abi, args, bytecode, ...request }) {
5298
+ function deployContract(walletClient, {
5299
+ abi,
5300
+ args,
5301
+ bytecode,
5302
+ ...request
5303
+ }) {
4984
5304
  const calldata = encodeDeployData({
4985
5305
  abi,
4986
5306
  args,
@@ -5021,10 +5341,9 @@ async function requestPermissions(client, permissions) {
5021
5341
  // src/actions/wallet/sendTransaction.ts
5022
5342
  async function sendTransaction(client, args) {
5023
5343
  const {
5024
- account,
5344
+ account: account_ = client.account,
5025
5345
  chain = client.chain,
5026
5346
  accessList,
5027
- assertChain = true,
5028
5347
  data,
5029
5348
  gas,
5030
5349
  gasPrice,
@@ -5035,13 +5354,20 @@ async function sendTransaction(client, args) {
5035
5354
  value,
5036
5355
  ...rest
5037
5356
  } = args;
5357
+ if (!account_)
5358
+ throw new AccountNotFoundError({
5359
+ docsPath: "/docs/actions/wallet/sendTransaction"
5360
+ });
5361
+ const account = parseAccount(account_);
5038
5362
  try {
5039
5363
  assertRequest(args);
5040
- const currentChainId = await getChainId(client);
5041
- if (assertChain && chain && currentChainId !== chain?.id)
5042
- throw new ChainMismatchError({ chain, currentChainId });
5364
+ const chainId = await getChainId(client);
5365
+ if (chain !== null && chainId !== chain?.id) {
5366
+ if (!chain)
5367
+ throw new ChainNotFoundError();
5368
+ throw new ChainMismatchError({ chain, currentChainId: chainId });
5369
+ }
5043
5370
  if (account.type === "local") {
5044
- const chainId = chain?.id ?? currentChainId;
5045
5371
  const request2 = await prepareRequest(client, {
5046
5372
  account,
5047
5373
  accessList,
@@ -5090,15 +5416,28 @@ async function sendTransaction(client, args) {
5090
5416
  params: [request]
5091
5417
  });
5092
5418
  } catch (err) {
5093
- throw getTransactionError(err, args);
5419
+ throw getTransactionError(err, {
5420
+ ...args,
5421
+ account,
5422
+ chain: args.chain || void 0
5423
+ });
5094
5424
  }
5095
5425
  }
5096
5426
 
5097
5427
  // src/actions/wallet/signMessage.ts
5098
- async function signMessage(client, { account, data, message }) {
5428
+ async function signMessage2(client, {
5429
+ account: account_ = client.account,
5430
+ data,
5431
+ message
5432
+ }) {
5433
+ if (!account_)
5434
+ throw new AccountNotFoundError({
5435
+ docsPath: "/docs/actions/wallet/signMessage"
5436
+ });
5437
+ const account = parseAccount(account_);
5099
5438
  const message_ = message || data;
5100
5439
  if (account.type === "local")
5101
- return account.signMessage(message_);
5440
+ return account.signMessage({ message: message_ });
5102
5441
  return client.request({
5103
5442
  method: "personal_sign",
5104
5443
  params: [toHex(message_), account.address]
@@ -5107,12 +5446,17 @@ async function signMessage(client, { account, data, message }) {
5107
5446
 
5108
5447
  // src/actions/wallet/signTypedData.ts
5109
5448
  async function signTypedData(client, {
5110
- account,
5449
+ account: account_ = client.account,
5111
5450
  domain,
5112
5451
  message,
5113
5452
  primaryType,
5114
5453
  types: types_
5115
5454
  }) {
5455
+ if (!account_)
5456
+ throw new AccountNotFoundError({
5457
+ docsPath: "/docs/actions/wallet/signTypedData"
5458
+ });
5459
+ const account = parseAccount(account_);
5116
5460
  const types = {
5117
5461
  EIP712Domain: [
5118
5462
  domain?.name && { name: "name", type: "string" },
@@ -5148,47 +5492,6 @@ async function signTypedData(client, {
5148
5492
  params: [account.address, typedData]
5149
5493
  });
5150
5494
  }
5151
- function validateTypedData({
5152
- domain,
5153
- message,
5154
- primaryType,
5155
- types: types_
5156
- }) {
5157
- const types = types_;
5158
- const validateData = (struct, value_) => {
5159
- for (const param of struct) {
5160
- const { name, type: type_ } = param;
5161
- const type2 = type_;
5162
- const value = value_[name];
5163
- const integerMatch = type2.match(integerRegex);
5164
- if (integerMatch && (typeof value === "number" || typeof value === "bigint")) {
5165
- const [_type, base, size_] = integerMatch;
5166
- numberToHex(value, {
5167
- signed: base === "int",
5168
- size: parseInt(size_) / 8
5169
- });
5170
- }
5171
- if (type2 === "address" && typeof value === "string" && !isAddress(value))
5172
- throw new InvalidAddressError({ address: value });
5173
- const bytesMatch = type2.match(bytesRegex);
5174
- if (bytesMatch) {
5175
- const [_type, size_] = bytesMatch;
5176
- if (size_ && size(value) !== parseInt(size_))
5177
- throw new BytesSizeMismatchError({
5178
- expectedSize: parseInt(size_),
5179
- givenSize: size(value)
5180
- });
5181
- }
5182
- const struct2 = types[type2];
5183
- if (struct2)
5184
- validateData(struct2, value);
5185
- }
5186
- };
5187
- if (types["EIP712Domain"] && domain)
5188
- validateData(types["EIP712Domain"], domain);
5189
- const type = types[primaryType];
5190
- validateData(type, message);
5191
- }
5192
5495
 
5193
5496
  // src/actions/wallet/switchChain.ts
5194
5497
  async function switchChain(client, { id: id2 }) {
@@ -5262,7 +5565,17 @@ function parseGwei(ether, unit = "wei") {
5262
5565
  // src/utils/transaction/prepareRequest.ts
5263
5566
  var defaultTip = parseGwei("1.5");
5264
5567
  async function prepareRequest(client, args) {
5265
- const { account, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce } = args;
5568
+ const {
5569
+ account: account_,
5570
+ gas,
5571
+ gasPrice,
5572
+ maxFeePerGas,
5573
+ maxPriorityFeePerGas,
5574
+ nonce
5575
+ } = args;
5576
+ if (!account_)
5577
+ throw new AccountNotFoundError();
5578
+ const account = parseAccount(account_);
5266
5579
  const block = await getBlock(client, { blockTag: "latest" });
5267
5580
  const request = { ...args, from: account.address };
5268
5581
  if (typeof nonce === "undefined")
@@ -5354,6 +5667,56 @@ export {
5354
5667
  InvalidAddressError,
5355
5668
  BlockNotFoundError,
5356
5669
  ChainDoesNotSupportContract,
5670
+ parseAccount,
5671
+ concat,
5672
+ concatBytes,
5673
+ concatHex,
5674
+ isBytes,
5675
+ isHex,
5676
+ pad,
5677
+ padHex,
5678
+ padBytes,
5679
+ trim,
5680
+ size,
5681
+ slice,
5682
+ sliceBytes,
5683
+ sliceHex,
5684
+ boolToHex,
5685
+ bytesToHex,
5686
+ toHex,
5687
+ numberToHex,
5688
+ stringToHex,
5689
+ toBytes,
5690
+ boolToBytes,
5691
+ hexToBytes,
5692
+ numberToBytes,
5693
+ stringToBytes,
5694
+ toRlp,
5695
+ fromHex,
5696
+ hexToBigInt,
5697
+ hexToBool,
5698
+ hexToNumber,
5699
+ hexToString,
5700
+ fromBytes,
5701
+ bytesToBigint,
5702
+ bytesToBool,
5703
+ bytesToNumber,
5704
+ bytesToString,
5705
+ fromRlp,
5706
+ extractFunctionParts,
5707
+ extractFunctionName,
5708
+ extractFunctionParams,
5709
+ extractFunctionType,
5710
+ keccak256,
5711
+ getEventSelector,
5712
+ getFunctionSelector,
5713
+ isAddress,
5714
+ getAddress,
5715
+ getContractAddress2 as getContractAddress,
5716
+ getCreateAddress,
5717
+ getCreate2Address,
5718
+ isAddressEqual,
5719
+ toAccount,
5357
5720
  multicall3Abi,
5358
5721
  panicReasons,
5359
5722
  etherUnits,
@@ -5411,54 +5774,6 @@ export {
5411
5774
  RpcError,
5412
5775
  TimeoutError,
5413
5776
  UrlRequiredError,
5414
- concat,
5415
- concatBytes,
5416
- concatHex,
5417
- isBytes,
5418
- isHex,
5419
- pad,
5420
- padHex,
5421
- padBytes,
5422
- trim,
5423
- size,
5424
- slice,
5425
- sliceBytes,
5426
- sliceHex,
5427
- boolToHex,
5428
- bytesToHex,
5429
- toHex,
5430
- numberToHex,
5431
- stringToHex,
5432
- toBytes,
5433
- boolToBytes,
5434
- hexToBytes,
5435
- numberToBytes,
5436
- stringToBytes,
5437
- toRlp,
5438
- fromHex,
5439
- hexToBigInt,
5440
- hexToBool,
5441
- hexToNumber,
5442
- hexToString,
5443
- fromBytes,
5444
- bytesToBigint,
5445
- bytesToBool,
5446
- bytesToNumber,
5447
- bytesToString,
5448
- fromRlp,
5449
- extractFunctionParts,
5450
- extractFunctionName,
5451
- extractFunctionParams,
5452
- extractFunctionType,
5453
- keccak256,
5454
- getEventSelector,
5455
- getFunctionSelector,
5456
- isAddress,
5457
- getAddress,
5458
- getContractAddress2 as getContractAddress,
5459
- getCreateAddress,
5460
- getCreate2Address,
5461
- isAddressEqual,
5462
5777
  encodeAbiParameters,
5463
5778
  decodeAbiParameters,
5464
5779
  formatAbiItem,
@@ -5481,7 +5796,6 @@ export {
5481
5796
  parseAbiItem,
5482
5797
  parseAbiParameter,
5483
5798
  parseAbiParameters,
5484
- getAccount,
5485
5799
  isDeterministicError,
5486
5800
  buildRequest,
5487
5801
  defineChain,
@@ -5507,9 +5821,13 @@ export {
5507
5821
  getSocket,
5508
5822
  rpc,
5509
5823
  hashMessage,
5824
+ validateTypedData,
5825
+ hashTypedData,
5510
5826
  recoverAddress,
5511
5827
  recoverMessageAddress,
5828
+ recoverTypedDataAddress,
5512
5829
  verifyMessage,
5830
+ verifyTypedData,
5513
5831
  assertRequest,
5514
5832
  call,
5515
5833
  simulateContract,
@@ -5580,7 +5898,7 @@ export {
5580
5898
  requestAddresses,
5581
5899
  requestPermissions,
5582
5900
  sendTransaction,
5583
- signMessage,
5901
+ signMessage2 as signMessage,
5584
5902
  signTypedData,
5585
5903
  switchChain,
5586
5904
  watchAsset,
@@ -5593,4 +5911,4 @@ export {
5593
5911
  formatGwei,
5594
5912
  parseEther
5595
5913
  };
5596
- //# sourceMappingURL=chunk-ISLCPEI2.mjs.map
5914
+ //# sourceMappingURL=chunk-PB263D6W.mjs.map